hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
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
270
max_issues_repo_name
stringlengths
5
116
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
270
max_forks_repo_name
stringlengths
5
116
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
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
2d5344593bbee092a6b00cbcc53469a16e0f8ffd
66,555
cpp
C++
src/script/syntax.cpp
LePtitDev/lite-script
2bd3233586737b6e53d5748b03cc21d53702a6c2
[ "BSD-3-Clause" ]
6
2017-09-01T11:27:47.000Z
2020-01-16T18:53:10.000Z
src/script/syntax.cpp
LePtitDev/lite-script
2bd3233586737b6e53d5748b03cc21d53702a6c2
[ "BSD-3-Clause" ]
null
null
null
src/script/syntax.cpp
LePtitDev/lite-script
2bd3233586737b6e53d5748b03cc21d53702a6c2
[ "BSD-3-Clause" ]
null
null
null
///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// /* Copyright (C) 2017 LePtitDev All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. Author: Arthur Ferré <leptitdev.com> */ ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// #include <cstdlib> #include "../types/internal.hpp" #include "syntax.hpp" std::array<unsigned char, LiteScript::Syntax::Operators::OP_NUMBER> LiteScript::Syntax::OP_Priority({ 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 8, 9, 10, 11, 12, 13, 13, 13, 13, 13 }); unsigned int LiteScript::Syntax::ReadUndefined(const char *text) { std::string str; return (ReadName(text, str) > 0 && str == "undefined") ? 9 : 0; } unsigned int LiteScript::Syntax::ReadNull(const char *text) { std::string str; return (ReadName(text, str) > 0 && str == "null") ? 4 : 0; } unsigned int LiteScript::Syntax::ReadThis(const char *text) { std::string str; return (ReadName(text, str) > 0 && str == "this") ? 4 : 0; } unsigned int LiteScript::Syntax::ReadBoolean(const char *text, bool &res) { std::string str; if (ReadName(text, str) > 0) { if (str == "true") { res = true; return 4; } else if (str == "false") { res = false; return 5; } } return 0; } unsigned int LiteScript::Syntax::ReadUInteger(const char *text, unsigned int &res) { if (text[0] < '0' || text[0] > '9') return 0; res = 0; for (unsigned int i = 0; true; i++) { res += (unsigned int)(text[i] - '0'); if (text[i + 1] < '0' || text[i + 1] > '9') return i + 1; else res *= 10; } } unsigned int LiteScript::Syntax::ReadNumber(const char *text, float &res) { unsigned int nb; if (text[0] == '-') { nb = ReadUNumber(text + 1, res); if (nb == 0) return 0; res = -res; return nb + 1; } else if (text[0] == '+') { nb = ReadUNumber(text + 1, res); if (nb == 0) return 0; return nb + 1; } else { return ReadUNumber(text, res); } } unsigned int LiteScript::Syntax::ReadUNumber(const char *text, float &res) { unsigned int i = 0; if (text[0] >= '0' && text[0] <= '9') goto q1; if (text[0] == '.' && text[1] >= '0' && text[1] <= '9') goto q2; else return 0; q1: for (; text[i] >= '0' && text[i] <= '9'; i++); if (text[i] == '.') goto q2; if (text[i] == 'e') goto q3; else goto r; q2: for (i++; text[i] >= '0' && text[i] <= '9'; i++); if (text[i] == 'e') goto q3; else goto r; q3: i++; if (text[i] == '+' || text[i] == '-') i++; if (text[i] < '0' || text[i] > '9') return 0; for (; text[i] >= '0' && text[i] <= '9'; i++); r: res = (float)atof(text); return i; } unsigned int LiteScript::Syntax::ReadName(const char *text, std::string &name) { if ((text[0] < 'a' || text[0] > 'z') && (text[0] < 'A' || text[0] > 'Z') && text[0] != '$' && text[0] != '_') return 0; name.clear(); name += text[0]; unsigned int i; for (i = 1; (text[i] >= 'a' && text[i] <= 'z') || (text[i] >= 'A' && text[i] <= 'Z') || (text[i] >= '0' && text[i] <= '9') || text[i] == '$' || text[i] == '_'; i++) name += text[i]; return i; } int LiteScript::Syntax::ReadString(const char *text, std::string &string) { if (text[0] != '"' && text[0] != '\'') return 0; string.clear(); char end_char = text[0]; int i; for (i = 1; text[i] != end_char; i++) { if (text[i] == '\0') return -1; if (text[i] != '\\') { string += text[i]; } else { switch (text[++i]) { case 'n': string += '\n'; break; case 't': string += '\t'; break; default: string += text[i]; } } } return i + 1; } unsigned int LiteScript::Syntax::ReadComment(const char *text) { if (text[0] != '/') return 0; unsigned int i; if (text[1] == '/') { for (i = 2; text[i] != '\n' && text[i] != '\0'; i++); return i; } else if (text[1] == '*') { for (i = 2; text[i] != '\0'; i++) { if (text[i] == '*' && text[i + 1] == '/') { i += 2; break; } } return i; } else { return 0; } } unsigned int LiteScript::Syntax::ReadWhitespace(const char *text) { unsigned int i = 0, tmp; while (true) { if (text[i] == ' ' || text[i] == '\t' || text[i] == '\n') i++; else if ((tmp = ReadComment(text + i)) > 0) i += tmp; else break; } return i; } int LiteScript::Syntax::ReadArray(const char *text, std::vector<Instruction> &instrl, Script::ErrorType &errorType) { union { int i; unsigned int ui; } tmp; int i = 1; if (text[0] == '[') { // \[ ({expr}(,{expr})*)? \] instrl.push_back(Instruction(InstrCode::INSTR_VALUE_ARRAY)); unsigned int index = 0; while (text[i] != ']') { if ((tmp.ui = ReadWhitespace(text + i)) > 0) i += (int)tmp.ui; else if (index == 0 && (tmp.i = ReadExpression(text + i, instrl, errorType)) > 0) { i += tmp.i; instrl.push_back(Instruction(InstrCode::INSTR_ARRAY_PUSH_NUMERIC, (int)0)); index++; } else if (index > 0 && text[i] == ',' && (tmp.i = ReadExpression(text + i + 1, instrl, errorType)) > 0) { i += tmp.i + 1; instrl.push_back(Instruction(InstrCode::INSTR_ARRAY_PUSH_NUMERIC, (int)index++)); } else { if (tmp.i != 0) return tmp.i - i; else { errorType = Script::ErrorType::SCRPT_ERROR_SIMPLEARRAY_END; return -i; } } } return i + 1; } else if (text[0] == '{') { // \{ ({name}:{expr}(,{name}:{expr})*)? \} instrl.push_back(Instruction(InstrCode::INSTR_VALUE_ARRAY)); bool need_name = true; std::string tmp_str; while (text[i] != '}') { if ((tmp.ui = ReadWhitespace(text + i)) > 0) i += (int)tmp.ui; else if (need_name && (tmp.ui = ReadName(text + i, tmp_str)) > 0) { i += (int)tmp.ui; i += (int)ReadWhitespace(text + i); if (text[i] != ':') { errorType = Script::ErrorType::SCRPT_ERROR_NAMEDARRAY_COLON; return -i; } ++i; if ((tmp.i = ReadExpression(text + i, instrl, errorType)) <= 0) { if (tmp.i != 0) return tmp.i - i; else { errorType = Script::ErrorType::SCRPT_ERROR_NAMEDARRAY_EXPRESSION; return -i; } } i += tmp.i; instrl.push_back(Instruction(InstrCode::INSTR_ARRAY_PUSH_LITERAL, tmp_str.c_str())); need_name = false; } else if (!need_name && text[i] == ',') { i++; need_name = true; } else { if (tmp.i != 0) return tmp.i - i; else { errorType = Script::ErrorType::SCRPT_ERROR_NAMEDARRAY_END; return -i; } } } return i + 1; } else { return 0; } } int LiteScript::Syntax::ReadCallbackValue(const char *text, std::vector<Instruction> &instrl, Script::ErrorType &errorType) { std::string tmp_s; if (ReadName(text, tmp_s) == 0 || tmp_s != "function") return 0; int i = 8, tmp, jt = instrl.size(), line = instrl.size() + 1; instrl.push_back(Instruction(InstrCode::INSTR_JUMP_TO)); i += ReadWhitespace(text + i); // function\(({name}(,{name})*(...)?)?\){instructionBlock} if ((tmp = ReadCallbackArguments(text + i, instrl, errorType)) <= 0) { if (tmp != 0) return tmp - i; else { errorType = Script::ErrorType::SCRPT_ERROR_CALLBACK_ARGUMENTS; return -i; } } i += tmp; i += ReadWhitespace(text + i); if ((tmp = ReadInstructionBlock(text + i, instrl, errorType)) <= 0) { if (tmp != 0) return tmp - i; else { errorType = Script::ErrorType::SCRPT_ERROR_CALLBACK_INSTRUCTIONS; return -i; } } i += tmp; instrl.push_back(Instruction(InstrCode::INSTR_RETURN)); instrl[jt] = Instruction(InstrCode::INSTR_JUMP_TO, (int)instrl.size()); instrl.push_back(Instruction(InstrCode::INSTR_VALUE_CALLBACK, line)); return i; } int LiteScript::Syntax::ReadCallbackArguments(const char *text, std::vector<Instruction> &instrl, Script::ErrorType &errorType) { if (text[0] != '(') return 0; bool need_name = true; std::string name; int i = 1; union { int i; unsigned int ui; } tmp; int index = 0; while (text[i] != ')') { if ((tmp.ui = ReadWhitespace(text + i)) > 0) i += (int)tmp.ui; else if (need_name && (tmp.i = ReadName(text + i, name)) > 0) { i += tmp.i; instrl.push_back(Instruction(InstrCode::INSTR_VALUE_ARG, index)); instrl.push_back(Instruction(InstrCode::INSTR_DEFINE_VARIABLE, name.c_str())); need_name = false; } else if (!need_name && text[i] == ',') { i++; index++; need_name = true; } else if (!need_name && text[i] == '.' && text[i + 1] == '.' && text[i + 2] == '.') { instrl[instrl.size() - 2].code = InstrCode::INSTR_VALUE_ARGS; i += 3; i += ReadWhitespace(text + i); if (text[i] != ')') { errorType = Script::ErrorType::SCRPT_ERROR_CALLBACK_ARGUMENT_END; return -i; } } else { errorType = Script::ErrorType::SCRPT_ERROR_CALLBACK_ARGUMENT_END; return -i; } } if (need_name && index > 0) { errorType = Script::ErrorType::SCRPT_ERROR_CALLBACK_ARGUMENT_NAME; return -i; } return i + 1; } int LiteScript::Syntax::ReadClassValue(const char *text, std::vector<Instruction> &instrl, Script::ErrorType &errorType) { std::string tmp_s; if (ReadName(text, tmp_s) == 0 || tmp_s != "class") return 0; instrl.push_back(Instruction(InstrCode::INSTR_VALUE_CLASS)); int i = 5; union { int i; unsigned int ui; } tmp; i += ReadWhitespace(text + i); if ((tmp.i = ReadClassInherits(text + i, instrl, errorType)) >= 0) i += tmp.i; else return tmp.i - i; i += ReadWhitespace(text + i); if (text[i] != '{') { errorType = Script::ErrorType::SCRPT_ERROR_CLASS_BEGIN; return -i; } ++i; while (text[i] != '}') { if ((tmp.ui = ReadWhitespace(text + i)) > 0) i += (int)tmp.ui; else if ((tmp.i = ReadClassMember(text + i, instrl, errorType)) > 0) { i += tmp.i; } else { if (tmp.i != 0) return tmp.i - i; else { errorType = Script::ErrorType::SCRPT_ERROR_CLASS_END; return -i; } } } instrl.push_back(Instruction(InstrCode::INSTR_CLASS_CONSTRUCTOR, "constructor")); return i + 1; } int LiteScript::Syntax::ReadClassInherits(const char *text, std::vector<Instruction> &instrl, Script::ErrorType &errorType) { if (text[0] != ':') return 0; int i = 1; i += ReadWhitespace(text + i); union { int i; unsigned int ui; } tmp; bool need_expr = true; while (text[i] != '{') { if ((tmp.ui = ReadWhitespace(text + i)) > 0) i += (int)tmp.ui; else if (!need_expr && text[i] == ',') { i++; need_expr = true; } else if (need_expr && (tmp.i = ReadExpression(text + i, instrl, errorType)) > 0) { i += tmp.i; instrl.push_back(Instruction(InstrCode::INSTR_CLASS_INHERIT)); need_expr = false; } else { if (tmp.i != 0) return tmp.i - i; else { errorType = Script::ErrorType::SCRPT_ERROR_CLASS_INHERIT; return -i; } } } if (need_expr) { errorType = Script::ErrorType::SCRPT_ERROR_CLASS_INHERIT; return -i; } return i; } int LiteScript::Syntax::ReadClassMember(const char *text, std::vector<Instruction> &instrl, Script::ErrorType &errorType) { int i = 0, tmp, curr; if ((tmp = ReadClassOperator(text, instrl, errorType)) != 0) return tmp; if ((tmp = ReadClass(text, instrl, errorType)) != 0) { if (tmp > 0) instrl.back().code = InstrCode::INSTR_CLASS_PUSH_STATIC; return tmp; } bool is_static = false; if (text[0] == 's' && text[1] == 't' && text[2] == 'a' && text[3] == 't' && text[4] == 'i' && text[5] == 'c') { is_static = true; i = 6; i += ReadWhitespace(text + i); } if (text[i] == 'v') { curr = instrl.size(); if ((tmp = ReadVariableDefinition(text + i, instrl, errorType)) <= 0) { if (tmp != 0) return tmp - i; else { errorType = Script::ErrorType::SCRPT_ERROR_CLASS_INVALID; return -i; } } i += tmp; for (int sz = instrl.size(); curr < sz; curr++) { if (instrl[curr].code == InstrCode::INSTR_DEFINE_VARIABLE) instrl[curr].code = is_static ? InstrCode::INSTR_CLASS_PUSH_STATIC : InstrCode::INSTR_CLASS_PUSH_USTATIC; } i += ReadWhitespace(text + i); if (text[i] != ';') { errorType = Script::ErrorType::SCRPT_ERROR_SEMICOLON; return -i; } ++i; } else if (text[i] == 'f') { if ((tmp = ReadCallback(text + i, instrl, errorType)) <= 0) { if (tmp != 0) return tmp - i; else { errorType = Script::ErrorType::SCRPT_ERROR_CLASS_INVALID; return -i; } } i += tmp; instrl.back().code = is_static ? InstrCode::INSTR_CLASS_PUSH_STATIC : InstrCode::INSTR_CLASS_PUSH_USTATIC; } else { errorType = Script::ErrorType::SCRPT_ERROR_CLASS_INVALID; return -i; } return i; } int LiteScript::Syntax::ReadClassOperator(const char *text, std::vector<Instruction> &instrl, Script::ErrorType &errorType) { if (text[0] != 'o' || text[1] != 'p' || text[2] != 'e' || text[3] != 'r' || text[4] != 'a' || text[5] != 't' || text[6] != 'o' || text[7] != 'r') return 0; int i = 8; union { int i; unsigned int ui; } tmp; i += ReadWhitespace(text + i); std::string name; if ((tmp.ui = ReadName(text + i, name)) <= 0) { errorType = Script::ErrorType::SCRPT_ERROR_CLASS_OPERATOR_NAME; return -i; } Class::OperatorType op; if (name == "assign") op = Class::OperatorType::OP_TYPE_ASSIGN; else if (name == "unary_plus") op = Class::OperatorType::OP_TYPE_UNARY_PLUS; else if (name == "unary_minus") op = Class::OperatorType::OP_TYPE_UNARY_MINUS; else if (name == "pre_increment") op = Class::OperatorType::OP_TYPE_PRE_INCR; else if (name == "pre_decrement") op = Class::OperatorType::OP_TYPE_PRE_DECR; else if (name == "post_increment") op = Class::OperatorType::OP_TYPE_POST_INCR; else if (name == "post_decrement") op = Class::OperatorType::OP_TYPE_POST_DECR; else if (name == "add") op = Class::OperatorType::OP_TYPE_ADD; else if (name == "subtract") op = Class::OperatorType::OP_TYPE_SUB; else if (name == "multiply") op = Class::OperatorType::OP_TYPE_MUL; else if (name == "divide") op = Class::OperatorType::OP_TYPE_DIV; else if (name == "modulo") op = Class::OperatorType::OP_TYPE_MOD; else if (name == "equal") op = Class::OperatorType::OP_TYPE_EQU; else if (name == "not_equal") op = Class::OperatorType::OP_TYPE_ADD; else if (name == "greater") op = Class::OperatorType::OP_TYPE_GREAT; else if (name == "lesser") op = Class::OperatorType::OP_TYPE_LESS; else if (name == "greater_equal") op = Class::OperatorType::OP_TYPE_GREAT_EQU; else if (name == "lesser_equal") op = Class::OperatorType::OP_TYPE_LESS_EQU; else if (name == "not") op = Class::OperatorType::OP_TYPE_LOG_NOT; else if (name == "and") op = Class::OperatorType::OP_TYPE_LOG_AND; else if (name == "or") op = Class::OperatorType::OP_TYPE_LOG_OR; else if (name == "bitwise_not") op = Class::OperatorType::OP_TYPE_BIT_NOT; else if (name == "bitwise_and") op = Class::OperatorType::OP_TYPE_BIT_AND; else if (name == "bitwise_or") op = Class::OperatorType::OP_TYPE_BIT_OR; else if (name == "bitwise_xor") op = Class::OperatorType::OP_TYPE_BIT_XOR; else if (name == "left_shift") op = Class::OperatorType::OP_TYPE_LSHIFT; else if (name == "right_shift") op = Class::OperatorType::OP_TYPE_RSHIFT; else if (name == "add_assign") op = Class::OperatorType::OP_TYPE_ADD_ASSIGN; else if (name == "subtract_assign") op = Class::OperatorType::OP_TYPE_SUB_ASSIGN; else if (name == "multiply_assign") op = Class::OperatorType::OP_TYPE_MUL_ASSIGN; else if (name == "divide_assign") op = Class::OperatorType::OP_TYPE_DIV_ASSIGN; else if (name == "get") op = Class::OperatorType::OP_TYPE_ARRAY; else if (name == "call") op = Class::OperatorType::OP_TYPE_CALL; else { errorType = Script::ErrorType::SCRPT_ERROR_CLASS_OPERATOR_INVALID; return -i; } instrl.push_back(Instruction(InstrCode::INSTR_JUMP_TO)); int call_pos = instrl.size(); i += (int)tmp.ui; i += ReadWhitespace(text + i); if ((tmp.i = ReadCallbackArguments(text + i, instrl, errorType)) <= 0) { if (tmp.i != 0) return tmp.i - i; else { errorType = Script::ErrorType::SCRPT_ERROR_CALLBACK_ARGUMENTS; return -i; } } i += tmp.i; i += ReadWhitespace(text + i); if ((tmp.i = ReadInstructionBlock(text + i, instrl, errorType)) <= 0) { if (tmp.i != 0) return tmp.i - i; else { errorType = Script::ErrorType::SCRPT_ERROR_CALLBACK_INSTRUCTIONS; return -i; } } i += tmp.i; instrl[call_pos - 1] = Instruction(InstrCode::INSTR_JUMP_TO, (int)instrl.size()); instrl.push_back(Instruction(InstrCode::INSTR_VALUE_CALLBACK, (int)call_pos)); instrl.push_back(Instruction(InstrCode::INSTR_CLASS_PUSH_OPERATOR, (int)op)); return i; } int LiteScript::Syntax::ReadValue(const char *text, std::vector<Instruction> &instrl, Script::ErrorType &errorType) { union { int i; unsigned int ui; } tmp; union { bool b; float f; } res; std::string tmp_s; if ((tmp.ui = ReadUndefined(text)) > 0) { instrl.push_back(Instruction(InstrCode::INSTR_VALUE_UNDEFINED)); return (int) tmp.ui; } else if ((tmp.ui = ReadNull(text)) > 0) { instrl.push_back(Instruction(InstrCode::INSTR_VALUE_NULL)); return (int) tmp.ui; } else if ((tmp.ui = ReadThis(text)) > 0) { instrl.push_back(Instruction(InstrCode::INSTR_VALUE_THIS)); return (int) tmp.ui; } else if ((tmp.ui = ReadBoolean(text, res.b)) > 0) { instrl.push_back(Instruction(InstrCode::INSTR_VALUE_BOOLEAN, res.b)); return (int) tmp.ui; } else if ((tmp.ui = ReadNumber(text, res.f)) > 0) { instrl.push_back(Instruction(InstrCode::INSTR_VALUE_NUMBER, res.f)); return (int) tmp.ui; } else if ((tmp.i = ReadCallbackValue(text, instrl, errorType)) > 0) { return tmp.i; } else if (tmp.i != 0) return tmp.i; else if ((tmp.i = ReadClassValue(text, instrl, errorType)) > 0) { return tmp.i; } else if (tmp.i != 0) return tmp.i; else if ((tmp.ui = ReadName(text, tmp_s)) > 0) { instrl.push_back(Instruction(InstrCode::INSTR_VALUE_VARIABLE, tmp_s.c_str())); return (int) tmp.ui; } else if ((tmp.i = ReadString(text, tmp_s)) > 0) { instrl.push_back(Instruction(InstrCode::INSTR_VALUE_STRING, tmp_s.c_str())); return tmp.i; } else if (tmp.i != 0) return tmp.i; else if ((tmp.i = ReadArray(text, instrl, errorType)) > 0) { return tmp.i; } else if (tmp.i != 0) return tmp.i; else if (text[0] == '(') { int i = 1; i += ReadWhitespace(text + i); if ((tmp.i = ReadExpression(text + i, instrl, errorType)) <= 0) { if (tmp.i != 0) return tmp.i - i; else { errorType = Script::ErrorType::SCRPT_ERROR_EXPRESSION; return -i; } } i += tmp.i; i += ReadWhitespace(text + i); if (text[i] != ')') { errorType = Script::ErrorType::SCRPT_ERROR_PARENTHESIS_CLOSE; return -i; } return i + 1; } else return 0; } void LiteScript::Syntax::PopOperator(std::vector<Operators> &op, std::vector<Instruction>& instrl) { switch (op.back()) { // LEVEL 1 case Operators::OP_POST_INCR: instrl.push_back(Instruction(InstrCode::INSTR_OP_POST_INCR)); break; case Operators::OP_POST_DECR: instrl.push_back(Instruction(InstrCode::INSTR_OP_POST_DECR)); break; case Operators::OP_CALL: instrl.push_back(Instruction(InstrCode::INSTR_OP_CALL)); break; case Operators::OP_GET: instrl.push_back(Instruction(InstrCode::INSTR_OP_ARRAY)); break; case Operators::OP_MEMBER: instrl.back().code = InstrCode::INSTR_OP_MEMBER; break; // LEVEL 2 case Operators::OP_PRE_INCR: instrl.push_back(Instruction(InstrCode::INSTR_OP_PRE_INCR)); break; case Operators::OP_PRE_DECR: instrl.push_back(Instruction(InstrCode::INSTR_OP_PRE_DECR)); break; case Operators::OP_UNARY_PLUS: instrl.push_back(Instruction(InstrCode::INSTR_OP_UNARY_PLUS)); break; case Operators::OP_UNARY_MINUS: instrl.push_back(Instruction(InstrCode::INSTR_OP_UNARY_MINUS)); break; case Operators::OP_NOT: instrl.push_back(Instruction(InstrCode::INSTR_OP_LOG_NOT)); break; case Operators::OP_BIT_NOT: instrl.push_back(Instruction(InstrCode::INSTR_OP_BIT_NOT)); break; case Operators::OP_NEW: instrl.push_back(Instruction(InstrCode::INSTR_VALUE_OBJECT)); break; // LEVEL 3 case Operators::OP_MUL: instrl.push_back(Instruction(InstrCode::INSTR_OP_MUL)); break; case Operators::OP_DIV: instrl.push_back(Instruction(InstrCode::INSTR_OP_DIV)); break; case Operators::OP_MOD: instrl.push_back(Instruction(InstrCode::INSTR_OP_MOD)); break; // LEVEL 4 case Operators::OP_ADD: instrl.push_back(Instruction(InstrCode::INSTR_OP_ADD)); break; case Operators::OP_SUB: instrl.push_back(Instruction(InstrCode::INSTR_OP_SUB)); break; // LEVEL 5 case Operators::OP_LSHIFT: instrl.push_back(Instruction(InstrCode::INSTR_OP_LSHIFT)); break; case Operators::OP_RSHIFT: instrl.push_back(Instruction(InstrCode::INSTR_OP_RSHIFT)); break; // LEVEL 6 case Operators::OP_LESS: instrl.push_back(Instruction(InstrCode::INSTR_OP_LESS)); break; case Operators::OP_LESS_EQU: instrl.push_back(Instruction(InstrCode::INSTR_OP_LESS_EQU)); break; case Operators::OP_GREAT: instrl.push_back(Instruction(InstrCode::INSTR_OP_GREAT)); break; case Operators::OP_GREAT_EQU: instrl.push_back(Instruction(InstrCode::INSTR_OP_GREAT_EQU)); break; // LEVEL 7 case Operators::OP_EQU: instrl.push_back(Instruction(InstrCode::INSTR_OP_EQU)); break; case Operators::OP_DIF: instrl.push_back(Instruction(InstrCode::INSTR_OP_DIF)); break; // LEVEL 8 case Operators::OP_BIT_AND: instrl.push_back(Instruction(InstrCode::INSTR_OP_BIT_AND)); break; // LEVEL 9 case Operators::OP_BIT_XOR: instrl.push_back(Instruction(InstrCode::INSTR_OP_BIT_XOR)); break; // LEVEL 10 case Operators::OP_BIT_OR: instrl.push_back(Instruction(InstrCode::INSTR_OP_BIT_OR)); break; // LEVEL 11 case Operators::OP_AND: instrl.push_back(Instruction(InstrCode::INSTR_OP_LOG_AND)); break; // LEVEL 12 case Operators::OP_OR: instrl.push_back(Instruction(InstrCode::INSTR_OP_LOG_OR)); break; // LEVEL 13 case Operators::OP_ASSIGN: instrl.push_back(Instruction(InstrCode::INSTR_OP_ASSIGN)); break; case Operators::OP_ADD_ASSIGN: instrl.push_back(Instruction(InstrCode::INSTR_OP_ADD_ASSIGN)); break; case Operators::OP_SUB_ASSIGN: instrl.push_back(Instruction(InstrCode::INSTR_OP_SUB_ASSIGN)); break; case Operators::OP_MUL_ASSIGN: instrl.push_back(Instruction(InstrCode::INSTR_OP_MUL_ASSIGN)); break; case Operators::OP_DIV_ASSIGN: instrl.push_back(Instruction(InstrCode::INSTR_OP_DIV_ASSIGN)); break; default: break; } op.pop_back(); } void LiteScript::Syntax::PushOperator(std::vector<Operators> &opl, Operators opc, std::vector<Instruction>& instrl) { while (opl.size() > 0 && OP_Priority[opl.back()] <= OP_Priority[opc]) PopOperator(opl, instrl); opl.push_back(opc); } int LiteScript::Syntax::ReadPrefixOperator(const char *text, std::vector<Operators> &op, std::vector<Instruction> &instrl, Script::ErrorType &errorType) { if (text[0] == 'n' && text[1] == 'e' && text[2] == 'w') { PushOperator(op, Operators::OP_NEW, instrl); return 3; } else if (text[0] == '+') { if (text[1] == '+') { PushOperator(op, Operators::OP_PRE_INCR, instrl); return 2; } else { PushOperator(op, Operators::OP_UNARY_PLUS, instrl); return 1; } } else if (text[0] == '-') { if (text[1] == '-') { PushOperator(op, Operators::OP_PRE_DECR, instrl); return 2; } else { PushOperator(op, Operators::OP_UNARY_MINUS, instrl); return 1; } } else if (text[0] == '!') { PushOperator(op, Operators::OP_NOT, instrl); return 1; } else if (text[0] == '~') { PushOperator(op, Operators::OP_BIT_NOT, instrl); return 1; } else return 0; } int LiteScript::Syntax::ReadSuffixOperator(const char *text, std::vector<Operators> &op, std::vector<Instruction> &instrl, Script::ErrorType &errorType) { if (text[0] == '+' && text[1] == '+') { PushOperator(op, Operators::OP_POST_INCR, instrl); return 2; } else if (text[0] == '-' && text[1] == '-') { PushOperator(op, Operators::OP_POST_DECR, instrl); return 2; } else return 0; } int LiteScript::Syntax::ReadOperator(const char *text, std::vector<Operators> &op, bool& need_value, std::vector<Instruction> &instrl, Script::ErrorType &errorType) { need_value = true; if (text[0] == '(') { while (op.size() > 0 && OP_Priority[op.back()] == 1) PopOperator(op, instrl); instrl.push_back(Instruction(InstrCode::INSTR_PUSH_ARGS)); int i = 1, index = 0; union { int i; unsigned int ui; } tmp; bool need_arg = true; while (text[i] != ')') { if ((tmp.ui = ReadWhitespace(text + i)) > 0) i += (int)tmp.ui; else if (need_arg && (tmp.i = ReadExpression(text + i, instrl, errorType)) > 0) { i += tmp.i; need_arg = false; instrl.push_back(Instruction(InstrCode::INSTR_DEFINE_ARG, index++)); } else if (tmp.i < 0) return tmp.i - i; else if (!need_arg && text[i] == ',') { i++; need_arg = true; } else { errorType = Script::ErrorType::SCRPT_ERROR_PARENTHESIS_CLOSE; return -i; } } if (need_arg && index > 0) { errorType = Script::ErrorType::SCRPT_ERROR_EXPRESSION; return -i; } if (op.size() > 0 && op.back() == Operators::OP_NEW) { op.pop_back(); instrl.push_back(Instruction(InstrCode::INSTR_VALUE_OBJECT)); } else instrl.push_back(Instruction(InstrCode::INSTR_OP_CALL)); need_value = false; return i + 1; } else if (text[0] == '[') { while (op.size() > 0 && OP_Priority[op.back()] == 1) PopOperator(op, instrl); int i = 1, tmp; i += (int)ReadWhitespace(text + i); if ((tmp = ReadExpression(text + i, instrl, errorType)) <= 0) { if (tmp != 0) return tmp - i; else { errorType = Script::ErrorType::SCRPT_ERROR_EXPRESSION; return -i; } } i += tmp; i += (int)ReadWhitespace(text + i); if (text[i] != ']') { errorType = Script::ErrorType::SCRPT_ERROR_BRACKET_CLOSE; return -i; } instrl.push_back(Instruction(InstrCode::INSTR_OP_ARRAY)); need_value = false; return i + 1; } else if (text[0] == '.') { while (op.size() > 0 && OP_Priority[op.back()] == 1) PopOperator(op, instrl); int i = 1; i += (int)ReadWhitespace(text + i); unsigned int tmp; std::string name; if ((tmp = ReadName(text + i, name)) == 0) { errorType = Script::ErrorType::SCRPT_ERROR_NAME; return -i; } i += (int)tmp; instrl.push_back(Instruction(InstrCode::INSTR_OP_MEMBER, name.c_str())); need_value = false; return i; } else if (text[0] == '?') { while (op.size() > 0 && OP_Priority[op.back()] == OP_Priority[Operators::OP_ASSIGN]) PopOperator(op, instrl); int i = 1, tmp, line_je = instrl.size(); i += (int)ReadWhitespace(text + i); instrl.push_back(Instruction(InstrCode::INSTR_JUMP_ELSE)); if ((tmp = ReadExpression(text + i, instrl, errorType)) <= 0) { if (tmp != 0) return tmp - i; else { errorType = Script::ErrorType::SCRPT_ERROR_EXPRESSION; return -i; } } i += tmp; i += (int)ReadWhitespace(text + i); int line_jt = instrl.size(); instrl.push_back(Instruction(InstrCode::INSTR_JUMP_TO)); instrl[line_je] = Instruction(InstrCode::INSTR_JUMP_ELSE, (int)instrl.size()); if (text[i] != ':') { errorType = Script::ErrorType::SCRPT_ERROR_COLON; return -i; } i += (int)ReadWhitespace(text + i); if ((tmp = ReadExpression(text + i, instrl, errorType)) <= 0) { if (tmp != 0) return tmp - i; else { errorType = Script::ErrorType::SCRPT_ERROR_EXPRESSION; return -i; } } instrl[line_jt] = Instruction(InstrCode::INSTR_JUMP_TO, (int)instrl.size()); i += tmp; return i; } else { switch (text[0]) { case '+': if (text[1] == '=') { PushOperator(op, Operators::OP_ADD_ASSIGN, instrl); return 2; } else { PushOperator(op, Operators::OP_ADD, instrl); return 1; } case '-': if (text[1] == '=') { PushOperator(op, Operators::OP_SUB_ASSIGN, instrl); return 2; } else { PushOperator(op, Operators::OP_SUB, instrl); return 1; } case '*': if (text[1] == '=') { PushOperator(op, Operators::OP_MUL_ASSIGN, instrl); return 2; } else { PushOperator(op, Operators::OP_MUL, instrl); return 1; } case '/': if (text[1] == '=') { PushOperator(op, Operators::OP_DIV_ASSIGN, instrl); return 2; } else { PushOperator(op, Operators::OP_DIV, instrl); return 1; } case '%': PushOperator(op, Operators::OP_MOD, instrl); return 1; case '=': if (text[1] == '=') { PushOperator(op, Operators::OP_EQU, instrl); return 2; } else { PushOperator(op, Operators::OP_ASSIGN, instrl); return 1; } case '!': if (text[1] == '=') { PushOperator(op, Operators::OP_DIF, instrl); return 2; } else { errorType = Script::ErrorType::SCRPT_ERROR_OPERATOR; return -1; } case '<': if (text[1] == '=') { PushOperator(op, Operators::OP_LESS_EQU, instrl); return 2; } else if (text[1] == '<') { PushOperator(op, Operators::OP_LSHIFT, instrl); return 2; } else { PushOperator(op, Operators::OP_LESS, instrl); return 1; } case '>': if (text[1] == '=') { PushOperator(op, Operators::OP_GREAT_EQU, instrl); return 2; } else if (text[1] == '>') { PushOperator(op, Operators::OP_RSHIFT, instrl); return 2; } else { PushOperator(op, Operators::OP_GREAT, instrl); return 1; } case '&': if (text[1] == '&') { PushOperator(op, Operators::OP_AND, instrl); return 2; } else { PushOperator(op, Operators::OP_BIT_AND, instrl); return 1; } case '|': if (text[1] == '|') { PushOperator(op, Operators::OP_OR, instrl); return 2; } else { PushOperator(op, Operators::OP_BIT_OR, instrl); return 1; } case '^': PushOperator(op, Operators::OP_BIT_XOR, instrl); return 1; default: need_value = false; return 0; } } } int LiteScript::Syntax::ReadExpression(const char *text, std::vector<Instruction> &instrl, Script::ErrorType &errorType) { union { int i; unsigned int ui; } tmp; int i = 0, index = 0; std::vector<Operators> op_heap; bool need_value = true; while (true) { if ((tmp.ui = ReadWhitespace(text + i)) > 0) i += (int)tmp.ui; else if (need_value) { bool terminate = true; if ((tmp.i = ReadPrefixOperator(text + i, op_heap, instrl, errorType)) > 0) { terminate = false; i += tmp.i; i += (int)ReadWhitespace(text + i); } if ((tmp.i = ReadValue(text + i, instrl, errorType)) <= 0) { if (tmp.i != 0) return tmp.i; if (terminate) break; errorType = Script::ErrorType::SCRPT_ERROR_VALUE; return -i; } i += tmp.i; if ((tmp.i = ReadSuffixOperator(text + i, op_heap, instrl, errorType)) > 0) i += tmp.i; need_value = false; index++; } else { if ((tmp.i = ReadOperator(text + i, op_heap, need_value, instrl, errorType)) <= 0) { if (tmp.i != 0) return tmp.i - i; else break; } i += tmp.i; } } if (need_value) { if (index == 0) return 0; else { errorType = Script::ErrorType::SCRPT_ERROR_VALUE; return -i; } } while (!op_heap.empty()) PopOperator(op_heap, instrl); return i; } int LiteScript::Syntax::ReadVariableDefinition(const char *text, std::vector<Instruction> &instrl, Script::ErrorType &errorType) { if (text[0] != 'v' || text[1] != 'a' || text[2] != 'r' || text[3] != ' ') return 0; int i = 4, index = 0; union { int i; unsigned int ui; } tmp; bool need_name = true; std::string name; while (true) { if ((tmp.ui = ReadWhitespace(text + i)) > 0) i += (int)tmp.ui; else if (need_name && (tmp.ui = ReadName(text + i, name)) > 0) { i += (int)tmp.ui; i += (int)ReadWhitespace(text + i); if (text[i] == '=') { i++; i += (int)ReadWhitespace(text + i); if ((tmp.i = ReadExpression(text + i, instrl, errorType)) <= 0) { if (tmp.i != 0) return tmp.i - i; else { errorType = Script::ErrorType::SCRPT_ERROR_EXPRESSION; return -i; } } i += tmp.i; } else instrl.push_back(Instruction(InstrCode::INSTR_VALUE_NULL)); instrl.push_back(Instruction(InstrCode::INSTR_VALUE_ASSIGN)); instrl.push_back(Instruction(InstrCode::INSTR_DEFINE_VARIABLE, name.c_str())); need_name = false; index++; } else if (!need_name && text[i] == ',') { need_name = true; i++; } else { break; } } if (need_name) { if (index > 0) { errorType = Script::ErrorType::SCRPT_ERROR_NAME; return -i; } else return 0; } return i; } int LiteScript::Syntax::ReadControlIf(const char *text, std::vector<Instruction> &instrl, Script::ErrorType &errorType) { if (text[0] != 'i' || text[1] != 'f') return 0; int i = 2, tmp; i += (int)ReadWhitespace(text + i); if (text[i] != '(') { errorType = Script::ErrorType::SCRPT_ERROR_PARENTHESIS_OPEN; return -i; } i++; i += (int)ReadWhitespace(text + i); if ((tmp = ReadExpression(text + i, instrl, errorType)) <= 0) { if (tmp != 0) return tmp - i; else { errorType = Script::ErrorType::SCRPT_ERROR_EXPRESSION; return -i; } } i += tmp; i += (int)ReadWhitespace(text + i); if (text[i] != ')') { errorType = Script::ErrorType::SCRPT_ERROR_PARENTHESIS_CLOSE; return -i; } int je = instrl.size(); instrl.push_back(Instruction(InstrCode::INSTR_JUMP_ELSE)); i++; i += (int)ReadWhitespace(text + i); if ((tmp = ReadInstruction(text + i, instrl, errorType)) <= 0) { if (tmp != 0) return tmp - i; else { errorType = Script::ErrorType::SCRPT_ERROR_INSTRUCTION; return -i; } } i += tmp; i += (int)ReadWhitespace(text + i); if (text[i+0] != 'e' || text[i+1] != 'l' || text[i+2] != 's' || text[i+3] != 'e') { instrl[je] = Instruction(InstrCode::INSTR_JUMP_ELSE, (int)instrl.size()); return i; } i += 4; int jt = instrl.size(); instrl.push_back(Instruction(InstrCode::INSTR_JUMP_TO)); instrl[je] = Instruction(InstrCode::INSTR_JUMP_ELSE, (int)instrl.size()); if ((tmp = ReadInstruction(text + i, instrl, errorType)) <= 0) { if (tmp != 0) return tmp - i; else { errorType = Script::ErrorType::SCRPT_ERROR_INSTRUCTION; return -i; } } instrl[jt] = Instruction(InstrCode::INSTR_JUMP_TO, (int)instrl.size()); i += tmp; return i; } int LiteScript::Syntax::ReadReturn(const char *text, std::vector<Instruction> &instrl, Script::ErrorType &errorType) { std::string keyword; if (ReadName(text, keyword) == 0 || keyword != "return") return 0; int i = 6; i += (int)ReadWhitespace(text + i); if (text[i] == ';') { instrl.push_back(Instruction(InstrCode::INSTR_RETURN)); return i + 1; } int tmp; if ((tmp = ReadExpression(text + i, instrl, errorType)) <= 0) { if (tmp != 0) return tmp - i; else { errorType = Script::ErrorType::SCRPT_ERROR_RETURN; return -i; } } i += tmp; i += (int)ReadWhitespace(text + i); instrl.push_back(Instruction(InstrCode::INSTR_DEFINE_RETURN)); instrl.push_back(Instruction(InstrCode::INSTR_RETURN)); if (text[i] != ';') { errorType = Script::ErrorType::SCRPT_ERROR_SEMICOLON; return -i; } return i + 1; } int LiteScript::Syntax::ReadBreak(const char *text, std::vector<Instruction> &instrl, Script::ErrorType &errorType) { std::string keyword; if (ReadName(text, keyword) == 0 || keyword != "break") return 0; int i = 5; i += (int)ReadWhitespace(text + i); instrl.push_back(Instruction(InstrCode::INSTR_JUMP_TO, "break")); if (text[i] != ';') { errorType = Script::ErrorType::SCRPT_ERROR_SEMICOLON; return i; } return i + 1; } int LiteScript::Syntax::ReadContinue(const char *text, std::vector<Instruction> &instrl, Script::ErrorType &errorType) { std::string keyword; if (ReadName(text, keyword) == 0 || keyword != "continue") return 0; int i = 8; i += (int)ReadWhitespace(text + i); instrl.push_back(Instruction(InstrCode::INSTR_JUMP_TO, "continue")); if (text[i] != ';') { errorType = Script::ErrorType::SCRPT_ERROR_SEMICOLON; return i; } return i + 1; } int LiteScript::Syntax::ReadControlWhile(const char *text, std::vector<Instruction> &instrl, Script::ErrorType &errorType) { std::string keyword; if (ReadName(text, keyword) == 0 || keyword != "while") return 0; int i = 5, tmp, jc = instrl.size(); i += (int)ReadWhitespace(text + i); if (text[i] != '(') { errorType = Script::ErrorType::SCRPT_ERROR_PARENTHESIS_OPEN; return -i; } ++i; if ((tmp = ReadExpression(text + i, instrl, errorType)) <= 0) { if (tmp != 0) return tmp - i; else { errorType = Script::ErrorType::SCRPT_ERROR_EXPRESSION; return -i; } } i += tmp; i += (int)ReadWhitespace(text + i); if (text[i] != ')') { errorType = Script::ErrorType::SCRPT_ERROR_PARENTHESIS_CLOSE; return -i; } ++i; i += (int)ReadWhitespace(text + i); int je = instrl.size(); instrl.push_back(Instruction(InstrCode::INSTR_JUMP_ELSE)); if ((tmp = ReadInstruction(text + i, instrl, errorType)) <= 0) { if (tmp != 0) return tmp - i; else { errorType = Script::ErrorType::SCRPT_ERROR_INSTRUCTION; return -i; } } i += tmp; instrl.push_back(Instruction(InstrCode::INSTR_JUMP_TO, jc)); instrl[je] = Instruction(InstrCode::INSTR_JUMP_ELSE, (int)instrl.size()); for (int it = je, sz = instrl.size() - 1; it < sz; it++) { if (instrl[it].code == InstrCode::INSTR_JUMP_TO && instrl[it].comp_type == Instruction::CompType::COMP_TYPE_STRING) { if (std::string(instrl[it].comp_value.v_string) == "break") instrl[it] = Instruction(InstrCode::INSTR_JUMP_TO, sz + 1); else if (std::string(instrl[it].comp_value.v_string) == "continue") instrl[it] = Instruction(InstrCode::INSTR_JUMP_TO, jc); } } return i; } int LiteScript::Syntax::ReadControlDo(const char *text, std::vector<Instruction> &instrl, Script::ErrorType &errorType) { std::string keyword; if (ReadName(text, keyword) == 0 || keyword != "do") return 0; int i = 2, tmp, ji = instrl.size(); i += (int)ReadWhitespace(text + i); if ((tmp = ReadInstruction(text + i, instrl, errorType)) <= 0) { if (tmp != 0) return tmp - i; else { errorType = Script::ErrorType::SCRPT_ERROR_INSTRUCTION; return -i; } } i += tmp; i += (int)ReadWhitespace(text + i); if (ReadName(text + i, keyword) == 0 || keyword != "while") { errorType = Script::ErrorType::SCRPT_ERROR_WHILE; return -i; } i += 5; i += (int)ReadWhitespace(text + i); if (text[i] != '(') { errorType = Script::ErrorType::SCRPT_ERROR_PARENTHESIS_OPEN; return -i; } ++i; i += (int)ReadWhitespace(text + i); if ((tmp = ReadExpression(text + i, instrl, errorType)) <= 0) { if (tmp != 0) return tmp - i; else { errorType = Script::ErrorType::SCRPT_ERROR_EXPRESSION; return -i; } } i += tmp; i += (int)ReadWhitespace(text + i); if (text[i] != ')') { errorType = Script::ErrorType::SCRPT_ERROR_PARENTHESIS_CLOSE; return -i; } ++i; i += (int)ReadWhitespace(text + i); instrl.push_back(Instruction(InstrCode::INSTR_JUMP_IF, ji)); if (text[i] != ';') { errorType = Script::ErrorType::SCRPT_ERROR_SEMICOLON; return -i; } return i + 1; } int LiteScript::Syntax::ReadControlFor(const char *text, std::vector<Instruction> &instrl, Script::ErrorType &errorType) { std::string keyword; if (ReadName(text, keyword) == 0 || keyword != "for") return 0; int i = 3, tmp; i += (int)ReadWhitespace(text + i); if (text[i] != '(') { errorType = Script::ErrorType::SCRPT_ERROR_PARENTHESIS_OPEN; return -i; } ++i; i += (int)ReadWhitespace(text + i); if (text[i] != ';') { if ((tmp = ReadVariableDefinition(text + i, instrl, errorType)) > 0) i += tmp; else if (tmp < 0) return tmp - i; else if ((tmp = ReadExpression(text + i, instrl, errorType)) > 0) { i += tmp; instrl.push_back(Instruction(InstrCode::INSTR_VALUE_POP)); } else if (tmp < 0) return tmp - i; else { errorType = Script::ErrorType::SCRPT_ERROR_FOR_INITIALISATION; return -i; } i += (int)ReadWhitespace(text + i); if (text[i] != ';') { errorType = Script::ErrorType::SCRPT_ERROR_SEMICOLON; return -i; } } ++i; i += (int)ReadWhitespace(text + i); int jc = instrl.size(); if ((tmp = ReadExpression(text + i, instrl, errorType)) <= 0) { if (tmp != 0) return tmp - i; else { errorType = Script::ErrorType::SCRPT_ERROR_FOR_CONDITION; return -i; } } i += tmp; i += (int)ReadWhitespace(text + i); if (text[i] != ';') { errorType = Script::ErrorType::SCRPT_ERROR_SEMICOLON; return -i; } ++i; i += (int)ReadWhitespace(text + i); int jb = instrl.size(); instrl.push_back(Instruction(InstrCode::INSTR_JUMP_ELSE)); instrl.push_back(Instruction(InstrCode::INSTR_JUMP_TO)); if ((tmp = ReadExpression(text + i, instrl, errorType)) > 0) { i += tmp; instrl.push_back(Instruction(InstrCode::INSTR_VALUE_POP)); } else if (tmp < 0) return tmp - i; i += (int)ReadWhitespace(text + i); instrl.push_back(Instruction(InstrCode::INSTR_JUMP_TO, jc)); instrl[jb + 1] = Instruction(InstrCode::INSTR_JUMP_TO, (int)instrl.size()); if (text[i] != ')') { errorType = Script::ErrorType::SCRPT_ERROR_PARENTHESIS_CLOSE; return -i; } ++i; i += (int)ReadWhitespace(text + i); int jex = instrl.size(); if ((tmp = ReadInstruction(text + i, instrl, errorType)) <= 0) { if (tmp != 0) return tmp - i; else { errorType = Script::ErrorType::SCRPT_ERROR_INSTRUCTION; return -i; } } i += tmp; instrl.push_back(Instruction(InstrCode::INSTR_JUMP_TO, jb + 2)); instrl[jb] = Instruction(InstrCode::INSTR_JUMP_ELSE, (int)instrl.size()); for (int it = jex, sz = instrl.size() - 1; it < sz; it++) { if (instrl[it].code == InstrCode::INSTR_JUMP_TO && instrl[it].comp_type == Instruction::CompType::COMP_TYPE_STRING) { if (std::string(instrl[it].comp_value.v_string) == "break") instrl[it] = Instruction(InstrCode::INSTR_JUMP_TO, sz + 1); else if (std::string(instrl[it].comp_value.v_string) == "continue") instrl[it] = Instruction(InstrCode::INSTR_JUMP_TO, jb + 2); } } return i; } int LiteScript::Syntax::ReadControlSwitch(const char *text, std::vector<Instruction> &instrl, Script::ErrorType &errorType) { std::string keyword; if (ReadName(text, keyword) == 0 || keyword != "switch") return 0; int i = 6, tmp; i += (int)ReadWhitespace(text + i); if (text[i] != '(') { errorType = Script::ErrorType::SCRPT_ERROR_PARENTHESIS_OPEN; return -i; } ++i; i += (int)ReadWhitespace(text + i); if ((tmp = ReadExpression(text + i, instrl, errorType)) <= 0) { if (tmp != 0) return tmp - i; else { errorType = Script::ErrorType::SCRPT_ERROR_EXPRESSION; return -i; } } i += tmp; i += (int)ReadWhitespace(text + i); if (text[i] != ')') { errorType = Script::ErrorType::SCRPT_ERROR_PARENTHESIS_CLOSE; return -i; } ++i; i += (int)ReadWhitespace(text + i); if (text[i] != '{') { errorType = Script::ErrorType::SCRPT_ERROR_BRACE_OPEN; return -i; } ++i; i += (int)ReadWhitespace(text + i); int jtn = -1, jen = -1, jb = instrl.size(); while (text[i] != '}') { if ((tmp = (int)ReadWhitespace(text + i)) > 0) i += tmp; else if (ReadName(text + i, keyword) > 0) { if (keyword == "case") { i += 4; i += (int) ReadWhitespace(text + i); instrl.push_back(Instruction(InstrCode::INSTR_VALUE_COPY)); if ((tmp = ReadExpression(text + i, instrl, errorType)) <= 0) { if (tmp != 0) return tmp - i; else { errorType = Script::ErrorType::SCRPT_ERROR_EXPRESSION; return -i; } } i += tmp; i += (int) ReadWhitespace(text + i); if (text[i] != ':') { errorType = Script::ErrorType::SCRPT_ERROR_COLON; return -i; } ++i; i += (int) ReadWhitespace(text + i); instrl.push_back((Instruction(InstrCode::INSTR_OP_EQU))); jen = instrl.size(); instrl.push_back((Instruction(InstrCode::INSTR_JUMP_ELSE))); if (jtn >= 0) instrl[jtn] = Instruction(InstrCode::INSTR_JUMP_TO, (int)instrl.size()); while (text[i] != '}' && (ReadName(text + i, keyword) == 0 || (keyword != "case" && keyword != "default"))){ if ((tmp = (int)ReadWhitespace(text + i)) > 0) i += tmp; else if ((tmp = ReadInstruction(text + i, instrl, errorType)) > 0) i += tmp; else { if (tmp != 0) return tmp - i; else { errorType = Script::ErrorType::SCRPT_ERROR_UNKNOW; return -i; } } } jtn = instrl.size(); instrl.push_back(Instruction(InstrCode::INSTR_JUMP_TO)); if (jen >= 0) instrl[jen] = Instruction(InstrCode::INSTR_JUMP_ELSE, (int)instrl.size()); } else if (keyword == "default") { i += 7; i += (int) ReadWhitespace(text + i); if (text[i] != ':') { errorType = Script::ErrorType::SCRPT_ERROR_COLON; return -i; } ++i; i += (int) ReadWhitespace(text + i); if (jtn >= 0) instrl[jtn] = Instruction(InstrCode::INSTR_JUMP_TO, (int)instrl.size()); if (jen >= 0) instrl[jen] = Instruction(InstrCode::INSTR_JUMP_ELSE, (int)instrl.size()); while (text[i] != '}') { if ((tmp = (int)ReadWhitespace(text + i)) > 0) i += tmp; else if ((tmp = ReadInstruction(text + i, instrl, errorType)) > 0) i += tmp; else { if (tmp != 0) return tmp - i; else { errorType = Script::ErrorType::SCRPT_ERROR_UNKNOW; return -i; } } } break; } else { errorType = Script::ErrorType::SCRPT_ERROR_SWITCH_KEYWORDS; return -i; } } else { errorType = Script::ErrorType::SCRPT_ERROR_SWITCH_END; return -i; } } if (text[i] != '}') { errorType = Script::ErrorType::SCRPT_ERROR_BRACE_CLOSE; return -i; } if (jtn >= 0) instrl[jtn] = Instruction(InstrCode::INSTR_JUMP_TO, (int)instrl.size()); if (jen >= 0) instrl[jen] = Instruction(InstrCode::INSTR_JUMP_ELSE, (int)instrl.size()); for (int it = jb, sz = instrl.size(); it < sz; it++) { if (instrl[it].code == InstrCode::INSTR_JUMP_TO && instrl[it].comp_type == Instruction::CompType::COMP_TYPE_STRING && std::string(instrl[it].comp_value.v_string) == "break") instrl[it] = Instruction(InstrCode::INSTR_JUMP_TO, sz); } instrl.push_back(Instruction(InstrCode::INSTR_VALUE_POP)); return i + 1; } int LiteScript::Syntax::ReadCallback(const char *text, std::vector<Instruction> &instrl, Script::ErrorType &errorType) { if (text[0] != 'f' || text[1] != 'u' || text[2] != 'n' || text[3] != 'c' || text[4] != 't' || text[5] != 'i' || text[6] != 'o' || text[7] != 'n' || text[8] != ' ') return 0; int i = 9, jt = instrl.size(), line = instrl.size() + 1;; union { int i; unsigned int ui; } tmp; std::string name; i += (int)ReadWhitespace(text + i); // function {name}\(({name}(,{name})*(...)?)?\){instructionBlock} if ((tmp.ui = ReadName(text + i, name)) == 0) return 0; instrl.push_back(Instruction(InstrCode::INSTR_JUMP_TO)); i += (int)tmp.ui; i += (int)ReadWhitespace(text + i); if ((tmp.i = ReadCallbackArguments(text + i, instrl, errorType)) <= 0) { if (tmp.i != 0) return tmp.i - i; else { errorType = Script::ErrorType::SCRPT_ERROR_CALLBACK_ARGUMENTS; return -i; } } i += tmp.i; i += ReadWhitespace(text + i); if ((tmp.i = ReadInstructionBlock(text + i, instrl, errorType)) <= 0) { if (tmp.i != 0) return tmp.i - i; else { errorType = Script::ErrorType::SCRPT_ERROR_CALLBACK_INSTRUCTIONS; return -i; } } i += tmp.i; instrl.push_back(Instruction(InstrCode::INSTR_RETURN)); instrl[jt] = Instruction(InstrCode::INSTR_JUMP_TO, (int)instrl.size()); instrl.push_back(Instruction(InstrCode::INSTR_VALUE_CALLBACK, line)); instrl.push_back(Instruction(InstrCode::INSTR_DEFINE_VARIABLE, name.c_str())); return i; } int LiteScript::Syntax::ReadClass(const char *text, std::vector<Instruction> &instrl, Script::ErrorType &errorType) { if (text[0] != 'c' || text[1] != 'l' || text[2] != 'a' || text[3] != 's' || text[4] != 's' || text[5] != ' ') return 0; int i = 6; union { int i; unsigned int ui; } tmp; std::string name; i += (int)ReadWhitespace(text + i); if ((tmp.ui = ReadName(text + i, name)) == 0) return 0; instrl.push_back(Instruction(InstrCode::INSTR_VALUE_CLASS)); i += (int)tmp.ui; i += ReadWhitespace(text + i); if ((tmp.i = ReadClassInherits(text + i, instrl, errorType)) >= 0) i += tmp.i; else return tmp.i - i; i += ReadWhitespace(text + i); if (text[i] != '{') { errorType = Script::ErrorType::SCRPT_ERROR_CLASS_BEGIN; return -i; } ++i; while (text[i] != '}') { if ((tmp.ui = ReadWhitespace(text + i)) > 0) i += (int)tmp.ui; else if ((tmp.i = ReadClassMember(text + i, instrl, errorType)) > 0) { i += tmp.i; } else { if (tmp.i != 0) return tmp.i - i; else { errorType = Script::ErrorType::SCRPT_ERROR_CLASS_END; return -i; } } } instrl.push_back(Instruction(InstrCode::INSTR_CLASS_CONSTRUCTOR, name.c_str())); instrl.push_back(Instruction(InstrCode::INSTR_DEFINE_VARIABLE, name.c_str())); return i + 1; } int LiteScript::Syntax::ReadNamespace(const char *text, std::vector<Instruction> &instrl, Script::ErrorType &errorType) { std::string keyword; if (ReadName(text, keyword) == 0 || keyword != "namespace") return 0; int i = 9, tmp; i += (int)ReadWhitespace(text + i); std::string nsp; bool need_name = true; while (text[i] != ';') { if ((tmp = (int)ReadWhitespace(text + i)) > 0) i += tmp; else if (need_name && (tmp = ReadName(text + i, keyword)) > 0) { i += tmp; nsp += keyword; need_name = false; } else if (!need_name && text[i] == '.') { ++i; nsp += '.'; need_name = true; } else { errorType = Script::ErrorType::SCRPT_ERROR_NAMESPACE; return -i; } } if (need_name) { errorType = Script::ErrorType::SCRPT_ERROR_NAMESPACE; return -i; } instrl.push_back(Instruction(InstrCode::INSTR_NAMESPACE_USE, nsp.c_str())); return i + 1; } int LiteScript::Syntax::ReadInstructionBlock(const char *text, std::vector<Instruction> &instrl, Script::ErrorType &errorType) { if (text[0] != '{') return 0; int i = 1; union { int i; unsigned int ui; } tmp; i += ReadWhitespace(text + i); while (text[i] != '}') { if ((tmp.ui = ReadWhitespace(text + i)) > 0) i += (int)tmp.ui; else if ((tmp.i = ReadInstruction(text + i, instrl, errorType)) > 0) { i += tmp.i; } else { if (tmp.i != 0) return -i; else { errorType = Script::ErrorType::SCRPT_ERROR_BRACE_CLOSE; return -i; } } } return i + 1; } int LiteScript::Syntax::ReadInstruction(const char *text, std::vector<Instruction> &instrl, Script::ErrorType &errorType) { int i = 0, tmp; i += ReadWhitespace(text + i); if (text[i] == ';') return i + 1; if ((tmp = ReadInstructionBlock(text + i, instrl, errorType)) > 0) return i + tmp; else if (tmp != 0) return tmp - i; if ((tmp = ReadVariableDefinition(text + i, instrl, errorType)) > 0) { i += tmp; i += ReadWhitespace(text + i); if (text[i] != ';') { errorType = Script::ErrorType::SCRPT_ERROR_SEMICOLON; return -i; } return i + 1; } else if (tmp != 0) return tmp - i; if ((tmp = ReadCallback(text + i, instrl, errorType)) > 0) return tmp + i; else if (tmp != 0) i = tmp - i; if ((tmp = ReadClass(text + i, instrl, errorType)) > 0) return tmp + i; else if (tmp != 0) i = tmp - i; if ((tmp = ReadControlIf(text + i, instrl, errorType)) > 0) return tmp + i; else if (tmp != 0) return tmp - i; if ((tmp = ReadReturn(text + i, instrl, errorType)) > 0) return tmp + i; else if (tmp != 0) return tmp - i; if ((tmp = ReadBreak(text + i, instrl, errorType)) > 0) return tmp + i; else if (tmp != 0) return tmp - i; if ((tmp = ReadContinue(text + i, instrl, errorType)) > 0) return tmp + i; else if (tmp != 0) return tmp - i; if ((tmp = ReadControlWhile(text + i, instrl, errorType)) > 0) return tmp + i; else if (tmp != 0) return tmp - i; if ((tmp = ReadControlDo(text + i, instrl, errorType)) > 0) return tmp + i; else if (tmp != 0) return tmp - i; if ((tmp = ReadControlFor(text + i, instrl, errorType)) > 0) return tmp + i; else if (tmp != 0) return tmp - i; if ((tmp = ReadControlSwitch(text + i, instrl, errorType)) > 0) return tmp + i; else if (tmp != 0) return tmp - i; if ((tmp = ReadNamespace(text + i, instrl, errorType)) > 0) return tmp + i; else if (tmp != 0) return tmp - i; if ((tmp = ReadExpression(text + i, instrl, errorType)) > 0) { i += tmp; i += ReadWhitespace(text + i); if (text[i] != ';') { errorType = Script::ErrorType::SCRPT_ERROR_SEMICOLON; return -i; } instrl.push_back(Instruction(InstrCode::INSTR_VALUE_POP)); return i + 1; } else if (tmp != 0) return tmp - i; if (errorType != Script::ErrorType::SCRPT_ERROR_NO) return i; return 0; } int LiteScript::Syntax::ReadScript(const char *text, std::vector<Instruction> &instrl, Script::ErrorType &errorType) { int i = 0, tmp; while (text[i] != '\0'){ if ((tmp = (int)ReadWhitespace(text + i)) > 0) i += tmp; else if ((tmp = ReadInstruction(text + i, instrl, errorType)) > 0) i += tmp; else { if (tmp != 0) return tmp - i; else { errorType = Script::ErrorType::SCRPT_ERROR_UNKNOW; return -i; } } } return i; }
33.579717
134
0.494538
[ "vector" ]
2d5404c7eb36d077387b52c783169e29a4bd897e
3,858
hpp
C++
ThirdParty-mod/java2cpp/java/security/AccessControlException.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
1
2019-04-03T01:53:28.000Z
2019-04-03T01:53:28.000Z
ThirdParty-mod/java2cpp/java/security/AccessControlException.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
ThirdParty-mod/java2cpp/java/security/AccessControlException.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: java.security.AccessControlException ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_SECURITY_ACCESSCONTROLEXCEPTION_HPP_DECL #define J2CPP_JAVA_SECURITY_ACCESSCONTROLEXCEPTION_HPP_DECL namespace j2cpp { namespace java { namespace lang { class SecurityException; } } } namespace j2cpp { namespace java { namespace lang { class String; } } } namespace j2cpp { namespace java { namespace security { class Permission; } } } #include <java/lang/SecurityException.hpp> #include <java/lang/String.hpp> #include <java/security/Permission.hpp> namespace j2cpp { namespace java { namespace security { class AccessControlException; class AccessControlException : public object<AccessControlException> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) explicit AccessControlException(jobject jobj) : object<AccessControlException>(jobj) { } operator local_ref<java::lang::SecurityException>() const; AccessControlException(local_ref< java::lang::String > const&); AccessControlException(local_ref< java::lang::String > const&, local_ref< java::security::Permission > const&); local_ref< java::security::Permission > getPermission(); }; //class AccessControlException } //namespace security } //namespace java } //namespace j2cpp #endif //J2CPP_JAVA_SECURITY_ACCESSCONTROLEXCEPTION_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_SECURITY_ACCESSCONTROLEXCEPTION_HPP_IMPL #define J2CPP_JAVA_SECURITY_ACCESSCONTROLEXCEPTION_HPP_IMPL namespace j2cpp { java::security::AccessControlException::operator local_ref<java::lang::SecurityException>() const { return local_ref<java::lang::SecurityException>(get_jobject()); } java::security::AccessControlException::AccessControlException(local_ref< java::lang::String > const &a0) : object<java::security::AccessControlException>( call_new_object< java::security::AccessControlException::J2CPP_CLASS_NAME, java::security::AccessControlException::J2CPP_METHOD_NAME(0), java::security::AccessControlException::J2CPP_METHOD_SIGNATURE(0) >(a0) ) { } java::security::AccessControlException::AccessControlException(local_ref< java::lang::String > const &a0, local_ref< java::security::Permission > const &a1) : object<java::security::AccessControlException>( call_new_object< java::security::AccessControlException::J2CPP_CLASS_NAME, java::security::AccessControlException::J2CPP_METHOD_NAME(1), java::security::AccessControlException::J2CPP_METHOD_SIGNATURE(1) >(a0, a1) ) { } local_ref< java::security::Permission > java::security::AccessControlException::getPermission() { return call_method< java::security::AccessControlException::J2CPP_CLASS_NAME, java::security::AccessControlException::J2CPP_METHOD_NAME(2), java::security::AccessControlException::J2CPP_METHOD_SIGNATURE(2), local_ref< java::security::Permission > >(get_jobject()); } J2CPP_DEFINE_CLASS(java::security::AccessControlException,"java/security/AccessControlException") J2CPP_DEFINE_METHOD(java::security::AccessControlException,0,"<init>","(Ljava/lang/String;)V") J2CPP_DEFINE_METHOD(java::security::AccessControlException,1,"<init>","(Ljava/lang/String;Ljava/security/Permission;)V") J2CPP_DEFINE_METHOD(java::security::AccessControlException,2,"getPermission","()Ljava/security/Permission;") } //namespace j2cpp #endif //J2CPP_JAVA_SECURITY_ACCESSCONTROLEXCEPTION_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
31.884298
157
0.736392
[ "object" ]
2d555d0a987049309debb89a9358221f8f0009b0
13,993
cpp
C++
compiler/nnc/backends/soft_backend/ModelAnalyzer.cpp
chogba6/ONE
3d35259f89ee3109cfd35ab6f38c231904487f3b
[ "Apache-2.0" ]
255
2020-05-22T07:45:29.000Z
2022-03-29T23:58:22.000Z
compiler/nnc/backends/soft_backend/ModelAnalyzer.cpp
chogba6/ONE
3d35259f89ee3109cfd35ab6f38c231904487f3b
[ "Apache-2.0" ]
5,102
2020-05-22T07:48:33.000Z
2022-03-31T23:43:39.000Z
compiler/nnc/backends/soft_backend/ModelAnalyzer.cpp
chogba6/ONE
3d35259f89ee3109cfd35ab6f38c231904487f3b
[ "Apache-2.0" ]
120
2020-05-22T07:51:08.000Z
2022-02-16T19:08:05.000Z
/* * Copyright (c) 2018 Samsung Electronics Co., Ltd. All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ModelAnalyzer.h" #include "mir/Shape.h" #include "mir/Graph.h" #include "mir/OpDefs.h" #include <stack> #include <map> using namespace std; namespace nnc { using namespace mir; using namespace sir; void ModelAnalyzer::appendOperationToInference(Operation *op, const string &function_name, std::vector<size_t> aux_args) { vector<size_t> node_output_tensors; // process operation outputs if (op->getType() == Operation::Type::input) { // register input tensor const string &tensor_name = op->getOutput(0)->getName(); const auto tensor_id = declareInputTensor(tensor_name, op->getOutputShape(0)); node_output_tensors.push_back(tensor_id); } else if (op->getType() == Operation::Type::constant) { // register constant tensor // it's data is deserialized to described tensor by O(1) at runtime const auto tensor_id = declareTemporaryTensor(); node_output_tensors.push_back(tensor_id); } else if (op->getType() == Operation::Type::output) { assert(!op->getInput(0)->getName().empty()); } else { for (const auto &output : op->getOutputs()) { const auto &tensor_name = output.getName(); const auto tensor_id = tensor_name.empty() ? declareTemporaryTensor() : declarePersistentTensor(tensor_name); node_output_tensors.push_back(tensor_id); } } // process operation inputs vector<size_t> node_input_tensors; for (const Operation::Output *input : op->getInputs()) { size_t idx = input->getIndex(); const Operation *prev_op = input->getNode(); assert(_opToDescr.find(prev_op) != _opToDescr.end()); auto call = dynamic_cast<const CallFunction *>(_opToDescr[prev_op]); assert(call); const size_t &in_tensor_id = call->outputs[idx]; node_input_tensors.push_back(in_tensor_id); } std::copy(aux_args.begin(), aux_args.end(), std::back_inserter(node_input_tensors)); unique_ptr<Action> operation_call(new CallFunction( op, function_name, std::move(node_input_tensors), std::move(node_output_tensors))); _inferenceSequence.push_back(std::move(operation_call)); _opToDescr[op] = _inferenceSequence.back().get(); } void ModelAnalyzer::updateMaxTemporarySize(const size_t size) { _max_temp_size = std::max(_max_temp_size, size); } size_t ModelAnalyzer::declareInputTensor(const std::string &name, const mir::Shape &shape) { assert(!name.empty() && "Input tensor must have name"); size_t id = _allocatedTensors++; _tensors.push_back({id, TensorDescriptor::Type::input, name, shape}); _inputs.push_back(id); return id; } size_t ModelAnalyzer::declarePersistentTensor(const std::string &name) { assert(!name.empty()); size_t id = _allocatedTensors++; _tensors.push_back({id, TensorDescriptor::Type::persistent, name, {}}); _persistent_tensors.push_back(id); return id; } size_t ModelAnalyzer::declareTemporaryTensor() { size_t id = _allocatedTensors++; _tensors.push_back({id, TensorDescriptor::Type::temporary, "", {}}); return id; } void ModelAnalyzer::gatherDefUseInfo(const vector<unique_ptr<Action>> &post_order, map<size_t, size_t> &first_def, map<size_t, size_t> &last_use) { for (size_t pos = 0; pos < post_order.size(); ++pos) { const unique_ptr<Action> &action = post_order[pos]; const CallFunction *call = dynamic_cast<CallFunction *>(action.get()); assert(call); // update def info for (size_t output_tensor_id : call->outputs) { const TensorDescriptor &td = _tensors[output_tensor_id]; if (td.type != TensorDescriptor::Type::temporary) continue; if (!first_def.count(output_tensor_id)) first_def[output_tensor_id] = pos; } // update usage info for (size_t input_tensor_id : call->inputs) { const TensorDescriptor &td = _tensors[input_tensor_id]; if (td.type != TensorDescriptor::Type::temporary) continue; last_use[input_tensor_id] = pos; } } } void ModelAnalyzer::constructInferenceSequence(const vector<Operation *> &post_order) { // Run inference sequence construction over constructed list of operations for (auto it = post_order.rbegin(); it != post_order.rend(); ++it) { Operation *node = *it; node->accept(this); } // Insert temporary tensor constructors // map temporary tensor id to index in original sequence where it was defined/used first/last time map<size_t, size_t> first_def; map<size_t, size_t> last_use; // prepare use-def info gatherDefUseInfo(_inferenceSequence, first_def, last_use); // insert memory operations // Every iteration of loop contains three steps: // 1) insert constructors of temporary tensors used in current operations // and not used in inference sequence before // 2) insert operation call // 3) insert destructors of temporary tensors unused after current operation std::vector<unique_ptr<Action>> old_inference_seq; old_inference_seq.swap(_inferenceSequence); _inferenceSequence.reserve(old_inference_seq.size()); for (size_t pos = 0; pos < old_inference_seq.size(); ++pos) { unique_ptr<Action> &action = old_inference_seq[pos]; const CallFunction *call = dynamic_cast<CallFunction *>(action.get()); assert(call); // construct required temporary tensors for (size_t output_tensor_id : call->outputs) { const TensorDescriptor &td = _tensors[output_tensor_id]; assert(td.id == output_tensor_id); if (td.type != TensorDescriptor::Type::temporary) continue; if (first_def[output_tensor_id] == pos) { unique_ptr<Action> tmp_constructor(new CreateTmp(output_tensor_id)); _inferenceSequence.push_back(std::move(tmp_constructor)); } } // Insert operation call _inferenceSequence.push_back(std::move(action)); // destroy unused temporary tensors for (size_t input_tensor_id : call->inputs) { const TensorDescriptor &td = _tensors[input_tensor_id]; assert(td.id == input_tensor_id); if (td.type != TensorDescriptor::Type::temporary) continue; if (last_use[input_tensor_id] == pos) { unique_ptr<Action> tmp_destructor(new DestroyTmp(input_tensor_id)); _inferenceSequence.push_back(std::move(tmp_destructor)); } } } } void ModelAnalyzer::collectOutputs(const mir::Graph *g) { for (ops::OutputOp *out_op : g->getOutputs()) { auto op_call = dynamic_cast<const CallFunction *>(_opToDescr[out_op]); assert(op_call->inputs.size() == 1); _outputs.push_back(op_call->inputs[0]); } } void ModelAnalyzer::analyze(const mir::Graph *g) { // Current path through graph stack<pair<Operation *, size_t>> s; // Nodes in Reverse Post Order stored by DFS vector<Operation *> post_order; // Set contains pointer to node if it is visited by DFS set<Operation *> visited; vector<Operation *> init_ops; for (Operation *op : g->getNodes()) { if (op->getNumInputs() == 0) { init_ops.emplace_back(op); } } // Register temporary tensor for im2col buffer _temp_tensor_id = declareTemporaryTensor(); // Walk all network inputs for (Operation *in : init_ops) { if (!visited.count(in)) { visited.insert(in); s.push({in, 0}); } // main DFS loop while (!s.empty()) { // top stores current node and current outgoing edge from it auto &top = s.top(); Operation *node = top.first; auto edge = top.second++; // FIXME Refactor me. std::vector<Operation *> next_nodes; for (const auto &out : node->getOutputs()) { const auto &uses = out.getUses(); std::transform(uses.begin(), uses.end(), std::back_inserter(next_nodes), [](Operation::Use use) { return use.getNode(); }); } if (edge == next_nodes.size()) { // this node is fully analyzed, push it into RPO and pop from stack post_order.push_back(node); s.pop(); } else { // Search current outgoing edge Operation *successor = next_nodes[edge]; if (!visited.count(successor)) { visited.insert(successor); s.push({next_nodes[edge], 0}); } } } } constructInferenceSequence(post_order); collectOutputs(g); } void ModelAnalyzer::visit(ops::ConcatOp &op) { appendOperationToInference(&op, "concat"); } void ModelAnalyzer::visit(ops::Conv2DOp &op) { assert(op.getNumGroups() == 1); const auto &kernel_shape = op.getInputShape(1); const auto &out_shape = op.getOutputShape(0); const int32_t tmp_size = kernel_shape.dim(1) * kernel_shape.dim(2) * kernel_shape.dim(3) * out_shape.dim(0) * out_shape.dim(1) * out_shape.dim(2); updateMaxTemporarySize(static_cast<size_t>(tmp_size)); appendOperationToInference(&op, "conv2d", {_temp_tensor_id}); } void ModelAnalyzer::visit(ops::DepthwiseConv2DOp &op) { appendOperationToInference(&op, "depthwiseConv2d"); } void ModelAnalyzer::visit(ops::SoftmaxOp &op) { appendOperationToInference(&op, "softmax"); } void ModelAnalyzer::visit(ops::AvgPool2DOp &op) { appendOperationToInference(&op, "avgPool"); } void ModelAnalyzer::visit(ops::MaxPool2DOp &op) { appendOperationToInference(&op, "maxPool"); } void ModelAnalyzer::visit(ops::FullyConnectedOp &op) { appendOperationToInference(&op, "fullConnect"); } void ModelAnalyzer::visit(ops::BroadcastOp &op) { appendOperationToInference(&op, "broadcast"); } void ModelAnalyzer::visit(ops::CappedReluOp &op) { appendOperationToInference(&op, "cappedRelu"); } void ModelAnalyzer::visit(ops::InputOp &op) { assert(op.getNumInputs() == 0); appendOperationToInference(&op, "in"); } void ModelAnalyzer::visit(ops::ConstantOp &op) { assert(op.getNumInputs() == 0); // FIXME This is to work around deserializeTensors not being able to deserialize tensors of type // other than float32. const auto *output = op.getOutput(0); if (output->getUses().empty()) return; appendOperationToInference(&op, "constant"); } void ModelAnalyzer::visit(ops::ReluOp &op) { appendOperationToInference(&op, "relu"); } void ModelAnalyzer::visit(ops::ReshapeOp &op) { appendOperationToInference(&op, "reshape"); } void ModelAnalyzer::visit(mir::ops::ResizeOp &op) { const auto &in_shape = op.getInputShape(0); const auto &out_shape = op.getOutputShape(0); assert(in_shape.rank() == 4); assert(in_shape.rank() == out_shape.rank()); if (in_shape.dim(0) != out_shape.dim(0) || in_shape.dim(3) != out_shape.dim(3)) throw std::runtime_error("Not supported Resize on other dims besides height and width!"); switch (op.getMode()) { case mir::ops::ResizeOp::ResizeMethod::nearestNeighbor: appendOperationToInference(&op, "resize"); break; default: assert(false && "Not Implemented!"); } } void ModelAnalyzer::visit(mir::ops::SliceOp &op) { appendOperationToInference(&op, "slice"); } void ModelAnalyzer::visit(mir::ops::TanhOp &op) { appendOperationToInference(&op, "tanhActivation"); } void ModelAnalyzer::visit(mir::ops::EluOp &op) { appendOperationToInference(&op, "elu"); } void ModelAnalyzer::visit(mir::ops::DeConv2DOp &op) { const auto &kernel_shape = op.getInputShape(1); const auto &out_shape = op.getOutputShape(0); const int32_t tmp_size = kernel_shape.dim(0) * kernel_shape.dim(1) * kernel_shape.dim(3) * out_shape.dim(0) * out_shape.dim(1) * out_shape.dim(2); updateMaxTemporarySize(static_cast<size_t>(tmp_size)); appendOperationToInference(&op, "convTransposed2d", {_temp_tensor_id}); } void ModelAnalyzer::visit(ops::SqueezeOp &op) { appendOperationToInference(&op, "reshape"); } void ModelAnalyzer::visit(ops::SqrtOp &op) { appendOperationToInference(&op, "sqrtFN"); } void ModelAnalyzer::visit(mir::ops::PadOp &op) { appendOperationToInference(&op, "pad"); } void ModelAnalyzer::visit(mir::ops::ReduceMeanOp &op) { appendOperationToInference(&op, "reduceMean"); } void ModelAnalyzer::visit(mir::ops::TransposeOp &op) { appendOperationToInference(&op, "transpose"); } void ModelAnalyzer::visit(mir::ops::GatherOp &op) { appendOperationToInference(&op, "gather"); } void ModelAnalyzer::visit(mir::ops::SigmoidOp &op) { appendOperationToInference(&op, "sigmoid"); } void ModelAnalyzer::visit(mir::ops::LeakyReluOp &op) { appendOperationToInference(&op, "leakyRelu"); } void ModelAnalyzer::visit(mir::ops::OutputOp &op) { appendOperationToInference(&op, "out"); } void ModelAnalyzer::visit(mir::ops::AbsOp &op) { appendOperationToInference(&op, "absFN"); } void ModelAnalyzer::visit(mir::ops::AddOp &op) { appendOperationToInference(&op, "ElementWise<Add>"); } void ModelAnalyzer::visit(mir::ops::DivOp &op) { appendOperationToInference(&op, "ElementWise<Div>"); } void ModelAnalyzer::visit(mir::ops::MaxOp &op) { appendOperationToInference(&op, "ElementWise<Max>"); } void ModelAnalyzer::visit(mir::ops::MulOp &op) { appendOperationToInference(&op, "ElementWise<Mul>"); } void ModelAnalyzer::visit(mir::ops::SubOp &op) { appendOperationToInference(&op, "ElementWise<Sub>"); } void ModelAnalyzer::visit_fallback(mir::Operation &) { throw std::runtime_error("NYI operation"); } } // namespace nnc
30.889625
100
0.688773
[ "shape", "vector", "transform" ]
0623633e0f856d765d84c23940ef72904add400f
376
cpp
C++
0053-maximum-subarray.cpp
lwcM/leetcode_solution
a5e714a9785fd94e530396d93c81f71fd8b9c1b6
[ "MIT" ]
2
2018-09-12T05:37:47.000Z
2018-10-19T12:02:09.000Z
0053-maximum-subarray.cpp
lwcM/leetcode_solution
a5e714a9785fd94e530396d93c81f71fd8b9c1b6
[ "MIT" ]
null
null
null
0053-maximum-subarray.cpp
lwcM/leetcode_solution
a5e714a9785fd94e530396d93c81f71fd8b9c1b6
[ "MIT" ]
null
null
null
class Solution { public: int maxSubArray(vector<int>& nums) { if(nums.size()==0) return 0; int ans=nums[0], sum=0; for(int x:nums) { ans = max(ans, sum+=x); if(sum < 0) sum = 0; } return ans; } }; static const auto __=[]{ ios::sync_with_stdio(false); cin.tie(nullptr); return nullptr; }();
18.8
40
0.5
[ "vector" ]
06240f40d17afbbe34934e162d34c8bca74473b8
1,257
cpp
C++
dynamic_programming/lcs_iterative.cpp
ankit2001/CP_Algos
eadc0f9cd92a5a01791e3171dfe894e6db948b2b
[ "MIT" ]
1
2020-08-11T17:50:01.000Z
2020-08-11T17:50:01.000Z
dynamic_programming/lcs_iterative.cpp
ankit2001/CP_Algos
eadc0f9cd92a5a01791e3171dfe894e6db948b2b
[ "MIT" ]
null
null
null
dynamic_programming/lcs_iterative.cpp
ankit2001/CP_Algos
eadc0f9cd92a5a01791e3171dfe894e6db948b2b
[ "MIT" ]
null
null
null
//Keep calm and admire #include<bits/stdc++.h> using namespace std; #define ll long long int #define fastio() ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); #define F first #define S second #define endl "\n" #define pb push_back #define all(v) v.begin(),v.end() ll MAX = 1e18; ll MOD = 1000000007; ll MIN = -1e17; int main(){ fastio(); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt","w",stdout); #endif ll tc = 1; cin >> tc; for (ll tt = 1; tt <= tc; tt++){ //cout << "Case "<<tt<<" :"; string s1; cin >> s1; string s2; cin >> s2; ll n = s1.length(), m = s2.length(); vector<vector<ll>> dp(n + 1, vector<ll> (m + 1, 0)); vector<vector<ll>> vis(n + 1, vector<ll> (m + 1, false)); for(ll i = 0; i <= n; i++){ dp[i][0] = 0; } for(ll i = 0; i <= m; i++){ dp[0][i] = 0; } for(ll i = 1; i <= n; i++){ for(ll j = 1; j <=m; j++){ if(s1[n - i] == s2[m - j]){ dp[i][j] = 1 + dp[i - 1][j - 1]; } else{ dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); } } } cout << dp[n][m] << endl; } cerr<<"Time taken: "<<int((clock()*1000.)/CLOCKS_PER_SEC)<<"ms"<<endl; return 0; }
23.716981
74
0.485282
[ "vector" ]
062b57e5be3e7c54bcfbaa671b13197b1b8ec7c9
2,809
cpp
C++
core-lib/include/oh-core/InstanceInfo.cpp
sgrottel/open-here
4834e7064d92c49592585e83c930015a7b407615
[ "Apache-2.0" ]
null
null
null
core-lib/include/oh-core/InstanceInfo.cpp
sgrottel/open-here
4834e7064d92c49592585e83c930015a7b407615
[ "Apache-2.0" ]
null
null
null
core-lib/include/oh-core/InstanceInfo.cpp
sgrottel/open-here
4834e7064d92c49592585e83c930015a7b407615
[ "Apache-2.0" ]
null
null
null
// // Open Here // core-lib - InstanceInfo.cpp // Info about a found instance of a File Explorer // // Copyright 2022 SGrottel (https://www.sgrottel.de) // // 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 permissionsand // limitations under the License. // #include "oh-core/InstanceInfo.h" #include <string> #include <vector> openhere::InstanceInfo::InstanceInfo() { // intentionally empty } openhere::InstanceInfo::~InstanceInfo() { // intentionally empty } void openhere::InstanceInfo::setWindowHandle(intptr_t hWnd) { this->hWnd = hWnd; } void openhere::InstanceInfo::setZDepth(unsigned int zDepth) { this->zDepth = zDepth; } void openhere::InstanceInfo::setInstanceType(const std::wstring& type) { this->instanceType = type; } std::vector<std::wstring>& openhere::InstanceInfo::accessOpenedPaths() { return this->openedPaths; } std::vector<std::wstring>& openhere::InstanceInfo::accessSelectedItems() { return this->selectedItems; } void openhere::InstanceInfo::markAsTopWindow(bool mark) { this->markedAsTopWindow = mark; } void openhere::InstanceInfo::markAsForegroundWindow(bool mark) { this->markedAsForegroundWindow = mark; } intptr_t openhere::InstanceInfo::getWindowHandle(void) const { return this->hWnd; } unsigned int openhere::InstanceInfo::getZDepth(void) const { return this->zDepth; } const wchar_t* openhere::InstanceInfo::getInstanceType() const { return this->instanceType.c_str(); } unsigned int openhere::InstanceInfo::getOpenedPathsCount() const { return static_cast<unsigned int>(this->openedPaths.size()); } const wchar_t* openhere::InstanceInfo::getOpenedPath(unsigned int idx) const { if (idx >= this->openedPaths.size()) return nullptr; return this->openedPaths[idx].c_str(); } unsigned int openhere::InstanceInfo::getSelectedItemsCount() const { return static_cast<unsigned int>(this->selectedItems.size()); } const wchar_t* openhere::InstanceInfo::getSelectedItem(unsigned int idx) const { if (idx >= this->selectedItems.size()) return nullptr; return this->selectedItems[idx].c_str(); } bool openhere::InstanceInfo::isMarkedAsTopWindow() const { return this->markedAsTopWindow; } bool openhere::InstanceInfo::isMarkedAsForegroundWindow() const { return this->markedAsForegroundWindow; }
28.663265
81
0.728373
[ "vector" ]
062f78f2359c448a02f88bb78f16a265d651a965
10,441
cpp
C++
src/libraries/core/meshTools/searchableSurface/searchablePlate.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/meshTools/searchableSurface/searchablePlate.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/meshTools/searchableSurface/searchablePlate.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2011-2015 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "searchablePlate.hpp" #include "addToRunTimeSelectionTable.hpp" #include "SortableList.hpp" // * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * // namespace CML { defineTypeNameAndDebug(searchablePlate, 0); addToRunTimeSelectionTable(searchableSurface, searchablePlate, dict); } // * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * // CML::direction CML::searchablePlate::calcNormal(const point& span) { direction normalDir = 3; for (direction dir = 0; dir < vector::nComponents; dir++) { if (span[dir] < 0) { FatalErrorInFunction << "Span should have two positive and one zero entry. Now:" << span << exit(FatalError); } else if (span[dir] < VSMALL) { if (normalDir == 3) { normalDir = dir; } else { // Multiple zero entries. Flag and exit. normalDir = 3; break; } } } if (normalDir == 3) { FatalErrorInFunction << "Span should have two positive and one zero entry. Now:" << span << exit(FatalError); } return normalDir; } // Returns miss or hit with face (always 0) CML::pointIndexHit CML::searchablePlate::findNearest ( const point& sample, const scalar nearestDistSqr ) const { // For every component direction can be // left of min, right of max or inbetween. // - outside points: project first one x plane (either min().x() // or max().x()), then onto y plane and finally z. You should be left // with intersection point // - inside point: find nearest side (compare to mid point). Project onto // that. // Project point on plane. pointIndexHit info(true, sample, 0); info.rawPoint()[normalDir_] = origin_[normalDir_]; // Clip to edges if outside for (direction dir = 0; dir < vector::nComponents; dir++) { if (dir != normalDir_) { if (info.rawPoint()[dir] < origin_[dir]) { info.rawPoint()[dir] = origin_[dir]; } else if (info.rawPoint()[dir] > origin_[dir]+span_[dir]) { info.rawPoint()[dir] = origin_[dir]+span_[dir]; } } } // Check if outside. Optimisation: could do some checks on distance already // on components above if (magSqr(info.rawPoint() - sample) > nearestDistSqr) { info.setMiss(); info.setIndex(-1); } return info; } CML::pointIndexHit CML::searchablePlate::findLine ( const point& start, const point& end ) const { pointIndexHit info ( true, vector::zero, 0 ); const vector dir(end-start); if (mag(dir[normalDir_]) < VSMALL) { info.setMiss(); info.setIndex(-1); } else { scalar t = (origin_[normalDir_]-start[normalDir_]) / dir[normalDir_]; if (t < 0 || t > 1) { info.setMiss(); info.setIndex(-1); } else { info.rawPoint() = start+t*dir; info.rawPoint()[normalDir_] = origin_[normalDir_]; // Clip to edges for (direction dir = 0; dir < vector::nComponents; dir++) { if (dir != normalDir_) { if (info.rawPoint()[dir] < origin_[dir]) { info.setMiss(); info.setIndex(-1); break; } else if (info.rawPoint()[dir] > origin_[dir]+span_[dir]) { info.setMiss(); info.setIndex(-1); break; } } } } } // Debug if (info.hit()) { treeBoundBox bb(origin_, origin_+span_); bb.min()[normalDir_] -= 1e-6; bb.max()[normalDir_] += 1e-6; if (!bb.contains(info.hitPoint())) { FatalErrorInFunction << "bb:" << bb << endl << "origin_:" << origin_ << endl << "span_:" << span_ << endl << "normalDir_:" << normalDir_ << endl << "hitPoint:" << info.hitPoint() << abort(FatalError); } } return info; } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // CML::searchablePlate::searchablePlate ( const IOobject& io, const point& origin, const vector& span ) : searchableSurface(io), origin_(origin), span_(span), normalDir_(calcNormal(span_)) { if (debug) { Info<< "searchablePlate::searchablePlate :" << " origin:" << origin_ << " origin+span:" << origin_+span_ << " normal:" << vector::componentNames[normalDir_] << endl; } bounds() = boundBox(origin_, origin_ + span_); } CML::searchablePlate::searchablePlate ( const IOobject& io, const dictionary& dict ) : searchableSurface(io), origin_(dict.lookup("origin")), span_(dict.lookup("span")), normalDir_(calcNormal(span_)) { if (debug) { Info<< "searchablePlate::searchablePlate :" << " origin:" << origin_ << " origin+span:" << origin_+span_ << " normal:" << vector::componentNames[normalDir_] << endl; } bounds() = boundBox(origin_, origin_ + span_); } // * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * // CML::searchablePlate::~searchablePlate() {} // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // const CML::wordList& CML::searchablePlate::regions() const { if (regions_.empty()) { regions_.setSize(1); regions_[0] = "region0"; } return regions_; } CML::tmp<CML::pointField> CML::searchablePlate::coordinates() const { return tmp<pointField>(new pointField(1, origin_ + 0.5*span_)); } void CML::searchablePlate::boundingSpheres ( pointField& centres, scalarField& radiusSqr ) const { centres.setSize(1); centres[0] = origin_ + 0.5*span_; radiusSqr.setSize(1); radiusSqr[0] = CML::magSqr(0.5*span_); // Add a bit to make sure all points are tested inside radiusSqr += CML::sqr(SMALL); } CML::tmp<CML::pointField> CML::searchablePlate::points() const { tmp<pointField> tPts(new pointField(4)); pointField& pts = tPts(); pts[0] = origin_; pts[2] = origin_ + span_; if (span_.x() < span_.y() && span_.x() < span_.z()) { pts[1] = origin_ + point(0, span_.y(), 0); pts[3] = origin_ + point(0, 0, span_.z()); } else if (span_.y() < span_.z()) { pts[1] = origin_ + point(span_.x(), 0, 0); pts[3] = origin_ + point(0, 0, span_.z()); } else { pts[1] = origin_ + point(span_.x(), 0, 0); pts[3] = origin_ + point(0, span_.y(), 0); } return tPts; } bool CML::searchablePlate::overlaps(const boundBox& bb) const { return ( (origin_.x() + span_.x()) >= bb.min().x() && origin_.x() <= bb.max().x() && (origin_.y() + span_.y()) >= bb.min().y() && origin_.y() <= bb.max().y() && (origin_.z() + span_.z()) >= bb.min().z() && origin_.z() <= bb.max().z() ); } void CML::searchablePlate::findNearest ( const pointField& samples, const scalarField& nearestDistSqr, List<pointIndexHit>& info ) const { info.setSize(samples.size()); forAll(samples, i) { info[i] = findNearest(samples[i], nearestDistSqr[i]); } } void CML::searchablePlate::findLine ( const pointField& start, const pointField& end, List<pointIndexHit>& info ) const { info.setSize(start.size()); forAll(start, i) { info[i] = findLine(start[i], end[i]); } } void CML::searchablePlate::findLineAny ( const pointField& start, const pointField& end, List<pointIndexHit>& info ) const { findLine(start, end, info); } void CML::searchablePlate::findLineAll ( const pointField& start, const pointField& end, List<List<pointIndexHit> >& info ) const { List<pointIndexHit> nearestInfo; findLine(start, end, nearestInfo); info.setSize(start.size()); forAll(info, pointI) { if (nearestInfo[pointI].hit()) { info[pointI].setSize(1); info[pointI][0] = nearestInfo[pointI]; } else { info[pointI].clear(); } } } void CML::searchablePlate::getRegion ( const List<pointIndexHit>& info, labelList& region ) const { region.setSize(info.size()); region = 0; } void CML::searchablePlate::getNormal ( const List<pointIndexHit>& info, vectorField& normal ) const { normal.setSize(info.size()); normal = vector::zero; forAll(normal, i) { normal[i][normalDir_] = 1.0; } } void CML::searchablePlate::getVolumeType ( const pointField& points, List<volumeType>& volType ) const { FatalErrorInFunction << "Volume type not supported for plate." << exit(FatalError); } // ************************************************************************* //
23.410314
79
0.518916
[ "vector" ]
06340427af34e54a6c85472396f7fdec5c1d3046
50,125
cpp
C++
aspects/electrical/SolarArray/test/UtGunnsElectPvRegShunt.cpp
nasa/gunns
248323939a476abe5178538cd7a3512b5f42675c
[ "NASA-1.3" ]
18
2020-01-23T12:14:09.000Z
2022-02-27T22:11:35.000Z
aspects/electrical/SolarArray/test/UtGunnsElectPvRegShunt.cpp
nasa/gunns
248323939a476abe5178538cd7a3512b5f42675c
[ "NASA-1.3" ]
39
2020-11-20T12:19:35.000Z
2022-02-22T18:45:55.000Z
aspects/electrical/SolarArray/test/UtGunnsElectPvRegShunt.cpp
nasa/gunns
248323939a476abe5178538cd7a3512b5f42675c
[ "NASA-1.3" ]
7
2020-02-10T19:25:43.000Z
2022-03-16T01:10:00.000Z
/** @copyright Copyright 2019 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. All Rights Reserved. LIBRARY DEPENDENCY: ((aspects/electrical/SolarArray/GunnsElectPvRegShunt.o) (software/exceptions/TsInitializationException.o)) */ #include "software/exceptions/TsInitializationException.hh" #include <iostream> #include "strings/UtResult.hh" #include "UtGunnsElectPvRegShunt.hh" #include "math/MsMath.hh" /// @details Test identification number. int UtGunnsElectPvRegShunt::TEST_ID = 0; //////////////////////////////////////////////////////////////////////////////////////////////////// /// @details This is the default constructor for the UtGunnsElectPvRegShunt class. //////////////////////////////////////////////////////////////////////////////////////////////////// UtGunnsElectPvRegShunt::UtGunnsElectPvRegShunt() : tLinks(), tNodes(), tNodeList(), tPort0(0), tPort1(0), tName(""), tConfigData(0), tInputData(0), tArticle(0), tOutputConductance(0.0), tShuntConductance(0.0), tSensorIin(), tSensorVin(), tSensorIout(), tSensorVout(), tInOverCurrentTrip(0.0), tInOverVoltageTrip(0.0), tOutOverCurrentTrip(0.0), tOutOverVoltageTrip(0.0), tOutUnderVoltageTrip(0.0), tTripPriority(0), tArray(0), tArrayConfig(0), tArrayInput(0), tVoltageSetpoint(0.0), tPowered(false), tEnabled(false), tMinOperatePower(0.0) { // nothing to do } //////////////////////////////////////////////////////////////////////////////////////////////////// /// @details This is the default destructor for the UtGunnsElectPvRegShunt class. //////////////////////////////////////////////////////////////////////////////////////////////////// UtGunnsElectPvRegShunt::~UtGunnsElectPvRegShunt() { // nothing to do } //////////////////////////////////////////////////////////////////////////////////////////////////// /// @details Executed before each unit test. //////////////////////////////////////////////////////////////////////////////////////////////////// void UtGunnsElectPvRegShunt::setUp() { tName = "tArticle"; /// - Define the nominal port mapping. tPort0 = 0; tPort1 = 1; /// - Initialize the nodes list. tNodeList.mNodes = tNodes; tNodeList.mNumNodes = N_NODES; const unsigned int numSections = 3; const unsigned int numStrings = 12; const unsigned int numStringsBySection = numStrings / numSections; /// - Initialize the sensors. GunnsSensorAnalogWrapperConfigData sensorConfig("tSensorVin", 0.0, 20.0); GunnsSensorAnalogWrapperInputData sensorInput; tSensorVin.initialize(&sensorConfig, &sensorInput); sensorConfig.mName = "tSensorIin"; tSensorIin.initialize(&sensorConfig, &sensorInput); sensorConfig.mName = "tSensorVout"; tSensorVout.initialize(&sensorConfig, &sensorInput); sensorConfig.mName = "tSensorIout"; tSensorIout.initialize(&sensorConfig, &sensorInput); /// - Create and initialize a nominal array. We use the same config & input data as in /// UtGunnsElectPvArray. tArrayConfig = new GunnsElectPvArrayConfigData("tArray", &tNodeList, numSections, numStrings, 0.8, 0.75, false, 31.636, 0.7, 0.5, 5, 20, 0.05, 1.0, 0.017, 200.0, 0.6, 294.0, -0.003, 0.00065); tArrayInput = new GunnsElectPvArrayInputData(31.626, 0.0, 1.0, 284.0); tArray = new FriendlyGunnsElectPvArray; tArray->initialize(*tArrayConfig, *tArrayInput, tLinks, tPort0); /// - Define the nominal configuration data. tOutputConductance = 100.0; tShuntConductance = 10.0; tInOverCurrentTrip = 5.0; tInOverVoltageTrip = 11.2; tOutOverCurrentTrip = 15.0; tOutOverVoltageTrip = 11.0; tOutUnderVoltageTrip = 5.0; tTripPriority = 2; tConfigData = new GunnsElectPvRegShuntConfigData(tName, &tNodeList, tOutputConductance, tShuntConductance, tArray, &tSensorIin, &tSensorVin, &tSensorIout, &tSensorVout, tInOverCurrentTrip, tInOverVoltageTrip, tOutOverCurrentTrip, tOutOverVoltageTrip, tOutUnderVoltageTrip, tTripPriority); /// - Configure the string load order. for (int section = numSections - 1; section > -1; --section) { for (int string = numStringsBySection - 1; string > -1; --string) { tConfigData->addStringLoadOrder(section, string); } } /// - Define the nominal input data. tVoltageSetpoint = 10.0; tPowered = true; tEnabled = true; tMinOperatePower = 100.0; tInputData = new GunnsElectPvRegShuntInputData(tVoltageSetpoint, tPowered, tEnabled, tMinOperatePower); /// - Default construct the nominal test article. tArticle = new FriendlyGunnsElectPvRegShunt; /// - Increment the test identification number. ++TEST_ID; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// @details Executed after each unit test. //////////////////////////////////////////////////////////////////////////////////////////////////// void UtGunnsElectPvRegShunt::tearDown() { /// - Deletes for news in setUp delete tArticle; delete tInputData; delete tConfigData; delete tArray; delete tArrayInput; delete tArrayConfig; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// @details Tests for construction of Photovoltaic Array Shunting Regulator Link configuration data. //////////////////////////////////////////////////////////////////////////////////////////////////// void UtGunnsElectPvRegShunt::testConfig() { UT_RESULT_FIRST; /// @test Configuration nominal construction. CPPUNIT_ASSERT_DOUBLES_EQUAL(tOutputConductance, tConfigData->mOutputConductance, 0.0); CPPUNIT_ASSERT_DOUBLES_EQUAL(tShuntConductance, tConfigData->mShuntConductance, 0.0); CPPUNIT_ASSERT(tArray == tConfigData->mArray); CPPUNIT_ASSERT(&tSensorIin == tConfigData->mInCurrentSensor); CPPUNIT_ASSERT(&tSensorVin == tConfigData->mInVoltageSensor); CPPUNIT_ASSERT(&tSensorIout == tConfigData->mOutCurrentSensor); CPPUNIT_ASSERT(&tSensorVout == tConfigData->mOutVoltageSensor); CPPUNIT_ASSERT(tInOverCurrentTrip == tConfigData->mInOverCurrentTrip); CPPUNIT_ASSERT(tInOverVoltageTrip == tConfigData->mInOverVoltageTrip); CPPUNIT_ASSERT(tOutOverCurrentTrip == tConfigData->mOutOverCurrentTrip); CPPUNIT_ASSERT(tOutOverVoltageTrip == tConfigData->mOutOverVoltageTrip); CPPUNIT_ASSERT(tTripPriority == tConfigData->mTripPriority); CPPUNIT_ASSERT(tArrayConfig->mNumStrings == tConfigData->mStringLoadOrder.size()); CPPUNIT_ASSERT(0 == tConfigData->mStringLoadOrder.back().mSection); CPPUNIT_ASSERT(0 == tConfigData->mStringLoadOrder.back().mString); /// @test Configuration data default construction. GunnsElectPvRegShuntConfigData defaultConfig; CPPUNIT_ASSERT(0.0 == defaultConfig.mOutputConductance); CPPUNIT_ASSERT(0.0 == defaultConfig.mShuntConductance); CPPUNIT_ASSERT(0 == defaultConfig.mArray); CPPUNIT_ASSERT(0 == defaultConfig.mInCurrentSensor); CPPUNIT_ASSERT(0 == defaultConfig.mInVoltageSensor); CPPUNIT_ASSERT(0 == defaultConfig.mOutCurrentSensor); CPPUNIT_ASSERT(0 == defaultConfig.mOutVoltageSensor); CPPUNIT_ASSERT(0.0 == defaultConfig.mInOverCurrentTrip); CPPUNIT_ASSERT(0.0 == defaultConfig.mInOverVoltageTrip); CPPUNIT_ASSERT(0.0 == defaultConfig.mOutOverCurrentTrip); CPPUNIT_ASSERT(0.0 == defaultConfig.mOutOverVoltageTrip); CPPUNIT_ASSERT(0 == defaultConfig.mTripPriority); CPPUNIT_ASSERT(0 == defaultConfig.mStringLoadOrder.size()); /// @test Load order functions for code coverage. GunnsElectPvStringLoadOrder order1(1, 2); GunnsElectPvStringLoadOrder* order2 = new GunnsElectPvStringLoadOrder(3, 4); *order2 = order1; CPPUNIT_ASSERT(*order2 == order1); delete order2; GunnsElectPvStringLoadOrder* order3 = new GunnsElectPvStringLoadOrder(order1); CPPUNIT_ASSERT(*order3 == order1); delete order3; UT_PASS; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// @details Tests for construction of Photovoltaic Array Shunting Regulator Link input data. //////////////////////////////////////////////////////////////////////////////////////////////////// void UtGunnsElectPvRegShunt::testInput() { UT_RESULT; /// @test Input data nominal construction. CPPUNIT_ASSERT_DOUBLES_EQUAL(tVoltageSetpoint, tInputData->mVoltageSetpoint, 0.0); CPPUNIT_ASSERT(tPowered == tInputData->mPowered); CPPUNIT_ASSERT(tEnabled == tInputData->mEnabled); CPPUNIT_ASSERT(tMinOperatePower == tInputData->mMinOperatePower); /// @test Input data default construction. GunnsElectPvRegShuntInputData defaultInput; CPPUNIT_ASSERT(0.0 == defaultInput.mVoltageSetpoint); CPPUNIT_ASSERT(false == defaultInput.mPowered); CPPUNIT_ASSERT(false == defaultInput.mEnabled); CPPUNIT_ASSERT(0.0 == defaultInput.mMinOperatePower); UT_PASS; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// @details Tests the constructor of the GunnsElectPvRegShunt class. //////////////////////////////////////////////////////////////////////////////////////////////////// void UtGunnsElectPvRegShunt::testConstruction() { UT_RESULT; /// @test Default construction. CPPUNIT_ASSERT(false == tArticle->mMalfVoltageBiasFlag); CPPUNIT_ASSERT(0.0 == tArticle->mMalfVoltageBiasValue); CPPUNIT_ASSERT(0.0 == tArticle->mOutputConductance); CPPUNIT_ASSERT(0.0 == tArticle->mShuntConductance); CPPUNIT_ASSERT(0 == tArticle->mArray); CPPUNIT_ASSERT(0.0 == tArticle->mStringLoadOrder.size()); CPPUNIT_ASSERT(0.0 == tArticle->mVoltageSetpoint); CPPUNIT_ASSERT(false == tArticle->mPowered); CPPUNIT_ASSERT(false == tArticle->mEnabled); CPPUNIT_ASSERT(0.0 == tArticle->mMinOperatePower); CPPUNIT_ASSERT(false == tArticle->mResetTrips); CPPUNIT_ASSERT(0 == tArticle->mSensors.mInCurrent); CPPUNIT_ASSERT(0 == tArticle->mSensors.mInVoltage); CPPUNIT_ASSERT(0 == tArticle->mSensors.mOutCurrent); CPPUNIT_ASSERT(0 == tArticle->mSensors.mOutVoltage); CPPUNIT_ASSERT(false == tArticle->mTrips.isTripped()); CPPUNIT_ASSERT(GunnsElectPvRegShunt::OFF == tArticle->mState); CPPUNIT_ASSERT(0.0 == tArticle->mRegulatedVoltage); CPPUNIT_ASSERT(0.0 == tArticle->mInputConductance); CPPUNIT_ASSERT(0.0 == tArticle->mShuntPower); CPPUNIT_ASSERT(0.0 == tArticle->mInputPower); CPPUNIT_ASSERT(0.0 == tArticle->mOutputPower); CPPUNIT_ASSERT(0.0 == tArticle->mWasteHeat); CPPUNIT_ASSERT(0.0 == tArticle->mPvBulkPowerAvail); CPPUNIT_ASSERT(0.0 == tArticle->mMaxRegCurrent); CPPUNIT_ASSERT("" == tArticle->mName); /// @test New/delete for code coverage. GunnsElectPvRegShunt* testArticle = new GunnsElectPvRegShunt(); delete testArticle; UT_PASS; } #include "UtGunnsElectPvSection.hh" #include "aspects/electrical/TripLogic/test/UtGunnsTripLogic.hh" //////////////////////////////////////////////////////////////////////////////////////////////////// /// @details Tests for Photovoltaic Array Shunting Regulator Link nominal initialization without /// exceptions, supplying a custom strings load order list. //////////////////////////////////////////////////////////////////////////////////////////////////// void UtGunnsElectPvRegShunt::testNominalInitialization() { UT_RESULT; /// - Initialize default constructed test article with nominal initialization data. CPPUNIT_ASSERT_NO_THROW(tArticle->initialize(*tConfigData, *tInputData, tLinks, tPort0, tPort1)); /// @test Nominal config data. CPPUNIT_ASSERT(tOutputConductance == tArticle->mOutputConductance); CPPUNIT_ASSERT(tShuntConductance == tArticle->mShuntConductance); CPPUNIT_ASSERT(tArray == tArticle->mArray); CPPUNIT_ASSERT(tArrayConfig->mNumStrings == tArticle->mStringLoadOrder.size()); CPPUNIT_ASSERT(0 == tArticle->mStringLoadOrder.back().mSection); CPPUNIT_ASSERT(0 == tArticle->mStringLoadOrder.back().mString); /// @test Nominal input data. CPPUNIT_ASSERT(tVoltageSetpoint == tArticle->mVoltageSetpoint); CPPUNIT_ASSERT(tPowered == tArticle->mPowered); CPPUNIT_ASSERT(tEnabled == tArticle->mEnabled); CPPUNIT_ASSERT(tMinOperatePower == tArticle->mMinOperatePower); /// @test Sensors package. CPPUNIT_ASSERT(&tSensorIin.mSensor == tArticle->mSensors.mInCurrent); CPPUNIT_ASSERT(&tSensorVin.mSensor == tArticle->mSensors.mInVoltage); CPPUNIT_ASSERT(&tSensorIout.mSensor == tArticle->mSensors.mOutCurrent); CPPUNIT_ASSERT(&tSensorVout.mSensor == tArticle->mSensors.mOutVoltage); /// @test Trips package. GunnsBasicLink::SolutionResult result; CPPUNIT_ASSERT(false == tArticle->mTrips.isTripped()); CPPUNIT_ASSERT(true == tArticle->mTrips.mInOverVoltage.checkForTrip(result, tInOverVoltageTrip + 0.01, tTripPriority)); CPPUNIT_ASSERT(true == tArticle->mTrips.mInOverCurrent.checkForTrip(result, tInOverCurrentTrip + 0.01, tTripPriority)); CPPUNIT_ASSERT(true == tArticle->mTrips.mOutOverVoltage.checkForTrip(result, tOutOverVoltageTrip + 0.01, tTripPriority)); CPPUNIT_ASSERT(true == tArticle->mTrips.mOutOverCurrent.checkForTrip(result, tOutOverCurrentTrip + 0.01, tTripPriority)); CPPUNIT_ASSERT(true == tArticle->mTrips.mOutUnderVoltage.checkForTrip(result, tOutUnderVoltageTrip - 0.01, tTripPriority)); /// @test Nominal state data. CPPUNIT_ASSERT(GunnsElectPvRegShunt::OFF == tArticle->mState); CPPUNIT_ASSERT(0.0 == tArticle->mRegulatedVoltage); CPPUNIT_ASSERT(0.0 == tArticle->mInputConductance); CPPUNIT_ASSERT(0.0 == tArticle->mShuntPower); CPPUNIT_ASSERT(0.0 == tArticle->mInputPower); CPPUNIT_ASSERT(0.0 == tArticle->mOutputPower); CPPUNIT_ASSERT(0.0 == tArticle->mWasteHeat); CPPUNIT_ASSERT(0.0 == tArticle->mPvBulkPowerAvail); CPPUNIT_ASSERT(0.0 == tArticle->mMaxRegCurrent); CPPUNIT_ASSERT(tName == tArticle->mName); CPPUNIT_ASSERT(true == tArticle->mInitFlag); UT_PASS; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// @details Tests for Photovoltaic Array Shunting Regulator Link nominal initialization without /// exceptions, with default string load order. //////////////////////////////////////////////////////////////////////////////////////////////////// void UtGunnsElectPvRegShunt::testDefaultLoadOrderInitialization() { UT_RESULT; /// - Initialize default constructed test article with nominal initialization data, using an /// empty string load order vector. tConfigData->mStringLoadOrder.clear(); CPPUNIT_ASSERT_NO_THROW(tArticle->initialize(*tConfigData, *tInputData, tLinks, tPort0, tPort1)); /// @test Nominal config data. CPPUNIT_ASSERT(tOutputConductance == tArticle->mOutputConductance); CPPUNIT_ASSERT(tShuntConductance == tArticle->mShuntConductance); CPPUNIT_ASSERT(tArray == tArticle->mArray); CPPUNIT_ASSERT(tArrayConfig->mNumStrings == tArticle->mStringLoadOrder.size()); const unsigned int section = tArrayConfig->mNumSections - 1; const unsigned int string = tArrayConfig->mNumStrings / tArrayConfig->mNumSections - 1; CPPUNIT_ASSERT(section == tArticle->mStringLoadOrder.back().mSection); CPPUNIT_ASSERT(string == tArticle->mStringLoadOrder.back().mString); /// @test Nominal input data. CPPUNIT_ASSERT(tVoltageSetpoint == tArticle->mVoltageSetpoint); CPPUNIT_ASSERT(tEnabled == tArticle->mEnabled); /// @test Nominal state data. CPPUNIT_ASSERT(GunnsElectPvRegShunt::OFF == tArticle->mState); CPPUNIT_ASSERT(0.0 == tArticle->mRegulatedVoltage); CPPUNIT_ASSERT(0.0 == tArticle->mInputConductance); CPPUNIT_ASSERT(0.0 == tArticle->mShuntPower); CPPUNIT_ASSERT(0.0 == tArticle->mInputPower); CPPUNIT_ASSERT(0.0 == tArticle->mOutputPower); CPPUNIT_ASSERT(0.0 == tArticle->mWasteHeat); CPPUNIT_ASSERT(0.0 == tArticle->mPvBulkPowerAvail); CPPUNIT_ASSERT(0.0 == tArticle->mMaxRegCurrent); CPPUNIT_ASSERT(tName == tArticle->mName); CPPUNIT_ASSERT(true == tArticle->mInitFlag); UT_PASS; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// @details Tests for Photovoltaic Array Shunting Regulator Link nominal initialization with exceptions. //////////////////////////////////////////////////////////////////////////////////////////////////// void UtGunnsElectPvRegShunt::testInitializationErrors() { UT_RESULT; /// @test Exception thrown for bad output conductance. tConfigData->mOutputConductance = 0.0; CPPUNIT_ASSERT_THROW(tArticle->initialize(*tConfigData, *tInputData, tLinks, tPort0, tPort1), TsInitializationException); tConfigData->mOutputConductance = tOutputConductance; /// @test Exception thrown for bad shunt conductance. tConfigData->mShuntConductance = 0.0; CPPUNIT_ASSERT_THROW(tArticle->initialize(*tConfigData, *tInputData, tLinks, tPort0, tPort1), TsInitializationException); tConfigData->mShuntConductance = tShuntConductance; /// @test Exception thrown for null array pointer. tConfigData->mArray = 0; CPPUNIT_ASSERT_THROW(tArticle->initialize(*tConfigData, *tInputData, tLinks, tPort0, tPort1), TsInitializationException); tConfigData->mArray = tArray; /// @test Exception thrown for uninitialized array. FriendlyGunnsElectPvArray badArray; tConfigData->mArray = &badArray; CPPUNIT_ASSERT_THROW(tArticle->initialize(*tConfigData, *tInputData, tLinks, tPort0, tPort1), TsInitializationException); tConfigData->mArray = tArray; /// @test Exception thrown for bad string load order vector length. tConfigData->addStringLoadOrder(0, 0); CPPUNIT_ASSERT_THROW(tArticle->initialize(*tConfigData, *tInputData, tLinks, tPort0, tPort1), TsInitializationException); tConfigData->mStringLoadOrder.pop_back(); /// @test Exception thrown for bad section # in string load order vector. tConfigData->mStringLoadOrder.pop_back(); tConfigData->addStringLoadOrder(5, 0); CPPUNIT_ASSERT_THROW(tArticle->initialize(*tConfigData, *tInputData, tLinks, tPort0, tPort1), TsInitializationException); tConfigData->mStringLoadOrder.pop_back(); tConfigData->addStringLoadOrder(0, 0); /// @test Exception thrown for bad string # in string load order vector. tConfigData->mStringLoadOrder.pop_back(); tConfigData->addStringLoadOrder(0, 67); CPPUNIT_ASSERT_THROW(tArticle->initialize(*tConfigData, *tInputData, tLinks, tPort0, tPort1), TsInitializationException); tConfigData->mStringLoadOrder.pop_back(); tConfigData->addStringLoadOrder(0, 0); /// @test Exception thrown for duplicate entry in string load order vector. tConfigData->mStringLoadOrder.pop_back(); tConfigData->mStringLoadOrder.pop_back(); tConfigData->addStringLoadOrder(0, 0); tConfigData->addStringLoadOrder(0, 0); CPPUNIT_ASSERT_THROW(tArticle->initialize(*tConfigData, *tInputData, tLinks, tPort0, tPort1), TsInitializationException); tConfigData->mStringLoadOrder.pop_back(); tConfigData->mStringLoadOrder.pop_back(); tConfigData->addStringLoadOrder(0, 1); tConfigData->addStringLoadOrder(0, 0); /// @test Exception thrown from section for bad trip priority. tConfigData->mTripPriority = 0; CPPUNIT_ASSERT_THROW(tArticle->initialize(*tConfigData, *tInputData, tLinks, tPort0, tPort1), TsInitializationException); tConfigData->mTripPriority = tTripPriority; /// @test Exception thrown from section for bad voltage setpoint. tInputData->mVoltageSetpoint = 0.0; CPPUNIT_ASSERT_THROW(tArticle->initialize(*tConfigData, *tInputData, tLinks, tPort0, tPort1), TsInitializationException); tInputData->mVoltageSetpoint = tVoltageSetpoint; CPPUNIT_ASSERT(false == tArticle->mInitFlag); UT_PASS; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// @details Tests for Array Shunting Regulator Link restart method. //////////////////////////////////////////////////////////////////////////////////////////////////// void UtGunnsElectPvRegShunt::testRestart() { UT_RESULT; /// - Initialize default constructed test article with nominal initialization data. CPPUNIT_ASSERT_NO_THROW(tArticle->initialize(*tConfigData, *tInputData, tLinks, tPort0, tPort1)); /// @test Restart method clears non-config and non-checkpointed data. tArticle->mState = GunnsElectPvRegShunt::SAG; tArticle->mRegulatedVoltage = 1.0; tArticle->mInputConductance = 1.0; tArticle->mShuntPower = 1.0; tArticle->mInputPower = 1.0; tArticle->mOutputPower = 1.0; tArticle->mWasteHeat = 1.0; tArticle->mPvBulkPowerAvail = 1.0; tArticle->mMaxRegCurrent = 1.0; tArticle->restart(); CPPUNIT_ASSERT(GunnsElectPvRegShunt::OFF == tArticle->mState); CPPUNIT_ASSERT(0.0 == tArticle->mRegulatedVoltage); CPPUNIT_ASSERT(0.0 == tArticle->mInputConductance); CPPUNIT_ASSERT(0.0 == tArticle->mShuntPower); CPPUNIT_ASSERT(0.0 == tArticle->mInputPower); CPPUNIT_ASSERT(0.0 == tArticle->mOutputPower); CPPUNIT_ASSERT(0.0 == tArticle->mWasteHeat); CPPUNIT_ASSERT(0.0 == tArticle->mPvBulkPowerAvail); CPPUNIT_ASSERT(0.0 == tArticle->mMaxRegCurrent); UT_PASS; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// @details Tests for Array Shunting Regulator Link step and updateState methods. //////////////////////////////////////////////////////////////////////////////////////////////////// void UtGunnsElectPvRegShunt::testStep() { UT_RESULT; /// - Initialize default constructed test article with nominal initialization data. CPPUNIT_ASSERT_NO_THROW(tArticle->initialize(*tConfigData, *tInputData, tLinks, tPort0, tPort1)); { /// @test Regulated voltage w/o setpoint malf, nominal max outputs, initial OFF->REG /// transition, [A] & {w} outputs in REG state. tArray->step(0.0); tArticle->step(0.0); double expectedPbulk, expectedGin; const double expectedVreg = tVoltageSetpoint; tArray->predictLoadAtVoltage(expectedPbulk, expectedGin, expectedVreg); const double expectedImax = tArrayConfig->mNumStrings * tArray->mSections[0].mStrings[0].getTerminal().mCurrent; const double expectedAin = expectedGin; const double expectedAout = tOutputConductance; const double expectedW = expectedVreg * expectedAout; CPPUNIT_ASSERT(tMinOperatePower < tArticle->mPvBulkPowerAvail); CPPUNIT_ASSERT(GunnsElectPvRegShunt::REG == tArticle->mState); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedVreg, tArticle->mRegulatedVoltage, DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedPbulk, tArticle->mPvBulkPowerAvail, DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedGin, tArticle->mInputConductance, DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedImax, tArticle->mMaxRegCurrent, FLT_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedAin, tArticle->mAdmittanceMatrix[0], DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(0.0, tArticle->mAdmittanceMatrix[1], DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(0.0, tArticle->mAdmittanceMatrix[2], DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedAout, tArticle->mAdmittanceMatrix[3], DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(0.0, tArticle->mSourceVector[0], DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedW, tArticle->mSourceVector[1], DBL_EPSILON); CPPUNIT_ASSERT(false == tArray->mSections[0].mStrings[0].isShunted()); CPPUNIT_ASSERT(true == tArticle->needAdmittanceUpdate()); CPPUNIT_ASSERT(true == tArticle->mOffToRegOccurred); } { /// @test Regulated voltage with setpoint malf, transition to OFF when disabled, /// [A] & {w} outputs in OFF state. tArticle->mMalfVoltageBiasFlag = true; tArticle->mMalfVoltageBiasValue = 1.0; tArticle->mEnabled = false; tArticle->step(0.0); double expectedPbulk, expectedGin; const double expectedVreg = tVoltageSetpoint + 1.0; tArray->predictLoadAtVoltage(expectedPbulk, expectedGin, expectedVreg); const double expectedAin = expectedGin; const double expectedAout = 1.0 / GunnsBasicLink::mConductanceLimit; const double expectedW = 0.0; CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedVreg, tArticle->mRegulatedVoltage, DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedAin, tArticle->mAdmittanceMatrix[0], DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(0.0, tArticle->mAdmittanceMatrix[1], DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(0.0, tArticle->mAdmittanceMatrix[2], DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedAout, tArticle->mAdmittanceMatrix[3], DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(0.0, tArticle->mSourceVector[0], DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedW, tArticle->mSourceVector[1], DBL_EPSILON); CPPUNIT_ASSERT(GunnsElectPvRegShunt::OFF == tArticle->mState); CPPUNIT_ASSERT(true == tArticle->needAdmittanceUpdate()); CPPUNIT_ASSERT(false == tArticle->mOffToRegOccurred); } { /// @test Transition from REG -> OFF due to low light. tArray->mSections[0].setSourceExposedFraction(0.5); tArray->mSections[1].setSourceExposedFraction(0.5); tArray->mSections[2].setSourceExposedFraction(0.5); tArray->step(0.0); tArticle->step(0.0); CPPUNIT_ASSERT(GunnsElectPvRegShunt::OFF == tArticle->mState); CPPUNIT_ASSERT(true == tArticle->needAdmittanceUpdate()); CPPUNIT_ASSERT(false == tArticle->mOffToRegOccurred); } { /// @test Array unlit, low-limit on regulated voltage. tArray->mSections[0].setSourceExposedFraction(0.0); tArray->mSections[1].setSourceExposedFraction(0.0); tArray->mSections[2].setSourceExposedFraction(0.0); tArray->mSections[0].setSourceFluxMagnitude(0.0); tArray->mSections[1].setSourceFluxMagnitude(0.0); tArray->mSections[2].setSourceFluxMagnitude(0.0); tArray->step(0.0); tArticle->mMalfVoltageBiasValue = -20.0; tArticle->step(0.0); const double expectedVreg = DBL_EPSILON; CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedVreg, tArticle->mRegulatedVoltage, DBL_EPSILON); CPPUNIT_ASSERT(GunnsElectPvRegShunt::OFF == tArticle->mState); CPPUNIT_ASSERT(true == tArticle->needAdmittanceUpdate()); CPPUNIT_ASSERT(false == tArticle->mOffToRegOccurred); } { /// - Force a trip. GunnsBasicLink::SolutionResult result; tArticle->mTrips.mInOverCurrent.checkForTrip(result, 1000.0, tTripPriority); CPPUNIT_ASSERT(true == tArticle->mTrips.isTripped()); /// @test Transition to off & reset trips when unpowered. tArticle->mPowered = false; tArticle->step(0.0); CPPUNIT_ASSERT(false == tArticle->mTrips.isTripped()); CPPUNIT_ASSERT(GunnsElectPvRegShunt::OFF == tArticle->mState); } { /// @test Link port assignment control. tArticle->mUserPortSelect = 0; tArticle->mUserPortSetControl = GunnsBasicLink::GROUND; tArticle->step(0.0); CPPUNIT_ASSERT(GunnsBasicLink::READY == tArticle->mUserPortSetControl); CPPUNIT_ASSERT(1 == tArticle->mNodeMap[0]); } { /// - Force a trip. GunnsBasicLink::SolutionResult result; tArticle->mTrips.mInOverCurrent.checkForTrip(result, 1000.0, tTripPriority); /// @test Transition to OFF when tripped. tArticle->mPowered = true; tArticle->mState = GunnsElectPvRegShunt::REG; tArticle->step(0.0); CPPUNIT_ASSERT(true == tArticle->mTrips.isTripped()); CPPUNIT_ASSERT(GunnsElectPvRegShunt::OFF == tArticle->mState); } { tArray->mSections[0].setSourceExposedFraction(1.0); tArray->mSections[1].setSourceExposedFraction(1.0); tArray->mSections[2].setSourceExposedFraction(1.0); tArray->mSections[0].setSourceFluxMagnitude(31.626); tArray->mSections[1].setSourceFluxMagnitude(31.626); tArray->mSections[2].setSourceFluxMagnitude(31.626); tArray->step(0.0); /// @test Reset trips from command. tArticle->mResetTrips = true; tArticle->step(0.0); CPPUNIT_ASSERT(false == tArticle->mTrips.isTripped()); } UT_PASS; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// @details Tests the Array Shunting Regulator Link minorStep method. //////////////////////////////////////////////////////////////////////////////////////////////////// void UtGunnsElectPvRegShunt::testMinorStep() { UT_RESULT; /// - Initialize default constructed test article with nominal initialization data. CPPUNIT_ASSERT_NO_THROW(tArticle->initialize(*tConfigData, *tInputData, tLinks, tPort0, tPort1)); { /// @test [A] and {w} outputs are updated in minorStep for REG state. tArticle->mState = GunnsElectPvRegShunt::REG; tArticle->mRegulatedVoltage = 10.0; tArticle->mInputConductance = 1.0; const double expectedAin = tArticle->mInputConductance; const double expectedAout = tOutputConductance; const double expectedW = tArticle->mRegulatedVoltage * expectedAout; tArticle->minorStep(0.0, 2); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedAin, tArticle->mAdmittanceMatrix[0], DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(0.0, tArticle->mAdmittanceMatrix[1], DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(0.0, tArticle->mAdmittanceMatrix[2], DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedAout, tArticle->mAdmittanceMatrix[3], DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(0.0, tArticle->mSourceVector[0], DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedW, tArticle->mSourceVector[1], DBL_EPSILON); CPPUNIT_ASSERT(true == tArticle->needAdmittanceUpdate()); } { /// @test [A] and {w} outputs are updated in minorStep for SAG state. tArticle->mState = GunnsElectPvRegShunt::SAG; const double expectedAout = tOutputConductance; const double expectedW = 0.0; tArticle->minorStep(0.0, 3); CPPUNIT_ASSERT_DOUBLES_EQUAL( expectedAout, tArticle->mAdmittanceMatrix[0], DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(-expectedAout, tArticle->mAdmittanceMatrix[1], DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(-expectedAout, tArticle->mAdmittanceMatrix[2], DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL( expectedAout, tArticle->mAdmittanceMatrix[3], DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(0.0, tArticle->mSourceVector[0], DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedW, tArticle->mSourceVector[1], DBL_EPSILON); CPPUNIT_ASSERT(true == tArticle->needAdmittanceUpdate()); } { /// @test [A] and {w} outputs are updated in minorStep for OFF state. tArticle->mState = GunnsElectPvRegShunt::OFF; const double expectedAin = tArticle->mInputConductance; const double expectedAout = 1.0 / GunnsBasicLink::mConductanceLimit; const double expectedW = 0.0; tArticle->minorStep(0.0, 4); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedAin, tArticle->mAdmittanceMatrix[0], DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(0.0, tArticle->mAdmittanceMatrix[1], DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(0.0, tArticle->mAdmittanceMatrix[2], DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedAout, tArticle->mAdmittanceMatrix[3], DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(0.0, tArticle->mSourceVector[0], DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedW, tArticle->mSourceVector[1], DBL_EPSILON); CPPUNIT_ASSERT(true == tArticle->needAdmittanceUpdate()); } UT_PASS; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// @details Tests the Array Shunting Regulator Link getter and setter methods. //////////////////////////////////////////////////////////////////////////////////////////////////// void UtGunnsElectPvRegShunt::testAccessors() { UT_RESULT; /// @test Link is non-linear. CPPUNIT_ASSERT(true == tArticle->isNonLinear()); /// @test Can set and get the voltage setpoint. tArticle->setVoltageSetpoint(5.0); CPPUNIT_ASSERT(5.0 == tArticle->getVoltageSetpoint()); /// @test Can set the enabled flag. tArticle->setEnabled(true); CPPUNIT_ASSERT(true == tArticle->mEnabled); /// @test Can get maximum regulated current. tArticle->mMaxRegCurrent = 15.0; CPPUNIT_ASSERT(15.0 == tArticle->getMaxRegCurrent()); /// @test Can set and get the minimum operate power. tArticle->setMinOperatePower(1000.0); CPPUNIT_ASSERT(1000.0 == tArticle->getMinOperatePower()); /// @test Can get the trip logic object. CPPUNIT_ASSERT(&tArticle->mTrips == tArticle->getTrips()); UT_PASS; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// @details Tests the confirmSolutionAcceptable method. //////////////////////////////////////////////////////////////////////////////////////////////////// void UtGunnsElectPvRegShunt::testConfirmSolutionAcceptable() { UT_RESULT; /// - Initialize default constructed test article with nominal initialization data. CPPUNIT_ASSERT_NO_THROW(tArticle->initialize(*tConfigData, *tInputData, tLinks, tPort0, tPort1)); /// - Step the article and array to update realistic states. tArray->step(0.0); tArticle->step(0.0); CPPUNIT_ASSERT(GunnsElectPvRegShunt::REG == tArticle->mState); CPPUNIT_ASSERT(true == tArticle->mOffToRegOccurred); /// @test REG state loads the array strings, remains in REG state since the strings have /// sufficient power, and remaining strings are shunted. double inputVolts = 11.0; double outputVolts = 9.9; double powerDemand = tVoltageSetpoint * tOutputConductance * (tVoltageSetpoint - outputVolts); tArticle->mPotentialVector[0] = inputVolts; tArticle->mPotentialVector[1] = outputVolts; tArray->mSections[0].mStrings[0].loadAtVoltage(tVoltageSetpoint); const double loadedStringP = tArray->mSections[0].mStrings[0].getTerminal().mPower; const double loadedStringG = tArray->mSections[0].mStrings[0].getTerminal().mConductance; tArray->mSections[0].mStrings[0].loadAtConductance(tShuntConductance); const double shuntedStringP = tArray->mSections[0].mStrings[0].getTerminal().mPower; const int numLoadedStrings = ceil(powerDemand / loadedStringP); const int numShuntedStrings = tArrayConfig->mNumStrings - numLoadedStrings; const int firstLoadedSection = tArrayConfig->mNumSections - 1; const int firstLoadedString = tArrayConfig->mNumStrings / tArrayConfig->mNumSections - 1; tArray->mSections[firstLoadedSection].mStrings[firstLoadedString].setShunted(true); double expectedPin = numLoadedStrings * loadedStringP; double expectedGin = numLoadedStrings * loadedStringG; double expectedPsh = numShuntedStrings * shuntedStringP; double expectedFlux = (tVoltageSetpoint - outputVolts) * tOutputConductance; CPPUNIT_ASSERT(GunnsBasicLink::CONFIRM == tArticle->confirmSolutionAcceptable(1, 2)); CPPUNIT_ASSERT(GunnsElectPvRegShunt::REG == tArticle->mState); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedPin, tArticle->mInputPower, FLT_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedGin, tArticle->mInputConductance, FLT_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedPsh, tArticle->mShuntPower, FLT_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedFlux, tArticle->mFlux, FLT_EPSILON); CPPUNIT_ASSERT(false == tArray->mCommonStringsOutput); CPPUNIT_ASSERT(true == tArray->mSections[0].mStrings[0].isShunted()); CPPUNIT_ASSERT(false == tArray->mSections[firstLoadedSection].mStrings[firstLoadedString].isShunted()); /// @test Sensor updates double expectedSensedVin = tArray->mSections[firstLoadedSection].mStrings[firstLoadedString].getTerminal().mVoltage; double expectedSensedIin = tArray->mSections[firstLoadedSection].mStrings[firstLoadedString].getTerminal().mCurrent; double expectedSensedVout = outputVolts; double expectedSensedIout = expectedFlux; double actualSensedVin = tArticle->mSensors.mInVoltage->getSensedOutput(); double actualSensedIin = tArticle->mSensors.mInCurrent->getSensedOutput(); double actualSensedVout = tArticle->mSensors.mOutVoltage->getSensedOutput(); double actualSensedIout = tArticle->mSensors.mOutCurrent->getSensedOutput(); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedSensedVin, actualSensedVin, FLT_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedSensedIin, actualSensedIin, FLT_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedSensedVout, actualSensedVout, FLT_EPSILON * expectedSensedVout); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedSensedIout, actualSensedIout, FLT_EPSILON); /// @test Transition from REG -> OFF due to insufficient array power, only after solution is /// converged, and all strings are shunted. This tests the scenario where /// vehicle load > PV available power > minimum operate power, which must be limited /// by the model from flipping between REG-OFF indefinitely. tArray->step(0.0); tArticle->step(0.0); CPPUNIT_ASSERT(GunnsElectPvRegShunt::REG == tArticle->mState); CPPUNIT_ASSERT(false == tArticle->mOffToRegOccurred); outputVolts = 9.0; powerDemand = tVoltageSetpoint * tOutputConductance * (tVoltageSetpoint - outputVolts); tArticle->mPotentialVector[1] = outputVolts; CPPUNIT_ASSERT(GunnsBasicLink::CONFIRM == tArticle->confirmSolutionAcceptable(0, 1)); CPPUNIT_ASSERT(GunnsElectPvRegShunt::REG == tArticle->mState); CPPUNIT_ASSERT(GunnsBasicLink::DELAY == tArticle->confirmSolutionAcceptable(1, 2)); CPPUNIT_ASSERT(GunnsElectPvRegShunt::REG == tArticle->mState); CPPUNIT_ASSERT(GunnsBasicLink::REJECT == tArticle->confirmSolutionAcceptable(2, 3)); CPPUNIT_ASSERT(GunnsElectPvRegShunt::OFF == tArticle->mState); CPPUNIT_ASSERT(GunnsBasicLink::CONFIRM == tArticle->confirmSolutionAcceptable(0, 4)); CPPUNIT_ASSERT(GunnsElectPvRegShunt::OFF == tArticle->mState); CPPUNIT_ASSERT(GunnsBasicLink::DELAY == tArticle->confirmSolutionAcceptable(1, 5)); CPPUNIT_ASSERT(GunnsElectPvRegShunt::OFF == tArticle->mState); CPPUNIT_ASSERT(GunnsBasicLink::REJECT == tArticle->confirmSolutionAcceptable(2, 6)); CPPUNIT_ASSERT(GunnsElectPvRegShunt::REG == tArticle->mState); CPPUNIT_ASSERT(true == tArticle->mOffToRegOccurred); CPPUNIT_ASSERT(GunnsBasicLink::CONFIRM == tArticle->confirmSolutionAcceptable(0, 7)); CPPUNIT_ASSERT(GunnsElectPvRegShunt::REG == tArticle->mState); CPPUNIT_ASSERT(GunnsBasicLink::DELAY == tArticle->confirmSolutionAcceptable(1, 8)); CPPUNIT_ASSERT(GunnsElectPvRegShunt::REG == tArticle->mState); CPPUNIT_ASSERT(GunnsBasicLink::REJECT == tArticle->confirmSolutionAcceptable(2, 9)); CPPUNIT_ASSERT(GunnsElectPvRegShunt::OFF == tArticle->mState); CPPUNIT_ASSERT(GunnsBasicLink::CONFIRM == tArticle->confirmSolutionAcceptable(0, 10)); CPPUNIT_ASSERT(GunnsElectPvRegShunt::OFF == tArticle->mState); CPPUNIT_ASSERT(GunnsBasicLink::CONFIRM == tArticle->confirmSolutionAcceptable(1, 11)); CPPUNIT_ASSERT(GunnsElectPvRegShunt::OFF == tArticle->mState); CPPUNIT_ASSERT(GunnsBasicLink::CONFIRM == tArticle->confirmSolutionAcceptable(2, 12)); CPPUNIT_ASSERT(GunnsElectPvRegShunt::OFF == tArticle->mState); /// @test Confirming in OFF state shunts all strings. expectedPin = 0.0; expectedGin = 0.0; expectedPsh = tArrayConfig->mNumStrings * shuntedStringP; expectedFlux = 0.0; CPPUNIT_ASSERT(true == tArray->mCommonStringsOutput); CPPUNIT_ASSERT(true == tArray->mSections[0].mStrings[0].isShunted()); CPPUNIT_ASSERT(true == tArray->mSections[firstLoadedSection].mStrings[firstLoadedString].isShunted()); /// @test Transition from REG -> OFF due to back-voltage. outputVolts = tVoltageSetpoint + 0.01; tArticle->mPotentialVector[1] = outputVolts; tArticle->mState = GunnsElectPvRegShunt::REG; CPPUNIT_ASSERT(GunnsBasicLink::REJECT == tArticle->confirmSolutionAcceptable(0, 1)); CPPUNIT_ASSERT(GunnsElectPvRegShunt::OFF == tArticle->mState); /// @test Delays, then rejects on trip from the output current sensor. inputVolts = 11.0; outputVolts = 9.8; tArticle->mPotentialVector[0] = inputVolts; tArticle->mPotentialVector[1] = outputVolts; tArticle->mState = GunnsElectPvRegShunt::REG; CPPUNIT_ASSERT(GunnsBasicLink::CONFIRM == tArticle->confirmSolutionAcceptable(0, 1)); CPPUNIT_ASSERT(GunnsElectPvRegShunt::REG == tArticle->mState); CPPUNIT_ASSERT(GunnsBasicLink::DELAY == tArticle->confirmSolutionAcceptable(1, 2)); CPPUNIT_ASSERT(GunnsElectPvRegShunt::REG == tArticle->mState); CPPUNIT_ASSERT(GunnsBasicLink::REJECT == tArticle->confirmSolutionAcceptable(2, 3)); CPPUNIT_ASSERT(GunnsElectPvRegShunt::OFF == tArticle->mState); /// @test Delays, then rejects on trip when optional output current sensor is missing, but /// the trip limit is still specified. tArticle->mTrips.resetTrips(); tArticle->mState = GunnsElectPvRegShunt::REG; tArticle->mSensors.mOutCurrent = 0; CPPUNIT_ASSERT(GunnsBasicLink::CONFIRM == tArticle->confirmSolutionAcceptable(0, 1)); CPPUNIT_ASSERT(GunnsElectPvRegShunt::REG == tArticle->mState); CPPUNIT_ASSERT(GunnsBasicLink::DELAY == tArticle->confirmSolutionAcceptable(1, 2)); CPPUNIT_ASSERT(GunnsElectPvRegShunt::REG == tArticle->mState); CPPUNIT_ASSERT(GunnsBasicLink::REJECT == tArticle->confirmSolutionAcceptable(2, 3)); CPPUNIT_ASSERT(GunnsElectPvRegShunt::OFF == tArticle->mState); /// @test Doesn't trip when not enabled. tArticle->mTrips.resetTrips(); tArticle->mState = GunnsElectPvRegShunt::OFF; tArticle->mEnabled = false; CPPUNIT_ASSERT(GunnsBasicLink::CONFIRM == tArticle->confirmSolutionAcceptable(0, 1)); CPPUNIT_ASSERT(GunnsElectPvRegShunt::OFF == tArticle->mState); CPPUNIT_ASSERT(GunnsBasicLink::CONFIRM == tArticle->confirmSolutionAcceptable(1, 2)); CPPUNIT_ASSERT(GunnsElectPvRegShunt::OFF == tArticle->mState); UT_PASS; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// @details Tests the computeFlows method. //////////////////////////////////////////////////////////////////////////////////////////////////// void UtGunnsElectPvRegShunt::testComputeFlows() { UT_RESULT; /// - Initialize default constructed test article with nominal initialization data. CPPUNIT_ASSERT_NO_THROW(tArticle->initialize(*tConfigData, *tInputData, tLinks, tPort0, tPort1)); /// - Step the article and array to update realistic states. tArray->step(0.0); tArticle->step(0.0); /// @test Outputs in REG state. double inputVolts = tVoltageSetpoint; double outputVolts = inputVolts - 0.1; double expectedPin = 100.0; double expectedPsh = 5.0; tArticle->mPotentialVector[0] = inputVolts; tArticle->mPotentialVector[1] = outputVolts; tArticle->mState = GunnsElectPvRegShunt::REG; tArticle->mInputPower = expectedPin; tArticle->mShuntPower = expectedPsh; double expectedDp = inputVolts - outputVolts; double expectedFlux = expectedDp * tOutputConductance; double expectedP = -expectedFlux * expectedDp; double expectedPout = expectedFlux * outputVolts; double expectedHeat = expectedPsh - expectedP; tArticle->mFlux = expectedFlux; tArticle->computeFlows(0.0); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedDp, tArticle->mPotentialDrop, DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedP, tArticle->mPower, DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedPout, tArticle->mOutputPower, DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedPin, tArticle->mInputPower, DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedHeat, tArticle->mWasteHeat, DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedFlux, tNodes[0].getOutflux(), DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedFlux, tNodes[1].getInflux(), DBL_EPSILON); /// @test Outputs in OFF state. outputVolts = inputVolts + 1.0; expectedPsh = 5.0; tArticle->mPotentialVector[0] = inputVolts; tArticle->mPotentialVector[1] = outputVolts; tArticle->mState = GunnsElectPvRegShunt::OFF; tArticle->mInputPower = 100.0; tArticle->mShuntPower = expectedPsh; expectedDp = inputVolts - outputVolts; expectedFlux = 0.0; expectedP = 0.0; expectedPin = 0.0; expectedPout = 0.0; expectedHeat = expectedPsh - expectedP; tNodes[0].resetFlows(); tNodes[1].resetFlows(); tArticle->mFlux = expectedFlux; tArticle->computeFlows(0.0); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedDp, tArticle->mPotentialDrop, DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedP, tArticle->mPower, DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedPout, tArticle->mOutputPower, DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedPin, tArticle->mInputPower, DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedHeat, tArticle->mWasteHeat, DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedFlux, tNodes[0].getOutflux(), DBL_EPSILON); CPPUNIT_ASSERT_DOUBLES_EQUAL(expectedFlux, tNodes[1].getInflux(), DBL_EPSILON); UT_PASS_LAST; }
51.56893
127
0.626294
[ "object", "vector", "model" ]
063bf65a72bf2655e117cc45d2e0669307ae5aa1
21,490
cc
C++
src/tmdgrid/createstructgrid.cc
vbertone/NangaParbat
49529d0a2e810dfe0ec676c8e96081be39a8800d
[ "MIT" ]
3
2020-01-16T17:15:54.000Z
2020-01-17T10:59:39.000Z
src/tmdgrid/createstructgrid.cc
vbertone/NangaParbat
49529d0a2e810dfe0ec676c8e96081be39a8800d
[ "MIT" ]
null
null
null
src/tmdgrid/createstructgrid.cc
vbertone/NangaParbat
49529d0a2e810dfe0ec676c8e96081be39a8800d
[ "MIT" ]
3
2020-01-18T22:10:02.000Z
2020-08-01T18:42:36.000Z
// // Author: Valerio Bertone: valerio.bertone@cern.ch // Chiara Bissolotti: chiara.bissolotti01@universitadipavia.it // #include "NangaParbat/createstructgrid.h" #include "NangaParbat/bstar.h" #include "NangaParbat/nonpertfunctions.h" #include "NangaParbat/tmdgrid.h" #include "NangaParbat/factories.h" #include "NangaParbat/listdir.h" #include "NangaParbat/direxists.h" #include "NangaParbat/numtostring.h" #include <LHAPDF/LHAPDF.h> #include <iomanip> #include <fstream> #include <sys/stat.h> namespace NangaParbat { //____________________________________________________________________________________________________ void ProduceStructGrid(std::string const& GridsDirectory, std::string const& GridTMDPDFfolder, std::string const& GridTMDFFfolder, std::string const& Output, std::string const& repID, std::string const& structype) { // Distribution type const std::string pf = structype; // Read configuration file const YAML::Node config = YAML::LoadFile(GridsDirectory + "/tables/config.yaml"); // Define vector for grid names std::vector<std::string> fnames; // Collect TMD grids to compute the structure function std::vector<std::unique_ptr<YAML::Emitter>> grids; // If the replica number (replica ID) is not specified, produce one structure function grid // for every TMD PDF grid present in the TMDPDF folder. TMD PDF and TMD FF are matched by replica ID. if (repID == "none") { for (auto const& f : list_dir(GridsDirectory + "/" + GridTMDPDFfolder)) { // TMDPDF grid file const std::string gridfile = GridsDirectory + "/" + GridTMDPDFfolder + "/" + f; // Check if the TMDPDF grid file exists std::fstream fs(gridfile); if (!fs.fail()) { if (f.substr(f.size() - 5, 5) == ".yaml") { // Get replica number from the name of the PDF Grids const std::string repnum = f.substr(f.size() - 9, 4); std::cout << "Computing grid for structure function with replica " << repnum << " ..." << std::endl; // Compute grid and push it back. In the case of // replica_0 push it in the front to make sure it's // the first replica. if (repnum == "0000") { grids.insert(grids.begin(), EmitStructGrid(GridsDirectory, GridTMDPDFfolder, GridTMDFFfolder, std::stoi(repnum), pf, Inter4DGrid(pf))); fnames.insert(fnames.begin(), repnum); } else { grids.push_back(EmitStructGrid(GridsDirectory, GridTMDPDFfolder, GridTMDFFfolder, std::stoi(repnum), pf, Inter4DGrid(pf))); fnames.push_back(repnum); } } } } } // If the replica ID is specified, do only the grid for that replica. else { std::cout << "Computing grid for structure function with replica " << repID << " ..." << std::endl; grids.push_back(EmitStructGrid(GridsDirectory, GridTMDPDFfolder, GridTMDFFfolder, std::stoi(repID), pf, Inter4DGrid(pf))); fnames.push_back(repID); } // Output directory const std::string outdir = GridsDirectory + "/" + Output; // Create output directory if it does not exist if (!dir_exists(Output)) mkdir(outdir.c_str(), ACCESSPERMS); // Write info file std::ofstream iout(outdir + "/" + Output + ".info"); iout << NangaParbat::EmitStructInfo(GridsDirectory, GridTMDPDFfolder, GridTMDFFfolder, config, grids.size(), pf, Inter4DGrid(pf))->c_str() << std::endl; iout.close(); // Dump grids to file for (int i = 0; i < (int) grids.size(); i++) { // Grids numbered sequentially // std::ofstream fpout(outdir + "/" + Output + "_" + num_to_string(i) + ".yaml"); // Grid number = replica number std::ofstream fpout(outdir + "/" + Output + "_" + num_to_string(std::stoi(fnames[i])) + ".yaml"); fpout << grids[i]->c_str() << std::endl; fpout.close(); } } //_________________________________________________________________________________ std::unique_ptr<YAML::Emitter> EmitStructGrid(std::string const& GridsDirectory, std::string const& GridTMDPDFfolder, std::string const& GridTMDFFfolder, int const& repnumber, std::string const& pf, FourDGrid const& fdg, int const& qToQcut) { // Timer apfel::Timer t; // Get TMDs distributions from grids std::cout << "Read TMD grids " << std::endl; NangaParbat::TMDGrid* TMDPDFs = NangaParbat::mkTMD(GridTMDPDFfolder, GridsDirectory, repnumber); NangaParbat::TMDGrid* TMDFFs = NangaParbat::mkTMD(GridTMDFFfolder, GridsDirectory, repnumber); // Allocate structure function on the four dimensional grid std::vector<std::vector<std::vector<std::vector<double>>>> SFs(fdg.Qg.size(), std::vector<std::vector<std::vector<double>>>(fdg.xg.size(), std::vector<std::vector<double>>(fdg.zg.size(), std::vector<double>(fdg.qToQg.size())))); // Compute structure function to put in grids, fully differential calculation. // At the moment the only SF implemented is FUUT. for (int iQ = 0; iQ < (int) fdg.Qg.size(); iQ++) { for (int ix = 0; ix < (int) fdg.xg.size(); ix++) { for (int iz = 0; iz < (int) fdg.zg.size(); iz++) { for (int iqT = 0; iqT < (int) fdg.qToQg.size(); iqT++) { const auto conv = Convolution(TMDPDFs, TMDFFs, [] (double const&) -> std::vector<double> { return apfel::QCh2;}, qToQcut); SFs[iQ][ix][iz][iqT] = conv(fdg.xg[ix], fdg.zg[iz], fdg.Qg[iQ], fdg.Qg[iQ] * fdg.qToQg[iqT]) / fdg.zg[iz] / (2 * M_PI); } } } // Report computation status const double perc = 100. * ( iQ + 1 ) / fdg.Qg.size(); std::cout << "Status report for the structure function grid computation: "<< std::setw(6) << std::setprecision(4) << perc << "\% completed...\r"; std::cout.flush(); } std::cout << "\n"; // Dump grids to emitter std::unique_ptr<YAML::Emitter> out = std::unique_ptr<YAML::Emitter>(new YAML::Emitter); out->SetFloatPrecision(6); out->SetDoublePrecision(6); *out << YAML::BeginMap; *out << YAML::Key << "Qg" << YAML::Value << YAML::Flow << fdg.Qg; *out << YAML::Key << "xg" << YAML::Value << YAML::Flow << fdg.xg; *out << YAML::Key << "zg" << YAML::Value << YAML::Flow << fdg.zg; *out << YAML::Key << "qToQg" << YAML::Value << YAML::Flow << fdg.qToQg; *out << YAML::Key << "StructureFunction" << YAML::Value << YAML::Flow << SFs; *out << YAML::EndMap; // Delete TMD objects delete TMDPDFs; delete TMDFFs; // Stop timer t.stop(); // Return the emitter return out; } //_________________________________________________________________________________ std::unique_ptr<YAML::Emitter> EmitStructGridDirect(std::string const& FitDirectory, int const& repnumber, std::string const& pf, FourDGrid const& fdg, int const& qToQcut) { // Timer apfel::Timer t; // Read configuration file const YAML::Node config = YAML::LoadFile(FitDirectory + "/tables/config.yaml"); // Perturbative order const int PerturbativeOrder = config["PerturbativeOrder"].as<int>(); // Scale-variation factors const double Ci = config["TMDscales"]["Ci"].as<double>(); const double Cf = config["TMDscales"]["Cf"].as<double>(); // Open LHAPDF sets LHAPDF::PDF* distpdf = LHAPDF::mkPDF(config["pdfset"]["name"].as<std::string>(), config["pdfset"]["member"].as<int>()); LHAPDF::PDF* distff = LHAPDF::mkPDF(config["ffset"]["name"].as<std::string>(), config["ffset"]["member"].as<int>()); // Get heavy-quark thresholds from the PDF LHAPDF set std::vector<double> ThresholdsPDF; for (auto const& v : distpdf->flavors()) if (v > 0 && v < 7) ThresholdsPDF.push_back(distpdf->quarkThreshold(v)); // Get heavy-quark thresholds from the FF LHAPDF set std::vector<double> ThresholdsFF; for (auto const& v : distff->flavors()) if (v > 0 && v < 7) ThresholdsFF.push_back(distff->quarkThreshold(v)); // Alpha_s (from PDFs and FFs) const auto AlphasPDF = [&] (double const& mu) -> double{ return distpdf->alphasQ(mu); }; const auto AlphasFF = [&] (double const& mu) -> double{ return distff->alphasQ(mu); }; // Setup APFEL++ x-space grid for PDFs std::vector<apfel::SubGrid> vsgp; for (auto const& sg : config["xgridpdf"]) vsgp.push_back({sg[0].as<int>(), sg[1].as<double>(), sg[2].as<int>()}); const apfel::Grid gpdf{vsgp}; // Setup APFEL++ x-space grid for FFs std::vector<apfel::SubGrid> vsgf; for (auto const& sg : config["xgridff"]) vsgf.push_back({sg[0].as<int>(), sg[1].as<double>(), sg[2].as<int>()}); const apfel::Grid gff{vsgf}; // Rotate PDF set into the QCD evolution basis const auto RotPDFs = [=] (double const& x, double const& mu) -> std::map<int,double> { return apfel::PhysToQCDEv(distpdf->xfxQ(x, mu)); }; const auto RotFFs = [=] (double const& x, double const& mu) -> std::map<int,double> { return apfel::PhysToQCDEv(distff->xfxQ(x, mu)); }; // Construct set of distributions as a function of the scale to be // tabulated const auto EvolvedPDFs = [=,&gpdf] (double const& mu) -> apfel::Set<apfel::Distribution> { return apfel::Set<apfel::Distribution>{apfel::EvolutionBasisQCD{apfel::NF(mu, ThresholdsPDF)}, DistributionMap(gpdf, RotPDFs, mu)}; }; const auto EvolvedFFs = [=,&gff] (double const& mu) -> apfel::Set<apfel::Distribution> { return apfel::Set<apfel::Distribution>{apfel::EvolutionBasisQCD{apfel::NF(mu, ThresholdsPDF)}, DistributionMap(gff, RotFFs, mu)}; }; // Tabulate collinear PDFs and FFs const apfel::TabulateObject<apfel::Set<apfel::Distribution>> TabPDFs{EvolvedPDFs, 100, 0.5, distpdf->qMax(), 3, ThresholdsPDF}; const auto CollPDFs = [&] (double const& mu) -> apfel::Set<apfel::Distribution> { return TabPDFs.Evaluate(mu); }; const apfel::TabulateObject<apfel::Set<apfel::Distribution>> TabFFs{EvolvedFFs, 100, 0.5, distff->qMax(), 3, ThresholdsPDF}; const auto CollFFs = [&] (double const& mu) -> apfel::Set<apfel::Distribution> { return TabFFs.Evaluate(mu); }; // Initialize TMD objects const auto TmdObjPDF = apfel::InitializeTmdObjects(gpdf, ThresholdsPDF); const auto TmdObjFF = apfel::InitializeTmdObjects(gff, ThresholdsPDF); // Build evolved TMD PDFs and FFs const auto EvTMDPDFs = BuildTmdPDFs(TmdObjPDF, CollPDFs, AlphasPDF, PerturbativeOrder, Ci); const auto EvTMDFFs = BuildTmdFFs(TmdObjFF, CollFFs, AlphasFF, PerturbativeOrder, Ci); // Functions used for the tabulation const auto TabFunc = [] (double const& b) -> double{ return log(b); }; const auto InvTabFunc = [] (double const& fb) -> double{ return exp(fb); }; // Get report const YAML::Node rep = YAML::LoadFile(FitDirectory + "/replica_" + std::to_string(repnumber) + "/Report.yaml"); // Get parameterisation NangaParbat::Parameterisation* fNP = NangaParbat::GetParametersation(rep["Parameterisation"].as<std::string>()); // Double-exponential quadrature object for the Hankel transform // const apfel::DoubleExponentialQuadrature DEObj{}; const apfel::OgataQuadrature DEObj{0, 1e-9, 0.00001}; // Convolution map to be used for all sets of distributions to // avoid problems with the heavy quark thresholds. const apfel::EvolutionBasisQCD cevb{6}; // Allocate structure function on the four dimensional grid std::vector<std::vector<std::vector<std::vector<double>>>> SFs(fdg.Qg.size(), std::vector<std::vector<std::vector<double>>>(fdg.xg.size(), std::vector<std::vector<double>>(fdg.zg.size(), std::vector<double>(fdg.qToQg.size())))); // Compute structure function to put in grids, fully differential calculation. // At the moment the only SF implemented is FUUT. for (int iQ = 0; iQ < (int) fdg.Qg.size(); iQ++) { const double Q = fdg.Qg[iQ]; // Renormalisation and rapidity scales const double mu = Cf * Q; const double zeta = Q * Q; // EW charges const std::vector<double> Bq = apfel::QCh2; // Number of active flavours at mu const int nf = apfel::NF(mu, ThresholdsPDF); // Define kT-distribution function for direct calculation const std::function<apfel::DoubleObject<apfel::Distribution>(double const&)> Lumib = [=] (double const& bs) -> apfel::DoubleObject<apfel::Distribution> { // Get Evolved TMD PDFs and FFs and rotate them into the physical basis. const std::map<int, apfel::Distribution> xF = QCDEvToPhys(EvTMDPDFs(bs, mu, zeta).GetObjects()); const std::map<int, apfel::Distribution> xD = QCDEvToPhys(EvTMDFFs(bs, mu, zeta).GetObjects()); // Luminosity apfel::DoubleObject<apfel::Distribution> L{}; for (int i = 1; i <= nf; i++) { L.AddTerm({Bq[i-1], xF.at(+i), xD.at(+i)}); L.AddTerm({Bq[i-1], xF.at(-i), xD.at(-i)}); } return L; }; // Perturbative contribution in b-space. We know a priori that // this is enclosed bewteen bmin and bmax. Include an overflow // (and underflow) by a 20% to avoid interpolation problems. const double overflow = 1.2; const double bmin = NangaParbat::bstarmin(0.00001, Q) / overflow; const double bmax = NangaParbat::bstarmin(10, Q) * overflow; const apfel::TabulateObject<apfel::DoubleObject<apfel::Distribution>> tLumib{Lumib, 200, bmin, bmax, 3, {}, TabFunc, InvTabFunc}; for (int ix = 0; ix < (int) fdg.xg.size(); ix++) { const double x = fdg.xg[ix]; for (int iz = 0; iz < (int) fdg.zg.size(); iz++) { const double z = fdg.zg[iz]; // Function in bT space const std::function<double(double const&)> bInt = [=] (double const& b) -> double { double bTintegrand = b * fNP->Evaluate(x, b, zeta, 0) * fNP->Evaluate(z, b, zeta, 1) / z / z * tLumib.EvaluatexzQ(x, z, NangaParbat::bstarmin(b, Q)); return bTintegrand; }; // Transform in qT space and fill grid for (int iqT = 0; iqT < (int) fdg.qToQg.size(); iqT++) { const double qT = Q * fdg.qToQg[iqT]; SFs[iQ][ix][iz][iqT] = DEObj.transform(bInt, qT)/ z / (2 * M_PI); } } } // Report computation status const double perc = 100. * ( iQ + 1 ) / fdg.Qg.size(); std::cout << "Status report for the structure function grid computation: "<< std::setw(6) << std::setprecision(4) << perc << "\% completed...\r"; std::cout.flush(); } std::cout << "\n"; // Dump grids to emitter std::unique_ptr<YAML::Emitter> out = std::unique_ptr<YAML::Emitter>(new YAML::Emitter); out->SetFloatPrecision(6); out->SetDoublePrecision(6); *out << YAML::BeginMap; *out << YAML::Key << "Qg" << YAML::Value << YAML::Flow << fdg.Qg; *out << YAML::Key << "xg" << YAML::Value << YAML::Flow << fdg.xg; *out << YAML::Key << "zg" << YAML::Value << YAML::Flow << fdg.zg; *out << YAML::Key << "qToQg" << YAML::Value << YAML::Flow << fdg.qToQg; *out << YAML::Key << "StructureFunction" << YAML::Value << YAML::Flow << SFs; *out << YAML::EndMap; // Stop timer t.stop(); // Return the emitter return out; } //_________________________________________________________________________________ std::unique_ptr<YAML::Emitter> EmitStructInfo(std::string const& GridsDirectory, std::string const& GridTMDPDFfolder, std::string const& GridTMDFFfolder, YAML::Node const& config, int const& NumMembers, std::string const& pf, FourDGrid const& fdg, std::vector<int> const& Flavors, std::string const& SetDesc, std::string const& Target, std::string const& Hadron, std::string const& Authors, std::string const& Reference, std::string const& SetIndex, std::string const& Format, std::string const& DataVersion, std::string const& ErrorType) { // Allocate YAML emitter std::unique_ptr<YAML::Emitter> out = std::unique_ptr<YAML::Emitter>(new YAML::Emitter); //Info file for TMDPDFs const YAML::Node pdfinfo = YAML::LoadFile(GridsDirectory + "/" + GridTMDPDFfolder + "/" + GridTMDPDFfolder + ".info"); //Info file for TMDFFs const YAML::Node ffinfo = YAML::LoadFile(GridsDirectory + "/" + GridTMDFFfolder + "/" + GridTMDFFfolder + ".info"); // FF distribution for final state hadron name const std::string ffdist = ffinfo["CollDist"].as<std::string>(); // Dump grids to emitter out->SetFloatPrecision(8); out->SetDoublePrecision(8); *out << YAML::BeginMap; *out << YAML::Key << "SetDesc" << YAML::Value << SetDesc; *out << YAML::Key << "Authors" << YAML::Value << Authors; *out << YAML::Key << "Reference" << YAML::Value << Reference; *out << YAML::Key << "SetIndex" << YAML::Value << SetIndex; *out << YAML::Key << "StructFuncType" << YAML::Value << pf; *out << YAML::Key << "TMDScheme" << YAML::Value << "Pavia SFs"; *out << YAML::Key << "Target" << YAML::Value << Target; // *out << YAML::Key << "FinalStateHadron" << YAML::Value << Hadron; *out << YAML::Key << "FinalStateHadron" << YAML::Value << ffdist.substr(ffdist.size() - 3, 3); *out << YAML::Key << "TMDPDF" << YAML::Value << pdfinfo["SetName"].as<std::string>(); *out << YAML::Key << "TMDFF" << YAML::Value << ffinfo["SetName"].as<std::string>(); *out << YAML::Key << "Format" << YAML::Value << Format; *out << YAML::Key << "DataVersion" << YAML::Value << DataVersion; *out << YAML::Key << "OrderQCD" << YAML::Value << pdfinfo["OrderQCD"].as<std::string>(); *out << YAML::Key << "NumMembers" << YAML::Value << NumMembers; *out << YAML::Key << "ErrorType" << YAML::Value << ErrorType; *out << YAML::Key << "NumFlavors" << YAML::Value << std::round(Flavors.size() / 2); *out << YAML::Key << "XMin" << YAML::Value << fdg.xg[0]; *out << YAML::Key << "XMax" << YAML::Value << fdg.xg.back(); *out << YAML::Key << "ZMin" << YAML::Value << fdg.zg[0]; *out << YAML::Key << "ZMax" << YAML::Value << fdg.zg.back(); *out << YAML::Key << "QMin" << YAML::Value << fdg.Qg[0]; *out << YAML::Key << "QMax" << YAML::Value << fdg.Qg.back(); *out << YAML::Key << "KtoQMin" << YAML::Value << fdg.qToQg[0]; *out << YAML::Key << "KtoQMax" << YAML::Value << fdg.qToQg.back(); *out << YAML::EndMap; // Return the emitter return out; } }
47.649667
167
0.540717
[ "object", "vector", "transform" ]
063fb9fb671613335943ef761dd68f63a1fd32e2
6,804
cpp
C++
implementations/ugene/src/corelibs/U2Algorithm/src/misc/FindAlgorithmTask.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/ugene/src/corelibs/U2Algorithm/src/misc/FindAlgorithmTask.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/ugene/src/corelibs/U2Algorithm/src/misc/FindAlgorithmTask.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2020 UniPro <ugene@unipro.ru> * http://ugene.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "FindAlgorithmTask.h" #include <QTextStream> #include <U2Core/AppContext.h> #include <U2Core/AppResources.h> #include <U2Core/BaseDocumentFormats.h> #include <U2Core/Counter.h> #include <U2Core/DNASequenceObject.h> #include <U2Core/DNATranslation.h> #include <U2Core/DocumentModel.h> #include <U2Core/DocumentUtils.h> #include <U2Core/IOAdapterUtils.h> #include <U2Core/ProjectModel.h> #include <U2Core/TextUtils.h> #include <U2Core/U2SafePoints.h> namespace U2 { class StrandContext; FindAlgorithmTask::FindAlgorithmTask(const FindAlgorithmTaskSettings &s) : Task(tr("Find in sequence task"), TaskFlag_None), config(s) { if (s.countTask) { GCOUNTER(cvar, tvar, "FindAlgorithmTask"); } tpm = Progress_Manual; assert(config.strand == FindAlgorithmStrand_Direct || config.complementTT != NULL); addTaskResource(TaskResourceUsage(RESOURCE_MEMORY, FindAlgorithm::estimateRamUsageInMbytes(config.patternSettings, config.proteinTT != NULL, config.pattern.length(), config.maxErr), true)); } void FindAlgorithmTask::run() { FindAlgorithm::find(dynamic_cast<FindAlgorithmResultsListener *>(this), config.proteinTT, config.complementTT, config.strand, config.patternSettings, config.useAmbiguousBases, config.sequence.constData(), config.sequence.size(), config.sequenceAlphabet, config.searchIsCircular, config.searchRegion, config.pattern.constData(), config.pattern.length(), config.maxErr, config.maxRegExpResultLength, stateInfo.cancelFlag, stateInfo.progress); } void FindAlgorithmTask::onResult(const FindAlgorithmResult &r) { if (r.err == FindAlgorithmResult::NOT_ENOUGH_MEMORY_ERROR) { stateInfo.cancelFlag = true; const QString error = "Pattern is too big. Not enough memory."; taskLog.error(error); return; } if (config.maxResult2Find != FindAlgorithmSettings::MAX_RESULT_TO_FIND_UNLIMITED && newResults.size() >= config.maxResult2Find) { stateInfo.cancelFlag = true; return; } if (stateInfo.isCoR()) { return; } lock.lock(); newResults.append(r); lock.unlock(); } QList<FindAlgorithmResult> FindAlgorithmTask::popResults() { lock.lock(); QList<FindAlgorithmResult> res = newResults; newResults.clear(); lock.unlock(); return res; } ////////////////////////////////////////////////////////////////////////// //LoadPatternsFileTask LoadPatternsFileTask::LoadPatternsFileTask(const QString &_filePath, const QString &_annotationName) : Task(tr("Load pattern from file"), TaskFlag_None), filePath(_filePath), isRawSequence(false), annotationName(_annotationName) { } Document *LoadPatternsFileTask::getDocumentFromFilePath() { // loading new document here and not reusing any loaded from the project // because a document in the project may be opened in 'merge' mode. QList<FormatDetectionResult> formats = DocumentUtils::detectFormat(filePath); if (formats.isEmpty()) { stateInfo.setError(tr("Detecting format error for file %1").arg(filePath)); return NULL; } DocumentFormat *format = formats.first().format; if (format->getFormatId() == BaseDocumentFormats::RAW_DNA_SEQUENCE) { isRawSequence = true; return NULL; } Q_ASSERT(format); GUrl fileUrl(filePath); IOAdapterFactory *iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(IOAdapterUtils::url2io(fileUrl)); QVariantMap hints; Document *doc = format->loadDocument(iof, fileUrl, hints, stateInfo); CHECK_OP(stateInfo, NULL); return doc; } void LoadPatternsFileTask::run() { typedef QPair<QString, QString> NamePattern; Document *doc = getDocumentFromFilePath(); if (doc != NULL && !isRawSequence) { const QList<GObject *> &objectsFromDoc = doc->findGObjectByType(GObjectTypes::SEQUENCE); foreach (GObject *object, objectsFromDoc) { U2SequenceObject *sequenceObject = qobject_cast<U2SequenceObject *>(object); assert(sequenceObject != NULL); QByteArray sequence = sequenceObject->getWholeSequenceData(stateInfo); CHECK_OP(stateInfo, ); QString seqName = sequenceObject->getSequenceName(); if (annotationName.isEmpty()) { namesPatterns.append(qMakePair(seqName, QString(sequence))); } else { namesPatterns.append(qMakePair(annotationName, QString(sequence))); } } } else { QFile file(filePath); if (!file.open(QIODevice::ReadOnly)) { setError(QString("Cannot open a file: %1").arg(filePath)); } QTextStream stream(&file); int fileSize = file.size(); while (!stream.atEnd() && !stateInfo.cancelFlag) { int streamPos = stream.device()->pos(); stateInfo.progress = 100 * streamPos / fileSize; QString pattern = stream.readLine(); if (!pattern.isEmpty()) { bool contains = false; foreach (const NamePattern &namePattern, namesPatterns) { if (namePattern.second == pattern) { contains = true; break; } } if (!contains) { namesPatterns.append(qMakePair("pattern" + QString::number(namesPatterns.size() + 1), pattern)); } } } file.close(); } } } // namespace U2
36.385027
168
0.623751
[ "object" ]
0644a1e1446086ba5e869083f13406a4de926601
4,302
cxx
C++
examples/Applications/ComputeTubeProbability/ComputeTubeProbability.cxx
kian-weimer/ITKTubeTK
88da3195bfeca017745e7cddfe04f82571bd00ee
[ "Apache-2.0" ]
27
2020-04-06T17:23:22.000Z
2022-03-02T13:25:52.000Z
examples/Applications/ComputeTubeProbability/ComputeTubeProbability.cxx
kian-weimer/ITKTubeTK
88da3195bfeca017745e7cddfe04f82571bd00ee
[ "Apache-2.0" ]
14
2020-04-09T00:23:15.000Z
2022-02-26T13:02:35.000Z
examples/Applications/ComputeTubeProbability/ComputeTubeProbability.cxx
kian-weimer/ITKTubeTK
88da3195bfeca017745e7cddfe04f82571bd00ee
[ "Apache-2.0" ]
14
2020-04-03T03:56:14.000Z
2022-01-14T07:51:32.000Z
/*========================================================================= Library: TubeTK Copyright Kitware Inc. All rights reserved. Licensed under the Apache License, Version 2.0 ( the "License" ); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ #include "../CLI/tubeCLIProgressReporter.h" #include "tubeMessage.h" #include <itkImageFileReader.h> #include <itkSpatialObjectReader.h> // Must include CLP before including tubeCLIHelperFunctions #include "ComputeTubeProbabilityCLP.h" // This needs to be declared for tubeCLIHelperFunctions. template< class TPixel, unsigned int VDimension > int DoIt( int itkNotUsed( argc ), char * itkNotUsed( argv )[] ); #include "../CLI/tubeCLIHelperFunctions.h" template< class TPixel, unsigned int VDimension > int DoIt( int argc, char * argv[] ) { PARSE_ARGS; typedef itk::Image< TPixel, VDimension > ImageType; typedef itk::GroupSpatialObject< VDimension > GroupType; typedef itk::ImageFileReader< ImageType > ImageReaderType; typedef itk::SpatialObjectReader< VDimension > SOReaderType; typedef itk::TubeSpatialObject< VDimension > TubeType; typedef typename TubeType::TubePointType TubePointType; tube::CLIProgressReporter progressReporter( "tubeDensityProbability", CLPProcessInformation ); progressReporter.Start(); /* * Read in spatial object file ( tubes ) */ typename SOReaderType::Pointer soReader = SOReaderType::New(); soReader->SetFileName( inTubeFile.c_str() ); soReader->Update(); typename GroupType::Pointer group = soReader->GetGroup(); progressReporter.Report( 0.1 ); /* * Read in ATLAS EMD image */ typename ImageReaderType::Pointer imReader = ImageReaderType::New(); imReader->SetFileName( inMeanImageFile.c_str() ); imReader->Update(); typename ImageType::Pointer meanImage = imReader->GetOutput(); progressReporter.Report( 0.2 ); char childName[] = "Tube"; typename TubeType::ChildrenListType * tubeList = group->GetChildren( group->GetMaximumDepth(), childName ); typename TubeType::ChildrenListType::const_iterator tubeIt = tubeList->begin(); TubePointType tubePoint; std::ofstream writeStream; writeStream.open( outFile.c_str(), std::ios::binary | std::ios::out ); while( tubeIt != tubeList->end() ) // Iterate over tubes { typename TubeType::Pointer tube = dynamic_cast<TubeType *>( ( *tubeIt ).GetPointer() ); tube->RemoveDuplicatePointsInObjectSpace(); tube->ComputeTangentsAndNormals(); itk::Point<double, VDimension> pnt; itk::Index< VDimension > indx; tube->Update(); for( unsigned int i=0; i<tube->GetNumberOfPoints(); i++ ) { // Get point tubePoint = static_cast<TubePointType>( tube->GetPoints()[i] ); // Get point's position pnt = tubePoint.GetPositionInWorldSpace(); // Get closest voxel meanImage->TransformPhysicalPointToIndex( pnt, indx ); // Write value of ATLAS EMD file at voxel writeStream << meanImage->GetPixel( indx ) << std::endl; } ++tubeIt; } writeStream.close(); delete tubeList; progressReporter.Report( 1.0 ); progressReporter.End(); return EXIT_SUCCESS; } int main( int argc, char * argv[] ) { PARSE_ARGS; itk::ImageIOBase::IOComponentEnum componentType; try { unsigned int dimension; tube::GetImageInformation( inMeanImageFile, componentType, dimension ); switch( dimension ) { case 2: return DoIt< short, 2 >( argc, argv ); case 3: return DoIt< short, 3 >( argc, argv ); default: return EXIT_FAILURE; } } catch( const std::exception & exception ) { tube::ErrorMessage( exception.what() ); return EXIT_FAILURE; } return EXIT_FAILURE; }
28.872483
75
0.669921
[ "object" ]
0648eb69a209a47c5eeb450d5c5c30fffa64e227
15,154
cpp
C++
qcom_msm8916_64_android5.0/sources/twrp/bootable/recovery/fixPermissions.cpp
largeriver/twrp
767b63ed5e0763538466569984cf7930d9c59921
[ "MIT" ]
null
null
null
qcom_msm8916_64_android5.0/sources/twrp/bootable/recovery/fixPermissions.cpp
largeriver/twrp
767b63ed5e0763538466569984cf7930d9c59921
[ "MIT" ]
null
null
null
qcom_msm8916_64_android5.0/sources/twrp/bootable/recovery/fixPermissions.cpp
largeriver/twrp
767b63ed5e0763538466569984cf7930d9c59921
[ "MIT" ]
null
null
null
/* Copyright 2012 bigbiff/Dees_Troy TeamWin This file is part of TWRP/TeamWin Recovery Project. TWRP is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. TWRP 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 TWRP. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <string.h> #include <libgen.h> #include <unistd.h> #include <sys/stat.h> #include <dirent.h> #include <errno.h> #include "gui/rapidxml.hpp" #include "fixPermissions.hpp" #include "twrp-functions.hpp" #include "twcommon.h" #ifdef HAVE_SELINUX #include "selinux/selinux.h" #include "selinux/label.h" #include "selinux/android.h" #include "selinux/label.h" #endif using namespace std; using namespace rapidxml; static const mode_t kMode_0600 = 0600; // S_IRUSR | S_IWUSR static const mode_t kMode_0640 = 0640; // S_IRUSR | S_IWUSR | S_IRGRP static const mode_t kMode_0644 = 0644; // S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH static const mode_t kMode_0660 = 0660; // S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP static const mode_t kMode_0755 = 0755; // S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH static const mode_t kMode_0771 = 0771; // S_IRWXU | S_IRWXG | S_IXOTH fixPermissions::fixPermissions() : head(NULL) { } fixPermissions::~fixPermissions() { deletePackages(); } #ifdef HAVE_SELINUX struct selabel_handle *sehandle; struct selinux_opt selinux_options[] = { { SELABEL_OPT_PATH, "/file_contexts" } }; int fixPermissions::restorecon(string entry, struct stat *sb) { char *oldcontext, *newcontext; if (lgetfilecon(entry.c_str(), &oldcontext) < 0) { LOGINFO("Couldn't get selinux context for %s\n", entry.c_str()); return -1; } if (selabel_lookup(sehandle, &newcontext, entry.c_str(), sb->st_mode) < 0) { LOGINFO("Couldn't lookup selinux context for %s\n", entry.c_str()); return -1; } if (strcmp(oldcontext, newcontext) != 0) { LOGINFO("Relabeling %s from %s to %s\n", entry.c_str(), oldcontext, newcontext); if (lsetfilecon(entry.c_str(), newcontext) < 0) { LOGINFO("Couldn't label %s with %s: %s\n", entry.c_str(), newcontext, strerror(errno)); } } freecon(oldcontext); freecon(newcontext); return 0; } int fixPermissions::fixDataDataContexts(void) { string dir = "/data/data/"; sehandle = selabel_open(SELABEL_CTX_FILE, selinux_options, 1); if (!sehandle) { LOGINFO("Unable to open /file_contexts\n"); return 0; } if (TWFunc::Path_Exists(dir)) { fixContextsRecursively(dir, 0); } selabel_close(sehandle); return 0; } int fixPermissions::fixContextsRecursively(string name, int level) { DIR *d; struct dirent *de; struct stat sb; string path; if (!(d = opendir(name.c_str()))) return -1; if (!(de = readdir(d))) return -1; do { if (de->d_type == DT_DIR) { if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0) continue; path = name + "/" + de->d_name; restorecon(path, &sb); fixContextsRecursively(path, level + 1); } else { path = name + "/" + de->d_name; restorecon(path, &sb); } } while ((de = readdir(d))); closedir(d); return 0; } int fixPermissions::fixDataInternalContexts(void) { DIR *d; struct dirent *de; struct stat sb; string dir, androiddir; sehandle = selabel_open(SELABEL_CTX_FILE, selinux_options, 1); if (!sehandle) { LOGINFO("Unable to open /file_contexts\n"); return 0; } // TODO: what about /data/media/1 etc.? if (TWFunc::Path_Exists("/data/media/0")) dir = "/data/media/0"; else dir = "/data/media"; if (!TWFunc::Path_Exists(dir)) { LOGINFO("fixDataInternalContexts: '%s' does not exist!\n", dir.c_str()); return 0; } LOGINFO("Fixing %s contexts\n", dir.c_str()); restorecon(dir, &sb); d = opendir(dir.c_str()); while (( de = readdir(d)) != NULL) { stat(de->d_name, &sb); string f; f = dir + "/" + de->d_name; restorecon(f, &sb); } closedir(d); androiddir = dir + "/Android/"; if (TWFunc::Path_Exists(androiddir)) { fixContextsRecursively(androiddir, 0); } selabel_close(sehandle); return 0; } #endif int fixPermissions::fixPerms(bool enable_debug, bool remove_data_for_missing_apps) { string packageFile = "/data/system/packages.xml"; debug = enable_debug; remove_data = remove_data_for_missing_apps; bool multi_user = TWFunc::Path_Exists("/data/user"); if (!(TWFunc::Path_Exists(packageFile))) { gui_print("Can't check permissions\n"); gui_print("after Factory Reset.\n"); gui_print("Please boot rom and try\n"); gui_print("again after you reboot into\n"); gui_print("recovery.\n"); return -1; } gui_print("Fixing permissions...\nLoading packages...\n"); if ((getPackages(packageFile)) != 0) { return -1; } gui_print("Fixing app permissions...\n"); if (fixApps() != 0) { return -1; } if (multi_user) { DIR *d = opendir("/data/user"); string new_path, user_id; if (d == NULL) { LOGERR("Error opening '/data/user'\n"); return -1; } if (d) { struct dirent *p; while ((p = readdir(d))) { if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, "..")) continue; new_path = "/data/user/"; new_path.append(p->d_name); user_id = "u"; user_id += p->d_name; user_id += "_"; if (p->d_type == DT_LNK) { char link[512], realPath[512]; strcpy(link, new_path.c_str()); memset(realPath, 0, sizeof(realPath)); while (readlink(link, realPath, sizeof(realPath)) > 0) { strcpy(link, realPath); memset(realPath, 0, sizeof(realPath)); } new_path = link; } else if (p->d_type != DT_DIR) { continue; } else { new_path.append("/"); // We're probably going to need to fix permissions on multi user but // it will have to wait for another time. Need to figure out where // the uid and gid is stored for other users. continue; } gui_print("Fixing %s permissions...\n", new_path.c_str()); if ((fixDataData(new_path)) != 0) { closedir(d); return -1; } } closedir(d); } } else { gui_print("Fixing /data/data permissions...\n"); if ((fixDataData("/data/data/")) != 0) { return -1; } } gui_print("Done fixing permissions.\n"); return 0; } int fixPermissions::fixContexts() { #ifdef HAVE_SELINUX gui_print("Fixing /data/data/ contexts.\n"); fixDataDataContexts(); fixDataInternalContexts(); gui_print("Done fixing contexts.\n"); return 0; #endif gui_print("Not fixing SELinux contexts; support not compiled in.\n"); return -1; } int fixPermissions::pchown(string fn, int puid, int pgid) { LOGINFO("Fixing %s, uid: %d, gid: %d\n", fn.c_str(), puid, pgid); if (chown(fn.c_str(), puid, pgid) != 0) { LOGERR("Unable to chown '%s' %i %i\n", fn.c_str(), puid, pgid); return -1; } return 0; } int fixPermissions::pchmod(string fn, mode_t mode) { LOGINFO("Fixing %s, mode: %o\n", fn.c_str(), mode); if (chmod(fn.c_str(), mode) != 0) { LOGERR("Unable to chmod '%s' %o\n", fn.c_str(), mode); return -1; } return 0; } int fixPermissions::fixApps() { package* temp = head; while (temp != NULL) { struct stat st; if (stat(temp->codePath.c_str(), &st) == 0) { int new_uid = 0; int new_gid = 0; mode_t perms = 0; bool fix = false; if (temp->appDir.compare("/system/app") == 0 || temp->appDir.compare("/system/priv-app") == 0) { fix = true; new_uid = 0; new_gid = 0; perms = kMode_0644; } else if (temp->appDir.compare("/data/app") == 0 || temp->appDir.compare("/sd-ext/app") == 0) { fix = true; new_uid = 1000; new_gid = 1000; perms = kMode_0644; } else if (temp->appDir.compare("/data/app-private") == 0 || temp->appDir.compare("/sd-ext/app-private") == 0) { fix = true; new_uid = 1000; new_gid = temp->gid; perms = kMode_0640; } else fix = false; if (fix) { if (debug) { LOGINFO("Looking at '%s'\n", temp->codePath.c_str()); LOGINFO("Fixing permissions on '%s'\n", temp->pkgName.c_str()); LOGINFO("Directory: '%s'\n", temp->appDir.c_str()); LOGINFO("Original package owner: %d, group: %d\n", temp->uid, temp->gid); } if (S_ISDIR(st.st_mode)) { // Android 5.0 introduced codePath pointing to a directory instead of the apk itself // TODO: check what this should do if (fixDir(temp->codePath, new_uid, new_gid, kMode_0755, new_uid, new_gid, perms) != 0) return -1; } else { if (pchown(temp->codePath, new_uid, new_gid) != 0) return -1; if (pchmod(temp->codePath, perms) != 0) return -1; } } } else if (remove_data) { //Remove data directory since app isn't installed string datapath = "/data/data/" + temp->dDir; if (TWFunc::Path_Exists(datapath) && temp->appDir.size() >= 9 && temp->appDir.substr(0, 9) != "/mnt/asec") { if (debug) LOGINFO("Looking at '%s', removing data dir: '%s', appDir: '%s'", temp->codePath.c_str(), datapath.c_str(), temp->appDir.c_str()); if (TWFunc::removeDir(datapath, false) != 0) { LOGINFO("Unable to removeDir '%s'\n", datapath.c_str()); return -1; } } } temp = temp->next; } return 0; } int fixPermissions::fixAllFiles(string directory, int uid, int gid, mode_t file_perms) { vector <string> files; string file; files = listAllFiles(directory); for (unsigned i = 0; i < files.size(); ++i) { file = directory + "/"; file.append(files.at(i)); if (debug) LOGINFO("Looking at file '%s'\n", file.c_str()); if (pchmod(file, file_perms) != 0) return -1; if (pchown(file, uid, gid) != 0) return -1; } return 0; } int fixPermissions::fixDir(const string& dir, int diruid, int dirgid, mode_t dirmode, int fileuid, int filegid, mode_t filemode) { if (pchmod(dir.c_str(), dirmode) != 0) return -1; if (pchown(dir.c_str(), diruid, dirgid) != 0) return -1; if (fixAllFiles(dir, fileuid, filegid, filemode) != 0) return -1; return 0; } int fixPermissions::fixDataData(string dataDir) { package* temp = head; while (temp != NULL) { string dir = dataDir + temp->dDir; if (TWFunc::Path_Exists(dir)) { vector <string> dataDataDirs = listAllDirectories(dir); for (unsigned n = 0; n < dataDataDirs.size(); ++n) { string directory = dir + "/"; directory.append(dataDataDirs.at(n)); if (debug) LOGINFO("Looking at data directory: '%s'\n", directory.c_str()); if (dataDataDirs.at(n) == ".") { if (fixDir(directory, temp->uid, temp->gid, kMode_0755, temp->uid, temp->gid, kMode_0755) != 0) return -1; } else if (dataDataDirs.at(n) == "..") { if (debug) LOGINFO("Skipping ..\n"); continue; } // TODO: when any of these fails, do we really want to stop everything? else if (dataDataDirs.at(n) == "lib") { if (fixDir(directory, 1000, 1000, kMode_0755, 1000, 1000, kMode_0755) != 0) return -1; } else if (dataDataDirs.at(n) == "shared_prefs") { if (fixDir(directory, temp->uid, temp->gid,kMode_0771, temp->uid, temp->gid, kMode_0660) != 0) return -1; } else if (dataDataDirs.at(n) == "databases") { if (fixDir(directory, temp->uid, temp->gid,kMode_0771, temp->uid, temp->gid, kMode_0660) != 0) return -1; } else if (dataDataDirs.at(n) == "cache") { if (fixDir(directory, temp->uid, temp->gid,kMode_0771, temp->uid, temp->gid, kMode_0600) != 0) return -1; } else { if (fixDir(directory, temp->uid, temp->gid,kMode_0771, temp->uid, temp->gid, kMode_0755) != 0) return -1; } } } temp = temp->next; } return 0; } // TODO: merge to listAllDirEntries(path, type) vector <string> fixPermissions::listAllDirectories(string path) { DIR *dir = opendir(path.c_str()); vector <string> dirs; if (dir == NULL) { LOGERR("Error opening '%s'\n", path.c_str()); return dirs; } struct dirent *entry = readdir(dir); while (entry != NULL) { if (entry->d_type == DT_DIR) dirs.push_back(entry->d_name); entry = readdir(dir); } closedir(dir); return dirs; } vector <string> fixPermissions::listAllFiles(string path) { DIR *dir = opendir(path.c_str()); vector <string> files; if (dir == NULL) { LOGERR("Error opening '%s'\n", path.c_str()); return files; } struct dirent *entry = readdir(dir); while (entry != NULL) { if (entry->d_type == DT_REG) files.push_back(entry->d_name); entry = readdir(dir); } closedir(dir); return files; } void fixPermissions::deletePackages() { while (head) { package* temp = head; head = temp->next; delete temp; } } int fixPermissions::getPackages(const string& packageFile) { deletePackages(); head = NULL; // TODO: simply skip all packages in /system/framework? or why are these excluded? vector <string> skip; skip.push_back("/system/framework/framework-res.apk"); skip.push_back("/system/framework/com.htc.resources.apk"); ifstream xmlFile(packageFile.c_str()); xmlFile.seekg(0, ios::end); int len = (int) xmlFile.tellg(); xmlFile.seekg(0, ios::beg); vector<char> xmlBuf(len + 1); xmlFile.read(&xmlBuf[0], len); xmlBuf[len] = '\0'; xml_document<> pkgDoc; LOGINFO("Parsing packages.xml, size=%i...\n", len); pkgDoc.parse<parse_full>(&xmlBuf[0]); xml_node<> * pkgNode = pkgDoc.first_node("packages"); if (pkgNode == NULL) { LOGERR("No packages found to fix.\n"); return -1; } // Get packages for (xml_node<>* node = pkgNode->first_node(); node; node = node->next_sibling()) { if (node->type() != node_element) continue; string elementName = node->name(); // we want <package> and <updated-package> if (!(elementName == "package" || elementName == "updated-package")) continue; xml_attribute<>* attName = node->first_attribute("name"); if (!attName) continue; string name = attName->value(); xml_attribute<>* attCodePath = node->first_attribute("codePath"); if (!attCodePath) { LOGINFO("No codePath on %s, skipping.\n", name.c_str()); continue; } string codePath = attCodePath->value(); bool doskip = std::find(skip.begin(), skip.end(), codePath) != skip.end(); if (doskip) { if (debug) LOGINFO("Skipping package %s\n", codePath.c_str()); continue; } if (debug) LOGINFO("Loading pkg: %s\n", name.c_str()); package* temp = new package; temp->pkgName = name; temp->codePath = codePath; temp->appDir = codePath; temp->dDir = name; xml_attribute<>* attUserId = node->first_attribute("userId"); if (!attUserId) attUserId = node->first_attribute("sharedUserId"); if (!attUserId) { LOGINFO("Problem with userID on %s\n", name.c_str()); } else { temp->uid = atoi(attUserId->value()); temp->gid = atoi(attUserId->value()); } temp->next = head; head = temp; } if (head == NULL) { LOGERR("No package found to fix.\n"); return -1; } return 0; }
27.602914
135
0.643328
[ "vector" ]
064e2e33e2e43f31afce5fc3df93c797c40108c2
2,528
cpp
C++
src/Auxiliary/Aux_GetCPUInfo.cpp
CliffLinTw/gamer
6974d0b19133f253f2b867542f97b2acf1e9d756
[ "BSD-3-Clause" ]
3
2019-01-26T10:38:01.000Z
2019-10-17T01:57:25.000Z
src/Auxiliary/Aux_GetCPUInfo.cpp
wt-liao/gamer_cyl
8f3a15216391c6bcb22b5a7769aac3d1ff9bf3c3
[ "BSD-3-Clause" ]
null
null
null
src/Auxiliary/Aux_GetCPUInfo.cpp
wt-liao/gamer_cyl
8f3a15216391c6bcb22b5a7769aac3d1ff9bf3c3
[ "BSD-3-Clause" ]
null
null
null
#include "GAMER.h" //------------------------------------------------------------------------------------------------------- // Function : Aux_GetCPUInfo // Description : Record the CPU information // // Parameter : FileName : Name of the output file //------------------------------------------------------------------------------------------------------- void Aux_GetCPUInfo( const char *FileName ) { FILE *Note = fopen( FileName, "a" ); char *line = NULL; size_t len = 0; char String[2][100]; // 1. get the CPU info const char *CPUInfo_Path = "/proc/cpuinfo"; if ( !Aux_CheckFileExist(CPUInfo_Path) ) { Aux_Message( stderr, "WARNING : CPU information file \"%s\" does not exist !!\n", CPUInfo_Path ); return; } FILE *CPUInfo = fopen( CPUInfo_Path, "r" ); while ( getline(&line, &len, CPUInfo) != -1 ) { sscanf( line, "%s%s", String[0], String[1] ); if ( strcmp( String[0], "model" ) == 0 && strcmp( String[1], "name" ) == 0 ) { strncpy( line, "CPU Type ", 10 ); fprintf( Note, "%s", line ); } if ( strcmp( String[0], "cpu" ) == 0 && strcmp( String[1], "MHz" ) == 0 ) { strncpy( line, "CPU MHz", 7 ); fprintf( Note, "%s", line ); } if ( strcmp( String[0], "cache" ) == 0 && strcmp( String[1], "size" ) == 0 ) { strncpy( line, "Cache Size", 10 ); fprintf( Note, "%s", line ); } if ( strcmp( String[0], "cpu" ) == 0 && strcmp( String[1], "cores" ) == 0 ) { strncpy( line, "CPU Cores", 9 ); fprintf( Note, "%s", line ); break; } } if ( line != NULL ) { free( line ); line = NULL; } fclose( CPUInfo ); // 2. get the memory info const char *MemInfo_Path = "/proc/meminfo"; if ( !Aux_CheckFileExist(MemInfo_Path) ) { Aux_Message( stderr, "WARNING : memory information file \"%s\" does not exist !!\n", MemInfo_Path ); return; } FILE *MemInfo = fopen( MemInfo_Path, "r" ); while ( getline(&line, &len, MemInfo) != -1 ) { sscanf( line, "%s%s", String[0], String[1] ); if ( strncmp( String[0], "MemTotal", 8 ) == 0 ) { fprintf( Note, "Total Memory : %4.1f GB\n", atof( String[1] )/(1<<20) ); break; } } if ( line != NULL ) { free( line ); line = NULL; } fclose( MemInfo ); fclose( Note ); } // FUNCTION : Aux_GetCPUInfo
24.543689
106
0.457278
[ "model" ]
065682e85a3c60be55b4eb1ee67c7942e835acf2
9,261
cpp
C++
src/primekeys.cpp
coinkeeper/2015-06-22_18-53_paycoin
e6b00068766c49b9908d691ee47de46302221bb2
[ "MIT" ]
null
null
null
src/primekeys.cpp
coinkeeper/2015-06-22_18-53_paycoin
e6b00068766c49b9908d691ee47de46302221bb2
[ "MIT" ]
null
null
null
src/primekeys.cpp
coinkeeper/2015-06-22_18-53_paycoin
e6b00068766c49b9908d691ee47de46302221bb2
[ "MIT" ]
null
null
null
// Copyright (c) 2015 The Paycoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "primekeys.h" #include "script.h" std::vector<std::string> pubKeyList350; std::vector<std::string> pubKeyList100; std::vector<std::string> pubKeyList20; std::vector<std::string> pubKeyList10; bool pubKeyListsInitialized = false; void getPrimePubKeyList(unsigned char primeType, std::vector<std::string> &pubKeyList, int &primeNodeRate) { if (!pubKeyListsInitialized) initPrimePubKeyLists(); switch (primeType) { case OP_PRIMENODE350: primeNodeRate = 350; pubKeyList = pubKeyList350; break; case OP_PRIMENODE100: primeNodeRate = 100; pubKeyList = pubKeyList100; break; case OP_PRIMENODE20: primeNodeRate = 20; pubKeyList = pubKeyList20; break; case OP_PRIMENODE10: primeNodeRate = 10; pubKeyList = pubKeyList10; break; } } void initPrimePubKeyLists() { pubKeyListsInitialized = true; pubKeyList350.push_back("0427096f2e3123970010d97a1f0e210499435482927b12b1d6a209f0c383e03b444a244e372cad494c144b47ac3686fc4feea2aec2df3ba77f41cc27dbf8f3c4ff"); pubKeyList350.push_back("04d96b945eca3ea23e1dfd414d2a4772c66e6c7297d0d4f88b7a3b7c285931c36f16ef26299704d49bda770621d9145d96365e02380b4329aceafe7b81012bef48"); pubKeyList350.push_back("040057901e3de5e6429912047c2b5175dde2586b981397a0e434d43accf2e49c108fb3361b3957fcbbfa39930d50aeff56c690e91ffb2d953eefa46aa50fcb6917"); pubKeyList350.push_back("0486022d6dd5c8d17c411cf28add879e5c738b64090e83a43cca1699ececdb8f3524379aa71bb76a2af2d7e8294c9d7b8179d98215afe589c921e4507f63c5c802"); pubKeyList350.push_back("0436639ad108f7630881fb3af5f540ded3bb4653dab695f1716e71ea5838bcee7c238fa624bc2f1bfe0990cea4c3ee3e9f949bbc61e347b5887815eb51468b5c88"); pubKeyList350.push_back("04d04183c8caad2f41edffbabd5b6a266e886457ef0621283b3418979d841bc2425e6b273ce0ea2b461b9797a7d3edd74a4407af9995a9702018cf69df8eee6aba"); pubKeyList350.push_back("04a8b4a8c55361f37cad732da49b2bccadb9be522dd84f9c2329a7dbfaac8c5dd093b803d791719c413196694c97fcb360b7935034dcc4b1b3c2e45a39e67b8dd6"); pubKeyList350.push_back("04b7930cd8bda83097841cfa0a2b5317ecc029a512bbf056a130421ee500773f16850f74e2cbffa4e8aa2a0b0a25009ea619e49839e8608db4469de285d6ee781d"); pubKeyList350.push_back("04d0e3e0e688659d07d4510e25a9884c12931e581b8a2bcdd8ad6c4362ae219b08089761e88e17109aa6618dfca152f854e880ca66414d7f8e5d1d95e70dc95dee"); pubKeyList350.push_back("04025f944a31226086da4f0f49188bfe12d29a304986d909b00560a5f8c84c09ab0f6d0e16926d42a07eaa522dad74404ef25ca863fbd78d45ecdb6da282caf9da"); pubKeyList350.push_back("04983ebed643535907ebbea93387ca38c262778d21dab385f0d0c5dc49b66ebe54c27d9e318ea2798800a067dc3ad8e414684d477e7633f261b08522a0f81b3c5e"); pubKeyList350.push_back("04512b7f555a89e73cd1f9d5138d8e46b81c49a184e0cb7b538167e046dea93689101f076c59874c085642b33b2ad58ff1dee34ffa1d03880c0272686291bd64b5"); pubKeyList350.push_back("045f46a60dd9c3c3e68a127aee68a4ad59d303f9cfe91e2015156fe25a42687855a6de4ccb53756f06e7c3cf66e295fd84d8c3c0fd73c7cee44966aaae3d033652"); pubKeyList350.push_back("049a0e427b86663cc928d6475d0e591fd6dbaf686e2b6a140e79e646fbaa0c88481984f61de390c9fc73c9f58d2c26bd8bdadbdd400a8cc96b4d7a6f52fbe1209d"); pubKeyList350.push_back("040da5d570e39531f25ae747a1698d67470c0d7fb4941f104d081235f7425cefb95b5eca24daf80a732cb267bd13d47b62ce4102394c180b2a792216f4a087d320"); pubKeyList350.push_back("04672dbddcb26bc82028652a5ff042f98c5c5f58f7330d49ad4a22268f9a93e2cca8ce2ed7a93012b83903f4ddcef5f1a0ea5fb90df3ae38528489d9b69cd0dd39"); pubKeyList350.push_back("04fb8a251640f766ec63aee35f74f49e46b5ae7f61f7bcabe6103d13ab56086c884c525b96e10741704a3c44982aa9c6577184f0259a36f18e4ca8325ff2cd8330"); pubKeyList350.push_back("04f9644ebc672e382eb45a82e221f2ab9d5124fea1de7de2d417c863ddd760c5c778f8fe39e09e7937ac99172a3a9d0b013020c1256b935da171b66864a1e16b9c"); pubKeyList350.push_back("048a58fe8de7c123f6f816667fb1bfe6d99b9f0ac415bde1fdf4e9725fc80d2699c30b362faf992cd00edb586df9f459081c3f586becbabdd33bdd8becf31f85c2"); pubKeyList350.push_back("0475a43388b6023722d93c03128541b3877153736a9ac7f48bf1d1a37e46aa1381a450aa0a6c40e2f4e317a4212c37c18bd1cf99ea3f70ecec83c30f4ceca65201"); pubKeyList350.push_back("04bf85a4920b6fb89868fac40c4917af40546867221f2da2de84b9a9f26c569cee689c2eafe0c911c31ac88d9005badb8f32fb0650ffe2e272194ef5df162b35ac"); pubKeyList350.push_back("04e75eda3a94f74d684a7239b8c6cc056e75fba2690888855f81810c439270265f4c3c46c3aedfaff81da2dfb236e091cc36b5759e6a0513898ad443cf91ff6631"); pubKeyList350.push_back("04c62eb46a011e45f0069d8881894ac22889988b384ba7234c5caeed42d4f11d16e2ba0b55198cec0a0a710714d0602e1ccaada5284ae07fa0ae43b0cb1e7d59b1"); pubKeyList350.push_back("043d60413953d4a9e144d86390c8ddb51b674df65ce1a05a26e400b3bc27cbc55c6c6b05d5030e60dfe59101dc9614e4298c33716be751feb0d494a788e00ad627"); pubKeyList350.push_back("041c10a07fa1799e8d43d4a0b74b89614722fabcfd90dac380d170ebfddd0b5f0462e67c0704172cbe925c77c1890af68000d44fed56d628cceea6101fcaf74d38"); pubKeyList350.push_back("04640a129ecf82ed28875881c28f59bf46b82aba8e8be77ad39bb1dd0ffd7944f49da4dc3de9cac50d88763167583b030d7df0e234e8a6e9de725aa337fcb1f0ed"); pubKeyList350.push_back("04e5cba6da1d31076d42db494613e6c8587ba4252693c8d8dbcdae033479e8cab10921c147b91127ef4b36d0209a8de917f3c51fd231b07acdcce47d0ac3a14de8"); pubKeyList350.push_back("0479502526431508d1edcb054bfb49dfed971e144ff1d3d89384f1af8c95a2ee3d6f296cade67c2dfb8c43b324ed6cc079395a5ec4118f0b8c5737fe8988d4ecfc"); pubKeyList350.push_back("04048059da03e2ecca976fb0c8e8ea408ea3a8e2b45c55c9ee095011077ded701f9b8639b265e1dc1eb0ac08f990f67b99da03f4bb5c68bef182488d49f5e27762"); pubKeyList350.push_back("04f3b1f9c8b07034eb3f7f609d150561ee4ae05a1051816060974221f5c36a1e3db4b79b46146da9bae303648dbf94bf740ad41d6e3297eeae6829bd2d9f3e3a5e"); pubKeyList350.push_back("048f400e748d54d8fdf148a270adcb7aa4b73c9d49f3c8bbdf57df6a8a349c54abaae8e223bab43cb1770e8a80c00cb11904e301f32ea0aeec5d59ce8a9b9dc5c1"); pubKeyList350.push_back("04cf206b074a8da673f6b06cdbd28b82253ef4b4aeb6689745bf9e42a5d9007269b18a3ba5becfabb3a2d5f7b4e84ad9f6d6283856fc315ddf4fd8e5797a4d8be7"); pubKeyList350.push_back("04ae324ce3d313a42a76ec17f09625185c53bfa99c5f06920105291bea676220203d3f1b7c0de605c2bbcaa760a632f5b9a55dd86d8f36b6b985932d61a9a88946"); pubKeyList350.push_back("040ba9aeeff11561fa33827d17957fc40ed5b1b8d260140535e0350ba431609abf3a31166a9e014d26553520f59de730dbcf5944fb433d1abfadb3f4f30668ab48"); pubKeyList350.push_back("0416683a0796c3dfda8065c6011a61747488345bf0a0f559836104b4e9074e6c40b206797850603862baac60ba61bea930db1f2b4362c117d54472dc2a8b93bbd4"); pubKeyList100.push_back("046ebc739ff7d6a0dbb3ae9bb9260a17b9d2fc40ca77d9c018784834ef863414c17b4fd3a580d9721ec0ee12c823f1eb48821b8135cd32aee26ba3be9cb22f7a31"); pubKeyList100.push_back("04ffcd9e3acffbd40d6472f354e76f03a5c806623a5fbe341796b92e71ad59f5c4a4ad5f04c4fe7d6e50f6546d361a06020f8670eae020e8a7a1d036155e75d10a"); pubKeyList100.push_back("04a61c5b67927c4a0389baa1089a87a93d60fbf15cc345823097245d0c331525d273a03544720f3a4e8f9afb443793f3ea595d5f0af7e17d764385750a9eb54d19"); pubKeyList100.push_back("04f9f78f1dcdb6f76ba0a962aba3058a605691e2ecd63e16b5e0e39d19c5821f8eda421d06b4bf1159bcee989f01b273a4337ba0bc9fc749ef35c32e6e4a7bc1e9"); pubKeyList100.push_back("0444b7d2aa1b9c74710325735df89692d1fa686a3a67d95462cbf4cb0d8f47eb9ac18da92bcce99b58e1be020c36736d9a1f85fa191c2ddcc779c53c4ede7c73b9"); pubKeyList100.push_back("0426bbbd25a4dc0a295b64d4f1d3787d39cba04534109cd145c5229a8cc3285d097462131dd6fa1968eb510d53fee8a012250390ef6149c2003784f5585fef97a2"); pubKeyList100.push_back("04ab438d669c7ed7db2e0eef61bd7ae4937ac32347d39adfb204f4d6e4e2a5adfa4548f69dc4cdc2ff3da0506e9382f69175138163328d445f110081dfa5d5d416"); pubKeyList100.push_back("04406932519cd5e47333a049922eb8bcddc6b722c31440f36ca2851e119314b375914b08c635837e47c7cbf6ace95acbadee62acb054551bc4255c81d03c485e95"); pubKeyList100.push_back("0454d677fbe06d5f56920db9bd124015edfd1fb32786c88a1a15cf0a84204d4386bd48fb31239eb3e594b13ca952b3c5f25aca9f3f702ad5b0120160dc355a6fbd"); pubKeyList100.push_back("0452f030183dffd2b53d639b16488bd451ba2dc9d1791464300f28abf5414036530735b6a8de119443e3875f2e67514b6b2678ed3966629d354e6aabdb8251ed19"); pubKeyList20.push_back("04ce27308191e2e0274459bb191ba2cb93ef4dc8a838e8e8310083fcf7e2be9c7c20b3b15e2dc2a1482275ee55138c2350771231b00d7740e1e495269987faa24b"); pubKeyList20.push_back("04311cc5333eeadbb3b18f6c70832df159796b1872bfa66bf214030ced65f8a33c4c6b4da48ffebb111a09129b337c9ed5129256995a4fa315fab3b81666cf2bad"); pubKeyList10.push_back("0428588850c9361e7f5848807ef40ac839d5cd664db6183cbc53f63b0e8682a5b4b6caa6782db2b314e3cab43503f05df280b9e98e82b2235a00e4dd24997b49a0"); pubKeyList10.push_back("04bf2832da17137215912a1173b3ad2675e1b03c4df22bb93f2f2fdb92bdd0097e0a267d8813799fe335d1b80ff23fa48809dea4517211b48eacadc85147d5c643"); pubKeyList10.push_back("04c8ad33bb094d7bee52ec9d08e4eea8ef33d49c1d871e6a4ee56f2fd6f44bb87a28a903bf1306cd855c4fa19baa42d604e2f6aa571b4a6a603ab7769162e7fcb8"); }
97.484211
162
0.903142
[ "vector" ]
066a89133241b7e5b0333f09e99d53938c573283
3,140
cpp
C++
gen/passes/StripExternals.cpp
sdrees/ldc
3354cca137c090c28e3db1ee9ecc98eabe594691
[ "Apache-2.0" ]
null
null
null
gen/passes/StripExternals.cpp
sdrees/ldc
3354cca137c090c28e3db1ee9ecc98eabe594691
[ "Apache-2.0" ]
null
null
null
gen/passes/StripExternals.cpp
sdrees/ldc
3354cca137c090c28e3db1ee9ecc98eabe594691
[ "Apache-2.0" ]
null
null
null
//===-- StripExternals.cpp - Strip available_externally symbols -----------===// // // LDC – the LLVM D compiler // // This file is distributed under the BSD-style LDC license. See the LICENSE // file for details. // //===----------------------------------------------------------------------===// // // This transform strips the bodies of available_externally functions and // initializers of available_externally globals, turning them into external // declarations. // This is useful to allow Global DCE (-globaldce) to clean up references to // globals only used by available_externally functions and initializers. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "strip-externals" #include "gen/passes/Passes.h" #include "llvm/ADT/Statistic.h" #include "llvm/IR/Module.h" #include "llvm/Pass.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; STATISTIC(NumFunctions, "Number of function bodies removed"); STATISTIC(NumVariables, "Number of global initializers removed"); namespace { struct LLVM_LIBRARY_VISIBILITY StripExternals { // run - Do the StripExternals pass on the specified module. // bool run(Module &M); }; struct LLVM_LIBRARY_VISIBILITY StripExternalsLegacyPass : public ModulePass { static char ID; // Pass identification, replacement for typeid StripExternalsLegacyPass() : ModulePass(ID) {} StripExternals pass; // run - Do the StripExternals pass on the specified module. // bool runOnModule(Module &M) override { return pass.run(M); }; }; } char StripExternalsLegacyPass::ID = 0; static RegisterPass<StripExternalsLegacyPass> X("strip-externals", "Strip available_externally bodies and initializers"); ModulePass *createStripExternalsPass() { return new StripExternalsLegacyPass(); } bool StripExternals::run(Module &M) { bool Changed = false; for (auto I = M.begin(); I != M.end();) { if (I->hasAvailableExternallyLinkage()) { assert(!I->isDeclaration() && "Declarations can't be available_externally"); Changed = true; ++NumFunctions; if (I->use_empty()) { LLVM_DEBUG(errs() << "Deleting function: " << *I); auto todelete = I; ++I; todelete->eraseFromParent(); continue; } else { I->deleteBody(); LLVM_DEBUG(errs() << "Deleted function body: " << *I); } } ++I; } for (auto I = M.global_begin(); I != M.global_end();) { if (I->hasAvailableExternallyLinkage()) { assert(!I->isDeclaration() && "Declarations can't be available_externally"); Changed = true; ++NumVariables; if (I->use_empty()) { LLVM_DEBUG(errs() << "Deleting global: " << *I); auto todelete = I; ++I; todelete->eraseFromParent(); continue; } else { I->setInitializer(nullptr); I->setLinkage(GlobalValue::ExternalLinkage); LLVM_DEBUG(errs() << "Deleted initializer: " << *I); } } ++I; } return Changed; }
30.485437
81
0.620064
[ "transform" ]
066d2f138037405cf871711e7c82fa3c3404be30
6,314
cpp
C++
Acorn/tools/IDLParser/src/V8IDLGenerators.cpp
IcyTv/Acorn
3068d9fd54401b310d42ef81277aab3d0ade0a0a
[ "Apache-2.0" ]
null
null
null
Acorn/tools/IDLParser/src/V8IDLGenerators.cpp
IcyTv/Acorn
3068d9fd54401b310d42ef81277aab3d0ade0a0a
[ "Apache-2.0" ]
null
null
null
Acorn/tools/IDLParser/src/V8IDLGenerators.cpp
IcyTv/Acorn
3068d9fd54401b310d42ef81277aab3d0ade0a0a
[ "Apache-2.0" ]
null
null
null
/** * Copyright (c) 2022 Michael Finger * * SPDX-License-Identifier: Apache-2.0 with Commons Clause * * For more Information on the license, see the LICENSE.md file */ // FIXME move to inja::Environment to precompile templates // FIXME move this project to a subproject or similar to reduce reconfigure complexity. // FIXME change parser to emit more favourable types for adding to SourceGenerator // FIXME Currently we assume that a wrapped function is in Acorn (Pascal case) style. This is not true for wrapped functions from other classes (i.e. glm::vec) #include "IDLTypes.h" #include "SourceGenerator.h" #include <fmt/format.h> #include <inja/inja.hpp> #include <fstream> #include <iostream> #include <queue> #include <utility> std::vector<std::string_view> s_HeaderSearchPaths; namespace Acorn::IDL { using namespace std::literals::string_view_literals; // To allow ""sv construction static std::string MakeInputAcceptableCpp(const std::string& input) { if (IsOneOf(input, "class", "template", "for", "default", "char", "namespace", "delete")) { return input + "_"; } std::string output(input); std::replace(output.begin(), output.end(), '-', '_'); return output; } static std::string ToCppType(std::shared_ptr<Type> ty) { if (ty->IsInteger()) { return "uint32_t"; } if (ty->IsNumeric()) { return "double"; } if (ty->IsString()) { return "std::string"; } if (ty->Name == "boolean") { return "bool"; } return ty->Name; } void GenerateHeader(const Interface& interface, std::filesystem::path outPath, std::string templateBasePath) { SourceGenerator generator(std::move(templateBasePath)); generator.Add("acorn_root", "Acorn/scripting/v8"); generator.Add("idl_filename", std::filesystem::path(interface.ModuleOwnPath).filename().string()); // EmitIncludesForAllImports(interface, generator, true); generator.Add("name", interface.Name); generator.Add("fully_qualified_name", interface.FullyQualifiedName); generator.Add("wrapper_class", interface.WrapperClass); generator.Add("wrapper_base_class", interface.WrapperBaseClass); // if (interface.WrapperBaseClass == "Wrapper") // GenerateIncludeForWrapper(generator, interface.WrapperClass); // ================== // == Enumerations == // ================== inja::json data; data["enums"] = inja::json::array(); for (const auto& enumeration : interface.Enums) { if (!enumeration.second.IsOriginalDefinition) continue; inja::json enumerationData; enumerationData["name"] = enumeration.first; enumerationData["values"] = inja::json::array(); for (const auto& value : enumeration.second.Values) { enumerationData["values"].push_back(value); } data["enums"].push_back(enumerationData); } generator.Add(data); generator.AppendFile("WrapperHeader.tpl"); std::ofstream out(outPath.string()); out << generator.Generate(); } void GenerateImplementation(const Interface& interface, std::filesystem::path outPath, std::string templateBasePath) { SourceGenerator generator(std::move(templateBasePath)); //TODO: ExtendedAttributes CustomCppClass=<classname> to wrap external, non-Acorn classes (i.e. glm) generator.Add("acorn_root", "Acorn/scripting/v8"); generator.Add("idl_filename", std::filesystem::path(interface.ModuleOwnPath).filename().string()); generator.Add("name", interface.Name); generator.Add("wrapper_name", std::string(interface.Name + "Wrapper")); inja::json data; data["constructors"] = inja::json::array(); for (const auto& ctor : interface.Constructors) { inja::json ctorData; ctorData["cpp_args"] = inja::json::array(); for (const auto& arg : ctor.Parameters) { ctorData["cpp_args"].push_back(ToCppType(arg.Type)); } data["constructors"].push_back(ctorData); } if(interface.WrapperBaseClass != "Wrapper") { data["inherit"] = interface.WrapperBaseClass; } else { data["inherit"] = false; } data["properties"] = inja::json::array(); for (const auto& prop : interface.Attributes) { std::cout << prop.Name << " " << prop.GetterNameCallback << ", " << prop.SetterNameCallback << std::endl; inja::json propData; propData["name"] = prop.Name; propData["readonly"] = prop.ReadOnly ? "true" : "false"; // TODO GetterNameCallback ExtendedAttributes,.... propData["virtual"] = prop.ReadOnly; data["properties"].push_back(propData); } data["methods"] = inja::json::array(); for(const auto& method: interface.Functions) { if(method.Name.empty()) continue; inja::json methodData; methodData["name"] = method.Name; //TODO data["methods"].push_back(methodData); } if(interface.IndexedPropertyGetter) { // TODO do we care about the function definition? //FIXME We should definitely assert that the function is a valid indexed getter... data["indexed_property_getter"] = true; } else { data["indexed_property_getter"] = false; } if(interface.IndexedPropertySetter) { //FIXME We should definitely assert that the function is a valid indexed setter... data["indexed_property_setter"] = { {"type", ToCppType(interface.IndexedPropertyGetter->Parameters[0].Type)} }; } else { data["indexed_property_setter"] = false; } if(interface.NamedPropertyGetter) { // TODO do we care about the function definition? //FIXME We should definitely assert that the function is a valid named getter... data["named_property_getter"] = true; } else { data["named_property_getter"] = false; } if(interface.NamedPropertySetter) { // TODO do we care about the function definition? //FIXME We should definitely assert that the function is a valid named setter... data["named_property_setter"] = { {"type", ToCppType(interface.IndexedPropertyGetter->Parameters[1].Type)} }; } else { data["named_property_setter"] = false; } if(interface.HasStringifier) { } // FIXME: for now setter without getter does not work, // TODO: Deleter generator.Add(data); std::cout << data << std::endl; // generator.Append(WrapperImplementation); generator.AppendFile("WrapperImplementation.tpl"); std::ofstream outFile(outPath.string()); outFile << generator.Generate(); } } // namespace Acorn::IDL
27.938053
159
0.689895
[ "vector" ]
066f27f655e2549e764480329df6a2b98323ab23
23,531
cpp
C++
src/pipelinedefinition.cpp
ayoubBouziane/model_server
03d6d325304e01fc197e6e033c84eb9af150301d
[ "Apache-2.0" ]
null
null
null
src/pipelinedefinition.cpp
ayoubBouziane/model_server
03d6d325304e01fc197e6e033c84eb9af150301d
[ "Apache-2.0" ]
null
null
null
src/pipelinedefinition.cpp
ayoubBouziane/model_server
03d6d325304e01fc197e6e033c84eb9af150301d
[ "Apache-2.0" ]
null
null
null
//***************************************************************************** // Copyright 2020 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #include "pipelinedefinition.hpp" #include <chrono> #include <set> #include <thread> #include "pipelinedefinitionunloadguard.hpp" #include "prediction_service_utils.hpp" namespace ovms { Status toNodeKind(const std::string& str, NodeKind& nodeKind) { if (str == DL_NODE_CONFIG_TYPE) { nodeKind = NodeKind::DL; return StatusCode::OK; } SPDLOG_ERROR("Unsupported node type:{}", str); return StatusCode::PIPELINE_NODE_WRONG_KIND_CONFIGURATION; } Status PipelineDefinition::validate(ModelManager& manager) { struct ValidationResultNotifier { ValidationResultNotifier() {} ~ValidationResultNotifier() { if (passed) { // status.notifyValidationPassed(); } else { // status.notifyValidationFailed(); } } bool passed = false; }; ValidationResultNotifier notifier; Status validationResult = validateNodes(manager); if (!validationResult.ok()) { return validationResult; } validationResult = validateForCycles(); if (!validationResult.ok()) { return validationResult; } notifier.passed = true; return validationResult; } Status PipelineDefinition::reload(ModelManager& manager, const std::vector<NodeInfo>&& nodeInfos, const pipeline_connections_t&& connections) { resetSubscriptions(manager); // this->status.notifyLoadInProgress(); while (requestsHandlesCounter > 0) { std::this_thread::sleep_for(std::chrono::microseconds(1)); } this->nodeInfos = std::move(nodeInfos); this->connections = std::move(connections); makeSubscriptions(manager); return validate(manager); } Status PipelineDefinition::waitForLoaded(std::unique_ptr<PipelineDefinitionUnloadGuard>& unloadGuard, const uint waitForLoadedTimeoutMicroseconds) { unloadGuard = std::make_unique<PipelineDefinitionUnloadGuard>(*this); /* const uint waitLoadedTimestepMicroseconds = 10; const uint waitCheckpoints = waitForLoadedTimeoutMicroseconds / waitLoadedTimestepMicroseconds; uint waitCheckpointsCounter = waitCheckpoints; while (waitCheckpointsCounter-- != 0) { if (status.getState() == ModelVersionState::AVAILABLE) { SPDLOG_INFO("Succesfully waited for pipeline:{}", getName()); // TODO change to DEBUG after part 2 break; } unloadGuard.reset(); if (status.getState() > ModelVersionState::AVAILABLE) { SPDLOG_INFO("Waiting for pipeline:{} ended since it started unloading.", getName()); // TODO change to DEBUG after part 2 return StatusCode::MODEL_VERSION_NOT_LOADED_ANYMORE; } SPDLOG_INFO("Waiting for available state for pipeline:{}, with timestep:{} timeout:{} check count:{}", getName(), waitLoadedTimestepMicroseconds, waitForModelLoadedTimeoutMicroseconds, waitCheckpointsCounter); // TODO change to DEBUG after part 2 finished status.waitForLoadedNotify(waitLoadedTimestepMicroseconds); unloadGuard = std::make_unique<PipelineDefinitionUnloadGuard(*this); } if (status.getState() != ModelVersionState::AVAILABLE) { if (status.getState() > ModelVersionState::AVAILABLE) { SPDLOG_INFO("Waiting for pipeline:{} ended since it started unloading.", getName()); // TODO change to DEBUG after part 2 return StatusCode::MODEL_VERSION_NOT_LOADED_ANYMORE; } else if (status.getState() > ModelVersionState::AVAILABLE) { SPDLOG_INFO("Waiting for pipeline:{} ended due to timeout.", getName()); // TODO change to DEBUG after part 2 return StatusCode::MODEL_VERSION_NOT_LOADED_YET; } } */ return StatusCode::OK; } Status PipelineDefinition::create(std::unique_ptr<Pipeline>& pipeline, const tensorflow::serving::PredictRequest* request, tensorflow::serving::PredictResponse* response, ModelManager& manager) { std::unique_ptr<PipelineDefinitionUnloadGuard> unloadGuard; Status status = waitForLoaded(unloadGuard); if (!status.ok()) { return status; } std::unordered_map<std::string, std::unique_ptr<Node>> nodes; EntryNode* entry = nullptr; ExitNode* exit = nullptr; for (const auto& info : nodeInfos) { SPDLOG_DEBUG("Creating pipeline:{}. Adding nodeName:{}, modelName:{}", getName(), info.nodeName, info.modelName); switch (info.kind) { case NodeKind::ENTRY: { auto node = std::make_unique<EntryNode>(request); entry = node.get(); nodes.insert(std::make_pair(info.nodeName, std::move(node))); break; } case NodeKind::DL: nodes.insert(std::make_pair(info.nodeName, std::move(std::make_unique<DLNode>(info.nodeName, info.modelName, info.modelVersion, manager, info.outputNameAliases)))); break; case NodeKind::EXIT: { auto node = std::make_unique<ExitNode>(response); exit = node.get(); nodes.insert(std::make_pair(info.nodeName, std::move(node))); break; } default: throw std::invalid_argument("unknown node kind"); } } for (const auto& kv : connections) { const auto& dependantNode = nodes.at(kv.first); for (const auto& pair : kv.second) { const auto& dependencyNode = nodes.at(pair.first); SPDLOG_DEBUG("Connecting pipeline:{}, from:{}, to:{}", getName(), dependencyNode->getName(), dependantNode->getName()); Pipeline::connect(*dependencyNode, *dependantNode, pair.second); } } pipeline = std::make_unique<Pipeline>(*entry, *exit, pipelineName); for (auto& kv : nodes) { pipeline->push(std::move(kv.second)); } return status; } void PipelineDefinition::resetSubscriptions(ModelManager& manager) { for (auto& [modelName, modelVersion] : subscriptions) { if (modelVersion) { SPDLOG_INFO("Unsubscribing pipeline:{} from model: {}, version:{}", getName(), modelName, modelVersion); manager.findModelByName(modelName)->getModelInstanceByVersion(modelVersion)->unsubscribe(*this); } else { // using default version SPDLOG_INFO("Unsubscribing pipeline:{} from model: {}", getName(), modelName); manager.findModelByName(modelName)->unsubscribe(*this); } } subscriptions.clear(); } static std::string createSubscriptionErrorMessage(const std::string& pipelineName, const NodeInfo& nodeInfo) { std::stringstream ss; ss << "Pipeline: " << pipelineName << " Failed to make subscription to model: " << nodeInfo.modelName; if (nodeInfo.modelVersion) { ss << " version: " << nodeInfo.modelVersion.value(); } ss << " because it was missing"; return ss.str(); } void PipelineDefinition::makeSubscriptions(ModelManager& manager) { for (auto& node : nodeInfos) { if (node.kind == NodeKind::DL) { if (subscriptions.find({node.modelName, node.modelVersion.value_or(0)}) != subscriptions.end()) { continue; } auto model = manager.findModelByName(node.modelName); if (nullptr == model) { SPDLOG_WARN(createSubscriptionErrorMessage(getName(), node)); continue; } if (node.modelVersion) { auto modelInstance = model->getModelInstanceByVersion(node.modelVersion.value()); if (nullptr == modelInstance) { SPDLOG_WARN(createSubscriptionErrorMessage(getName(), node)); continue; } modelInstance->subscribe(*this); } else { model->subscribe(*this); } subscriptions.insert({node.modelName, node.modelVersion.value_or(0)}); } } } Status PipelineDefinition::validateNode(ModelManager& manager, NodeInfo& node) { std::unique_ptr<ModelInstanceUnloadGuard> nodeModelInstanceUnloadGuard; std::shared_ptr<ModelInstance> nodeModelInstance; tensor_map_t nodeInputs; SPDLOG_DEBUG("Validation of pipeline: {} node: {} type: {}", getName(), node.nodeName, node.kind); Status result; if (node.kind == NodeKind::DL) { result = getModelInstance(manager, node.modelName, node.modelVersion.value_or(0), nodeModelInstance, nodeModelInstanceUnloadGuard); if (!result.ok()) { SPDLOG_ERROR("Validation of pipeline({}) definition failed. Missing model: {} version: {}", this->pipelineName, node.modelName, node.modelVersion.value_or(0)); return StatusCode::MODEL_NAME_MISSING; } auto& config = nodeModelInstance->getModelConfig(); if (config.getBatchingMode() == Mode::AUTO) { SPDLOG_ERROR("Validation of pipeline({}) definition failed. Node name {} used model name {} with dynamic batch size which is forbidden.", this->pipelineName, node.nodeName, node.modelName); return StatusCode::FORBIDDEN_MODEL_DYNAMIC_PARAMETER; } auto& shapes = config.getShapes(); for (auto& shape : shapes) { if (shape.second.shapeMode == Mode::AUTO) { SPDLOG_ERROR("Validation of pipeline({}) definition failed. Node name {} used model name {} with dynamic shape which is forbidden.", this->pipelineName, node.nodeName, node.modelName); return StatusCode::FORBIDDEN_MODEL_DYNAMIC_PARAMETER; } } nodeInputs = nodeModelInstance->getInputsInfo(); } for (auto& connection : connections[node.nodeName]) { std::unique_ptr<ModelInstanceUnloadGuard> sourceNodeModelInstanceUnloadGuard; const std::string& sourceNodeName = connection.first; auto findByName = [sourceNodeName](const NodeInfo& nodeInfo) { return nodeInfo.nodeName == sourceNodeName; }; std::vector<NodeInfo>::iterator sourceNodeInfo = std::find_if(std::begin(nodeInfos), std::end(nodeInfos), findByName); if (sourceNodeInfo == std::end(nodeInfos)) { SPDLOG_ERROR("Validation of pipeline({}) definition failed. For node: {} missing dependency node: {} ", this->pipelineName, node.nodeName, sourceNodeName); return StatusCode::MODEL_NAME_MISSING; } if (sourceNodeInfo->kind == NodeKind::DL) { std::shared_ptr<ModelInstance> sourceNodeModelInstance; result = getModelInstance(manager, sourceNodeInfo->modelName, 0, sourceNodeModelInstance, sourceNodeModelInstanceUnloadGuard); if (!result.ok()) { SPDLOG_ERROR("Validation of pipeline({}) definition failed. Missing model: {} version: {}", this->pipelineName, sourceNodeInfo->modelName, sourceNodeInfo->modelVersion.value_or(0)); return StatusCode::MODEL_MISSING; } const tensor_map_t& sourceNodeOutputs = sourceNodeModelInstance->getOutputsInfo(); if (connection.second.size() == 0) { SPDLOG_ERROR("Validation of pipeline({}) definition failed. Missing dependency mapping for node: {}", this->pipelineName, node.nodeName); return StatusCode::PIPELINE_DEFINITION_MISSING_DEPENDENCY_MAPPING; } for (auto alias : connection.second) { std::string& dependencyOutputAliasName = alias.first; std::string dependencyOutputName; if (sourceNodeInfo->outputNameAliases.count(dependencyOutputAliasName)) { dependencyOutputName = sourceNodeInfo->outputNameAliases[dependencyOutputAliasName]; } else { dependencyOutputName = dependencyOutputAliasName; } auto dependencyOutput = sourceNodeOutputs.find(dependencyOutputName); if (dependencyOutput == sourceNodeOutputs.end()) { SPDLOG_ERROR("Validation of pipeline({}) definition failed. Missing output: {} of model: {}", this->pipelineName, dependencyOutputName, sourceNodeModelInstance->getName()); return StatusCode::INVALID_MISSING_OUTPUT; } if (node.kind != NodeKind::DL) { break; } std::string& inputName = alias.second; auto nodeInput = nodeInputs.find(inputName); if (nodeInput == nodeInputs.end()) { SPDLOG_ERROR("Validation of pipeline({}) definition failed. Missing input: {} of node: {}", this->pipelineName, inputName, node.nodeName); return StatusCode::INVALID_MISSING_INPUT; } } } } return StatusCode::OK; } // Because of the way how pipeline_connections is implemented, this function is using // transpose of PipelineDefinition graph.(Transpose contains same cycles as original graph) Status PipelineDefinition::validateForCycles() { std::vector<std::string> visited; std::vector<std::string> parentNodes; visited.reserve(nodeInfos.size()); parentNodes.reserve(nodeInfos.size()); auto pred = [](const NodeInfo& nodeInfo) { return nodeInfo.kind == NodeKind::EXIT; }; const auto& itr = std::find_if(std::begin(nodeInfos), std::end(nodeInfos), pred); if (itr == nodeInfos.end()) { SPDLOG_ERROR("Pipeline does not contain response node."); return StatusCode::PIPELINE_MISSING_ENTRY_OR_EXIT; } std::string nodeName = itr->nodeName; visited.push_back(nodeName); bool anyUnvisitedLeft = true; while (anyUnvisitedLeft) { bool unvisistedFound = false; const auto& connectedToNode = connections[nodeName]; for (const auto& node : connectedToNode) { if (nodeName == node.first) { SPDLOG_ERROR("Node {} is connected to itself.", nodeName); return StatusCode::PIPELINE_CYCLE_FOUND; } if (std::find(visited.begin(), visited.end(), node.first) == visited.end()) { parentNodes.push_back(nodeName); visited.push_back(node.first); nodeName = node.first; unvisistedFound = true; break; } else { if (std::find(parentNodes.begin(), parentNodes.end(), node.first) != parentNodes.end()) { std::string cycleNodes; for (auto& cycleNode : parentNodes) { cycleNodes += cycleNode; if (cycleNode != parentNodes.back()) { cycleNodes += ", "; } } SPDLOG_ERROR("Following nodes creates cycle: {}", cycleNodes); return StatusCode::PIPELINE_CYCLE_FOUND; } } } if (!unvisistedFound) { if (parentNodes.size() == 0) { anyUnvisitedLeft = false; if (visited.size() != nodeInfos.size()) { SPDLOG_ERROR("There are nodes not connected to pipeline."); return StatusCode::PIPELINE_CONTAINS_UNCONNECTED_NODES; } } else { nodeName = parentNodes.back(); parentNodes.pop_back(); } } } return StatusCode::OK; } Status PipelineDefinition::validateNodes(ModelManager& manager) { SPDLOG_DEBUG("Validation of pipeline definition:{} nodes started.", getName()); bool entryFound = false; bool exitFound = false; for (auto& node : nodeInfos) { auto findByName = [node](const NodeInfo& nodeInfo) { return nodeInfo.nodeName == node.nodeName; }; if (std::count_if(nodeInfos.begin(), nodeInfos.end(), findByName) > 1) { return StatusCode::PIPELINE_NODE_NAME_DUPLICATE; } auto result = validateNode(manager, node); if (!result.ok()) { return result; } if (node.kind == NodeKind::ENTRY) { if (entryFound) { return StatusCode::PIPELINE_MULTIPLE_ENTRY_NODES; } entryFound = true; } if (node.kind == NodeKind::EXIT) { if (exitFound) { return StatusCode::PIPELINE_MULTIPLE_EXIT_NODES; } exitFound = true; } } if (!entryFound) { SPDLOG_ERROR("PipelineDefinition: {} is missing request node", pipelineName); return StatusCode::PIPELINE_MISSING_ENTRY_OR_EXIT; } if (!exitFound) { SPDLOG_ERROR("PipelineDefinition: {} is missing response node", pipelineName); return StatusCode::PIPELINE_MISSING_ENTRY_OR_EXIT; } return StatusCode::OK; } Status PipelineDefinition::getInputsInfo(tensor_map_t& inputsInfo, const ModelManager& manager) const { // Assumptions: this can only be called on available pipeline definition. // Add check if available when pipeline status will be implemented. static const auto byName = [](const std::string& name) { return [name](const NodeInfo& nodeInfo) { return nodeInfo.nodeName == name; }; }; for (const auto& [dependantNodeName, allMappings] : connections) { const auto& dependantNodeInfo = std::find_if(std::begin(nodeInfos), std::end(nodeInfos), byName(dependantNodeName)); for (const auto& [dependencyNodeName, specificDependencyMapping] : allMappings) { const auto& dependencyNodeInfo = std::find_if(std::begin(nodeInfos), std::end(nodeInfos), byName(dependencyNodeName)); if (dependencyNodeInfo->kind != NodeKind::ENTRY) { continue; } switch (dependantNodeInfo->kind) { case NodeKind::EXIT: { for (const auto& [alias, realName] : specificDependencyMapping) { inputsInfo.insert({alias, TensorInfo::getUnspecifiedTensorInfo()}); } break; } case NodeKind::DL: { auto instance = manager.findModelInstance(dependantNodeInfo->modelName, dependantNodeInfo->modelVersion.value_or(0)); if (!instance) { // TODO: Change to SPDLOG_DEBUG before release SPDLOG_INFO("Model:{} was unavailable during pipeline:{} inputs info fetching", dependantNodeInfo->modelName, this->getName()); return StatusCode::MODEL_MISSING; } std::unique_ptr<ModelInstanceUnloadGuard> unloadGuard; auto status = instance->waitForLoaded(0, unloadGuard); if (!status.ok()) { // TODO: Change to SPDLOG_DEBUG before release SPDLOG_INFO("Model:{} was unavailable during pipeline:{} inputs info fetching", instance->getName(), this->getName()); return status; } for (const auto& [alias, realName] : specificDependencyMapping) { inputsInfo[alias] = instance->getInputsInfo().at(realName); } break; } default: { // Pipeline validation does not allow connections into entry node. SPDLOG_ERROR("Unexpected dependant node kind (name:{})", this->getName()); return StatusCode::UNKNOWN_ERROR; } } } } return StatusCode::OK; } Status PipelineDefinition::getOutputsInfo(tensor_map_t& outputsInfo, const ModelManager& manager) const { // Assumptions: this can only be called on available pipeline definition. // Add check if available when pipeline status will be implemented. static const auto byName = [](const std::string& name) { return [name](const NodeInfo& nodeInfo) { return nodeInfo.nodeName == name; }; }; for (const auto& [dependantNodeName, allMappings] : connections) { const auto& dependantNodeInfo = std::find_if(std::begin(nodeInfos), std::end(nodeInfos), byName(dependantNodeName)); if (dependantNodeInfo->kind != NodeKind::EXIT) { continue; } for (const auto& [dependencyNodeName, specificDependencyMapping] : allMappings) { const auto& dependencyNodeInfo = std::find_if(std::begin(nodeInfos), std::end(nodeInfos), byName(dependencyNodeName)); switch (dependencyNodeInfo->kind) { case NodeKind::ENTRY: { for (const auto& [alias, realName] : specificDependencyMapping) { outputsInfo.insert({realName, TensorInfo::getUnspecifiedTensorInfo()}); } break; } case NodeKind::DL: { auto instance = manager.findModelInstance(dependencyNodeInfo->modelName, dependencyNodeInfo->modelVersion.value_or(0)); if (!instance) { // TODO: Change to SPDLOG_DEBUG before release SPDLOG_INFO("Model:{} was unavailable during pipeline:{} outputs info fetching", dependencyNodeInfo->modelName, this->getName()); return StatusCode::MODEL_MISSING; } std::unique_ptr<ModelInstanceUnloadGuard> unloadGuard; auto status = instance->waitForLoaded(0, unloadGuard); if (!status.ok()) { // TODO: Change to SPDLOG_DEBUG before release SPDLOG_INFO("Model:{} was unavailable during pipeline:{} outputs info fetching", instance->getName(), this->getName()); return status; } for (const auto& [alias, realName] : specificDependencyMapping) { const auto& finalName = dependencyNodeInfo->outputNameAliases.count(alias) > 0 ? dependencyNodeInfo->outputNameAliases.at(alias) : alias; outputsInfo[realName] = instance->getOutputsInfo().at(finalName); } break; } default: { // Pipeline validation does not allow connections from exit node. SPDLOG_ERROR("Unexpected dependency node kind (name:{})", this->getName()); return StatusCode::UNKNOWN_ERROR; } } } } return StatusCode::OK; } } // namespace ovms
44.566288
201
0.606774
[ "shape", "vector", "model" ]
0670a02e34ac5ac235e1ba67398bc04d950129fa
2,420
cc
C++
Fujitsu/benchmarks/resnet/implementations/mxnet/3rdparty/tvm/src/codegen/verilog/verilog_module.cc
mengkai94/training_results_v0.6
43dc3e250f8da47b5f8833197d74cb8cf1004fc9
[ "Apache-2.0" ]
42
2019-07-11T18:23:52.000Z
2021-09-14T08:21:09.000Z
src/codegen/verilog/verilog_module.cc
clhne/tvm
d59320c764bd09474775e1b292f3c05c27743d24
[ "Apache-2.0" ]
23
2019-07-29T05:21:52.000Z
2020-08-31T18:51:42.000Z
src/codegen/verilog/verilog_module.cc
clhne/tvm
d59320c764bd09474775e1b292f3c05c27743d24
[ "Apache-2.0" ]
51
2019-07-12T05:10:25.000Z
2021-07-28T16:19:06.000Z
/*! * Copyright (c) 2017 by Contributors * \file verilog_module.cc * \brief Build verilog source code. */ #include <tvm/runtime/packed_func.h> #include <tvm/codegen.h> #include <mutex> #include "codegen_verilog.h" #include "../../runtime/file_util.h" #include "../../runtime/meta_data.h" namespace tvm { namespace codegen { namespace verilog { using runtime::TVMArgs; using runtime::TVMRetValue; using runtime::PackedFunc; // Simulator function class VerilogModuleNode : public runtime::ModuleNode { public: VerilogModuleNode() : fmt_("v") {} const char* type_key() const { return "verilog"; } PackedFunc GetFunction( const std::string& name, const std::shared_ptr<ModuleNode>& sptr_to_self) final { CHECK(sptr_to_self.get() == this); if (!m_.fmap.count(name)) return PackedFunc(); auto f = [sptr_to_self, name, this](const runtime::TVMArgs& args, TVMRetValue* rv) { auto* fsim = runtime::Registry::Get("tvm_callback_verilog_simulator"); CHECK(fsim != nullptr) << "tvm_callback_verilog_simulator is not registered," <<" did you import tvm.addon.verilog?"; std::string code = m_.AppendSimMain(name); if (const auto* f = runtime::Registry::Get("tvm_callback_verilog_postproc")) { code = (*f)(code).operator std::string(); } std::vector<TVMValue> values; std::vector<int> codes; TVMValue v; v.v_str = code.c_str(); values.push_back(v); codes.push_back(kStr); for (int i = 0; i < args.num_args; ++i) { values.push_back(args.values[i]); codes.push_back(args.type_codes[i]); } fsim->CallPacked(TVMArgs(&values[0], &codes[0], args.num_args + 1), rv); }; return PackedFunc(f); } std::string GetSource(const std::string& format) final { return m_.code; } void Init(const Array<LoweredFunc>& funcs) { CodeGenVerilog cg; cg.Init(); for (LoweredFunc f : funcs) { cg.AddFunction(f); } m_ = cg.Finish(); } private: // the verilog code. data VerilogCodeGenModule m_; // format; std::string fmt_; }; TVM_REGISTER_API("codegen.build_verilog") .set_body([](TVMArgs args, TVMRetValue* rv) { std::shared_ptr<VerilogModuleNode> n = std::make_shared<VerilogModuleNode>(); n->Init(args[0]); *rv = runtime::Module(n); }); } // namespace verilog } // namespace codegen } // namespace tvm
27.5
88
0.645868
[ "vector" ]
0680b89544b96bce58679512ac36b0b186cd82c9
4,661
cc
C++
cpp/src/keyczar/ecdsa_key_unittest.cc
nawien-sharma/keyczar
c55563bbd70f4b6fefc7444e296aab9894475f9a
[ "Apache-2.0" ]
null
null
null
cpp/src/keyczar/ecdsa_key_unittest.cc
nawien-sharma/keyczar
c55563bbd70f4b6fefc7444e296aab9894475f9a
[ "Apache-2.0" ]
null
null
null
cpp/src/keyczar/ecdsa_key_unittest.cc
nawien-sharma/keyczar
c55563bbd70f4b6fefc7444e296aab9894475f9a
[ "Apache-2.0" ]
1
2019-06-05T01:23:02.000Z
2019-06-05T01:23:02.000Z
// Copyright 2009 Sebastien Martini (seb@dbzteam.org) // // 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 <string> #include <gtest/gtest.h> #include <keyczar/base/base64w.h> #include <keyczar/base/logging.h> #include <keyczar/base/ref_counted.h> #include <keyczar/base/file_path.h> #include <keyczar/base/file_util.h> #include <keyczar/base/scoped_ptr.h> #include <keyczar/base/values.h> #include <keyczar/ecdsa_private_key.h> #include <keyczar/ecdsa_public_key.h> #include <keyczar/key_type.h> #include <keyczar/keyczar_test.h> #include <keyczar/rw/keyset_file_reader.h> namespace keyczar { class ECDSATest : public KeyczarTest { protected: // Loads public key from JSON file. scoped_refptr<ECDSAPublicKey> LoadECDSAPublicKey(const FilePath& path, int key_version) { rw::KeysetJSONFileReader reader(path); scoped_ptr<Value> value(reader.ReadKey(key_version)); EXPECT_NE(static_cast<Value*>(NULL), value.get()); scoped_refptr<ECDSAPublicKey> public_key(ECDSAPublicKey::CreateFromValue( *value)); CHECK(public_key); return public_key; } }; TEST_F(ECDSATest, GenerateSignAndVerify) { const std::vector<int> sizes = KeyType::CipherSizes(KeyType::ECDSA_PRIV); scoped_refptr<ECDSAPrivateKey> private_key; for (std::vector<int>::const_iterator iter = sizes.begin(); iter != sizes.end(); ++iter) { // Generates a new private key. private_key = ECDSAPrivateKey::GenerateKey(*iter); ASSERT_TRUE(private_key.get()); // Attempts to sign and verify input data. std::string signature; EXPECT_TRUE(private_key->Sign(input_data_, &signature)); EXPECT_TRUE(private_key->Verify(input_data_, signature)); } } TEST_F(ECDSATest, VerifyDumpedSignature) { FilePath pub_path = data_path_.Append("ecdsa.public"); scoped_refptr<ECDSAPublicKey> public_key = LoadECDSAPublicKey(pub_path, 2); // Try to verify the signature file std::string b64w_signature; FilePath signature_file = data_path_.Append("ecdsa"); signature_file = signature_file.Append("2.out"); EXPECT_TRUE(base::ReadFileToString(signature_file, &b64w_signature)); std::string signature; EXPECT_TRUE(base::Base64WDecode(b64w_signature, &signature)); // Checks signature input_data_.push_back(Key::GetVersionByte()); EXPECT_TRUE(public_key->Verify(input_data_, signature.substr( Key::GetHeaderSize()))); } TEST_F(ECDSATest, LoadPEMPrivateKey) { const FilePath ecdsa_pem_path = data_path_.Append("ec_pem"); scoped_refptr<ECDSAPrivateKey> private_key; const FilePath simple_key = ecdsa_pem_path.Append("ec_priv.pem"); private_key = ECDSAPrivateKey::CreateFromPEMPrivateKey(simple_key.value(), NULL); EXPECT_TRUE(private_key); const std::string passphrase("cartman"); const FilePath protected_key = ecdsa_pem_path.Append( "ec_priv_encrypted.pem"); private_key = ECDSAPrivateKey::CreateFromPEMPrivateKey(protected_key.value(), &passphrase); EXPECT_TRUE(private_key); // Attempts to sign and verify input data. std::string signature; EXPECT_TRUE(private_key->Sign(input_data_, &signature)); EXPECT_TRUE(private_key->Verify(input_data_, signature)); } TEST_F(ECDSATest, ExportAndImportPrivateKey) { const FilePath pem = temp_path_.Append("ecdsa.pem"); const std::string password("cartman"); scoped_refptr<ECDSAPrivateKey> private_key = ECDSAPrivateKey::GenerateKey(256); ASSERT_TRUE(private_key.get()); // Exports private key EXPECT_TRUE(private_key->ExportPrivateKey(pem.value(), &password)); // Reloads private key scoped_refptr<ECDSAPrivateKey> imported_key = ECDSAPrivateKey::CreateFromPEMPrivateKey(pem.value(), &password); ASSERT_TRUE(imported_key.get()); // Sign data and verify std::string signature; EXPECT_TRUE(private_key->Sign(input_data_, &signature)); EXPECT_TRUE(private_key->Verify(input_data_, signature)); } } // namespace keyczar
36.131783
79
0.709504
[ "vector" ]
0684d5f23168310ceafb4659205dbc3813b86158
5,165
hpp
C++
spcppl/dataStructures/NDArray.hpp
s0rav/spcppl
a17886c9082055490dab09c47a250accfadd8513
[ "WTFPL" ]
30
2015-04-19T17:04:33.000Z
2022-03-22T13:26:53.000Z
spcppl/dataStructures/NDArray.hpp
s0rav/spcppl
a17886c9082055490dab09c47a250accfadd8513
[ "WTFPL" ]
4
2018-05-27T18:20:10.000Z
2021-11-28T15:22:12.000Z
spcppl/dataStructures/NDArray.hpp
s0rav/spcppl
a17886c9082055490dab09c47a250accfadd8513
[ "WTFPL" ]
8
2016-10-28T16:46:05.000Z
2021-02-24T16:49:20.000Z
#pragma once #include <cstddef> #include <array> #include <vector> #include <type_traits> #include <spcppl/typeTraits/enable_if_t.hpp> #include <spcppl/assert.hpp> #include <spcppl/ranges/fors.hpp> template <typename T, std::size_t depth> class NDArrayView { public: using Ref = std::conditional_t<depth == 1, T&, NDArrayView<T, depth - 1>>; Ref operator[] (std::size_t index) const { return get_element_impl(index); } Ref front() const { return get_at_index(0); } Ref back() const { if (suffixSizes[0] == 0) { return front(); } return get_at_index(suffixSizes[0] - (depth == 1 ? 1 : suffixSizes[1])); } operator NDArrayView<const T, depth>() const { return NDArrayView<const T, depth>(elements, suffixSizes); } NDArrayView(NDArrayView&&) = default; NDArrayView& operator= (const NDArrayView&) = delete; NDArrayView&& operator= (NDArrayView&&) = delete; private: template <std::size_t d = depth, enable_if_t<d == 1>* = nullptr> T& get_element_impl(std::size_t index) const { return elements[index]; } template <std::size_t d = depth, enable_if_t<d != 1>* = nullptr> NDArrayView<T, depth - 1> get_element_impl(std::size_t index) const { return NDArrayView<T, depth - 1>(elements + suffixSizes[1] * index, suffixSizes + 1); } template <std::size_t d = depth, enable_if_t<d == 1>* = nullptr> T& get_at_index(std::size_t index) const { return elements[index]; } template <std::size_t d = depth, enable_if_t<d != 1>* = nullptr> NDArrayView<T, depth - 1> get_at_index(std::size_t index) const { return NDArrayView<T, depth - 1>(elements + index, suffixSizes + 1); } NDArrayView(T* elements, const std::size_t* suffixSizes): elements(elements), suffixSizes(suffixSizes) { } T* elements; const std::size_t* suffixSizes; template <typename U, std::size_t d> friend class NDArray; template <typename U, std::size_t d> friend class NDArrayView; template <typename U, std::size_t d> friend void assignView(NDArrayView<U, d> lhs, NDArrayView<U, d> rhs); }; template <typename T, std::size_t depth> void assignView(NDArrayView<T, depth> lhs, NDArrayView<T, depth> rhs) { SPCPPL_ASSERT(lhs.suffixSizes[0] == rhs.suffixSizes[0]); std::copy(rhs.elements, rhs.elements + lhs.suffixSizes[0], lhs.elements); }; template <typename T, std::size_t d> bool operator==(const NDArrayView<T, d>&, const NDArrayView<T, d>&) = delete; template <typename T, std::size_t d> bool operator!=(const NDArrayView<T, d>&, const NDArrayView<T, d>&) = delete; template <typename T, std::size_t depth> using NDArrayConstView = NDArrayView<const T, depth>; template <typename T, std::size_t depth> class NDArray { public: using Ref = typename NDArrayView<T, depth>::Ref; using ConstRef = typename NDArrayView<const T, depth>::Ref; NDArray(const std::array<std::size_t, depth>& sizes): suffixSizes(suffixProducts(sizes)), elements(suffixSizes[0]) { } NDArray(const std::array<std::size_t, depth>& sizes, const T& t): suffixSizes(suffixProducts(sizes)), elements(suffixSizes[0], t) { } Ref operator[] (std::size_t index) { return static_cast<NDArrayView<T, depth>>(*this)[index]; } ConstRef operator[] (std::size_t index) const { return static_cast<NDArrayView<const T, depth>>(*this)[index]; } operator NDArrayView<T, depth>() { return NDArrayView<T, depth>(elements.data(), suffixSizes.data()); } operator NDArrayConstView<T, depth>() const { return NDArrayConstView<T, depth>(elements.data(), suffixSizes.data()); } Ref front() { return static_cast<NDArrayView<T, depth>>(*this).front(); } ConstRef front() const { return static_cast<NDArrayConstView<T, depth - 1>>(*this).front(); } Ref back() { return static_cast<NDArrayView<T, depth>>(*this).back(); } ConstRef back() const { return static_cast<NDArrayConstView<T, depth - 1>>(*this).back(); } private: static std::array<std::size_t, depth> suffixProducts(const std::array<std::size_t, depth>& sizes) { std::array<std::size_t, depth> result; std::size_t last = 1; for (std::size_t index: downrange(depth)) { last *= sizes[index]; result[index] = last; } return result; } std::array<std::size_t, depth> suffixSizes; std::vector<T> elements; template <typename U, std::size_t e> friend bool operator==(const NDArray<U, e>& lhs, const NDArray<U, e>& rhs); }; template <typename T, typename... Args> NDArray<T, sizeof...(Args)> makeArray(Args... sizes) { return NDArray<T, sizeof...(Args)>( std::array<std::size_t, sizeof...(Args)>{{ static_cast<std::size_t>(sizes)... }} ); } template <typename T, typename... Args> NDArray<T, sizeof...(Args)> makeFilledArray(const T& value, Args... sizes) { return NDArray<T, sizeof...(Args)>( std::array<std::size_t, sizeof...(Args)>{{ static_cast<std::size_t>(sizes)... }}, value ); } template <typename T, std::size_t d> bool operator==(const NDArray<T, d>& lhs, const NDArray<T, d>& rhs) { SPCPPL_ASSERT(lhs.suffixSizes == rhs.suffixSizes); return lhs.elements == rhs.elements; } template <typename T, std::size_t d> bool operator!=(const NDArray<T, d>& lhs, const NDArray<T, d>& rhs) { return !(lhs == rhs); }
27.918919
100
0.68635
[ "vector" ]
0686cfcfb079d310cba93f4e6c2441fb5f722277
2,780
cc
C++
src/CanvasGradient.cc
AF83/node-canvas
557a5aed11a9755280fe9c37c2f1bf5efd2e7fb4
[ "MIT", "Unlicense" ]
null
null
null
src/CanvasGradient.cc
AF83/node-canvas
557a5aed11a9755280fe9c37c2f1bf5efd2e7fb4
[ "MIT", "Unlicense" ]
null
null
null
src/CanvasGradient.cc
AF83/node-canvas
557a5aed11a9755280fe9c37c2f1bf5efd2e7fb4
[ "MIT", "Unlicense" ]
null
null
null
// // Gradient.cc // // Copyright (c) 2010 LearnBoost <tj@learnboost.com> // #include "color.h" #include "Canvas.h" #include "CanvasGradient.h" Persistent<FunctionTemplate> Gradient::constructor; /* * Initialize CanvasGradient. */ void Gradient::Initialize(Handle<Object> target) { HandleScope scope; // Constructor constructor = Persistent<FunctionTemplate>::New(FunctionTemplate::New(Gradient::New)); constructor->InstanceTemplate()->SetInternalFieldCount(1); constructor->SetClassName(String::NewSymbol("CanvasGradient")); // Prototype NODE_SET_PROTOTYPE_METHOD(constructor, "addColorStop", AddColorStop); target->Set(String::NewSymbol("CanvasGradient"), constructor->GetFunction()); } /* * Initialize a new CanvasGradient. */ Handle<Value> Gradient::New(const Arguments &args) { HandleScope scope; // Linear if (4 == args.Length()) { Gradient *grad = new Gradient( args[0]->NumberValue() , args[1]->NumberValue() , args[2]->NumberValue() , args[3]->NumberValue()); grad->Wrap(args.This()); return args.This(); } // Radial if (6 == args.Length()) { Gradient *grad = new Gradient( args[0]->NumberValue() , args[1]->NumberValue() , args[2]->NumberValue() , args[3]->NumberValue() , args[4]->NumberValue() , args[5]->NumberValue()); grad->Wrap(args.This()); return args.This(); } return ThrowException(Exception::TypeError(String::New("invalid arguments"))); } /* * Add color stop. */ Handle<Value> Gradient::AddColorStop(const Arguments &args) { HandleScope scope; if (!args[0]->IsNumber()) return ThrowException(Exception::TypeError(String::New("offset required"))); if (!args[1]->IsString()) return ThrowException(Exception::TypeError(String::New("color string required"))); Gradient *grad = ObjectWrap::Unwrap<Gradient>(args.This()); short ok; String::AsciiValue str(args[1]); uint32_t rgba = rgba_from_string(*str, &ok); if (ok) { rgba_t color = rgba_create(rgba); cairo_pattern_add_color_stop_rgba( grad->pattern() , args[0]->NumberValue() , color.r , color.g , color.b , color.a); } else { return ThrowException(Exception::TypeError(String::New("parse color failed"))); } return Undefined(); } /* * Initialize linear gradient. */ Gradient::Gradient(double x0, double y0, double x1, double y1) { _pattern = cairo_pattern_create_linear(x0, y0, x1, y1); } /* * Initialize radial gradient. */ Gradient::Gradient(double x0, double y0, double r0, double x1, double y1, double r1) { _pattern = cairo_pattern_create_radial(x0, y0, r0, x1, y1, r1); } /* * Destroy the pattern. */ Gradient::~Gradient() { cairo_pattern_destroy(_pattern); }
22.601626
88
0.660072
[ "object" ]
069046f6477e91a6e406c92f4f2054790ee3d5e1
1,766
hpp
C++
inc/prerequisites.hpp
TankleL/liblight
77e14df6c0b0345b0f1e8d69d7bb21d190833a56
[ "MIT" ]
3
2018-08-28T12:30:56.000Z
2021-02-22T10:17:56.000Z
inc/prerequisites.hpp
TankleL/liblight
77e14df6c0b0345b0f1e8d69d7bb21d190833a56
[ "MIT" ]
null
null
null
inc/prerequisites.hpp
TankleL/liblight
77e14df6c0b0345b0f1e8d69d7bb21d190833a56
[ "MIT" ]
null
null
null
#pragma once #include <assert.h> #include <memory> #include <cstring> #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <unordered_map> #include <string> #include <sstream> #include <exception> #include <thread> #include <mutex> #include <condition_variable> #ifdef WIN32 # ifdef API_DEV_MOD # define LIGHT_API __declspec(dllexport) # else # define LIGHT_API __declspec(dllimport) # endif #else # define LIGHT_API #endif #define ACCURACY_DOUBLE #define BEGIN_TRY() try{ #define CTA() }catch(...){throw;} namespace Light { typedef unsigned char byte; typedef int int32; typedef long long int64; typedef unsigned int uint32; typedef unsigned long long uint64; typedef void *pvoid; typedef size_t index; typedef size_t uintx; template<typename _Type> inline void safe_delete(_Type*& p_target) { if (p_target != nullptr) { delete p_target; p_target = nullptr; } } template<typename _Type> inline void safe_delete_arr(_Type*& p_target) { if (p_target != nullptr) { delete[] p_target; p_target = nullptr; } } template<typename _Type> inline void safe_release(_Type*& p_target) { if (p_target != nullptr) { p_target->release(); p_target = nullptr; } } template<typename _Type> inline void safe_delete(std::unique_ptr<_Type>& p_target) { if (nullptr != p_target) { delete p_target.release(); } } template<typename _Type> inline void safe_delete_arr(std::unique_ptr<_Type>& p_target) { if (nullptr != p_target) { delete[] p_target.release(); } } template<typename _Type> inline void safe_release(std::unique_ptr<_Type>& p_target) { if (nullptr != p_target) { p_target->release(); p_target.release(); } } }
17.145631
62
0.692525
[ "vector" ]
06918a270cf3a4c223516eaf41697e8e5f0eafc3
663
hpp
C++
src/exported/WindowOpenGl.hpp
Akaito/csaru-xapp-cpp
e44dd1e8c7de76958eeea8d7964e8242fe35f334
[ "Zlib" ]
null
null
null
src/exported/WindowOpenGl.hpp
Akaito/csaru-xapp-cpp
e44dd1e8c7de76958eeea8d7964e8242fe35f334
[ "Zlib" ]
null
null
null
src/exported/WindowOpenGl.hpp
Akaito/csaru-xapp-cpp
e44dd1e8c7de76958eeea8d7964e8242fe35f334
[ "Zlib" ]
null
null
null
#pragma once #include "Window.hpp" typedef void * SDL_GLContext; namespace csaru { namespace xapp { class WindowOpenGl : public Window { protected: SDL_GLContext m_glContext = nullptr; float m_clearColor[4]; void SetClearColor (float r, float g, float b, float a); public: virtual ~WindowOpenGl (); SDL_GLContext SdlGlContext () { return m_glContext; } public: // csaru::xapp::Window virtual bool Init (const char * title, uint32_t width, uint32_t height) override; virtual void Destroy () override; virtual void Clear () override; virtual void Render () override; }; } // namespace xapp } // namespace csaru
20.71875
85
0.692308
[ "render" ]
06985197ddae5ed329cfdf105b89c5a39a76f9cc
16,608
cpp
C++
test/test_cube.cpp
chuckwolber/Cube
56aae900c3c0c866940cade9d814c3fc7281ec33
[ "MIT" ]
2
2021-04-09T18:11:35.000Z
2022-02-12T18:12:10.000Z
test/test_cube.cpp
chuckwolber/Cube
56aae900c3c0c866940cade9d814c3fc7281ec33
[ "MIT" ]
5
2019-08-29T07:54:56.000Z
2021-08-19T07:01:34.000Z
test/test_cube.cpp
chuckwolber/Cube
56aae900c3c0c866940cade9d814c3fc7281ec33
[ "MIT" ]
1
2021-04-08T20:04:27.000Z
2021-04-08T20:04:27.000Z
/** * SPDX-License-Identifier: MIT * * Copyright (c) 2019 Chuck Wolber * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <cassert> #include <iostream> #include <vector> #include "../Algorithm.h" #include "../Cube.h" void test_constructors(); void test_sized_constructors(unsigned int cubeSize); void test_operators(); void test_getCubeSize(); void test_turns(); Cube getScrambled(); std::vector<CubieColor> getExpectedScrambled(); std::vector<CubieColor> getExpected(CubieColor referenceColor, unsigned int cubeSize); void setColors(std::vector<CubieColor>& cube, std::vector<CubieColor>colorList, unsigned int cubeSize); void verify_cube(Cube cube, std::vector<CubieColor> expected); int main() { test_constructors(); test_operators(); test_getCubeSize(); test_turns(); return 0; } void test_constructors() { std::cout << "Testing constructors... "; Cube c1; verify_cube(c1, getExpected(CubieColor::WHITE, 3)); Cube c2(CubieColor::WHITE); Cube c3(CubieColor::BLUE); Cube c4(CubieColor::GREEN); Cube c5(CubieColor::ORANGE); Cube c6(CubieColor::RED); Cube c7(CubieColor::YELLOW); verify_cube(c2, getExpected(CubieColor::WHITE, 3)); verify_cube(c3, getExpected(CubieColor::BLUE, 3)); verify_cube(c4, getExpected(CubieColor::GREEN, 3)); verify_cube(c5, getExpected(CubieColor::ORANGE, 3)); verify_cube(c6, getExpected(CubieColor::RED, 3)); verify_cube(c7, getExpected(CubieColor::YELLOW, 3)); for (unsigned int i = 0; i < 10; i++) test_sized_constructors(i); std::cout << "Passed" << std::endl; } void test_sized_constructors(unsigned int cubeSize) { Cube c1(CubieColor::WHITE, cubeSize); Cube c2(CubieColor::BLUE, cubeSize); Cube c3(CubieColor::GREEN, cubeSize); Cube c4(CubieColor::ORANGE, cubeSize); Cube c5(CubieColor::RED, cubeSize); Cube c6(CubieColor::YELLOW, cubeSize); Cube c1_cp(c1); Cube c2_cp(c2); Cube c3_cp(c3); Cube c4_cp(c4); Cube c5_cp(c5); Cube c6_cp(c6); verify_cube(c1, getExpected(CubieColor::WHITE, cubeSize)); verify_cube(c2, getExpected(CubieColor::BLUE, cubeSize)); verify_cube(c3, getExpected(CubieColor::GREEN, cubeSize)); verify_cube(c4, getExpected(CubieColor::ORANGE, cubeSize)); verify_cube(c5, getExpected(CubieColor::RED, cubeSize)); verify_cube(c6, getExpected(CubieColor::YELLOW, cubeSize)); verify_cube(c1_cp, getExpected(CubieColor::WHITE, cubeSize)); verify_cube(c2_cp, getExpected(CubieColor::BLUE, cubeSize)); verify_cube(c3_cp, getExpected(CubieColor::GREEN, cubeSize)); verify_cube(c4_cp, getExpected(CubieColor::ORANGE, cubeSize)); verify_cube(c5_cp, getExpected(CubieColor::RED, cubeSize)); verify_cube(c6_cp, getExpected(CubieColor::YELLOW, cubeSize)); Cube c1_mv(std::move(c1)); Cube c2_mv(std::move(c2)); Cube c3_mv(std::move(c3)); Cube c4_mv(std::move(c4)); Cube c5_mv(std::move(c5)); Cube c6_mv(std::move(c6)); verify_cube(c1_mv, getExpected(CubieColor::WHITE, cubeSize)); verify_cube(c2_mv, getExpected(CubieColor::BLUE, cubeSize)); verify_cube(c3_mv, getExpected(CubieColor::GREEN, cubeSize)); verify_cube(c4_mv, getExpected(CubieColor::ORANGE, cubeSize)); verify_cube(c5_mv, getExpected(CubieColor::RED, cubeSize)); verify_cube(c6_mv, getExpected(CubieColor::YELLOW, cubeSize)); } void test_operators() { std::cout << "Testing operators... "; Cube c4(CubieColor::WHITE, 4); Cube c5(CubieColor::BLUE, 5); Cube c6(CubieColor::GREEN, 6); Cube c7(CubieColor::ORANGE, 7); Cube c8(CubieColor::RED, 8); Cube c9(CubieColor::YELLOW, 9); verify_cube(c4, getExpected(CubieColor::WHITE, 4)); verify_cube(c5, getExpected(CubieColor::BLUE, 5)); verify_cube(c6, getExpected(CubieColor::GREEN, 6)); verify_cube(c7, getExpected(CubieColor::ORANGE, 7)); verify_cube(c8, getExpected(CubieColor::RED, 8)); verify_cube(c9, getExpected(CubieColor::YELLOW, 9)); Cube c4_cp; c4_cp = c4; assert(c4_cp == c4); Cube c5_cp; c5_cp = c5; assert(c5_cp == c5); Cube c6_cp; c6_cp = c6; assert(c6_cp == c6); Cube c7_cp; c7_cp = c7; assert(c7_cp == c7); Cube c8_cp; c8_cp = c8; assert(c8_cp == c8); Cube c9_cp; c9_cp = c9; assert(c9_cp == c9); verify_cube(c4_cp, getExpected(CubieColor::WHITE, 4)); verify_cube(c5_cp, getExpected(CubieColor::BLUE, 5)); verify_cube(c6_cp, getExpected(CubieColor::GREEN, 6)); verify_cube(c7_cp, getExpected(CubieColor::ORANGE, 7)); verify_cube(c8_cp, getExpected(CubieColor::RED, 8)); verify_cube(c9_cp, getExpected(CubieColor::YELLOW, 9)); Cube c4_mv; c4_mv = std::move(c4); Cube c5_mv; c5_mv = std::move(c5); Cube c6_mv; c6_mv = std::move(c6); Cube c7_mv; c7_mv = std::move(c7); Cube c8_mv; c8_mv = std::move(c8); Cube c9_mv; c9_mv = std::move(c9); verify_cube(c4_mv, getExpected(CubieColor::WHITE, 4)); verify_cube(c5_mv, getExpected(CubieColor::BLUE, 5)); verify_cube(c6_mv, getExpected(CubieColor::GREEN, 6)); verify_cube(c7_mv, getExpected(CubieColor::ORANGE, 7)); verify_cube(c8_mv, getExpected(CubieColor::RED, 8)); verify_cube(c9_mv, getExpected(CubieColor::YELLOW, 9)); std::cout << "Passed" << std::endl; } void test_getCubeSize() { std::cout << "Testing getCubeSize... "; Cube c1; assert(c1.getCubeSize() == 3); for (unsigned int i = 2; i < 10; i++) { Cube c(CubieColor::WHITE, i); assert(c.getCubeSize() == i); } std::cout << "Passed" << std::endl; } void test_turns() { std::cout << "Testing turns... "; Cube c1(CubieColor::RED), c2(CubieColor::RED), c3(CubieColor::RED); assert(c1.isSolved()); assert(c2.isSolved()); assert(c3.isSolved()); assert(c1 == c2); assert(c2 == c3); c1 = getScrambled(); verify_cube(c1, getExpectedScrambled()); assert(c1 != c2); assert(!c1.isSolved()); Algorithm alg; alg.setAlgorithm("R' B U' L F' U F' D"); c2.performAlgorithm(alg.getAlgorithm()); assert(c2 == c1); assert(!c2.isSolved()); verify_cube(c2, getExpectedScrambled()); c3.turn({Layer::R, false}); c3.turn({Layer::B, true}); c3.turn({Layer::U, false}); c3.turn({Layer::L, true}); c3.turn({Layer::F, false}); c3.turn({Layer::U, true}); c3.turn({Layer::F, false}); c3.turn({Layer::D, true}); assert(c3 == c2); assert(!c3.isSolved()); verify_cube(c3, getExpectedScrambled()); alg.setAlgorithm("D' F U' F L' U B' R"); c1.performAlgorithm(alg.getAlgorithm()); c2.performAlgorithm(alg.getAlgorithm()); c3.turn({Layer::D, false}); c3.turn({Layer::F, true}); c3.turn({Layer::U, false}); c3.turn({Layer::F, true}); c3.turn({Layer::L, false}); c3.turn({Layer::U, true}); c3.turn({Layer::B, false}); c3.turn({Layer::R, true}); verify_cube(c1, getExpected(CubieColor::RED, 3)); verify_cube(c2, getExpected(CubieColor::RED, 3)); verify_cube(c3, getExpected(CubieColor::RED, 3)); assert(c1.isSolved()); assert(c2.isSolved()); assert(c3.isSolved()); assert(c1 == c2); assert(c2 == c3); c1.turn({Layer::F, true}); assert(!c1.isSolved()); c1.turn({Layer::F, false}); assert(c1.isSolved()); c1.turn({Layer::U, true}); assert(!c1.isSolved()); c1.turn({Layer::U, false}); assert(c1.isSolved()); c1.turn({Layer::L, true}); assert(!c1.isSolved()); c1.turn({Layer::L, false}); assert(c1.isSolved()); c1.turn({Layer::R, true}); assert(!c1.isSolved()); c1.turn({Layer::R, false}); assert(c1.isSolved()); c1.turn({Layer::D, true}); assert(!c1.isSolved()); c1.turn({Layer::D, false}); assert(c1.isSolved()); c1.turn({Layer::B, true}); assert(!c1.isSolved()); c1.turn({Layer::B, false}); assert(c1.isSolved()); c1.turn({Layer::M, true}); assert(!c1.isSolved()); c1.turn({Layer::M, false}); assert(c1.isSolved()); c1.turn({Layer::E, true}); assert(!c1.isSolved()); c1.turn({Layer::E, false}); assert(c1.isSolved()); c1.turn({Layer::S, true}); assert(!c1.isSolved()); c1.turn({Layer::S, false}); assert(c1.isSolved()); c1.turn({Layer::M, true}); assert(!c1.isSolved()); c1.turn({Layer::M, true}); assert(!c1.isSolved()); c1.turn({Layer::M, true}); assert(!c1.isSolved()); c1.turn({Layer::M, true}); assert(c1.isSolved()); c1.turn({Layer::E, true}); assert(!c1.isSolved()); c1.turn({Layer::E, true}); assert(!c1.isSolved()); c1.turn({Layer::E, true}); assert(!c1.isSolved()); c1.turn({Layer::E, true}); assert(c1.isSolved()); c1.turn({Layer::S, true}); assert(!c1.isSolved()); c1.turn({Layer::S, true}); assert(!c1.isSolved()); c1.turn({Layer::S, true}); assert(!c1.isSolved()); c1.turn({Layer::S, true}); assert(c1.isSolved()); std::cout << "Passed" << std::endl; } /** * Returns a cube in the following arrangement: * * r o o * b w o * b y o * g w o w r b y b g w w w * g g w r r b y b y o o y * o o y g g b r g b y b y * r r w * g y w * g r r */ Cube getScrambled() { Cube c(CubieColor::RED, 3); c.turn({Layer::R, false}); c.turn({Layer::B, true}); c.turn({Layer::U, false}); c.turn({Layer::L, true}); c.turn({Layer::F, false}); c.turn({Layer::U, true}); c.turn({Layer::F, false}); c.turn({Layer::D, true}); return c; } std::vector<CubieColor> getExpectedScrambled() { std::vector<CubieColor> tmp; for (int i = 0; i < 3*4*3*3; i++) tmp.push_back(CubieColor::NOCOLOR); /* Up Face */ tmp.at(3) = CubieColor::RED; tmp.at(4) = CubieColor::ORANGE; tmp.at(5) = CubieColor::ORANGE; tmp.at(15) = CubieColor::BLUE; tmp.at(16) = CubieColor::WHITE; tmp.at(17) = CubieColor::ORANGE; tmp.at(27) = CubieColor::BLUE; tmp.at(28) = CubieColor::YELLOW; tmp.at(29) = CubieColor::ORANGE; /* Left Face */ tmp.at(36) = CubieColor::GREEN; tmp.at(37) = CubieColor::WHITE; tmp.at(38) = CubieColor::ORANGE; tmp.at(48) = CubieColor::GREEN; tmp.at(49) = CubieColor::GREEN; tmp.at(50) = CubieColor::WHITE; tmp.at(60) = CubieColor::ORANGE; tmp.at(61) = CubieColor::ORANGE; tmp.at(62) = CubieColor::YELLOW; /* Front Face */ tmp.at(39) = CubieColor::WHITE; tmp.at(40) = CubieColor::RED; tmp.at(41) = CubieColor::BLUE; tmp.at(51) = CubieColor::RED; tmp.at(52) = CubieColor::RED; tmp.at(53) = CubieColor::BLUE; tmp.at(63) = CubieColor::GREEN; tmp.at(64) = CubieColor::GREEN; tmp.at(65) = CubieColor::BLUE; /* Right Face */ tmp.at(42) = CubieColor::YELLOW; tmp.at(43) = CubieColor::BLUE; tmp.at(44) = CubieColor::GREEN; tmp.at(54) = CubieColor::YELLOW; tmp.at(55) = CubieColor::BLUE; tmp.at(56) = CubieColor::YELLOW; tmp.at(66) = CubieColor::RED; tmp.at(67) = CubieColor::GREEN; tmp.at(68) = CubieColor::BLUE; /* Back Face */ tmp.at(45) = CubieColor::WHITE; tmp.at(46) = CubieColor::WHITE; tmp.at(47) = CubieColor::WHITE; tmp.at(57) = CubieColor::ORANGE; tmp.at(58) = CubieColor::ORANGE; tmp.at(59) = CubieColor::YELLOW; tmp.at(69) = CubieColor::YELLOW; tmp.at(70) = CubieColor::BLUE; tmp.at(71) = CubieColor::YELLOW; /* Down Face */ tmp.at(75) = CubieColor::RED; tmp.at(76) = CubieColor::RED; tmp.at(77) = CubieColor::WHITE; tmp.at(87) = CubieColor::GREEN; tmp.at(88) = CubieColor::YELLOW; tmp.at(89) = CubieColor::WHITE; tmp.at(99) = CubieColor::GREEN; tmp.at(100) = CubieColor::RED; tmp.at(101) = CubieColor::RED; return tmp; } std::vector<CubieColor> getExpected(CubieColor referenceColor, unsigned int cubeSize) { if (cubeSize < 2) cubeSize = 2; std::vector<CubieColor> colorList; std::vector<CubieColor> tmp; for (unsigned int i = 0; i < cubeSize*4*cubeSize*3; i++) tmp.push_back(CubieColor::NOCOLOR); switch (referenceColor) { case CubieColor::BLUE: colorList.push_back(CubieColor::WHITE); colorList.push_back(CubieColor::RED); colorList.push_back(CubieColor::BLUE); colorList.push_back(CubieColor::ORANGE); colorList.push_back(CubieColor::GREEN); colorList.push_back(CubieColor::YELLOW); break; case CubieColor::GREEN: colorList.push_back(CubieColor::WHITE); colorList.push_back(CubieColor::ORANGE); colorList.push_back(CubieColor::GREEN); colorList.push_back(CubieColor::RED); colorList.push_back(CubieColor::BLUE); colorList.push_back(CubieColor::YELLOW); break; case CubieColor::ORANGE: colorList.push_back(CubieColor::WHITE); colorList.push_back(CubieColor::BLUE); colorList.push_back(CubieColor::ORANGE); colorList.push_back(CubieColor::GREEN); colorList.push_back(CubieColor::RED); colorList.push_back(CubieColor::YELLOW); break; case CubieColor::RED: colorList.push_back(CubieColor::WHITE); colorList.push_back(CubieColor::GREEN); colorList.push_back(CubieColor::RED); colorList.push_back(CubieColor::BLUE); colorList.push_back(CubieColor::ORANGE); colorList.push_back(CubieColor::YELLOW); break; case CubieColor::WHITE: colorList.push_back(CubieColor::GREEN); colorList.push_back(CubieColor::RED); colorList.push_back(CubieColor::WHITE); colorList.push_back(CubieColor::ORANGE); colorList.push_back(CubieColor::YELLOW); colorList.push_back(CubieColor::BLUE); break; case CubieColor::YELLOW: colorList.push_back(CubieColor::GREEN); colorList.push_back(CubieColor::ORANGE); colorList.push_back(CubieColor::YELLOW); colorList.push_back(CubieColor::RED); colorList.push_back(CubieColor::WHITE); colorList.push_back(CubieColor::BLUE); break; default: break; } setColors(tmp, colorList, cubeSize); return tmp; } void setColors(std::vector<CubieColor>& cube, std::vector<CubieColor>colorList, unsigned int cubeSize) { unsigned int i = 0; /* Up Face */ for (unsigned int j = 0; j < cubeSize; j++) { for (unsigned int k = 0; k < cubeSize; k++) i++; for (unsigned int k = 0; k < cubeSize; k++) cube.at(i++) = colorList.at(0); for (unsigned int k = 0; k < cubeSize; k++) i++; for (unsigned int k = 0; k < cubeSize; k++) i++; } /* Left, Front, Right, Back Faces */ for (unsigned int j = 0; j < cubeSize; j++) { for (unsigned int k = 0; k < cubeSize; k++) cube.at(i++) = colorList.at(1); for (unsigned int k = 0; k < cubeSize; k++) cube.at(i++) = colorList.at(2); for (unsigned int k = 0; k < cubeSize; k++) cube.at(i++) = colorList.at(3); for (unsigned int k = 0; k < cubeSize; k++) cube.at(i++) = colorList.at(4); } /* Down Face */ for (unsigned int j = 0; j < cubeSize; j++) { for (unsigned int k = 0; k < cubeSize; k++) i++; for (unsigned int k = 0; k < cubeSize; k++) cube.at(i++) = colorList.at(5); for (unsigned int k = 0; k < cubeSize; k++) i++; for (unsigned int k = 0; k < cubeSize; k++) i++; } } void verify_cube(Cube cube, std::vector<CubieColor> expected) { std::vector<CubieColor> result = cube.getCube(); assert(result.size() == expected.size()); for (unsigned int i = 0; i < result.size(); i++) assert(result.at(i) == expected.at(i)); }
36.501099
101
0.634694
[ "vector" ]
069d85f2548e70c38fd8b0b8ec89ac408a47bcad
2,770
cpp
C++
plugins/core/client/tools/Madgine_Tools/im3d/im3drenderpass.cpp
MadManRises/Madgine
c9949bc9cf8b30d63db0da2382c9fbc5b60bcd0f
[ "MIT" ]
5
2018-05-16T14:09:34.000Z
2019-10-24T19:01:15.000Z
plugins/core/client/tools/Madgine_Tools/im3d/im3drenderpass.cpp
MadManRises/Madgine
c9949bc9cf8b30d63db0da2382c9fbc5b60bcd0f
[ "MIT" ]
71
2017-06-20T06:41:42.000Z
2021-01-11T11:18:53.000Z
plugins/core/client/tools/Madgine_Tools/im3d/im3drenderpass.cpp
MadManRises/Madgine
c9949bc9cf8b30d63db0da2382c9fbc5b60bcd0f
[ "MIT" ]
2
2018-05-16T13:57:25.000Z
2018-05-16T13:57:51.000Z
#include "../clienttoolslib.h" #include "im3drenderpass.h" #include "Madgine/render/rendertarget.h" #include "im3d/im3d.h" #include "im3d/im3d_internal.h" #include "Madgine/render/camera.h" #include "Madgine/render/shadinglanguage/sl.h" #include "render/texturedescriptor.h" #define SL_SHADER im3d #include INCLUDE_SL_SHADER namespace Engine { namespace Render { Im3DRenderPass::Im3DRenderPass(Camera *camera, int priority) : mCamera(camera) , mPriority(priority) { mProgram.create("im3d", { sizeof(Im3DPerApplication) , sizeof(Im3DPerFrame), sizeof(Im3DPerObject) }); } void Im3DRenderPass::render(RenderTarget *target, size_t iteration) { if (!mProgram.available()) return; target->pushAnnotation("Im3D"); Im3D::Im3DContext *context = Im3D::GetCurrentContext(); target->clearDepthBuffer(); Vector2i size = target->size(); float aspectRatio = float(size.x) / size.y; { auto perApplication = mProgram.mapParameters(0).cast<Im3DPerApplication>(); perApplication->p = mCamera->getProjectionMatrix(aspectRatio); } { auto perFrame = mProgram.mapParameters(1).cast<Im3DPerFrame>(); perFrame->v = mCamera->getViewMatrix(); } /*for (const std::pair<Im3DNativeMesh, std::vector<Matrix4>> &p : context->mNativeMeshes) target->renderInstancedMesh(RenderPassFlags_NoLighting, p.first, p.second);*/ for (std::pair<const Im3DTextureId, Im3D::Im3DContext::RenderData> &p : context->mRenderData) { target->bindTextures({ { p.first, Render::TextureType_2D } }); { auto perObject = mProgram.mapParameters(2).cast<Im3DPerObject>(); perObject->hasDistanceField = false; perObject->m = Matrix4::IDENTITY; perObject->hasTexture = p.first != 0; perObject->hasDistanceField = bool(p.second.mFlags & RenderPassFlags_DistanceField); } for (size_t i = 0; i < IM3D_MESHTYPE_COUNT; ++i) { target->renderVertices(mProgram, i + 1, p.second.mVertices[i], p.second.mIndices[i]); /* GPUMeshData::Material mat; mat.mDiffuseHandle = p.first; target->renderVertices(mProgram, i + 1, p.second.mVertices2[i], p.second.mIndices2[i], &mat);*/ if (p.first) throw 0; target->renderVertices(mProgram, i + 1, p.second.mVertices2[i], p.second.mIndices2[i], nullptr); } } target->popAnnotation(); } int Im3DRenderPass::priority() const { return mPriority; } } }
29.157895
128
0.60361
[ "render", "vector" ]
06a1de4a79b2a109f2d43c14dae8f3f14a63f91f
4,155
cc
C++
cpp/Codeforces/301-350/327A_Flipping_Game.cc
phongvcao/CP_Contests_Solutions
2e76e73ee7e53c798f63e1870be47653c75180a9
[ "MIT" ]
null
null
null
cpp/Codeforces/301-350/327A_Flipping_Game.cc
phongvcao/CP_Contests_Solutions
2e76e73ee7e53c798f63e1870be47653c75180a9
[ "MIT" ]
null
null
null
cpp/Codeforces/301-350/327A_Flipping_Game.cc
phongvcao/CP_Contests_Solutions
2e76e73ee7e53c798f63e1870be47653c75180a9
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <sstream> #include <vector> #include <map> std::string indexesToString(int first, int last) { std::stringstream ss; ss << first << last; return ss.str(); } int countFlippedOnes(int *intArr, int first, int last, int length) { int flippedOnesCount = 0; for (int i = first; i != last + 1; ++i) { if (intArr[i] == 0) { ++flippedOnesCount; } } for (int i = 0; i != first; ++i) { if (intArr[i] == 1) { ++flippedOnesCount; } } for (int i = last + 1; i != length; ++i) { if (intArr[i] == 1) { ++flippedOnesCount; } } return flippedOnesCount; } void calculatePossibleFlippedOnes(int *intArr, int left, int right, int length, std::map<std::string, int>& flippedOnesMap) { if (left > right) return; std::string indexesStr = indexesToString(left, right); std::map<std::string, int>::iterator iter = flippedOnesMap.find(indexesStr); if (iter == flippedOnesMap.end()) { flippedOnesMap.insert(std::pair<std::string, int>(indexesStr, countFlippedOnes(intArr, left, right, length))); } else { return; } calculatePossibleFlippedOnes(intArr, left + 1, right, length, flippedOnesMap); calculatePossibleFlippedOnes(intArr, left, right - 1, length, flippedOnesMap); } void testCalculatePossibleFlippedOnes() { int intArr[] = { 1, 1, 1, 1, 1 }; std::map<std::string, int> flippedOnesMap; calculatePossibleFlippedOnes(intArr, 0, 4, 5, flippedOnesMap); for (std::map<std::string, int>::iterator iter = flippedOnesMap.begin(); iter != flippedOnesMap.end(); ++iter) { std::cout << iter->first << ": " << iter->second << std::endl; } } int maxOnes(int *intArr, int left, int right, int nonFlippedOnes) { int nonFlippedOnesLeft = intArr[left]; int nonFlippedOnesRight = intArr[right]; if (left > right) { if (intArr[left] == 0) { return 1; } else if (intArr[right] == 0) { return 1; } else { return 0; } } int maxRight = nonFlippedOnesLeft + maxOnes(intArr, left + 1, right, nonFlippedOnes + nonFlippedOnesLeft); int maxLeft = nonFlippedOnesRight + maxOnes(intArr, left, right - 1, nonFlippedOnes + nonFlippedOnesRight); std::cout << "left: " << left << std::endl; std::cout << "right: " << right << std::endl; std::cout << "nonFlippedOnesLeft: " << nonFlippedOnesLeft << std::endl; std::cout << "nonFlippedOnesRight: " << nonFlippedOnesRight << std::endl; std::cout << "maxRight: " << maxRight << std::endl; std::cout << "maxLeft: " << maxLeft << std::endl; std::cout << std::endl; return (maxLeft < maxRight) ? maxRight : maxLeft; } void testMaxOnes() { int intArr[] = { 1, 0, 0, 0, 1, 0}; std::cout << maxOnes(intArr, 0, 5, 0) << std::endl; } int main(int argc, char **argv) { // testMaxOnes(); // testCalculatePossibleFlippedOnes(); int n = 0; // Read the first line std::string line = ""; if (std::getline(std::cin, line)) { std::stringstream ss(line); ss >> n; } int intArr[n]; int intArrIdx = 0; // Read the second line if (std::getline(std::cin, line)) { std::stringstream ss(line); while (intArrIdx < n) { ss >> intArr[intArrIdx++]; } } // Logic starts here if (n == 1) { if (intArr[0] == 0) { std::cout << 1; } else { std::cout << 0; } } else { std::map<std::string, int> flippedOnesMap; calculatePossibleFlippedOnes(intArr, 0, n - 1, n, flippedOnesMap); int maxOnes = 0; std::string maxIndexes = ""; for (std::map<std::string, int>::iterator iter = flippedOnesMap.begin(); iter != flippedOnesMap.end(); ++iter) { if (iter->second > maxOnes) { maxOnes = iter->second; maxIndexes = iter->first; } } std::cout << maxOnes; } return 0; }
24.732143
125
0.558604
[ "vector" ]
a62c45adafc3f5256a3a35aceb5b1c2af8d94db7
14,098
cpp
C++
src/SpeechStuff.cpp
jfmherokiller/playerTextToSpeechSSE
3e546882f15a545ab14f400748746ed8956ca788
[ "MIT" ]
3
2021-08-08T15:40:11.000Z
2022-01-14T04:06:16.000Z
src/SpeechStuff.cpp
jfmherokiller/playerTextToSpeechSSE
3e546882f15a545ab14f400748746ed8956ca788
[ "MIT" ]
null
null
null
src/SpeechStuff.cpp
jfmherokiller/playerTextToSpeechSSE
3e546882f15a545ab14f400748746ed8956ca788
[ "MIT" ]
1
2022-01-14T04:06:19.000Z
2022-01-14T04:06:19.000Z
// // Created by peter on 7/27/21. // std::vector<ISpObjectToken*> gVoices; ISpVoice* gVoice = nullptr; // Default settings - should match those in Papyrus bool gModEnabled = true; uint32_t gPlayerVoiceID = 0; uint32_t gPlayerVoiceVolume = 50; int32_t gPlayerVoiceRateAdjust = 0; /************************* ** Player speech state ** **************************/ enum PlayerSpeechState { TOPIC_NOT_SELECTED = 0, TOPIC_SELECTED = 1, TOPIC_SPOKEN = 2 }; struct PlayerSpeech { PlayerSpeechState state; bool isNPCSpeechDelayed; uint32_t option; }; PlayerSpeech* gPlayerSpeech = nullptr; void initializePlayerSpeech() { if (gPlayerSpeech == nullptr) { gPlayerSpeech = new PlayerSpeech(); gPlayerSpeech->state = TOPIC_NOT_SELECTED; gPlayerSpeech->isNPCSpeechDelayed = false; } } /*************************************************** ** Event handling for when TTS finished speaking ** ****************************************************/ void TopicSpokenEventDelegateFn() { //uint32_t setTopic = 0x006740E0; //uint32_t sayTopicResponse = 0x006741B0; if (gPlayerSpeech->state == TOPIC_SELECTED) { gPlayerSpeech->state = TOPIC_SPOKEN; gPlayerSpeech->isNPCSpeechDelayed = false; // Here's the fun part: once TTS stopped speaking, we have to set the topic again, // then speak it. It's already done on the first click event, but we're ignoring it // with our onDialogueSayHook to allow TTS to speak. //RE::MenuTopicManager* mtm = RE::MenuTopicManager::GetSingleton(); //thisCall<void>(mtm, setTopic, gPlayerSpeech->option); //thisCall<void>(mtm, sayTopicResponse, 0, 0); } } void executeVoiceNotifyThread() { CSpEvent evt; HANDLE voiceNotifyHandle = gVoice->GetNotifyEventHandle(); do { WaitForSingleObject(voiceNotifyHandle, INFINITE); while (gVoice != nullptr && evt.GetFrom(gVoice) == S_OK) { if (evt.eEventId == SPEI_END_INPUT_STREAM) { SKSE::GetTaskInterface()->AddTask(TopicSpokenEventDelegateFn); } } } while (gVoice != nullptr); } /******************************************** ** Initializing voices and setting up TTS ** *********************************************/ std::vector<ISpObjectToken*> getVoices() { std::vector<ISpObjectToken*> voiceObjects; ULONG voiceCount = 0; ISpObjectToken* voiceObject; IEnumSpObjectTokens* enumVoiceObjects; SpEnumTokens(SPCAT_VOICES, nullptr, nullptr, &enumVoiceObjects); enumVoiceObjects->GetCount(&voiceCount); HRESULT hr = S_OK; ULONG i = 0; while (SUCCEEDED(hr) && i < voiceCount) { hr = enumVoiceObjects->Item(i, &voiceObject); voiceObjects.push_back(voiceObject); i++; } enumVoiceObjects->Release(); return voiceObjects; } ULONG getVoicesCount() { ULONG voiceCount = 0; IEnumSpObjectTokens* enumVoiceObjects; SpEnumTokens(SPCAT_VOICES, nullptr, nullptr, &enumVoiceObjects); enumVoiceObjects->GetCount(&voiceCount); enumVoiceObjects->Release(); return voiceCount; } void initializeVoices() { if (gVoice == nullptr) { gVoices = getVoices(); if (FAILED(CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED))) { //_MESSAGE("Problem: CoInitializeEx failed"); logger::error<>("Problem: CoCreateInstance failed"); } else if (FAILED(CoCreateInstance(CLSID_SpVoice, nullptr, CLSCTX_ALL, IID_ISpVoice, (void **)&gVoice))) { //_MESSAGE("Problem: CoCreateInstance failed"); logger::error<>("Problem: CoCreateInstance failed"); } CoUninitialize(); ULONGLONG eventTypes = SPFEI(SPEI_END_INPUT_STREAM); if (FAILED(gVoice->SetInterest(eventTypes, eventTypes))) { //_MESSAGE("Problem: SetInterest failed"); logger::error<>("Problem: SetInterest failed"); } CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)executeVoiceNotifyThread, nullptr, NULL, nullptr); } } void speak(const char* message) { auto masterVolumeSetting = RE::TESForm::LookupByID<RE::BGSSoundCategory>(0x000EB803)->GetCategoryVolume(); auto voiceVolumeSetting = RE::TESForm::LookupByID<RE::BGSSoundCategory>(0x000876BD)->GetCategoryVolume(); initializeVoices(); std::wstringstream messageStream; messageStream << message; // Volume is set every time because master / voice volume might have changed gVoice->SetVolume((u_short)round((float)gPlayerVoiceVolume * static_cast<float>(masterVolumeSetting) * (voiceVolumeSetting))); gVoice->Speak(messageStream.str().c_str(), SPF_ASYNC | SPF_IS_NOT_XML | SPF_PURGEBEFORESPEAK, nullptr); } void stopSpeaking() { gVoice->Speak(L"", SPF_ASYNC | SPF_IS_NOT_XML | SPF_PURGEBEFORESPEAK, nullptr); } /********************* ** ON TOPIC SETTER ** **********************/ //x86 //BYTE* gOnTopicSetter = (BYTE*)0x00674113; //x64 //uintptr_t gOnTopicSetter = 0x014056F910; uintptr_t gOnTopicSetter; uintptr_t gOnTopicSetterResume; uintptr_t* gOnTopicSetterResumePtr = &gOnTopicSetterResume; struct ObjectWithMessage { const char* message; }; struct ObjectWithObjectWithMessage { ObjectWithMessage* object; }; void onTopicSetterHook(RE::MenuTopicManager* object, uint32_t option) { if (!gModEnabled) { return; } initializePlayerSpeech(); if (gPlayerSpeech->state == TOPIC_NOT_SELECTED || gPlayerSpeech->state == TOPIC_SPOKEN) { gPlayerSpeech->state = TOPIC_SELECTED; gPlayerSpeech->isNPCSpeechDelayed = false; gPlayerSpeech->option = option; speak(object->lastSelectedDialogue->topicText.c_str()); } } //__declspec(naked) void onTopicSetterHooked() { // __asm { // push edx // mov edx, [esp+0xC] // The selected option is an argument to the function, and is still on the stack there // pushad // push edx // push esi // `esi` register here contains a pointer to an object, containing // // a pointer to another object with a pointer to the string of a chosen topic // // (I didn't bother to figure out what this object is) // call onTopicSetterHook // popad // pop edx // jmp[gOnTopicSetterResume] // } //} struct onTopicSetterHookedPatch : Xbyak::CodeGenerator { explicit onTopicSetterHookedPatch(uintptr_t SetterHook,uintptr_t ResumePtr) { mov(rbx, ptr [rsp+0x98]); //mov(edx,ptr [esp+0xC]); //pushad(); //push(edx); //push(esi); push(rcx); mov(rcx, rsi); push(rax); mov(rax, SetterHook); call(rax); pop(rax); pop(rcx); //popad(); //pop(edx); mov(r15, ResumePtr); mov(r15, ptr[r15]); jmp(r15); } }; /*********************** ** DIALOGUE SAY HOOK ** ************************/ uintptr_t gOnDialogueSay; uintptr_t gOnDialogueSayResume; uintptr_t gOnDialogueSaySkip; uintptr_t* gOnDialogueSayResumePtr = &gOnDialogueSayResume; bool shouldDelayNPCSpeech() { if (!gModEnabled) { return false; } initializePlayerSpeech(); // This is for when the user wants to skip the convo by (usually vigorously) clicking if (gPlayerSpeech->state == TOPIC_SELECTED && gPlayerSpeech->isNPCSpeechDelayed) { gPlayerSpeech->state = TOPIC_NOT_SELECTED; gPlayerSpeech->isNPCSpeechDelayed = false; stopSpeaking(); } else if (gPlayerSpeech->state == TOPIC_SELECTED) { gPlayerSpeech->isNPCSpeechDelayed = true; return true; } return false; } struct onDialogueSayHookedPatch : Xbyak::CodeGenerator { explicit onDialogueSayHookedPatch(uintptr_t DelayTest,uintptr_t ResumePtr,uintptr_t SaySkip) { Xbyak::Label DELAY_NPC_SPEECH; //pushad(); mov(ptr [rsp+0x20], ecx); mov(rcx, rbx); push(rcx); mov(rcx,DelayTest); call(rcx); pop(rcx); test(al,al); jnz(DELAY_NPC_SPEECH); //popad(); mov(rax, ResumePtr); mov(rax, ptr[rax]); jmp(rax); L(DELAY_NPC_SPEECH); mov(r8, SaySkip); jmp(r8); //popad(); } }; //__declspec(naked) void onDialogueSayHooked() { // __asm { // pushad // call shouldDelayNPCSpeech // test al, al // jnz DELAY_NPC_SPEECH // If we should delay NPC speech, go to some code after // popad // jmp[gOnDialogueSayResume] // // DELAY_NPC_SPEECH: // popad // jmp[gOnDialogueSaySkip] // } //} /********************************************** ** Registered functions and their delegates ** **********************************************/ void SetVoiceFn() { initializeVoices(); gVoice->SetVoice(gVoices[gPlayerVoiceID]); } void SetRateAdjustFn() { initializeVoices(); gVoice->SetRate(gPlayerVoiceRateAdjust); } std::string getAvailableTTSVoices(RE::StaticFunctionTag*) { std::vector<ISpObjectToken*> voices = getVoices(); // We can't just use `gVoices` because it's on another thread std::vector<std::string> vmVoiceList; WCHAR* szDesc{}; const char* szDescString; size_t size = voices.size(); vmVoiceList.resize(size); for (size_t i = 0; i < size; i++) { SpGetDescription(voices[i], &szDesc); _bstr_t szDescCommon(szDesc); szDescString = szDescCommon; vmVoiceList[i] = std::string(szDescString); voices[i]->Release(); } voices.clear(); auto joinedParts = boost::algorithm::join(vmVoiceList, "::"); return joinedParts; } uint32_t setModEnabled(RE::StaticFunctionTag*, bool modEnabled) { gModEnabled = modEnabled; return 1; // Pretty sure it'll be successful } int32_t setTTSPlayerVoiceID(RE::StaticFunctionTag*, int32_t id) { int32_t isSuccessful = 1; if (static_cast<uint32_t>(id) >= getVoicesCount()) { id = 0; isSuccessful = 0; } gPlayerVoiceID = id; SKSE::GetTaskInterface()->AddTask(SetVoiceFn); return isSuccessful; } int32_t setTTSPlayerVoiceVolume(RE::StaticFunctionTag*, int32_t volume) { int32_t isSuccessful = 1; if (volume > 100 || volume < 0) { volume = 50; isSuccessful = 0; } gPlayerVoiceVolume = volume; return isSuccessful; } int32_t setTTSPlayerVoiceRateAdjust(RE::StaticFunctionTag*, int32_t rateAdjust) { int32_t isSuccessful = 1; if (rateAdjust < -10 || rateAdjust > 10) { rateAdjust = 0; isSuccessful = 0; } gPlayerVoiceRateAdjust = rateAdjust; SKSE::GetTaskInterface()->AddTask(SetRateAdjustFn); return isSuccessful; } bool registerFuncs(RE::BSScript::Internal::VirtualMachine* a_registry) { a_registry->RegisterFunction("GetAvailableTTSVoices", "TTS_Voiced_Player_Dialogue_MCM_Script", getAvailableTTSVoices); a_registry->RegisterFunction("SetTTSModEnabled", "TTS_Voiced_Player_Dialogue_MCM_Script", setModEnabled); a_registry->RegisterFunction("SetTTSPlayerVoiceID", "TTS_Voiced_Player_Dialogue_MCM_Script", setTTSPlayerVoiceID); a_registry->RegisterFunction("SetTTSPlayerVoiceVolume", "TTS_Voiced_Player_Dialogue_MCM_Script", setTTSPlayerVoiceVolume); a_registry->RegisterFunction("SetTTSPlayerVoiceRateAdjust", "TTS_Voiced_Player_Dialogue_MCM_Script", setTTSPlayerVoiceRateAdjust); return true; } /******************** ** Initialization ** *********************/ bool InnerPluginLoad() { //x86 //BYTE* gOnDialogueSaySkip = (BYTE*)0x006D39C4; //x64 //uintptr_t gOnDialogueSaySkip = 0x01405E83D8; //file offset 0x005E77D8 //RVA seems to be 0x5E83D8 gOnDialogueSaySkip = REL::Offset(0x5E83D1).address(); //x86 //BYTE* gOnDialogueSay = (BYTE*)0x006D397E; //comparison https://i.imgur.com/i2exbOy.png //X64 //uintptr_t gOnDialogueSay = 0x01405E837F; gOnDialogueSay = REL::Offset(0x5E83C5).address(); gOnDialogueSayResume = REL::Offset(0x5E83C9).address(); //x86 //BYTE* gOnTopicSetter = (BYTE*)0x00674113; //x64 //uintptr_t gOnTopicSetter = 0x014056F910; //comparison https://i.imgur.com/4ZAN0aU.png //file offset 0x0056ED10 //RVA seems to be 0x56F910 gOnTopicSetter = REL::Offset(0x56F910).address(); gOnTopicSetterResume = REL::Offset(0x56F918).address(); // These set up injection points to the game: auto& trampoline = SKSE::GetTrampoline(); onTopicSetterHookedPatch Tsh{ reinterpret_cast<uintptr_t>(onTopicSetterHook), reinterpret_cast<uintptr_t>(gOnTopicSetterResumePtr) }; onDialogueSayHookedPatch Dsh{ reinterpret_cast<uintptr_t>(shouldDelayNPCSpeech), reinterpret_cast<uintptr_t>(gOnDialogueSayResumePtr), gOnDialogueSaySkip }; const auto onTopicSetterHooked = trampoline.allocate(Tsh); const auto onDialogueSayHooked = trampoline.allocate(Dsh); // 1. When the topic is clicked, we'd like to remember the selected // option (so that we can trigger same option choice later) and actually speak the TTS message //gOnTopicSetterResume = detourWithTrampoline(gOnTopicSetter, (BYTE*)onTopicSetterHooked, 5); REL::safe_fill(gOnTopicSetter, 0x90, 8); trampoline.write_branch<5>(gOnTopicSetter,onTopicSetterHooked); // 2. When the NPC is about to speak, we'd like prevent them initially, but still allow other dialogue events. // We also check there, well, if user clicks during a convo to try to skip it, we'll also stop the TTS speaking. //gOnDialogueSayResume = detourWithTrampoline(gOnDialogueSay, (BYTE*)onDialogueSayHooked, 6); //REL::safe_fill(gOnDialogueSay, 0x90, 7); //trampoline.write_branch<5>(gOnDialogueSay,onDialogueSayHooked); //if (!g_papyrusInterface) { // _MESSAGE("Problem: g_papyrusInterface is false"); // return false; // } auto papyrus = SKSE::GetPapyrusInterface(); if (!papyrus->Register(registerFuncs)) { return false; } //g_taskInterface = static_cast<SKSETaskInterface*>(skse->QueryInterface(kInterface_Task)); //if (!g_taskInterface) { // _MESSAGE("Problem: task registration failed"); // return false; // } logger::info<>("TTS Voiced Player Dialogue loaded"); return true; }
30.581345
157
0.661299
[ "object", "vector" ]
a62d329f4e2f7c444adbbdbd2037fe0f7f5fec62
4,624
hpp
C++
NetKet/Hamiltonian/graph_hamiltonian.hpp
stavros11/netket
1cec25a4884bdbd2fddb5d24daae627cd89316d8
[ "Apache-2.0" ]
null
null
null
NetKet/Hamiltonian/graph_hamiltonian.hpp
stavros11/netket
1cec25a4884bdbd2fddb5d24daae627cd89316d8
[ "Apache-2.0" ]
null
null
null
NetKet/Hamiltonian/graph_hamiltonian.hpp
stavros11/netket
1cec25a4884bdbd2fddb5d24daae627cd89316d8
[ "Apache-2.0" ]
1
2020-10-26T21:05:38.000Z
2020-10-26T21:05:38.000Z
// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef NETKET_BOND_HAMILTONIAN_CC #define NETKET_BOND_HAMILTONIAN_CC #include <Eigen/Dense> #include <array> #include <unordered_map> #include <vector> #include "Utils/json_helper.hpp" #include "local_operator.hpp" namespace netket { // BondHamiltonian on an arbitrary graph template <class G> class GraphHamiltonian : public AbstractHamiltonian { std::vector<LocalOperator> operators_; Hilbert hilbert_; // Arbitrary graph const G &graph_; // const std::size_t nvertices_; const int nvertices_; public: using MatType = LocalOperator::MatType; explicit GraphHamiltonian(const G &graph, const json &pars) : hilbert_(pars), graph_(graph), nvertices_(graph.Nsites()) { auto pars_hamiltonian = pars["Hamiltonian"]; // Ensure that at least one of SiteOps and BondOps was initialized if (!FieldExists(pars_hamiltonian, "SiteOps") and FieldExists(pars_hamiltonian, "BondOps")) { pars_hamiltonian["SiteOps"] = std::vector<MatType>(); } else if (!FieldExists(pars_hamiltonian, "BondOps") and FieldExists(pars_hamiltonian, "SiteOps")) { pars_hamiltonian["BondOps"] = std::vector<MatType>(); } else if (!FieldExists(pars_hamiltonian, "BondOps") and !FieldExists(pars_hamiltonian, "SiteOps")) { throw InvalidInputError("Must input at least SiteOps or BondOps"); } // Ensure that parameters are arrays if (!pars_hamiltonian["SiteOps"].is_array()) { throw InvalidInputError( "Hamiltonian: Bond operators object is not an array!"); } if (!pars_hamiltonian["BondOps"].is_array()) { throw InvalidInputError( "Hamiltonian: Bond operators object is not an array!"); } // Check BondOpColors if (!FieldExists(pars_hamiltonian, "BondOpColors")) { if (pars_hamiltonian["BondOps"].size() == 0) { pars_hamiltonian["BondOpColors"] = std::vector<int>(); } else { pars_hamiltonian["BondOpColors"] = std::vector<int>(pars_hamiltonian["BondOps"].size(), 0); } } if (!pars_hamiltonian["BondOpColors"].is_array()) { throw InvalidInputError("Hamiltonian.BondOpColors is not an array"); } // Save operators and bond colors auto sop = pars_hamiltonian["SiteOps"].get<std::vector<MatType>>(); auto bop = pars_hamiltonian["BondOps"].get<std::vector<MatType>>(); auto op_color = pars_hamiltonian["BondOpColors"].get<std::vector<int>>(); // Site operators if (sop.size() > 0) { for (int i = 0; i < nvertices_; i++) { for (std::size_t j = 0; j < sop.size(); j++) { operators_.push_back( LocalOperator(hilbert_, sop[j], std::vector<int>{i})); } } } // Bond operators if (bop.size() != op_color.size()) { throw InvalidInputError( "The bond Hamiltonian definition is inconsistent." "The sizes of BondOps and BondOpColors do not match."); } if (bop.size() > 0) { // Use EdgeColors to populate operators for (auto const &kv : graph_.EdgeColors()) { for (std::size_t c = 0; c < op_color.size(); c++) { if (op_color[c] == kv.second && kv.first[0] < kv.first[1]) { std::vector<int> edge = {kv.first[0], kv.first[1]}; operators_.push_back(LocalOperator(hilbert_, bop[c], edge)); } } } } InfoMessage() << "Size of operators_ " << operators_.size() << std::endl; } void FindConn(const Eigen::VectorXd &v, std::vector<std::complex<double>> &mel, std::vector<std::vector<int>> &connectors, std::vector<std::vector<double>> &newconfs) const override { connectors.clear(); newconfs.clear(); mel.resize(0); for (std::size_t i = 0; i < operators_.size(); i++) { operators_[i].AddConn(v, mel, connectors, newconfs); } } const Hilbert &GetHilbert() const override { return hilbert_; } }; } // namespace netket #endif
33.751825
77
0.644247
[ "object", "vector" ]
a62dc939b77814bc835a8a52d8965e5d3850e790
7,330
cpp
C++
MTable.cpp
sakurakitten/Bungo-chat
02c60f1c4b40ebe216cbc6f7c1fd534f9df7a981
[ "BSD-3-Clause" ]
null
null
null
MTable.cpp
sakurakitten/Bungo-chat
02c60f1c4b40ebe216cbc6f7c1fd534f9df7a981
[ "BSD-3-Clause" ]
null
null
null
MTable.cpp
sakurakitten/Bungo-chat
02c60f1c4b40ebe216cbc6f7c1fd534f9df7a981
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <map> #include <vector> #include <string> #include <random> #include <sstream> #include <fstream> #include <set> #include <cstdlib> #include "MTable.h" #include "Main.h" MTable::MTable(){} MTable::~MTable(){} MTable::MTable(const std::string& input){ std::string line; #if 1 std::ifstream ifs(input.c_str()); //std::getline(ifs,line); //loadBeginnings(line); while(std::getline(ifs,line)){ loadTableRow(line); } #else std::getline(std::cin,line); //loadBeginnings(line); while(std::getline(std::cin,line)){ loadTableRow(line); } #endif } #if 0 void MTable::loadBeginnings(const std::string& line){ std::stringstream sline; sline<<line; std::string s1,s2; while(sline>>s1&&sline>>s2){ beginnings.push_back(std::make_pair(std::move(s1),std::move(s2))); } } #endif void MTable::loadTableRow(const std::string& line){ std::stringstream sline; sline<<line; std::string s0,s1,s2; sline>>s0>>s1; //std::vector<std::string> row; while(sline>>s2){ //row.push_back(std::move(s2)); forwardTable[std::make_pair(s0,s1)].push_back(s2); middleTable[s1].push_back(std::make_pair(s0,s2)); reverseTable[std::make_pair(s1,s2)].push_back(s0); if(s0=="。"){ beginnings.push_back(std::make_pair(s1,s2)); } } //forward[std::make_pair(std::move(s0),std::move(s1))]=std::move(row); } std::string MTable::respondMarkov(const std::vector<std::string>& words)const{ std::string res; std::set<int> checked; while(true){ int next = rand()%words.size(); if (checked.count(next))continue; //既に調べた単語 res = makeSentence(words[next]); if (!res.empty()) { //文生成成功 break; } else { //nextの単語では文を続けられない checked.insert(next); if (checked.size() == words.size()) return ""; //与えられた単語での文生成不可能 } } return res; } std::string MTable::extendSentence(const std::string& s1, const std::string& s2)const{ if(s2=="。")return s1; //文の終わり std::pair<std::string,std::string> p=std::make_pair(s1,s2); if(forwardTable.find(p)==forwardTable.end())return ""; //2引数に続く単語は存在しない std::string res; std::set<int> checked; //std::uniform_int_distribution<int> dist(0, forwardTable.at(p).size()-1); while (true){ int next = /*dist(mtRand)*/rand()%forwardTable.find(p)->second.size(); if (checked.count(next))continue; //既に調べた単語 res = extendSentence(s2, forwardTable.find(p)->second[next]); if (!res.empty()) { //文生成成功 break; } else { //nextの単語では文を続けられない checked.insert(next); if (checked.size() == forwardTable.find(p)->second.size()) return ""; //与えられた単語での文生成不可能 } } return s1+res; } std::string MTable::extendSentenceBack(const std::string& s1, const std::string& s2)const{ //std::cout<<"extendSentenceBack()"<<std::endl; //std::cout<<s1<<" "<<s2<<std::endl; if(s1=="。")return s2; std::pair<std::string,std::string> p=std::make_pair(s1,s2); if(reverseTable.find(p)==reverseTable.end())return ""; std::string res; std::set<int> checked; //std::uniform_int_distribution<int> dist(0, reverseTable.at(p).size()-1); while (true){ int next = /*dist(mtRand)*/rand()%reverseTable.find(p)->second.size(); if (checked.count(next))continue; //既に調べた単語 res = extendSentence(s2, reverseTable.find(p)->second[next]); if (!res.empty()) { //文生成成功 break; } else { //nextの単語では文を続けられない checked.insert(next); if (checked.size() == reverseTable.find(p)->second.size()) return ""; //与えられた単語での文生成不可能 } } return res+s2; } std::string MTable::makeSentenceRand()const{ std::string res; std::set<int> checked; //std::uniform_int_distribution<int> dist(0, beginnings.size()-1); while(true){ int next = /*dist(mtRand)*/rand()%beginnings.size(); if (checked.count(next))continue; //既に調べた単語 std::pair<std::string,std::string> p=beginnings[next]; //直した!!!!!! res = extendSentence(p.first, p.second); if (!res.empty()) { //文生成成功 break; } else { //nextの単語では文を続けられない checked.insert(next); if (checked.size() == forwardTable.find(p)->second.size()) return ""; //与えられた単語での文生成不可能 } } return res; } std::string MTable::startSentence(const std::string& str)const{ std::pair<std::string,std::string> p=std::make_pair("。",str); if(forwardTable.find(p)==forwardTable.end())return ""; //与えられた単語から文を始めることはできない std::string res; std::set<int> checked; //std::uniform_int_distribution<int> dist(0, forwardTable.at(p).size() - 1); while(true){ int next = /*dist(mtRand)*/rand()%forwardTable.find(p)->second.size(); if (checked.count(next))continue; //既に調べた単語 res = extendSentence(str, forwardTable.find(p)->second[next]); if (!res.empty()) { //文生成成功 break; } else { //nextの単語では文を続けられない checked.insert(next); if (checked.size() == forwardTable.find(p)->second.size()) return ""; //与えられた単語での文生成不可能 } } return res; } std::string MTable::makeSentence(const std::string& str)const{ if (middleTable.find(str) == middleTable.end())return ""; std::string res1; std::string res2; std::set<int> checked1; //std::uniform_int_distribution<int> dist1(0, middleTable.at(str).size()-1); while(true){ int next1 = /*dist1(mtRand)*/rand()%middleTable.find(str)->second.size(); if (checked1.count(next1))continue; //既に調べた単語のペア std::pair<std::string,std::string> p=middleTable.find(str)->second[next1]; std::string s0 = p.first; std::string s2 = p.second; std::pair<std::string, std::string> p1 = std::make_pair(s0, str); if (forwardTable.find(std::make_pair(str, s2)) == forwardTable.end()) { //strの次に来る単語はない checked1.insert(next1); if (checked1.size() == middleTable.find(str)->second.size()) return ""; //与えられた単語での文生成不可能 }; res1 = extendSentenceBack(p1.first,str); if (!res1.empty()) { //strより前の文生成成功 std::set<int> checked2; //std::uniform_int_distribution<int> dist2(0, forwardTable.at(p1).size()-1); while (true) { std::pair<std::string,std::string> p2=std::make_pair(str, s2); int next2 = /*dist2(mtRand)*/rand()%forwardTable.find(p2)->second.size(); if (checked2.count(next2))continue; std::string s3 = forwardTable.find(p2)->second[next2]; std::pair<std::string,std::string> p3=std::make_pair(s2, s3); res2 = extendSentence(s2, s3); if (!res2.empty()) { //strより後の文生成成功 break; } else { checked2.insert(next2); if (checked2.size() == forwardTable.find(p2)->second.size()) break; //str,s2の組み合わせ(=next1)が絶望的 //一つ目のwhileループ内でcontinueしたい } } if (res2.empty()) { //next1が絶望的 checked1.insert(next1); if (checked1.size() == middleTable.find(str)->second.size()) return ""; //与えられた単語での文生成不可能 }else{ //文生成成功 return res1+res2; } } else { //next1の単語では文を続けられない checked1.insert(next1); if (checked1.size() == middleTable.find(str)->second.size()) return ""; //与えられた単語での文生成不可能 } } // std::pair<std::string,std::string> p=middleTable.at(str)[dist(mtRand)]; //std::uniform_int_distribution<int> dist2(0, forwardTable.at(std::make_pair(str, p.second)).size()-1); //std::string s2=forwardTable.at(std::make_pair(str, p.second))[dist2(mtRand)]; //std::cout<<"makeSentence()"<<std::endl; //extendSentenceBack(p.first,str)+extendSentence(p.second, s2) }
30.414938
107
0.64693
[ "vector" ]
a62e710501640dffd58a366dc1d4a16e3c37a512
13,508
cc
C++
LiteCore/RevTrees/VersionVector.cc
udkyo/couchbase-lite-core
18f3368186875461c49a559705f9a791e31c6fb9
[ "Apache-2.0" ]
null
null
null
LiteCore/RevTrees/VersionVector.cc
udkyo/couchbase-lite-core
18f3368186875461c49a559705f9a791e31c6fb9
[ "Apache-2.0" ]
null
null
null
LiteCore/RevTrees/VersionVector.cc
udkyo/couchbase-lite-core
18f3368186875461c49a559705f9a791e31c6fb9
[ "Apache-2.0" ]
null
null
null
// // VersionVector.cc // Couchbase Lite Core // // Created by Jens Alfke on 5/23/16. // Copyright (c) 2016 Couchbase. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. #include "VersionVector.hh" #include "Error.hh" #include "StringUtil.hh" #include "varint.hh" #include "slice_stream.hh" #include <algorithm> #include <unordered_map> namespace litecore { using namespace std; using namespace fleece; using vec = VersionVector::vec; #pragma mark - CONVERSION: #if DEBUG void VersionVector::validate() const { //OPT: This is O(n^2) if (count() > 1) { for (auto i = next(_vers.begin()); i != _vers.end(); ++i) { peerID author = i->author(); for (auto j = _vers.begin(); j != i; ++j) if (j->author() == author) error::_throw(error::BadRevisionID, "Duplicate ID in version vector"); } } } #endif void VersionVector::readBinary(slice data) { reset(); slice_istream in(data); if (in.size < 1 || in.readByte() != 0) Version::throwBadBinary(); while (in.size > 0) _vers.emplace_back(in); validate(); } alloc_slice VersionVector::asBinary(peerID myID) const { auto result = slice_ostream::alloced(1 + _vers.size() * 2 * kMaxVarintLen64, [&](slice_ostream &out) { if (!out.writeByte(0)) // leading 0 byte distinguishes it from a `revid` return false; for (auto &v : _vers) if (!v.writeBinary(out, myID)) return false; return true; }); Assert(result); return result; } size_t VersionVector::maxASCIILen() const { return _vers.size() * (Version::kMaxASCIILength + 1); } bool VersionVector::writeASCII(slice_ostream &out, peerID myID) const { int n = 0; for (auto &v : _vers) { if (n++ && !out.writeByte(',')) return false; if (!v.writeASCII(out, myID)) return false; } return true; } alloc_slice VersionVector::asASCII(peerID myID) const { if (empty()) return nullslice; auto result = slice_ostream::alloced(maxASCIILen(), [&](slice_ostream &out) { return writeASCII(out, myID); }); Assert(result); return result; } #if DEBUG string VersionVector::asString() const { return std::string(asASCII()); } #endif Version VersionVector::readCurrentVersionFromBinary(slice data) { slice_istream in(data); if (data.size < 1 || in.readByte() != 0) Version::throwBadBinary(); return Version(in); } void VersionVector::readASCII(slice str, peerID myPeerID) { reset(); while (str.size > 0) { const void *comma = str.findByteOrEnd(','); _vers.emplace_back(str.upTo(comma), myPeerID); str = str.from(comma); if (str.size > 0) str.moveStart(1); // skip comma } validate(); } void VersionVector::readHistory(const slice history[], size_t historyCount, peerID myPeerID) { Assert(historyCount > 0); readASCII(history[0], myPeerID); if (historyCount == 1) return; // -> Single version vector (or single version) if (count() > 1) error::_throw(error::BadRevisionID, "Invalid version history (vector followed by other history)"); if (historyCount == 2) { Version newVers = _vers[0]; readASCII(history[1], myPeerID); add(newVers); // -> New version plus parent vector } else { for (size_t i = 1; i < historyCount; ++i) { Version parentVers(history[i], myPeerID); if (auto gen = genOfAuthor(parentVers.author()); gen ==0) _vers.push_back(parentVers); else if (gen <= parentVers.gen()) error::_throw(error::BadRevisionID, "Invalid version history (increasing generation)"); } } // -> List of versions } #pragma mark - OPERATIONS: versionOrder VersionVector::compareTo(const Version& v) const { auto mine = findPeerIter(v.author()); if (mine == _vers.end()) return kOlder; else if (mine->gen() < v.gen()) return kOlder; else if (mine->gen() == v.gen() && mine == _vers.begin()) return kSame; else return kNewer; } versionOrder Version::compareTo(const VersionVector &vv) const { versionOrder o = vv.compareTo(*this); if (o == kOlder) return kNewer; else if (o == kNewer) return kOlder; else return o; } versionOrder VersionVector::compareTo(const VersionVector &other) const { // First check if either or both are empty: auto myCount = count(), otherCount = other.count(); if (myCount == 0) return otherCount == 0 ? kSame : kOlder; else if (otherCount == 0) return kNewer; versionOrder o = kSame; ssize_t countDiff = ssize_t(myCount) - ssize_t(otherCount); if (countDiff < 0) o = kOlder; // other must have versions from authors I don't have else if (countDiff > 0) o = kNewer; // I must have versions from authors other doesn't have else if (myCount > 0 && (*this)[0] == other[0]) return kSame; // first revs are identical so vectors are equal //OPT: This is O(n^2), since the `for` loop calls `other[ ]`, which is a linear search. for (auto &v : _vers) { auto othergen = other[v.author()]; if (v.gen() < othergen) { o = versionOrder(o | kOlder); } else if (v.gen() > othergen) { o = versionOrder(o | kNewer); if (othergen == 0) { // other doesn't have this author, which makes its remaining entries more likely // to have authors I don't have; when that becomes certainty, set 'older' flag: if (--countDiff < 0) o = versionOrder(o | kOlder); } } if (o == kConflicting) break; } return o; } bool VersionVector::isNewerIgnoring(peerID ignoring, const VersionVector &other) const { for (const Version &v : _vers) { if (v.author() != ignoring && v.gen() > other[v.author()]) return true; } return false; } vec::iterator VersionVector::findPeerIter(peerID author) const { auto &vers = const_cast<VersionVector*>(this)->_vers; auto v = vers.begin(); for (; v != vers.end(); ++v) { if (v->author() == author) break; } return v; } generation VersionVector::genOfAuthor(peerID author) const { auto v = const_cast<VersionVector*>(this)->findPeerIter(author); return (v != _vers.end()) ? v->gen() : 0; } #pragma mark - MODIFICATION: void VersionVector::limitCount(size_t maxCount) { if (_vers.size() > maxCount) _vers.erase(_vers.begin() + maxCount, _vers.end()); } void VersionVector::incrementGen(peerID author) { generation gen = 1; if (auto versP = findPeerIter(author); versP != _vers.end()) { gen += versP->gen(); _vers.erase(versP); } _vers.insert(_vers.begin(), Version(gen, author)); } bool VersionVector::add(Version v) { if (auto versP = findPeerIter(v.author()); versP != _vers.end()) { if (versP->gen() >= v.gen()) return false; _vers.erase(versP); } _vers.insert(_vers.begin(), v); return true; } void VersionVector::push_back(const Version &vers) { if (genOfAuthor(vers.author()) > 0) error::_throw(error::BadRevisionID, "Adding duplicate ID to version vector"); _vers.push_back(vers); } // bool VersionVector::addHistory(VersionVector &&earlier) { // if (empty()) { // _vers = move(earlier._vers); // } else { // for (auto &v : earlier._vers) { // if (genOfAuthor(v.author()) > 0) // return false; // duplicate author // _vers.push_back(v); // } // } // return true; // } void VersionVector::compactMyPeerID(peerID myID) { if (genOfAuthor(kMePeerID) > 0) error::_throw(error::BadRevisionID, "Vector already contains '*'"); auto versP = findPeerIter(myID); if (versP != _vers.end()) *versP = Version(versP->gen(), kMePeerID); } void VersionVector::expandMyPeerID(peerID myID) { if (genOfAuthor(myID) > 0) error::_throw(error::BadRevisionID, "Vector already contains myID"); auto versP = findPeerIter(kMePeerID); if (versP != _vers.end()) *versP = Version(versP->gen(), myID); } bool VersionVector::isExpanded() const { return genOfAuthor(kMePeerID) == 0; } #pragma mark - MERGING: // A hash table mapping peerID->generation, as an optimization for versionVector operations class versionMap { public: versionMap(const vec &vec) { _map.reserve(vec.size()); for (auto &v : vec) add(v); } void add(const Version &vers) { _map[vers.author().id] = vers.gen(); } generation operator[] (peerID author) { auto i = _map.find(author.id); return (i == _map.end()) ? 0 : i->second; } private: unordered_map<uint64_t, generation> _map; }; VersionVector VersionVector::mergedWith(const VersionVector &other) const { // Walk through the two vectors in parallel, adding the current component from each if it's // newer than the corresponding component in the other. This isn't going to produce the // optimal ordering, but it should be pretty close. versionMap myMap(_vers), otherMap(other._vers); VersionVector result; size_t mySize = _vers.size(), itsSize = other._vers.size(), maxSize = max(mySize, itsSize); for (size_t i = 0; i < maxSize; ++i) { if (i < mySize) { if (auto &vers = _vers[i]; vers.gen() >= otherMap[vers.author()]) result.push_back(vers); } if (i < itsSize) { if (auto &vers = other._vers[i]; vers.gen() > myMap[vers.author()]) result.push_back(vers); } } return result; } /* A delta from A to B is a prefix of B, containing all the versions in B that are newer than in A. */ optional<VersionVector> VersionVector::deltaFrom(const VersionVector &src) const { if (src.empty()) return *this; // a delta from nothing is the same as me else if (src.count() > count()) return nullopt; // src must be newer if it has more versions; fail // Look through myself for a version equal to one in `src`: auto i = _vers.begin(); for (; i != _vers.end(); ++i) { int64_t deltaGen = i->gen() - src[i->author()]; if (deltaGen == 0) break; // found equal version; changes are done else if (deltaGen < 0) return nullopt; // src is newer (or a conflict), so fail } // Return a prefix of me to before the matching version: return VersionVector(_vers.begin(), i); } VersionVector VersionVector::byApplyingDelta(const VersionVector &delta) const { // Reconstruct the target vector by appending to `delta` all components of myself that // don't appear in it. VersionVector result = delta; result._vers.reserve(_vers.size()); for (auto &vers : _vers) { if (auto genInDelta = delta[vers.author()]; genInDelta == 0) result._vers.push_back(vers); else if (genInDelta < vers.gen()) error::_throw(error::BadRevisionID, "Invalid VersionVector delta"); } result.validate(); assert(result >= *this); // should be impossible given the above checks return result; } }
33.60199
100
0.54042
[ "vector" ]
a632175dfb30a7accf9f491690cf667e3a644d62
1,183
cc
C++
leetcode/Recursion/permutations_ii.cc
LIZHICHAOUNICORN/Toolkits
db45dac4de14402a21be0c40ba8e87b4faeda1b6
[ "Apache-2.0" ]
null
null
null
leetcode/Recursion/permutations_ii.cc
LIZHICHAOUNICORN/Toolkits
db45dac4de14402a21be0c40ba8e87b4faeda1b6
[ "Apache-2.0" ]
null
null
null
leetcode/Recursion/permutations_ii.cc
LIZHICHAOUNICORN/Toolkits
db45dac4de14402a21be0c40ba8e87b4faeda1b6
[ "Apache-2.0" ]
null
null
null
// Author: zhichaoli // Time: 2020年02月12日 #include <algorithm> #include <string> #include <vector> #include <gperftools/profiler.h> #include "third_party/gflags/include/gflags.h" #include "third_party/glog/include/logging.h" using std::vector; using std::string; class Solution { public: void recursion(vector<int> num, int i, int j, vector<vector<int>> &res) { if (i == j - 1) { res.push_back(num); return; } for (int k = i; k < j; k++) { if (i != k && num[i] == num[k]) continue; std::swap(num[i], num[k]); recursion(num, i + 1, j, res); } } vector<vector<int>> permuteUnique(vector<int> &num) { sort(num.begin(), num.end()); vector<vector<int>> res; recursion(num, 0, num.size(), res); return res; } }; int main(int argc, char *argv[]) { google::InitGoogleLogging(argv[0]); gflags::ParseCommandLineFlags(&argc, &argv, false); Solution solu; ProfilerStart("my.prof"); vector<int> num = {1, 2}; vector<vector<int>> ret = solu.permuteUnique(num); ProfilerStop(); for (auto vec : ret) { LOG(INFO) << "start again"; for (auto it : vec) { LOG(INFO) << it; } } return 0; }
22.75
75
0.60186
[ "vector" ]
a6324b969e19fa23f3d8041248102b405130a06b
4,715
cpp
C++
src/blend2d/pipegen/blfetchsolidpart.cpp
dan-eicher/blend2d
097f89cbaae699cb3ba67712c4d1c8ebad78b99c
[ "Zlib" ]
null
null
null
src/blend2d/pipegen/blfetchsolidpart.cpp
dan-eicher/blend2d
097f89cbaae699cb3ba67712c4d1c8ebad78b99c
[ "Zlib" ]
null
null
null
src/blend2d/pipegen/blfetchsolidpart.cpp
dan-eicher/blend2d
097f89cbaae699cb3ba67712c4d1c8ebad78b99c
[ "Zlib" ]
null
null
null
// [Blend2D] // 2D Vector Graphics Powered by a JIT Compiler. // // [License] // ZLIB - See LICENSE.md file in the package. #include "../blapi-build_p.h" #include "../pipegen/blcompoppart_p.h" #include "../pipegen/blfetchsolidpart_p.h" #include "../pipegen/blpipecompiler_p.h" namespace BLPipeGen { #define REL_SOLID(FIELD) BL_OFFSET_OF(BLPipeFetchData::Solid, FIELD) // ============================================================================ // [BLPipeGen::FetchSolidPart - Construction / Destruction] // ============================================================================ FetchSolidPart::FetchSolidPart(PipeCompiler* pc, uint32_t fetchType, uint32_t fetchPayload, uint32_t format) noexcept : FetchPart(pc, fetchType, fetchPayload, format) { _maxOptLevelSupported = kOptLevel_X86_AVX; _maxPixels = kUnlimitedMaxPixels; _pixel.reset(); _isTransparent = false; } // ============================================================================ // [BLPipeGen::FetchSolidPart - Init / Fini] // ============================================================================ void FetchSolidPart::_initPart(x86::Gp& x, x86::Gp& y) noexcept { BL_UNUSED(x); BL_UNUSED(y); } void FetchSolidPart::_finiPart() noexcept { // This injects a spill sequence at the end of the initialization code added // by a solid fetch type. This prevents spills in the middle of the generated // code in case there are no more registers. ScopedInjector(cc, &_globalHook); // Packed and unpacked pixels are kept in registers, unpacked alpha values are // spilled. if (!_pixel.ua.empty()) cc->spill(_pixel.ua[0]); if (!_pixel.uia.empty()) cc->spill(_pixel.uia[0]); } // ============================================================================ // [BLPipeGen::FetchSolidPart - InitSolidFlags] // ============================================================================ void FetchSolidPart::initSolidFlags(uint32_t flags) noexcept { ScopedInjector injector(cc, &_globalHook); PixelARGB& s = _pixel; if ((flags & PixelARGB::kAny) && s.pc.empty()) { s.pc.init(cc->newXmm("pixel.pc")); x86::Vec& pix = s.pc[0]; if (!isTransparent()) { pc->vloadi32(pix, x86::dword_ptr(pc->_fetchData)); pc->vswizi32(pix, pix, x86::Predicate::shuf(0, 0, 0, 0)); } else { pc->vzeropi(pix); } } pc->xSatisfySolid(s, flags); } // ============================================================================ // [BLPipeGen::FetchSolidPart - Fetch] // ============================================================================ void FetchSolidPart::fetch1(PixelARGB& p, uint32_t flags) noexcept { if (flags & PixelARGB::kAny) { initSolidFlags(flags & PixelARGB::kAny); PixelARGB& s = _pixel; if (flags & PixelARGB::kImmutable) { if (flags & PixelARGB::kPC ) { p.pc.init(s.pc); } if (flags & PixelARGB::kUC ) { p.uc.init(s.uc); } if (flags & PixelARGB::kUA ) { p.ua.init(s.ua); } if (flags & PixelARGB::kUIA) { p.uia.init(s.uia); } } else { if (flags & PixelARGB::kPC) { p.pc.init(cc->newXmm("p.pc0")); pc->vmov(p.pc[0], s.pc[0]); } if (flags & PixelARGB::kUC) { p.uc.init(cc->newXmm("p.uc0")); pc->vmov(p.uc[0], s.uc[0]); } if (flags & PixelARGB::kUA) { p.ua.init(cc->newXmm("p.ua0")); pc->vmov(p.ua[0], s.ua[0]); } if (flags & PixelARGB::kUIA) { p.uia.init(cc->newXmm("p.uia0")); pc->vmov(p.uia[0], s.uia[0]); } } } pc->xSatisfyARGB32_1x(p, flags); } void FetchSolidPart::fetch4(PixelARGB& p, uint32_t flags) noexcept { if (flags & PixelARGB::kAny) { initSolidFlags(flags & PixelARGB::kAny); PixelARGB& s = _pixel; if (flags & PixelARGB::kImmutable) { if (flags & PixelARGB::kPC ) { p.pc.init(s.pc); } if (flags & PixelARGB::kUC ) { p.uc.init(s.uc); } if (flags & PixelARGB::kUA ) { p.ua.init(s.ua); } if (flags & PixelARGB::kUIA) { p.uia.init(s.uia); } } else { if (flags & PixelARGB::kPC) { pc->newXmmArray(p.pc, 1, "p.pc"); pc->vmov(p.pc[0], s.pc[0]); } if (flags & PixelARGB::kUC) { pc->newXmmArray(p.uc, 2, "p.uc"); pc->vmov(p.uc[0], s.uc[0]); pc->vmov(p.uc[1], s.uc[0]); } if (flags & PixelARGB::kUA) { pc->newXmmArray(p.ua, 2, "p.ua"); pc->vmov(p.ua[0], s.ua[0]); pc->vmov(p.ua[1], p.ua[0]); } if (flags & PixelARGB::kUIA) { pc->newXmmArray(p.uia, 2, "p.uia"); pc->vmov(p.uia[0], s.uia[0]); pc->vmov(p.uia[1], p.uia[0]); } } } pc->xSatisfyARGB32_Nx(p, flags); } } // {BLPipeGen}
30.031847
117
0.516437
[ "vector", "solid" ]
a632f30372068701ea09d7db80ac351dd0b90777
2,950
cpp
C++
dali/internal/accessibility/tizen-wayland/atspi/bridge-action.cpp
Coquinho/dali-adaptor
a8006aea66b316a5eb710e634db30f566acda144
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
dali/internal/accessibility/tizen-wayland/atspi/bridge-action.cpp
Coquinho/dali-adaptor
a8006aea66b316a5eb710e634db30f566acda144
[ "Apache-2.0", "BSD-3-Clause" ]
2
2020-10-19T13:45:40.000Z
2020-12-10T20:21:03.000Z
dali/internal/accessibility/tizen-wayland/atspi/bridge-action.cpp
expertisesolutions/dali-adaptor
810bf4dea833ea7dfbd2a0c82193bc0b3b155011
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2019 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // CLASS HEADER #include <dali/internal/accessibility/tizen-wayland/atspi/bridge-action.h> // EXTERNAL INCLUDES #include <iostream> using namespace Dali::Accessibility; void BridgeAction::RegisterInterfaces() { DBus::DBusInterfaceDescription desc{AtspiDbusInterfaceAction}; AddGetPropertyToInterface( desc, "NActions", &BridgeAction::GetActionCount ); AddFunctionToInterface( desc, "GetName", &BridgeAction::GetActionName ); AddFunctionToInterface( desc, "GetLocalizedName", &BridgeAction::GetLocalizedActionName ); AddFunctionToInterface( desc, "GetDescription", &BridgeAction::GetActionDescription ); AddFunctionToInterface( desc, "GetKeyBinding", &BridgeAction::GetActionKeyBinding ); AddFunctionToInterface( desc, "DoAction", &BridgeAction::DoAction ); AddFunctionToInterface( desc, "DoActionName", &BridgeAction::DoActionName ); dbusServer.addInterface( "/", desc, true ); } Action* BridgeAction::FindSelf() const { auto s = BridgeBase::FindSelf(); assert( s ); auto s2 = dynamic_cast< Action* >( s ); if( !s2 ) throw std::domain_error{"object " + s->GetAddress().ToString() + " doesn't have Action interface"}; return s2; } DBus::ValueOrError< std::string > BridgeAction::GetActionName( int32_t index ) { return FindSelf()->GetActionName( index ); } DBus::ValueOrError< std::string > BridgeAction::GetLocalizedActionName( int32_t index ) { return FindSelf()->GetLocalizedActionName( index ); } DBus::ValueOrError< std::string > BridgeAction::GetActionDescription( int32_t index ) { return FindSelf()->GetActionDescription( index ); } DBus::ValueOrError< std::string > BridgeAction::GetActionKeyBinding( int32_t index ) { return FindSelf()->GetActionKeyBinding( index ); } DBus::ValueOrError< int32_t > BridgeAction::GetActionCount() { return FindSelf()->GetActionCount(); ; } DBus::ValueOrError< bool > BridgeAction::DoAction( int32_t index ) { return FindSelf()->DoAction( index ); } DBus::ValueOrError< bool > BridgeAction::DoActionName( std::string name ) { auto self = FindSelf(); auto cnt = self->GetActionCount(); for( auto i = 0u; i < cnt; ++i ) { if( self->GetActionName( i ) == name ) { return self->DoAction( i ); } } throw std::domain_error{"object " + self->GetAddress().ToString() + " doesn't have action '" + name + "'"}; }
31.052632
109
0.722373
[ "object" ]
a6330db6b4d8d46fd93a0d7f0212e9bb3797e5e3
3,028
cpp
C++
src/misc/game_mode_selector.cpp
adct-the-experimenter/Thief-Fighters
1f34df8505612ccc4fe3934242ac942f0c1686a8
[ "MIT" ]
1
2021-07-25T21:22:11.000Z
2021-07-25T21:22:11.000Z
src/misc/game_mode_selector.cpp
adct-the-experimenter/Thief-Fighters
1f34df8505612ccc4fe3934242ac942f0c1686a8
[ "MIT" ]
1
2021-07-01T04:11:55.000Z
2021-07-01T04:39:49.000Z
src/misc/game_mode_selector.cpp
adct-the-experimenter/Thief-Fighters
1f34df8505612ccc4fe3934242ac942f0c1686a8
[ "MIT" ]
null
null
null
#include "game_mode_selector.h" static std::string game_mode_choices [2] = {"Versus","Story - Alpha"}; GameModeSelector::GameModeSelector() { m_current_mode_select = 0; move_next_state = false; move_prev_state = false; m_confirm_selection = false; } GameModeSelector::~GameModeSelector() { } void GameModeSelector::Init() { m_current_mode_select = 0; move_next_state = false; m_confirm_selection = false; //initialize render slot locations for(size_t it = 0; it < mode_boxes.size(); it++) { mode_boxes[it].render_rect = {320 - 100, static_cast<float>( 100 + 30*(it+1) ), 100, 20}; mode_boxes[it].text = game_mode_choices[it]; } m_font = GetFontDefault(); } void GameModeSelector::handle_input(ControllerInput& controller_input, KeyboardInput& key_input) { GameModeSelector::handle_controller_input(controller_input); } static const int16_t joystick_border = 32600; static bool moveBool = false; void GameModeSelector::handle_controller_input(ControllerInput& input) { //number of character boxes and number of players should be the same //only first game pad decides number of players size_t i = 0; //if joystick moved up, go up a slot if(input.gamepads_vec[i].left_y_dir_axis == -1 || input.gamepads_vec[i].left_y_dir_digital == -1) { if(m_current_mode_select > 0 && moveBool){m_current_mode_select--;} moveBool = false; } //else if joystick moved down, go down a slot else if(input.gamepads_vec[i].left_y_dir_axis == 1 || input.gamepads_vec[i].left_y_dir_digital == 1) { if(m_current_mode_select < 1 && moveBool){m_current_mode_select++;} moveBool = false; } if(input.gamepads_vec[i].left_y_dir_axis == 0 ) { moveBool = true; } //if a button pressed, turn confirm bool on if(input.gamepads_vec[i].button_up_released == SDL_CONTROLLER_BUTTON_A) { m_confirm_selection = true; } //else if b button pressed, go back to previous state if(input.gamepads_vec[i].button_up_released == SDL_CONTROLLER_BUTTON_B) { move_prev_state = true; } } void GameModeSelector::logic() { //if selection confirmed if(m_confirm_selection) { move_next_state = true; } } void GameModeSelector::render() { for(size_t i = 0; i < mode_boxes.size(); i++) { //draw each slot if(i != m_current_mode_select) { DrawRectangleRec(mode_boxes[i].render_rect,WHITE); DrawTextRec(m_font,mode_boxes[i].text.c_str(),mode_boxes[i].render_rect,12,2.0f, true, BLACK); } else { DrawRectangleRec(mode_boxes[i].render_rect,YELLOW); DrawTextRec(m_font,mode_boxes[i].text.c_str(),mode_boxes[i].render_rect,12,2.0f, true, BLACK); } } } void GameModeSelector::sound() { } bool GameModeSelector::MoveToNextStateBool(){return move_next_state;} bool GameModeSelector::MoveToPreviousStateBool(){return move_prev_state;} std::uint8_t GameModeSelector::GetModeSelected(){return m_current_mode_select;} void GameModeSelector::Reset() { m_current_mode_select = 0; move_next_state = false; move_prev_state = false; m_confirm_selection = false; }
22.939394
97
0.732827
[ "render" ]
a633859f11cd5579f4a88f54135486755e54a1e4
6,157
cpp
C++
src/rfx/scene/MaterialShader.cpp
rfruesmer/rfx
96c15a11ee8e2192c9d2ff233924eee884835f17
[ "MIT" ]
null
null
null
src/rfx/scene/MaterialShader.cpp
rfruesmer/rfx
96c15a11ee8e2192c9d2ff233924eee884835f17
[ "MIT" ]
null
null
null
src/rfx/scene/MaterialShader.cpp
rfruesmer/rfx
96c15a11ee8e2192c9d2ff233924eee884835f17
[ "MIT" ]
null
null
null
#include "rfx/pch.h" #include "rfx/scene/MaterialShader.h" using namespace rfx; using namespace std; using namespace filesystem; // --------------------------------------------------------------------------------------------------------------------- MaterialShader::MaterialShader( GraphicsDevicePtr graphicsDevice, string id, string vertexShaderId, string fragmentShaderId) : graphicsDevice(move(graphicsDevice)), id(move(id)), vertexShaderId(move(vertexShaderId)), fragmentShaderId(move(fragmentShaderId)) {} // --------------------------------------------------------------------------------------------------------------------- void MaterialShader::create( ShaderProgramPtr shaderProgram, VkDescriptorSetLayout shaderDescriptorSetLayout, VkDescriptorSet shaderDescriptorSet, BufferPtr shaderDataBuffer, VkDescriptorSetLayout materialDescriptorSetLayout) { this->shaderProgram = move(shaderProgram); this->shaderDescriptorSetLayout = shaderDescriptorSetLayout; this->shaderDescriptorSet = shaderDescriptorSet; this->shaderDataBuffer = move(shaderDataBuffer); this->materialDescriptorSetLayout = materialDescriptorSetLayout; } // --------------------------------------------------------------------------------------------------------------------- MaterialShader::~MaterialShader() { destroy(); } // --------------------------------------------------------------------------------------------------------------------- void MaterialShader::destroy() { VkDevice device = graphicsDevice->getLogicalDevice(); if (materialDescriptorSetLayout != VK_NULL_HANDLE) { vkDestroyDescriptorSetLayout(device, materialDescriptorSetLayout, nullptr); materialDescriptorSetLayout = VK_NULL_HANDLE; } if (shaderDescriptorSetLayout != VK_NULL_HANDLE) { vkDestroyDescriptorSetLayout(device, shaderDescriptorSetLayout, nullptr); shaderDescriptorSetLayout = VK_NULL_HANDLE; } if (pipeline != VK_NULL_HANDLE) { vkDestroyPipeline(device, pipeline, nullptr); pipeline = VK_NULL_HANDLE; } if (pipelineLayout != VK_NULL_HANDLE) { vkDestroyPipelineLayout(device, pipelineLayout, nullptr); pipelineLayout = VK_NULL_HANDLE; } } // --------------------------------------------------------------------------------------------------------------------- const string& MaterialShader::getId() const { return id; } // --------------------------------------------------------------------------------------------------------------------- const string& MaterialShader::getVertexShaderId() const { return vertexShaderId; } // --------------------------------------------------------------------------------------------------------------------- const string& MaterialShader::getFragmentShaderId() const { return fragmentShaderId; } // --------------------------------------------------------------------------------------------------------------------- const ShaderProgramPtr& MaterialShader::getShaderProgram() const { return shaderProgram; } // --------------------------------------------------------------------------------------------------------------------- vector<string> MaterialShader::getShaderDefinesFor(const MaterialPtr& material) { return vector<string>(); } // --------------------------------------------------------------------------------------------------------------------- vector<string> MaterialShader::getVertexShaderInputsFor(const MaterialPtr& material) { return vector<string>(); } // --------------------------------------------------------------------------------------------------------------------- vector<string> MaterialShader::getVertexShaderOutputsFor(const MaterialPtr& material) { return vector<string>(); } // --------------------------------------------------------------------------------------------------------------------- vector<string> MaterialShader::getFragmentShaderInputsFor(const MaterialPtr& material) { return vector<string>(); } // --------------------------------------------------------------------------------------------------------------------- VkDescriptorSetLayout MaterialShader::getMaterialDescriptorSetLayout() const { return materialDescriptorSetLayout; } // --------------------------------------------------------------------------------------------------------------------- void MaterialShader::setPipeline(VkPipelineLayout pipelineLayout, VkPipeline pipeline) { this->pipelineLayout = pipelineLayout; this->pipeline = pipeline; } // --------------------------------------------------------------------------------------------------------------------- VkPipelineLayout MaterialShader::getPipelineLayout() const { return pipelineLayout; } // --------------------------------------------------------------------------------------------------------------------- VkPipeline MaterialShader::getPipeline() const { return pipeline; } // --------------------------------------------------------------------------------------------------------------------- void MaterialShader::updateDataBuffer() { const uint32_t dataSize = getDataSize(); if (dataSize > 0) { shaderDataBuffer->load(dataSize, getData()); } } // --------------------------------------------------------------------------------------------------------------------- VkDescriptorSetLayout MaterialShader::getShaderDescriptorSetLayout() const { return shaderDescriptorSetLayout; } // --------------------------------------------------------------------------------------------------------------------- VkDescriptorSet MaterialShader::getShaderDescriptorSet() const { return shaderDescriptorSet; } // --------------------------------------------------------------------------------------------------------------------- void MaterialShader::update(const MaterialPtr& material) const { material->loadUniformBufferData(createDataFor(material)); } // ---------------------------------------------------------------------------------------------------------------------
32.57672
120
0.442098
[ "vector" ]
a63802b2d765197591f97695535de0a2edaa960e
40,913
cpp
C++
app/src/main/cpp/zwcontrol-jni.cpp
huimumua/Project_sig_ma
1181776845d67e8f185a57f3e145f0080f7a5a78
[ "Apache-2.0" ]
2
2018-11-17T14:02:34.000Z
2020-06-13T08:43:06.000Z
app/src/main/cpp/zwcontrol-jni.cpp
huimumua/ZwaveControlServer_ZipGateway281
1181776845d67e8f185a57f3e145f0080f7a5a78
[ "Apache-2.0" ]
null
null
null
app/src/main/cpp/zwcontrol-jni.cpp
huimumua/ZwaveControlServer_ZipGateway281
1181776845d67e8f185a57f3e145f0080f7a5a78
[ "Apache-2.0" ]
null
null
null
#include <string.h> #include <stdint.h> #include <jni.h> #include <android/log.h> extern "C" { #include "zwcontrol/zwcontrol_api.h" } #define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0]))) static hl_appl_ctx_t appl_ctx = {0}; static jclass ZwControlServiceClass; static JavaVM *ZwControlServiceVM = NULL; static jmethodID CallBackMethodID = NULL; static jmethodID CallBackMethodID2 = NULL; static void check_and_clear_exceptions(JNIEnv* env, const char* method_name) { if (!env->ExceptionCheck()) { return; } ALOGE("An exception was thrown by '%s'.", method_name); env->ExceptionClear(); } static JNIEnv* getJNIEnv(int* needsDetach) { *needsDetach = 0; JNIEnv* env; if(ZwControlServiceVM == NULL) { return NULL; } if (ZwControlServiceVM->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) { env = NULL; } if (env == NULL) { JavaVMAttachArgs args = {JNI_VERSION_1_4, NULL, NULL}; int result = ZwControlServiceVM->AttachCurrentThread(&env, (void*) &args); if (result != JNI_OK) { ALOGE("thread attach failed: %#x", result); return NULL; } *needsDetach = 1; } return env; } static void detachJNI() { if(ZwControlServiceVM == NULL) { return; } int result = ZwControlServiceVM->DetachCurrentThread(); if (result != JNI_OK) { ALOGE("thread detach failed: %#x", result); } } static int ZwControlResCallBack(const char* res) { if(ZwControlServiceClass == NULL) return -1; int needDetach; JNIEnv* env = getJNIEnv(&needDetach); if(env == NULL) { return -1; } if(CallBackMethodID == NULL) { CallBackMethodID = env->GetStaticMethodID(ZwControlServiceClass, "ZwaveControlRes_CallBack", "([BI)V"); if(CallBackMethodID == NULL) { if(needDetach) { detachJNI(); } return -1; } } int len = strlen(res); jbyteArray bytes = env->NewByteArray(len); env->SetByteArrayRegion(bytes, 0, len, (jbyte*)res); env->CallStaticVoidMethod(ZwControlServiceClass, CallBackMethodID, bytes, len); check_and_clear_exceptions(env, __FUNCTION__); env->DeleteLocalRef(bytes); if(needDetach) { detachJNI(); } return 0; } static int ZwControlReqCallBack(const char* res) { if(ZwControlServiceClass == NULL) return -1; int needDetach; JNIEnv* env = getJNIEnv(&needDetach); if(env == NULL) { return -1; } if(CallBackMethodID2 == NULL) { CallBackMethodID2 = env->GetStaticMethodID(ZwControlServiceClass, "ZwaveControlReq_CallBack", "([BI)I"); if(CallBackMethodID2 == NULL) { if(needDetach) { detachJNI(); } return -1; } } int len = strlen(res); jbyteArray bytes = env->NewByteArray(len); env->SetByteArrayRegion(bytes, 0, len, (jbyte*)res); int val = env->CallStaticIntMethod(ZwControlServiceClass, CallBackMethodID2, bytes, len); check_and_clear_exceptions(env, __FUNCTION__); env->DeleteLocalRef(bytes); if(needDetach) { detachJNI(); } return val; } static int create_controller(JNIEnv *env, jclass object) { if(ZwControlServiceClass == NULL) { ZwControlServiceClass = (jclass)env->NewGlobalRef(object); } return 0; } static jint open_controller(JNIEnv *env, jclass object, jstring path, jstring InfoPath, jbyteArray result) { if(env == NULL) { return -1; } const char *resPath = env->GetStringUTFChars(path, 0); const char *infoFile = env->GetStringUTFChars(InfoPath, 0); uint8_t str[1024] = {0}; if(zwcontrol_init(&appl_ctx, resPath, infoFile, str) != 0) { env->ReleaseStringUTFChars(path, resPath); env->ReleaseStringUTFChars(InfoPath, infoFile); return -1; } env->ReleaseStringUTFChars(path, resPath); env->ReleaseStringUTFChars(InfoPath, infoFile); zwcontrol_setcallback(ZwControlResCallBack, ZwControlReqCallBack); int len = (int)strlen((char*)str); env->SetByteArrayRegion(result, 0, len, (jbyte*)str); return 0; } static int close_controller(JNIEnv *env, jclass object) { if(zwcontrol_exit(&appl_ctx) == 0) { memset(&appl_ctx, 0x00, sizeof(hl_appl_ctx_t)); } return 0; } static int destroy_controller(JNIEnv *env, jclass object) { if(ZwControlServiceClass != NULL) { env->DeleteGlobalRef(ZwControlServiceClass); } return 0; } static int controller_adddevice(JNIEnv *env, jclass object) { return zwcontrol_add_node(&appl_ctx); } static int controller_removedevice(JNIEnv *env, jclass object) { return zwcontrol_rm_node(&appl_ctx); } static int controller_getDeviceList(JNIEnv *env, jclass object) { return zwcontrol_get_node_list(&appl_ctx); } static int controller_getDeviceInfo(JNIEnv *env, jclass object) { return zwcontrol_get_node_info(&appl_ctx); } static int controller_getSpecifyDeviceInfo(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_get_specify_node_info(&appl_ctx, (uint32_t)nodeId); } static int controller_removeFailedDevice(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_rm_failed_node(&appl_ctx, nodeId); } static int controller_replaceFailedDevice(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_rp_failed_node(&appl_ctx, nodeId); } static int controller_setDefault(JNIEnv *env, jclass object) { return zwcontrol_default_set(&appl_ctx); } static int controller_stopAddDevice(JNIEnv *env, jclass object) { return zwcontrol_stop_op(&appl_ctx); } static int controller_stopRemoveDevice(JNIEnv *env, jclass object) { return zwcontrol_stop_op(&appl_ctx); } static int controller_getDeviceBattery(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_battery_get(&appl_ctx, (uint32_t)nodeId); } static int controller_getSensorMultiLevel(JNIEnv *env, jclass object, jint nodeId/*, jint sensor_type, jint unit*/) { return zwcontrol_sensor_multilevel_get(&appl_ctx, (uint32_t)nodeId/*, (uint8_t)sensor_type, (uint8_t)unit*/); } static int control_update_node(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_update_node(&appl_ctx, (uint32_t)nodeId); } static int control_saveNodeInfo(JNIEnv *env, jclass object, jstring infoFile) { const char *infoPath = env->GetStringUTFChars(infoFile, 0); if(zwcontrol_save_nodeinfo(&appl_ctx, infoPath)) { env->ReleaseStringUTFChars(infoFile, infoPath); return -1; } env->ReleaseStringUTFChars(infoFile, infoPath); return 0; } static int control_getBasic(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_basic_get(&appl_ctx, (uint32_t)nodeId); } static int control_setBasic(JNIEnv *env, jclass object, jint nodeId, jint value) { return zwcontrol_basic_set(&appl_ctx, nodeId, value); } static int controller_getSwitchMultiLevel(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_switch_multilevel_get(&appl_ctx, (uint32_t)nodeId); } static int controller_setSwitchMultiLevel(JNIEnv *env, jclass object, jint nodeId, jint levValue, jint duration) { return zwcontrol_switch_multilevel_set(&appl_ctx, (uint32_t)nodeId,(uint16_t)levValue, (uint8_t)duration); } static int controller_getSupportedSwitchType(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_get_support_switch_type(&appl_ctx, (uint32_t)nodeId); } static int controller_getConfiguration(JNIEnv *env, jclass object, jint nodeId, jint paramMode, jint paramNumber, jint rangeStart, jint rangeEnd) { return zwcontrol_configuration_get(&appl_ctx, (uint32_t)nodeId,(uint8_t)paramMode, (uint8_t)paramNumber, (uint16_t)rangeStart, (uint16_t)rangeEnd); } static int controller_setConfiguration(JNIEnv *env, jclass object, jint nodeId, jint paramNumber, jint paramSize, jint useDefault, jint paramValue) { return zwcontrol_configuration_set(&appl_ctx, (uint32_t)nodeId, (uint8_t)paramNumber, (uint8_t)paramSize, (uint8_t)useDefault, (int32_t)paramValue); } static int controller_setConfigurationBulk(JNIEnv *env, jclass object, jint nodeId, jint offset1, jint offset2, jint paramNumber, jint paramSize, jint useDefault, jintArray paramValue) { jint *param_value; param_value = env->GetIntArrayElements(paramValue, JNI_FALSE); if(param_value == NULL) { return -1; } int result = 0; env->ReleaseIntArrayElements(paramValue, param_value, 0); return result; } static int controller_startStopSwitchLevelChange(JNIEnv *env, jclass object, jint nodeId, jint startLvlVal, jint duration, jint pmyChangeDir, jint secChangeDir, jint secStep) { return zwcontrol_start_stop_switchlevel_change(&appl_ctx, (uint32_t)nodeId, (uint16_t)startLvlVal, (uint8_t)duration, (uint8_t)pmyChangeDir, (uint8_t)secChangeDir, (uint8_t)secStep); } static int controller_getPowerLevel(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_powerLevel_get(&appl_ctx, (uint32_t)nodeId); } static int controller_setPowerLevel(JNIEnv *env, jclass object, jint nodeId, jint powerLvl, jint timeout) { return zwcontrol_powerLevel_set(&appl_ctx, (uint32_t)nodeId, (uint32_t)powerLvl, (uint32_t)timeout); } static int controller_setSwitchAllOn(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_switch_all_on(&appl_ctx, (uint32_t)nodeId); } /*static int controller_setSwitchAllOnBroadcast(JNIEnv *env, jclass object) { return zwcontrol_switch_all_on_broadcast(&appl_ctx); }*/ static int controller_setSwitchAllOff(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_switch_all_off(&appl_ctx,(uint32_t)nodeId); } /*static int controller_setSwitchAllOffBroadcast(JNIEnv *env, jclass object) { return zwcontrol_switch_all_off_broadcast(&appl_ctx); }*/ static int controller_setSwitchAll(JNIEnv *env, jclass object, jint nodeId, jint value) { return zwcontrol_switch_all_set(&appl_ctx, (uint32_t)nodeId, (uint8_t)value); } static int controller_getSwitchAll(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_switch_all_get(&appl_ctx, (uint32_t)nodeId); } static int controller_startLearnMode(JNIEnv *env, jclass object) { return zwcontrol_start_learn_mode(&appl_ctx); } static int controller_setBinarySwitchState(JNIEnv *env, jclass object, jint nodeId, jint state) { return zwcontrol_switch_binary_set(&appl_ctx, (uint32_t)nodeId, (uint8_t)state); } static int controller_getBinarySwitchState(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_switch_binary_get(&appl_ctx, (uint32_t)nodeId); } static int controller_getSensorBinary(JNIEnv *env, jclass object, jint nodeId, jint sensor_type) { return zwcontrol_sensor_binary_get(&appl_ctx, (uint32_t)nodeId, (uint8_t)sensor_type); } static int controller_getSensorBinarySupportedSensor(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_sensor_binary_supported_sensor_get(&appl_ctx, (uint32_t)nodeId); } static int controller_getMeter(JNIEnv *env, jclass object, jint nodeId, jint meter_unit) { return zwcontrol_meter_get(&appl_ctx, (uint32_t)nodeId, (uint8_t)meter_unit); } static int controller_resetMeter(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_meter_reset(&appl_ctx, (uint32_t)nodeId); } static int controller_getMeterSupported(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_meter_supported_get(&appl_ctx, (uint32_t)nodeId); } static int controller_getWakeUpSettings(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_wake_up_interval_get(&appl_ctx, (uint32_t)nodeId); } static int controller_setWakeUpInterval(JNIEnv *env, jclass object, jint nodeId, jint interval) { return zwcontrol_wake_up_interval_set(&appl_ctx, (uint32_t)nodeId, (uint32_t)interval); } static int controller_getDoorLockOperation(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_door_lock_operation_get(&appl_ctx, (uint32_t)nodeId); } static int controller_setDoorLockOperation(JNIEnv *env, jclass object, jint nodeId, jint mode) { return zwcontrol_door_lock_operation_set(&appl_ctx, (uint32_t)nodeId, (uint8_t)mode); } static int controller_getDoorLockConfiguration(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_door_lock_config_get(&appl_ctx, (uint32_t)nodeId); } static int controller_setDoorLockConfiguration(JNIEnv *env, jclass object, jint nodeId, jint type, jint out_sta, jint in_sta, jint tmout_min, jint tmout_sec) { return zwcontrol_door_lock_config_set(&appl_ctx, (uint32_t)nodeId, (uint8_t)type, (uint8_t)out_sta, (uint8_t)in_sta, (uint8_t)tmout_min, (uint8_t)tmout_sec); } /*static int controller_getUserCode(JNIEnv *env, jclass object, jint nodeId, jint user_id) { return 0; } static int controller_setUserCode(JNIEnv *env, jclass object, jint nodeId, jint user_id, jint status) { return 0; } static int controller_getUserCodeNumber(JNIEnv *env, jclass object, jint nodeId) { return 0; }*/ static int controller_getProtection(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_protection_get(&appl_ctx, (uint32_t)nodeId); } static int controller_setProtection(JNIEnv *env, jclass object, jint nodeId, jint local_port, jint rf_port) { return zwcontrol_protection_set(&appl_ctx, (uint32_t)nodeId, (uint8_t)local_port, (uint8_t)rf_port); } static int controller_getSupportedProtection(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_supported_protection_get(&appl_ctx, (uint32_t)nodeId); } static int controller_getProtectionExcControlNode(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_protection_exclusive_control_node_get(&appl_ctx, (uint32_t)nodeId); } static int controller_getIndicator(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_indicator_get(&appl_ctx, (uint32_t)nodeId); } static int controller_setIndicator(JNIEnv *env, jclass object, jint nodeId, jint value) { return zwcontrol_indicator_set(&appl_ctx, (uint32_t)nodeId, (uint16_t)value); } static int controller_setProtectionExcControlNode(JNIEnv *env, jclass object, jint nodeId, jint node_id) { return zwcontrol_protection_exclusive_control_node_set(&appl_ctx, (uint32_t)nodeId, (uint8_t)node_id); } static int controller_getProtectionTimeout(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_protection_timeout_get(&appl_ctx, (uint32_t)nodeId); } static int controller_setProtectionTimeout(JNIEnv *env, jclass object, jint nodeId, jint unit, jint time) { return zwcontrol_protection_timeout_set(&appl_ctx, (uint32_t)nodeId, (uint8_t)unit, (uint8_t)time); } /*static int controller_getDoorLockLoggingSupportedRecords(JNIEnv *env, jclass object, jint nodeId) { return 0; } static int controller_getDoorLockLoggingRecords(JNIEnv *env, jclass object, jint nodeId, jint rec_num) { return 0; } static int controller_getLanguage(JNIEnv *env, jclass object, jint nodeId) { return 0; }*/ static int controller_getSwitchColor(JNIEnv *env, jclass object, jint nodeId, jint compId) { return zwcontrol_switch_color_get(&appl_ctx, (uint32_t)nodeId, (uint8_t)compId); } static int controller_getSupportedSwitchColor(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_switch_color_supported_get(&appl_ctx, (uint32_t)nodeId); } static int controller_setSwitchColor(JNIEnv *env, jclass object, jint nodeId, jint compId, jint value) { return zwcontrol_switch_color_set(&appl_ctx, (uint32_t)nodeId, (uint8_t)compId, (uint8_t)value); } static int controller_startStopSwitchColorLevelChange(JNIEnv *env, jclass object, jint nodeId, jint dir, jint ignore, jint compId, jint startLvlVal) { return zwcontrol_start_stop_color_levelchange(&appl_ctx, (uint32_t)nodeId, (uint8_t)dir, (uint8_t)ignore, (uint8_t)compId, (uint8_t)startLvlVal); } /*static int controller_setBarrierOperator(JNIEnv *env, jclass object, jint nodeId, jint value) { return 0; } static int controller_getBarrierOperator(JNIEnv *env, jclass object, jint nodeId) { return 0; } static int controller_setBarrierOperatorSignal(JNIEnv *env, jclass object, jint nodeId, jint subType, jint state) { return 0; } static int controller_getBarrierOperatorSignal(JNIEnv *env, jclass object, jint nodeId, jint subType) { return 0; } static int controller_getSupportedBarrierOperatorSignal(JNIEnv *env, jclass object, jint nodeId) { return 0; } static int controller_getBasicTariffInfo(JNIEnv *env, jclass object, jint nodeId) { return 0; }*/ static int controller_getGroupInfo(JNIEnv *env, jclass object, jint nodeId, jint groupId, jint endpointId) { return zwcontrol_get_group_info(&appl_ctx, (uint32_t)nodeId, (uint8_t)groupId, (uint8_t)endpointId); } static int controller_addEndpointsToGroup(JNIEnv *env, jclass object, jint nodeId, jint groupId, jintArray intArray, jint endpointId) { jint *node_list = NULL; node_list = env->GetIntArrayElements(intArray, 0); if(node_list == NULL) { return -1; } int result = zwcontrol_add_endpoints_to_group(&appl_ctx, (uint32_t)nodeId, (uint8_t)groupId, (uint32_t*)node_list, (uint8_t)endpointId); env->ReleaseIntArrayElements(intArray, node_list, 0); return result; } static int controller_removeEndpointsFromGroup(JNIEnv *env, jclass object, jint nodeId, jint groupId, jintArray intArray, jint endpointId) { jint *node_list = NULL; node_list = env->GetIntArrayElements(intArray, JNI_FALSE); if(node_list == NULL) { ALOGE("GetIntArrayElements Failed"); return -1; } int result = zwcontrol_remove_endpoints_from_group(&appl_ctx, (uint32_t)nodeId, (uint8_t)groupId, (uint32_t*)node_list, (uint8_t)endpointId); env->ReleaseIntArrayElements(intArray, node_list, 0); return result; } static int controller_getMaxSupportedGroups(JNIEnv *env, jclass object, jint nodeId, jint endpointId) { return zwcontrol_get_max_supported_groups(&appl_ctx, (uint32_t)nodeId, (uint8_t)endpointId); } static int controller_getSpecificGroup(JNIEnv *env, jclass object, jint nodeId, jint endpointId) { return zwcontrol_get_specific_group(&appl_ctx, (uint32_t)nodeId, (uint8_t)endpointId); } static int controller_setNotification(JNIEnv *env, jclass object, jint nodeId, jint type, jint status) { return zwcontrol_notification_set(&appl_ctx, (uint32_t)nodeId, (uint8_t)type, (uint8_t)status); } static int controller_getNotification(JNIEnv *env, jclass object, jint nodeId, jint alarmType, jint notifType, jint evt) { return zwcontrol_notification_get(&appl_ctx,(uint32_t)nodeId, (uint8_t)alarmType, (uint8_t)notifType, (uint8_t)evt); } static int controller_getSupportedNotification(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_notification_supported_get(&appl_ctx, (uint32_t)nodeId); } static int controller_getSupportedEventNotification(JNIEnv *env, jclass object, jint nodeId, jint notifType) { return zwcontrol_notification_supported_event_get(&appl_ctx, (uint32_t)nodeId, (uint8_t)notifType); } static int controller_getSupportedCentralScene(JNIEnv *env, jclass object, jint nodeId, jint endpointId) { return zwcontrol_central_scene_supported_get(&appl_ctx, (uint32_t)nodeId, (uint8_t)endpointId); } static int controller_getSceneActuatorConf(JNIEnv *env, jclass object, jint nodeId, jint sceneId) { return zwcontrol_scene_actuator_conf_get(&appl_ctx, (uint32_t)nodeId, (uint8_t)sceneId); } static int controller_setSceneActuatorConf(JNIEnv *env, jclass object, jint nodeId, jint sceneId, jint dimDuration, jint override, jint level) { return zwcontrol_scene_actuator_conf_set(&appl_ctx, (uint32_t)nodeId, (uint8_t)sceneId, (uint8_t)dimDuration, (uint8_t)override, (uint8_t)level); } static int controller_multiCmdEncap(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_multi_cmd_encap(&appl_ctx, (uint32_t)nodeId); } static int controller_getFirmwareUpdateInfo(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_firmwareupdate_info_get(&appl_ctx, (uint32_t)nodeId); } static int controller_requestFirmwareUpdate(JNIEnv *env, jclass object, jint nodeId, jint vendorId, jint firmwareId, jint firmwareTarget, jint hw_ver, jstring firmwareFile) { const char *updateFile = env->GetStringUTFChars(firmwareFile, 0); int result = zwcontrol_firmwareupdate_request(&appl_ctx, (uint32_t)nodeId, (uint8_t)vendorId, (uint8_t)firmwareId, (uint8_t)firmwareTarget, (uint16_t)hw_ver, updateFile); env->ReleaseStringUTFChars(firmwareFile, updateFile); return result; } static int controller_getCommandQueueState(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_command_queue_state_get(&appl_ctx, (uint32_t)nodeId); } static int controller_controlCommandQueue(JNIEnv *env, jclass object, jint nodeId, jint state) { return zwcontrol_command_queue_turn_on_off(&appl_ctx, (uint32_t)nodeId, (uint8_t)state); } static int controller_viewCommandQueue(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_command_queue_view(&appl_ctx, (uint32_t)nodeId); } static int controller_cancelAllCommandQueue(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_command_queue_cancel(&appl_ctx, (uint32_t)nodeId); } /*static int controller_getControllerNetworkRssiInfo(JNIEnv *env, jclass object) { return zwcontrol_get_network_rssi_info(&appl_ctx, 0x01); // controller node id 1 } static int controller_getNodeNetworkRssiInfo(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_get_network_rssi_info(&appl_ctx, (uint32_t)nodeId); }*/ static int controller_startNetworkHealthCheck(JNIEnv *env, jclass object) { return zwcontrol_network_health_check(&appl_ctx); } static int controller_addProvisionListEntry(JNIEnv *env, jclass object, jbyteArray dsk, jint dsklen, jobjectArray plInfo, jint infoCnt) { char array[200]; env->GetByteArrayRegion(dsk, 0, dsklen, (jbyte*)array); jclass objectClass = (env)->FindClass("com/askey/firefly/zwave/control/application/ZwaveProvisionList"); jobject provision_list = NULL; pl_info_t * pl_info = (pl_info_t*)malloc(sizeof(pl_info_t) * infoCnt); for(int i = 0; i < infoCnt; i++) { provision_list = env->GetObjectArrayElement(plInfo, i); if(provision_list == NULL) { ALOGE("GetIntArrayElements Failed"); return -1; } jfieldID bType = (env)->GetFieldID(objectClass, "type", "I"); pl_info[i].type = (env)->GetIntField(provision_list, bType); jclass stProvisionListClass = env->FindClass("com/askey/firefly/zwave/control/application/ZwaveProvisionList$ProvisionListInfo"); jfieldID plInfo_st = env->GetFieldID(objectClass, "stProvisionList", "Lcom/askey/firefly/zwave/control/application/ZwaveProvisionList$ProvisionListInfo;"); jfieldID name = env->GetFieldID(stProvisionListClass, "name", "Ljava/lang/String;"); jfieldID location = env->GetFieldID(stProvisionListClass,"loc", "Ljava/lang/String;"); jfieldID interval = env->GetFieldID(stProvisionListClass,"interval", "I"); jfieldID inclusion_state = env->GetFieldID(stProvisionListClass,"inclusionState", "I"); jfieldID bootmode = env->GetFieldID(stProvisionListClass,"boot_mode", "I"); jobject plInfoClassObject = env->GetObjectField(provision_list, plInfo_st); // jstring jstr = (jstring)env->GetObjectField(plInfoClassObject, name); const char* pName = NULL; if(jstr) { pName = (char*)env->GetStringUTFChars(jstr, 0); } jstring jstr1 = (jstring)env->GetObjectField(plInfoClassObject, location); const char* pLoc = NULL; if(jstr1) { pLoc = (char*)env->GetStringUTFChars(jstr1, 0); } jclass ptiClass = env->FindClass("com/askey/firefly/zwave/control/application/ZwaveProvisionList$ProvisionListInfo$ProductTypeInfo"); jfieldID pti_st = env->GetFieldID(stProvisionListClass, "pti", "Lcom/askey/firefly/zwave/control/application/ZwaveProvisionList$ProvisionListInfo$ProductTypeInfo;"); jfieldID generic_cls = env->GetFieldID(ptiClass,"generic_cls", "I"); jfieldID specific_cls = env->GetFieldID(ptiClass,"specific_cls", "I"); jfieldID icon_type = env->GetFieldID(ptiClass,"icon_type", "I"); jobject plPtiObject = env->GetObjectField(plInfoClassObject, pti_st); // jclass piiClass = env->FindClass("com/askey/firefly/zwave/control/application/ZwaveProvisionList$ProvisionListInfo$ProductIdInfo"); jfieldID pii_st = env->GetFieldID(stProvisionListClass, "pii", "Lcom/askey/firefly/zwave/control/application/ZwaveProvisionList$ProvisionListInfo$ProductIdInfo;"); jfieldID manf_id = env->GetFieldID(piiClass,"manf_id", "I"); jfieldID prod_type = env->GetFieldID(piiClass,"prod_type", "I"); jfieldID prod_id = env->GetFieldID(piiClass,"prod_id", "I"); jfieldID app_ver = env->GetFieldID(piiClass,"app_ver", "I"); jfieldID app_sub_ver = env->GetFieldID(piiClass,"app_sub_ver", "I"); jobject plPiiObject = env->GetObjectField(plInfoClassObject, pii_st); // switch (pl_info[i].type) { case PL_INFO_TYPE_PROD_TYPE: pl_info[i].info.prod_type.generic_cls = (env)->GetIntField(plPtiObject, generic_cls); pl_info[i].info.prod_type.specific_cls = (env)->GetIntField(plPtiObject, specific_cls);; pl_info[i].info.prod_type.icon_type = (env)->GetIntField(plPtiObject, icon_type); /*ALOGI(" ==== generic: %x, specific:%x, icon_type:%x,",pl_info[i].info.prod_type.generic_cls, pl_info[i].info.prod_type.specific_cls, pl_info[i].info.prod_type.icon_type);*/ break; case PL_INFO_TYPE_PROD_ID: pl_info[i].info.prod_id.manf_id = (env)->GetIntField(plPiiObject, manf_id); pl_info[i].info.prod_id.prod_type = (env)->GetIntField(plPiiObject, prod_type); pl_info[i].info.prod_id.prod_id = (env)->GetIntField(plPiiObject, prod_id); pl_info[i].info.prod_id.app_ver = (env)->GetIntField(plPiiObject, app_ver); pl_info[i].info.prod_id.app_sub_ver = (env)->GetIntField(plPiiObject, app_sub_ver); /*ALOGI(" ==== manf_id:%x, prod_type:%x, prod_id:%x",pl_info[i].info.prod_id.manf_id, pl_info[i].info.prod_id.prod_type, pl_info[i].info.prod_id.prod_id);*/ break; case PL_INFO_TYPE_INC_INTV: pl_info[i].info.interval = env->GetIntField(plInfoClassObject, interval); break; case PL_INFO_TYPE_NAME: strcpy(pl_info[i].info.name, pName); //ALOGI("==== name :%s",pl_info[i].info.name); break; case PL_INFO_TYPE_LOC: strcpy(pl_info[i].info.loc, pLoc); //ALOGI("==== loc: %s",pl_info[i].info.loc); break; case PL_INFO_TYPE_INCL_STS: pl_info[i].info.incl_sts = env->GetIntField(plInfoClassObject, inclusion_state); ALOGI("==== inclusion state: %d",pl_info[i].info.incl_sts); break; /*case PL_INFO_TYPE_S2_GRNT: buf[j++] = meta_type | PL_INFO_CRITICAL_MASK; buf[j++] = 1; buf[j++] = pl_info[i].info.grnt_keys; break;*/ case PL_INFO_TYPE_BOOT_MODE: pl_info[i].info.boot_mode = env->GetIntField(plInfoClassObject, bootmode); ALOGI("==== boot_mode: %d",pl_info[i].info.boot_mode); break; case PL_INFO_TYPE_NW_STS: //Disallowed break; } } int result = zwcontrol_add_provision_list_entry(&appl_ctx, array, pl_info, infoCnt); return result; } static int controller_rmProvisionListEntry(JNIEnv *env, jclass object, jbyteArray dsk, jint dsklen) { char array[200]; env->GetByteArrayRegion(dsk, 0, dsklen, (jbyte*)array); int result = zwcontrol_rm_provision_list_entry(&appl_ctx, array); return result; } static int controller_getProvisionListEntry(JNIEnv *env, jclass object, jbyteArray dsk, jint dsklen) { char array[200]; env->GetByteArrayRegion(dsk, 0, dsklen, (jbyte*)array); int result = zwcontrol_get_provision_list_entry(&appl_ctx, array); return result; } static int controller_getAllProvisionListEntry(JNIEnv *env, jclass object) { return zwcontrol_get_all_provision_list_entry(&appl_ctx); } static int controller_rmAllProvisionListEntry(JNIEnv *env, jclass object) { return zwcontrol_rm_all_provision_list_entry(&appl_ctx); } static int controller_checkNodeIsFailed(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_check_node_isFailed(&appl_ctx, (uint32_t)nodeId); } static int controller_getSecurity2CmdSupported(JNIEnv *env, jclass object, jint nodeId) { return zwcontrol_s2_command_supported_get(&appl_ctx, (uint32_t)nodeId); } static int controller_sendNodeInformationFrame(JNIEnv *env, jclass object, jint nodeId, jint flag) { return zwcontrol_send_node_information(&appl_ctx, (uint32_t)nodeId, (uint32_t)flag); } static const JNINativeMethod gMethods[] = { {"CreateZwController", "()I", (void *)create_controller}, {"OpenZwController", "(Ljava/lang/String;Ljava/lang/String;[B)I", (void *)open_controller}, {"CloseZwController", "()I", (void *)close_controller}, {"DestoryZwController", "()I", (void *)destroy_controller}, {"ZwController_AddDevice", "()I", (void*)controller_adddevice}, {"ZwController_RemoveDevice", "()I", (void *)controller_removedevice}, {"ZwController_GetDeviceList", "()I", (void *)controller_getDeviceList}, {"ZwController_GetDeviceInfo", "()I", (void *)controller_getDeviceInfo}, {"ZwController_getSpecifyDeviceInfo", "(I)I", (void *)controller_getSpecifyDeviceInfo}, {"ZwController_RemoveFailedDevice", "(I)I", (void *)controller_removeFailedDevice}, {"ZwController_ReplaceFailedDevice", "(I)I", (void *)controller_replaceFailedDevice}, {"ZwController_SetDefault", "()I", (void*)controller_setDefault}, {"ZwController_StopAddDevice", "()I", (void*)controller_stopAddDevice}, {"ZwController_StopRemoveDevice", "()I", (void*)controller_stopRemoveDevice}, {"ZwController_GetDeviceBattery", "(I)I", (void*)controller_getDeviceBattery}, {"ZwController_GetSensorMultiLevel", "(I)I", (void*)controller_getSensorMultiLevel}, {"ZwController_UpdateNode", "(I)I", (void*)control_update_node}, {"ZwController_saveNodeInfo", "(Ljava/lang/String;)I", (void*)control_saveNodeInfo}, {"ZwController_GetBasic", "(I)I", (void*)control_getBasic}, {"ZwController_SetBasic", "(II)I", (void*)control_setBasic}, {"ZwController_GetSwitchMultiLevel", "(I)I", (void*)controller_getSwitchMultiLevel}, {"ZwController_SetSwitchMultiLevel", "(III)I", (void*)controller_setSwitchMultiLevel}, {"ZwController_GetSupportedSwitchType", "(I)I", (void*)controller_getSupportedSwitchType}, {"ZwController_GetConfiguration", "(IIIII)I", (void*)controller_getConfiguration}, {"ZwController_SetConfiguration", "(IIIII)I", (void*)controller_setConfiguration}, {"ZwController_SetConfigurationBulk", "(IIIIII[I)I", (void*)controller_setConfigurationBulk}, {"ZwController_startStopSwitchLevelChange", "(IIIIII)I", (void*)controller_startStopSwitchLevelChange}, {"ZwController_GetPowerLevel", "(I)I", (void*)controller_getPowerLevel}, {"ZwController_SetPowerLevel", "(III)I", (void*)controller_setPowerLevel}, {"ZwController_SetSwitchAllOn", "(I)I", (void*)controller_setSwitchAllOn}, {"ZwController_SetSwitchAllOff", "(I)I", (void*)controller_setSwitchAllOff}, //{"ZwController_SetSwitchAllOnBroadcast", "()I", (void*)controller_setSwitchAllOnBroadcast}, //{"ZwController_SetSwitchAllOffBroadcast", "()I", (void*)controller_setSwitchAllOffBroadcast}, {"ZwController_SetSwitchAll", "(II)I", (void*)controller_setSwitchAll}, {"ZwController_GetSwitchAll", "(I)I", (void*)controller_getSwitchAll}, {"ZwController_StartLearnMode", "()I", (void*)controller_startLearnMode}, {"ZwController_SetBinarySwitchState", "(II)I", (void*)controller_setBinarySwitchState}, {"ZwController_GetBinarySwitchState", "(I)I", (void*)controller_getBinarySwitchState}, {"ZwController_GetSensorBinary", "(II)I", (void*)controller_getSensorBinary}, {"ZwController_GetSensorBinarySupportedSensor", "(I)I", (void*)controller_getSensorBinarySupportedSensor}, {"ZwController_GetMeter", "(II)I", (void*)controller_getMeter}, {"ZwController_resetMeter", "(I)I", (void*)controller_resetMeter}, {"ZwController_getMeterSupported", "(I)I", (void*)controller_getMeterSupported}, {"ZwController_getWakeUpSettings", "(I)I", (void*)controller_getWakeUpSettings}, {"ZwController_setWakeUpInterval", "(II)I", (void*)controller_setWakeUpInterval}, {"ZwController_getDoorLockOperation", "(I)I", (void*)controller_getDoorLockOperation}, {"ZwController_setDoorLockOperation", "(II)I", (void*)controller_setDoorLockOperation}, {"ZwController_getDoorLockConfiguration", "(I)I", (void*)controller_getDoorLockConfiguration}, {"ZwController_setDoorLockConfiguration", "(IIIIII)I", (void*)controller_setDoorLockConfiguration}, /*{"ZwController_getUserCode", "(II)I", (void*)controller_getUserCode}, {"ZwController_setUserCode", "(III)I", (void*)controller_setUserCode}, {"ZwController_getUserCodeNumber", "(I)I", (void*)controller_getUserCodeNumber},*/ {"ZwController_getProtection", "(I)I", (void*)controller_getProtection}, {"ZwController_setProtection", "(III)I", (void*)controller_setProtection}, {"ZwController_getSupportedProtection", "(I)I", (void*)controller_getSupportedProtection}, {"ZwController_getProtectionExcControlNode", "(I)I", (void*)controller_getProtectionExcControlNode}, {"ZwController_setProtectionExcControlNode", "(II)I", (void*)controller_setProtectionExcControlNode}, {"ZwController_getProtectionTimeout", "(I)I", (void*)controller_getProtectionTimeout}, {"ZwController_setProtectionTimeout", "(III)I", (void*)controller_setProtectionTimeout}, {"ZwController_getIndicator", "(I)I", (void*)controller_getIndicator}, {"ZwController_setIndicator", "(II)I", (void*)controller_setIndicator}, /*{"ZwController_getDoorLockLoggingSupportedRecords", "(I)I", (void*)controller_getDoorLockLoggingSupportedRecords}, {"ZwController_getDoorLockLoggingRecords", "(II)I", (void*)controller_getDoorLockLoggingRecords}, {"ZwController_getLanguage", "(I)I", (void*)controller_getLanguage},*/ {"ZwController_getSwitchColor", "(II)I", (void*)controller_getSwitchColor}, {"ZwController_getSupportedSwitchColor", "(I)I", (void*)controller_getSupportedSwitchColor}, {"ZwController_setSwitchColor", "(III)I", (void*)controller_setSwitchColor}, {"ZwController_startStopSwitchColorLevelChange", "(IIIII)I", (void*)controller_startStopSwitchColorLevelChange}, /*{"ZwController_setBarrierOperator", "(II)I", (void*)controller_setBarrierOperator}, {"ZwController_getBarrierOperator", "(I)I", (void*)controller_getBarrierOperator}, {"ZwController_setBarrierOperatorSignal", "(III)I", (void*)controller_setBarrierOperatorSignal}, {"ZwController_getBarrierOperatorSignal", "(II)I", (void*)controller_getBarrierOperatorSignal}, {"ZwController_getSupportedBarrierOperatorSignal", "(I)I", (void*)controller_getSupportedBarrierOperatorSignal}, {"ZwController_getBasicTariffInfo", "(I)I", (void*)controller_getBasicTariffInfo},*/ {"ZwController_getGroupInfo", "(III)I", (void*)controller_getGroupInfo}, {"ZwController_addEndpointsToGroup", "(II[II)I", (void*)controller_addEndpointsToGroup}, {"ZwController_removeEndpointsFromGroup", "(II[II)I", (void*)controller_removeEndpointsFromGroup}, {"ZwController_getMaxSupportedGroups", "(II)I", (void*)controller_getMaxSupportedGroups}, {"ZwController_getSpecificGroup", "(II)I", (void*)controller_getSpecificGroup}, {"ZwController_setNotification", "(III)I", (void*)controller_setNotification}, {"ZwController_getNotification", "(IIII)I", (void*)controller_getNotification}, {"ZwController_getSupportedNotification", "(I)I", (void*)controller_getSupportedNotification}, {"ZwController_getSupportedEventNotification", "(II)I", (void*)controller_getSupportedEventNotification}, {"ZwController_getSupportedCentralScene", "(II)I", (void*)controller_getSupportedCentralScene}, {"ZwController_getSceneActuatorConf", "(II)I", (void*)controller_getSceneActuatorConf}, {"ZwController_setSceneActuatorConf", "(IIIII)I", (void*)controller_setSceneActuatorConf}, {"ZwController_multiCmdEncap", "(I)I", (void*)controller_multiCmdEncap}, {"ZwController_getFirmwareUpdateInfo", "(I)I", (void*)controller_getFirmwareUpdateInfo}, {"ZwController_requestFirmwareUpdate", "(IIIIILjava/lang/String;)I" , (void*)controller_requestFirmwareUpdate}, {"ZwController_getCommandQueueState", "(I)I", (void*)controller_getCommandQueueState}, {"ZwController_controlCommandQueue", "(II)I", (void*)controller_controlCommandQueue}, {"ZwController_viewCommandQueue", "(I)I", (void*)controller_viewCommandQueue}, {"ZwController_cancelAllCommandQueue", "(I)I", (void*)controller_cancelAllCommandQueue}, /*{"ZwController_getControllerNetworkRssiInfo", "()I", (void*)controller_getControllerNetworkRssiInfo}, {"ZwController_getDeviceNetworkRssiInfo", "(I)I", (void*)controller_getNodeNetworkRssiInfo},*/ {"ZwController_startNetworkHealthCheck", "()I", (void*)controller_startNetworkHealthCheck}, {"ZwController_addProvisionListEntry", "([BI[Ljava/lang/Object;I)I", (void*)controller_addProvisionListEntry}, {"ZwController_rmProvisionListEntry", "([BI)I", (void*)controller_rmProvisionListEntry}, {"ZwController_getProvisionListEntry", "([BI)I", (void*)controller_getProvisionListEntry}, {"ZwController_getAllProvisionListEntry", "()I", (void*)controller_getAllProvisionListEntry}, {"ZwController_rmAllProvisionListEntry", "()I", (void*)controller_rmAllProvisionListEntry}, {"ZwController_checkNodeIsFailed", "(I)I", (void*)controller_checkNodeIsFailed}, {"ZwController_getSecurity2CmdSupported", "(I)I", (void*)controller_getSecurity2CmdSupported}, {"ZwController_sendNodeInformationFrame", "(II)I", (void*)controller_sendNodeInformationFrame}, }; static int registerNativeMethods(JNIEnv* env, const char* className, const JNINativeMethod* methods, int numMethods) { jclass clazz; clazz = env->FindClass(className); if (clazz == NULL) { return JNI_FALSE; } if (env->RegisterNatives(clazz, methods, numMethods) < 0) { return JNI_FALSE; } env->DeleteLocalRef(clazz); return JNI_TRUE; } JNIEXPORT jint JNI_OnLoad(JavaVM* g_javaVM, void* reserved) { int status; if(g_javaVM == NULL) { return -1; } JNIEnv* env = NULL; status = g_javaVM->GetEnv((void **) &env, JNI_VERSION_1_4); if(status < 0) { status = g_javaVM->AttachCurrentThread(&env, NULL); if(status < 0) { env = NULL; } return -1; } if(registerNativeMethods(env, "com/askey/firefly/zwave/control/jni/ZwaveControlHelper", gMethods, NELEM(gMethods)) < 0) { return -1; } ZwControlServiceVM = g_javaVM; return JNI_VERSION_1_4; }
37.707834
173
0.707672
[ "object" ]
a647ab5b9d60ce0090f2ede5fe05be6dfbb503f9
2,788
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/wifi/CWifiScannerParcelableScanResults.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/wifi/CWifiScannerParcelableScanResults.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/wifi/CWifiScannerParcelableScanResults.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "elastos/droid/wifi/CWifiScannerParcelableScanResults.h" namespace Elastos { namespace Droid { namespace Wifi { CAR_INTERFACE_IMPL_2(CWifiScannerParcelableScanResults, Object, IWifiScannerParcelableScanResults, IParcelable) CAR_OBJECT_IMPL(CWifiScannerParcelableScanResults) ECode CWifiScannerParcelableScanResults::constructor() { return NOERROR; } ECode CWifiScannerParcelableScanResults::constructor( /* [in] */ ArrayOf<IScanResult*>* results) { mResults = results; return NOERROR; } ECode CWifiScannerParcelableScanResults::SetResults( /* [in] */ ArrayOf<IScanResult*>* results) { mResults = results; return NOERROR; } ECode CWifiScannerParcelableScanResults::GetResults( /* [out, callee] */ ArrayOf<IScanResult*>** result) { VALIDATE_NOT_NULL(result); *result = mResults; REFCOUNT_ADD(*result); return NOERROR; } /** Implement the Parcelable interface {@hide} */ ECode CWifiScannerParcelableScanResults::DescribeContents( /* [out] */ Int32* contents) { VALIDATE_NOT_NULL(contents); *contents = 0; return NOERROR; } /** Implement the Parcelable interface {@hide} */ ECode CWifiScannerParcelableScanResults::WriteToParcel( /* [in] */ IParcel* dest, /* [in] */ Int32 flags) { if (mResults != NULL) { Int32 length = mResults->GetLength(); dest->WriteInt32(length); for (Int32 i = 0; i < length; i++) { AutoPtr<IScanResult> result = (*mResults)[i]; assert(0); // TODO // result->WriteToParcel(dest, flags); } } else { dest->WriteInt32(0); } return NOERROR; } ECode CWifiScannerParcelableScanResults::ReadFromParcel( /* [in] */ IParcel* source) { assert(0); // TODO return E_NOT_IMPLEMENTED; } ECode CWifiScannerParcelableScanResults::WriteToParcel( /* [in] */ IParcel* dest) { assert(0); // TODO return E_NOT_IMPLEMENTED; } } // namespace Wifi } // namespace Droid } // namespace Elastos
26.552381
111
0.651004
[ "object" ]
a6547fe8ef8e5d0d6f33f9638fabd2c29cd9c870
12,979
cpp
C++
sqlite/src/ossimGpkgTileEntry.cpp
ossimlabs/ossim-plugins
88abcbce9e2d0f5ebb06e63d701e6bacf77e93c0
[ "MIT" ]
12
2016-09-09T01:24:12.000Z
2022-01-09T21:45:58.000Z
sqlite/src/ossimGpkgTileEntry.cpp
ossimlabs/ossim-plugins
88abcbce9e2d0f5ebb06e63d701e6bacf77e93c0
[ "MIT" ]
5
2016-02-04T16:10:40.000Z
2021-06-29T05:00:29.000Z
sqlite/src/ossimGpkgTileEntry.cpp
ossimlabs/ossim-plugins
88abcbce9e2d0f5ebb06e63d701e6bacf77e93c0
[ "MIT" ]
20
2015-11-17T11:46:22.000Z
2021-11-12T19:23:54.000Z
//---------------------------------------------------------------------------- // // File: ossimGpkgTileEntry.cpp // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Description: Container class for GeoPackage tile entry. // // Holds a gpkg_tile_matrix_set and a vector of gpkg_tile_matrix. // //---------------------------------------------------------------------------- // $Id$ #include "ossimGpkgTileEntry.h" #include <ossim/base/ossimDpt.h> #include <ossim/base/ossimIpt.h> #include <ossim/base/ossimKeywordlist.h> #include <ossim/base/ossimString.h> #include <ossim/projection/ossimEpsgProjectionFactory.h> #include <ossim/projection/ossimEquDistCylProjection.h> #include <ossim/projection/ossimGoogleProjection.h> #include <ossim/projection/ossimMapProjection.h> #include <ossim/projection/ossimProjection.h> #include <algorithm> /* for std::sort */ #include <iomanip> #include <ostream> static bool tileMatrixSort( const ossimGpkgTileMatrixRecord& i, const ossimGpkgTileMatrixRecord& j ) { // This is backwards, want the highest zoom level should be at lowest index. return ( i.m_zoom_level > j.m_zoom_level ); } static bool tileMatrixExtentSort( const ossimGpkgNsgTileMatrixExtentRecord& i, const ossimGpkgNsgTileMatrixExtentRecord& j ) { // This is backwards, want the highest zoom level should be at lowest index. return ( i.m_zoom_level > j.m_zoom_level ); } ossimGpkgTileEntry::ossimGpkgTileEntry() : m_srs(), m_tileMatrixSet(), m_tileMatrix(0), m_tileMatrixExtents(0) { } ossimGpkgTileEntry::ossimGpkgTileEntry(const ossimGpkgTileEntry& obj) : m_srs(obj.m_srs), m_tileMatrixSet(obj.m_tileMatrixSet), m_tileMatrix(obj.m_tileMatrix), m_tileMatrixExtents(obj.m_tileMatrixExtents) { } const ossimGpkgTileEntry& ossimGpkgTileEntry::operator=(const ossimGpkgTileEntry& obj) { if ( this != &obj ) { m_srs = obj.m_srs; m_tileMatrixSet = obj.m_tileMatrixSet; m_tileMatrix = obj.m_tileMatrix; m_tileMatrixExtents = obj.m_tileMatrixExtents; } return *this; } ossimGpkgTileEntry::~ossimGpkgTileEntry() { } void ossimGpkgTileEntry::setTileMatrixSet(const ossimGpkgTileMatrixSetRecord& set) { m_tileMatrixSet = set; } const ossimGpkgTileMatrixSetRecord& ossimGpkgTileEntry::getTileMatrixSet() const { return m_tileMatrixSet; } void ossimGpkgTileEntry::setSrs( const ossimGpkgSpatialRefSysRecord& srs ) { m_srs = srs; } const ossimGpkgSpatialRefSysRecord& ossimGpkgTileEntry::getSrs() const { return m_srs; } void ossimGpkgTileEntry::addTileMatrix(const ossimGpkgTileMatrixRecord& level) { m_tileMatrix.push_back( level ); } const std::vector<ossimGpkgTileMatrixRecord>& ossimGpkgTileEntry::getTileMatrix() const { return m_tileMatrix; } void ossimGpkgTileEntry::addTileMatrixExtent(const ossimGpkgNsgTileMatrixExtentRecord& record) { m_tileMatrixExtents.push_back( record ); } const std::vector<ossimGpkgNsgTileMatrixExtentRecord>& ossimGpkgTileEntry::getTileMatrixExtent() const { return m_tileMatrixExtents; } void ossimGpkgTileEntry::sortTileMatrix() { std::sort(m_tileMatrix.begin(), m_tileMatrix.end(), tileMatrixSort); } void ossimGpkgTileEntry::sortTileMatrixExtents() { std::sort(m_tileMatrixExtents.begin(), m_tileMatrixExtents.end(), tileMatrixExtentSort); } void ossimGpkgTileEntry::saveState( ossimKeywordlist& kwl, const std::string& prefix ) const { m_srs.saveState( kwl, prefix ); m_tileMatrixSet.saveState( kwl, prefix ); std::string myPrefix = prefix; myPrefix += "gpkg_tile_matrix"; for ( ossim_uint32 i = 0; i < (ossim_uint32)m_tileMatrix.size(); ++i ) { std::string p = myPrefix; p += ossimString::toString(i).string(); p += "."; m_tileMatrix[i].saveState( kwl, p ); } } std::ostream& ossimGpkgTileEntry::print(std::ostream& out) const { ossimKeywordlist kwl; saveState(kwl, std::string("")); out << kwl; return out; } std::ostream& ossimGpkgTileEntry::printValidate(std::ostream& out) const { m_tileMatrixSet.print( out ); // Capture the original flags. std::ios_base::fmtflags f = out.flags(); // Set the new precision capturing old. std::streamsize oldPrecision = out.precision(15); ossim_float64 w = m_tileMatrixSet.getWidth(); ossim_float64 h = m_tileMatrixSet.getHeight(); out << std::setiosflags(std::ios::fixed) << "gpkg_tile_matrix_set.width: " << w << "\n" << "gpkg_tile_matrix_set.height: " << h << "\n"; for ( ossim_uint32 i = 0; i < (ossim_uint32)m_tileMatrix.size(); ++i ) { ossim_float64 computedX = w / m_tileMatrix[i].m_matrix_width / m_tileMatrix[i].m_tile_width; ossim_float64 computedY = h / m_tileMatrix[i].m_matrix_height / m_tileMatrix[i].m_tile_height; std::cout << "gpkg_tile_matrix[" << i << "].zoom_level: " << m_tileMatrix[i].m_zoom_level << "\ngpkg_tile_matrix[" << i << "].pixel_x_size: " << m_tileMatrix[i].m_pixel_x_size << "\ngpkg_tile_matrix[" << i << "].pixel_x_size_computed: " << computedX << "\ngpkg_tile_matrix[" << i << "].pixel_x_size_delta: " << m_tileMatrix[i].m_pixel_x_size - computedX << "\ngpkg_tile_matrix[" << i << "].pixel_y_size: " << m_tileMatrix[i].m_pixel_y_size << "\ngpkg_tile_matrix[" << i << "].pixel_y_size_computed: " << computedY << "\ngpkg_tile_matrix[" << i << "].pixel_y_size_delta: " << m_tileMatrix[i].m_pixel_y_size - computedY << "\n"; } // Reset flags and precision. out.setf(f); out.precision(oldPrecision); return out; } std::ostream& operator<<(std::ostream& out, const ossimGpkgTileEntry& obj) { return obj.print( out ); } ossim_uint32 ossimGpkgTileEntry::getNumberOfLines( ossim_uint32 resLevel ) const { ossim_uint32 result = 0; if ( resLevel < m_tileMatrix.size() ) { // m_tileMatrixExtents may or may not be there. if ( ( resLevel < m_tileMatrixExtents.size() ) && ( m_tileMatrixExtents[resLevel].m_zoom_level == m_tileMatrix[resLevel].m_zoom_level ) ) { result = m_tileMatrixExtents[resLevel].m_max_row - m_tileMatrixExtents[resLevel].m_min_row + 1; } else { ossim_float64 lines = ( m_tileMatrixSet.m_max_y - m_tileMatrixSet.m_min_y ) / m_tileMatrix[resLevel].m_pixel_y_size; if ( lines > 0.0 ) { result = (ossim_uint32)(lines + 0.5); } } } return result; } ossim_uint32 ossimGpkgTileEntry::getNumberOfSamples( ossim_uint32 resLevel ) const { ossim_uint32 result = 0; if ( resLevel < m_tileMatrix.size() ) { // m_tileMatrixExtents may or may not be there. if ( ( resLevel < m_tileMatrixExtents.size() ) && ( m_tileMatrixExtents[resLevel].m_zoom_level == m_tileMatrix[resLevel].m_zoom_level ) ) { result = m_tileMatrixExtents[resLevel].m_max_column - m_tileMatrixExtents[resLevel].m_min_column + 1; } else { ossim_float64 samples = ( m_tileMatrixSet.m_max_x - m_tileMatrixSet.m_min_x ) / m_tileMatrix[resLevel].m_pixel_x_size; if ( samples > 0.0 ) { result = (ossim_uint32)(samples + 0.5); } } } return result; } void ossimGpkgTileEntry::getSubImageOffset( ossim_uint32 resLevel, ossimIpt& offset ) const { // m_tileMatrixExtents may or may not be there. if ( ( resLevel < m_tileMatrix.size() ) && ( resLevel < m_tileMatrixExtents.size() ) && ( m_tileMatrixExtents[resLevel].m_zoom_level == m_tileMatrix[resLevel].m_zoom_level ) ) { offset.x = m_tileMatrixExtents[resLevel].m_min_column; offset.y = m_tileMatrixExtents[resLevel].m_min_row; } else { offset.x = 0; offset.y = 0; } } void ossimGpkgTileEntry::getTiePoint( ossimDpt& tie ) const { // m_tileMatrixExtents may or may not be there. if ( m_tileMatrix.size() && m_tileMatrixExtents.size() && ( m_tileMatrixExtents[0].m_zoom_level == m_tileMatrix[0].m_zoom_level ) ) { tie.x = m_tileMatrixExtents[0].m_min_x; tie.y = m_tileMatrixExtents[0].m_max_y; } else { tie.x = m_tileMatrixSet.m_min_x; tie.y = m_tileMatrixSet.m_max_y; } } void ossimGpkgTileEntry::getGsd( ossim_uint32 index, ossimDpt& gsd ) const { if ( index < m_tileMatrix.size() ) { gsd.x = m_tileMatrix[index].m_pixel_x_size; gsd.y = m_tileMatrix[index].m_pixel_y_size; } else { gsd.makeNan(); } } void ossimGpkgTileEntry::getZoomLevels( std::vector<ossim_int32>& zoomLevels ) const { zoomLevels.clear(); std::vector<ossimGpkgTileMatrixRecord>::const_iterator i = m_tileMatrix.begin(); while ( i != m_tileMatrix.end() ) { zoomLevels.push_back( (*i).m_zoom_level ); ++i; } } void ossimGpkgTileEntry::getZoomLevelMatrixSizes( std::vector<ossimIpt>& zoomLevelMatrixSizes ) const { zoomLevelMatrixSizes.clear(); std::vector<ossimGpkgTileMatrixRecord>::const_iterator i = m_tileMatrix.begin(); while ( i != m_tileMatrix.end() ) { zoomLevelMatrixSizes.push_back( ossimIpt((*i).m_matrix_width, (*i).m_matrix_height) ); ++i; } } ossimRefPtr<ossimMapProjection> ossimGpkgTileEntry::getNewMapProjection() const { ossimRefPtr<ossimMapProjection> mapProj = 0; if ( m_tileMatrix.size() ) { // Must have code, and scale to continue: if ( m_srs.m_organization_coordsys_id && m_tileMatrix[0].m_pixel_x_size && m_tileMatrix[0].m_pixel_y_size ) { std::string org = ossimString(m_srs.m_organization).upcase().string(); if ( org == "EPSG" ) { ossim_uint32 code = (ossim_uint32)m_srs.m_organization_coordsys_id; ossimDpt gsd; getGsd( 0, gsd ); // Avoid factory call for two most common projections. if ( code == 4326 ) { // Geographic, WGS 84 //--- // ossimEquDistCylProjection uses the origin_latitude for meters per pixel // (gsd) computation. Compute to achieve the proper horizontal sccaling. //--- ossimGpt origin(0.0, 0.0); ossim_float64 tmpDbl = ossim::acosd(gsd.y/gsd.x); if ( !ossim::isnan(tmpDbl) ) { origin.lat = tmpDbl; } mapProj = new ossimEquDistCylProjection(ossimEllipsoid(), origin); } else if ( ( code == 3857 ) || ( code == 900913) ) { mapProj = new ossimGoogleProjection(); } else { ossimString name = "EPSG:"; name += ossimString::toString(code); ossimRefPtr<ossimProjection> proj = ossimEpsgProjectionFactory::instance()->createProjection(name); if ( proj.valid() ) { mapProj = dynamic_cast<ossimMapProjection*>( proj.get() ); } } if ( mapProj.valid() ) { //--- // Set the tie and scale. NOTE the tie is center of the upper left // pixel; hence, the half pixel shif. //--- ossimDpt tie; getTiePoint( tie ); if ( mapProj->isGeographic() ) { mapProj->setDecimalDegreesPerPixel(gsd); // Tie latitude, longitude: ossimGpt tiePoint( tie.y, tie.x ); ossimDpt half_pixel_shift = gsd * 0.5; tiePoint.lat -= half_pixel_shift.lat; tiePoint.lon += half_pixel_shift.lon; mapProj->setUlTiePoints(tiePoint); } else { mapProj->setMetersPerPixel(gsd); // Tie Easting Northing: ossimDpt half_pixel_shift = gsd * 0.5; tie.y -= half_pixel_shift.y; tie.x += half_pixel_shift.x; mapProj->setUlTiePoints(tie); } } } // Matches: if ( org == "epsg" ) } // Matches: if ( m_srs.m_organization_coordsys_id && ... } // Matches: if ( m_tileMatrix.size() ) return mapProj; } // End: ossimGpkgTileEntry::getNewMapProjection()
29.836782
98
0.60151
[ "vector" ]
a6554faf92f8772e8b60393a9ff36bd79aa794b3
18,620
cpp
C++
webaccountmanager/cpp/scenario6_customprovider.xaml.cpp
kaid7pro/old-Windows-universal-samples
f97d2b880420fff7bcf7ea0aaf20ee837c002d7d
[ "MIT" ]
6
2015-12-23T22:28:56.000Z
2021-11-06T17:05:51.000Z
webaccountmanager/cpp/scenario6_customprovider.xaml.cpp
y3key/Windows-universal-samples
f97d2b880420fff7bcf7ea0aaf20ee837c002d7d
[ "MIT" ]
null
null
null
webaccountmanager/cpp/scenario6_customprovider.xaml.cpp
y3key/Windows-universal-samples
f97d2b880420fff7bcf7ea0aaf20ee837c002d7d
[ "MIT" ]
8
2015-10-26T01:44:51.000Z
2022-03-12T09:47:56.000Z
// Copyright (c) Microsoft. All rights reserved. #include "pch.h" #include "Scenario6_CustomProvider.xaml.h" using namespace SDKTemplate; using namespace Platform; using namespace Platform::Collections; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::Security::Authentication::Web::Core; using namespace Windows::Security::Credentials; using namespace Windows::Storage; using namespace Windows::UI::Popups; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Navigation; using namespace Windows::UI::ApplicationSettings; Scenario6_CustomProvider::Scenario6_CustomProvider() : rootPage(MainPage::Current) { InitializeComponent(); InitalizeAccountsControlDialog(); } void Scenario6_CustomProvider::OnNavigatedFrom(NavigationEventArgs^ e) { CleanupAccountsControlDialog(); } void SDKTemplate::Scenario6_CustomProvider::Button_SignIn_Click(Object^ sender, RoutedEventArgs^ e) { AccountsSettingsPane::Show(); } void SDKTemplate::Scenario6_CustomProvider::Button_GetTokenSilently_Click(Object^ sender, RoutedEventArgs^ e) { AuthenticateWithRequestTokenSilent(m_account->WebAccountProvider, (String^)MSA_SCOPE_REQUESTED, (String^)MSA_CLIENT_ID, m_account); } void SDKTemplate::Scenario6_CustomProvider::Button_ManageAccount_Click(Object^ sender, RoutedEventArgs^ e) { AccountsSettingsPane::Show(); } void SDKTemplate::Scenario6_CustomProvider::Button_Reset_Click(Object^ sender, RoutedEventArgs^ e) { rootPage->NotifyUser("Resetting", NotifyType::StatusMessage); RemoveCustomProviders(); LogoffAndRemoveAccount(); rootPage->NotifyUser("Done Resetting", NotifyType::StatusMessage); } void SDKTemplate::Scenario6_CustomProvider::Button_AddProvider_Click(Object^ sender, RoutedEventArgs^ e) { AddCustomProvider(textBox_ProviderId->Text, textBox_Authority->Text); } void SDKTemplate::Scenario6_CustomProvider::InitalizeAccountsControlDialog() { // Add to the event AccountCommandsRequested to load our list of providers into the AccountSettingsPane m_accountCommandsRequestedRegistrationToken = AccountsSettingsPane::GetForCurrentView()->AccountCommandsRequested::add( ref new TypedEventHandler<AccountsSettingsPane^, AccountsSettingsPaneCommandsRequestedEventArgs^>( this, &SDKTemplate::Scenario6_CustomProvider::OnAccountCommandsRequested) ); // Populate our list of providers with the MSA provider, and attempt to find any accounts saved. GetProvidersAndAccounts(); } void SDKTemplate::Scenario6_CustomProvider::CleanupAccountsControlDialog() { // Remove the event handler from the AccountCommandsRequested AccountsSettingsPane::GetForCurrentView()->AccountCommandsRequested::remove(m_accountCommandsRequestedRegistrationToken); // Clean up any account that may still be logged in LogoffAndRemoveAccount(); } void SDKTemplate::Scenario6_CustomProvider::OnAccountCommandsRequested( AccountsSettingsPane^ sender, AccountsSettingsPaneCommandsRequestedEventArgs^ e) { // This scenario only supports a single account at one time. // If there already is an account, we do not include a provider in the list // This will prevent the add account button from showing up. if (ApplicationData::Current->LocalSettings->Values->HasKey((String^) STORED_ACCOUNT_ID_KEY)) { AddWebAccount(e); } else { AddWebAccountProviders(e); } AddLinksAndDescription(e); } // Function to create our Map of providers and load an account if an account id is saved void SDKTemplate::Scenario6_CustomProvider::GetProvidersAndAccounts() { //Instantiate the provider list m_providers = ref new Map<String^, WebAccountProvider^>(); if (ApplicationData::Current->LocalSettings->Values->HasKey((String^) STORED_ACCOUNT_ID_KEY)) { LoadAccount(); } } // We've found that we have some key information saved about a previous // account, so we will call FindAccountAsync to grab the WebAccount and save it void SDKTemplate::Scenario6_CustomProvider::LoadAccount() { String^ accountID = (String^)ApplicationData::Current->LocalSettings->Values->Lookup((String^) STORED_ACCOUNT_ID_KEY); String^ providerID = (String^)ApplicationData::Current->LocalSettings->Values->Lookup((String^) STORED_PROVIDER_ID_KEY); String^ authority = (String^)ApplicationData::Current->LocalSettings->Values->Lookup((String^) STORED_AUTHORITY_ID_KEY); if (accountID == nullptr || providerID == nullptr || authority == nullptr) { return; } concurrency::create_task(WebAuthenticationCoreManager::FindAccountProviderAsync(providerID)) .then([this, providerID, accountID, authority](WebAccountProvider^ provider) { concurrency::create_task(WebAuthenticationCoreManager::FindAccountAsync(provider, accountID)) .then([this](WebAccount^ foundAccount) { if (foundAccount != nullptr) { SaveAccount(foundAccount); } }); }); } // This function takes the passed in strings from the textboxes for adding a custom provider. // It will check to make sure the provider is found, then add the provider to our list of providers and // clear the textboxes. void SDKTemplate::Scenario6_CustomProvider::AddCustomProvider(String^ providerId, String^ authority) { try { Concurrency::task<WebAccountProvider^> getCustomProvider; if (authority->IsEmpty() == true) { getCustomProvider = concurrency::create_task(WebAuthenticationCoreManager::FindAccountProviderAsync(providerId)); } else { getCustomProvider = concurrency::create_task(WebAuthenticationCoreManager::FindAccountProviderAsync(providerId, authority)); } getCustomProvider.then([this, providerId](WebAccountProvider^ provider) { if (provider != nullptr) { m_providers->Insert(provider->Id, provider); textBox_ProviderId->Text = ""; textBox_Authority->Text = ""; rootPage->NotifyUser("Provider was found and added for id: " + providerId + ".", NotifyType::StatusMessage); } else { rootPage->NotifyUser("Provider was not found for that provider id: " + providerId + ".", NotifyType::ErrorMessage); } }); } catch (InvalidArgumentException^ e) { rootPage->NotifyUser("An invalid provider id or authority was used.", NotifyType::ErrorMessage); } } // Similar to Scenario 1, but with a loop for the different providers we now support and declared earlier void SDKTemplate::Scenario6_CustomProvider::AddWebAccountProviders(AccountsSettingsPaneCommandsRequestedEventArgs^ e) { for (auto pair : m_providers) { // Create a new WebAccountProviderCommandInvokedHandler for the event fired when a user clicks on a provider in the AccountSettingsPane WebAccountProviderCommandInvokedHandler^ handler = ref new WebAccountProviderCommandInvokedHandler(this, &SDKTemplate::Scenario6_CustomProvider::WebAccountProviderCommandInvoked); // Make a new command based on the provider and the click handler we just created WebAccountProviderCommand^ ProviderCommand = ref new WebAccountProviderCommand(pair->Value, handler); // Append that command to the WebAccountProviderCommands list for the AccountSettingsPane e->WebAccountProviderCommands->Append(ProviderCommand); } } //Creates a web account command object for our account, if we have one saved, and adds it to the AccountsControl list of web account commands void SDKTemplate::Scenario6_CustomProvider::AddWebAccount(AccountsSettingsPaneCommandsRequestedEventArgs^ e) { // Create a new WebAccountCommandInvokedHandler for the event fired when a user clicks on an account in the AccountSettingsPane WebAccountCommandInvokedHandler^ handler = ref new WebAccountCommandInvokedHandler(this, &SDKTemplate::Scenario6_CustomProvider::WebAccountCommandInvoked); // Make a new command based on the account and the click handler we just created WebAccountCommand^ AccountCommand = ref new WebAccountCommand(SDKTemplate::Scenario6_CustomProvider::m_account, handler, SupportedWebAccountActions::Remove); // Append that command to the WebAccountProviderCommands list for the AccountSettingsPane e->WebAccountCommands->Append(AccountCommand); } // You can add links and descriptive text such as privacy policy, help, general account settings void SDKTemplate::Scenario6_CustomProvider::AddLinksAndDescription(AccountsSettingsPaneCommandsRequestedEventArgs^ e) { e->HeaderText = "Describe what adding an account to your application will do for the user."; e->Commands->Append(ref new SettingsCommand("privacypolicy", "Privacy Policy", ref new UICommandInvokedHandler(this, &SDKTemplate::Scenario6_CustomProvider::PrivacyPolicyInvoked))); e->Commands->Append(ref new SettingsCommand("otherlink", "Other Link", ref new UICommandInvokedHandler(this, &SDKTemplate::Scenario6_CustomProvider::OtherLinkInvoked))); } // The function that will be called from AccountSettingsPane with the WebAccountProvider // that was clicked by the user void SDKTemplate::Scenario6_CustomProvider::WebAccountProviderCommandInvoked(WebAccountProviderCommand^ command) { if (command->WebAccountProvider->Authority == "organizations") { AuthenticateWithRequestToken(command->WebAccountProvider, (String^)AAD_SCOPE_REQUESTED, (String^)AAD_CLIENT_ID); } else { AuthenticateWithRequestToken(command->WebAccountProvider, (String^)MSA_SCOPE_REQUESTED, (String^)MSA_CLIENT_ID); } } // Handler function for when users select different commands for accounts in the AccountControl void SDKTemplate::Scenario6_CustomProvider::WebAccountCommandInvoked(WebAccountCommand^ command, WebAccountInvokedArgs^ args) { if (args->Action == WebAccountAction::Remove) { LogoffAndRemoveAccount(); } } // Displays privacy policy message on clicking it in the AccountsControl void SDKTemplate::Scenario6_CustomProvider::PrivacyPolicyInvoked(IUICommand^ command) { rootPage->NotifyUser("Privacy policy clicked by user", NotifyType::StatusMessage); } // Displays other link message on clicking it in the AccountsControl void SDKTemplate::Scenario6_CustomProvider::OtherLinkInvoked(IUICommand^ command) { rootPage->NotifyUser("Other link pressed by user", NotifyType::StatusMessage); } // Create a new WebAccountManager WebTokenRequest based on the Provider, Scope, ClientID and then create a task to send // that request asynchronously to WebAccountManager's RequestTokenAsync API // // WebAccountManager will then try three steps, in order: // (1): Check it's local cache to see if it has a valid token // (2): Try to silently request a new token from the MSA service // (3): Show the MSA UI for user interaction required (user credentials) before it may return a token. // // Because of WebAccountManager's ability to cache tokens, you should only need to call WebAccountManager when making token // based requests and not require the ability to store a cached token within your app. void SDKTemplate::Scenario6_CustomProvider::AuthenticateWithRequestToken(WebAccountProvider^ provider, String^ scope, String^ clientID) { rootPage->NotifyUser("Requested " + provider->DisplayName + " from AccountsManager dialog.", NotifyType::StatusMessage); WebTokenRequest^ wtr = ref new WebTokenRequest(provider, scope, clientID); auto getWebTokenRequestResult = concurrency::create_task(WebAuthenticationCoreManager::RequestTokenAsync(wtr)); // When our task finishes it will return result of the operation, and if successful it will contain a token // and WebAccount. We save the WebAccount as the "active" account. getWebTokenRequestResult.then([this, provider](WebTokenRequestResult^ webTokenRequestResult) { if (webTokenRequestResult->ResponseStatus == WebTokenRequestStatus::Success) { if (webTokenRequestResult->ResponseData->GetAt(0)->WebAccount != nullptr) { if (ApplicationData::Current->LocalSettings->Values->HasKey((String^)STORED_ACCOUNT_ID_KEY)) { ApplicationData::Current->LocalSettings->Values->Remove((String^)STORED_ACCOUNT_ID_KEY); } WebAccount^ account = webTokenRequestResult->ResponseData->GetAt(0)->WebAccount; SaveAccount(account); } } OutputTokenResult(webTokenRequestResult); }); } // Create a new WebAccountManager WebTokenRequest based on the Provider, Scope, ClientID and then create a task to send // that request and the account to get the token for asynchronously to WebAccountManager's GetTokenSilentlyAsync API // // WebAccountManager's GetTokenSilentlyAsync will then try : // (1): Check it's local cache to see if it has a valid token // (2): Try to silently request a new token from the MSA service // (3): Return a status of UserInteractionRequired if we need the user credentials // // Because of WebAccountManager's ability to cache tokens, you should only need to call WebAccountManager when making token // based requests and not require the ability to store a cached token within your app. void SDKTemplate::Scenario6_CustomProvider::AuthenticateWithRequestTokenSilent(WebAccountProvider^ provider, String^ scope, String^ clientID, WebAccount^ account) { rootPage->NotifyUser("Requested " + provider->DisplayName + " from AccountsManager dialog.", NotifyType::StatusMessage); WebTokenRequest^ wtr = ref new WebTokenRequest(provider, scope, clientID); auto getWebTokenRequestResult = concurrency::create_task(WebAuthenticationCoreManager::GetTokenSilentlyAsync(wtr, account)); // When our task finishes it will return result of the operation, and if successful it will contain a token // and WebAccount. We save the WebAccount as the "active" account. getWebTokenRequestResult.then([this](WebTokenRequestResult^ webTokenRequestResult) { if (webTokenRequestResult->ResponseStatus == WebTokenRequestStatus::Success) { // Perform an operation with the token you just got } OutputTokenResult(webTokenRequestResult); }); } // Displays the result of requesting a token asynchronously to the main page void SDKTemplate::Scenario6_CustomProvider::OutputTokenResult(WebTokenRequestResult^ result) { if (result->ResponseStatus == WebTokenRequestStatus::Success) { rootPage->NotifyUser(result->ResponseStatus.ToString() + "!\nUser: " + result->ResponseData->GetAt(0)->WebAccount->Id + "\n Token returned was: " + result->ResponseData->GetAt(0)->Token, NotifyType::StatusMessage); } else if (result->ResponseStatus == WebTokenRequestStatus::ProviderError) { // The account provider has passed us an error and we should handle it. rootPage->NotifyUser(result->ResponseStatus.ToString() + " " + result->ResponseError->ErrorCode + ": " + result->ResponseError->ErrorMessage, NotifyType::ErrorMessage); } else if (result->ResponseStatus == WebTokenRequestStatus::AccountProviderNotAvailable) { // The account provider is unavailable, this is a temporary error. rootPage->NotifyUser(result->ResponseStatus.ToString(), NotifyType::ErrorMessage); } else if (result->ResponseStatus == WebTokenRequestStatus::UserInteractionRequired) { // The account provider needs to display a UI, since we called request token silently we should call it // with RequestTokenAsync. rootPage->NotifyUser(result->ResponseStatus.ToString(), NotifyType::StatusMessage); } else if (result->ResponseStatus == WebTokenRequestStatus::UserCancel) { // The user cancelled the sign in process for the account provider, handle // that how you need to. rootPage->NotifyUser(result->ResponseStatus.ToString(), NotifyType::StatusMessage); } else { // An unexpected error was encountered rootPage->NotifyUser(result->ResponseStatus.ToString() + " " + result->ResponseError->ErrorCode + ": " + result->ResponseError->ErrorMessage, NotifyType::ErrorMessage); } } // Saves the AccountId in LocalSettings and keeps an instance // of the WebAccount saved void SDKTemplate::Scenario6_CustomProvider::SaveAccount(WebAccount^ account) { ApplicationData::Current->LocalSettings->Values->Insert((String^)STORED_ACCOUNT_ID_KEY, account->Id); m_account = account; //Update the UI button_SignIn->IsEnabled = false; button_GetTokenSilently->IsEnabled = true; button_ManageAccount->IsEnabled = true; textblock_SignedInStatus->Text = "Signed in with:"; textblock_SignedInStatus->Foreground = ref new SolidColorBrush(Windows::UI::Colors::Green); listview_SignedInAccounts->Items->Append(account->Id); } // Signs out the account using the SignOutAsync Token Broker API // and removes our saved AccountId as it won't be valid when SignOutAsync finishes. void SDKTemplate::Scenario6_CustomProvider::LogoffAndRemoveAccount() { if (m_account != nullptr) { //concurrency::create_task(account->SignOutAsync((String^) MSA_SCOPE_REQUESTED)); } if (ApplicationData::Current->LocalSettings->Values->HasKey((String^) STORED_ACCOUNT_ID_KEY)) { ApplicationData::Current->LocalSettings->Values->Remove((String^) STORED_ACCOUNT_ID_KEY); } //Update UI button_SignIn->IsEnabled = true; button_GetTokenSilently->IsEnabled = false; button_ManageAccount->IsEnabled = false; textblock_SignedInStatus->Text = "Not signed in."; textblock_SignedInStatus->Foreground = ref new SolidColorBrush(Windows::UI::Colors::Red); listview_SignedInAccounts->Items->Clear(); } void SDKTemplate::Scenario6_CustomProvider::RemoveCustomProviders() { m_providers->Clear(); GetProvidersAndAccounts(); }
45.975309
220
0.735822
[ "object" ]
a65bd8d81e16ae4b31d0a1c5b0a112c850428338
10,220
cpp
C++
plugins/robots/common/twoDModel/src/engine/model/physics/realisticPhysicsEngine.cpp
RexTremendaeMajestatis/QREAL
94786d40e84c18a4407069570588f7d2c4c63aea
[ "Apache-2.0" ]
6
2017-07-03T13:55:35.000Z
2018-11-28T03:39:51.000Z
plugins/robots/common/twoDModel/src/engine/model/physics/realisticPhysicsEngine.cpp
RexTremendaeMajestatis/QREAL
94786d40e84c18a4407069570588f7d2c4c63aea
[ "Apache-2.0" ]
27
2017-06-29T09:36:37.000Z
2017-11-25T14:50:04.000Z
plugins/robots/common/twoDModel/src/engine/model/physics/realisticPhysicsEngine.cpp
RexTremendaeMajestatis/QREAL
94786d40e84c18a4407069570588f7d2c4c63aea
[ "Apache-2.0" ]
null
null
null
/* Copyright 2007-2015 QReal Research Group * * 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 "realisticPhysicsEngine.h" #include <QtCore/QtMath> #include <qrutils/mathUtils/math.h> #include <qrutils/mathUtils/geometry.h> #include "twoDModel/engine/model/constants.h" #include "twoDModel/engine/model/worldModel.h" #include "twoDModel/engine/model/timeline.h" #include "src/engine/items/wallItem.h" using namespace twoDModel::model; using namespace physics; using namespace mathUtils; RealisticPhysicsEngine::RealisticPhysicsEngine(const WorldModel &worldModel, const Timeline &timeline) : PhysicsEngineBase(worldModel) , mForceMoment(0.0) , mAngularVelocity(0.0) { QObject::connect(&timeline, &Timeline::started, [=]() { mVelocity = QVector2D(); mAngularVelocity = 0.0; mForceMoment = 0.0; }); } void RealisticPhysicsEngine::recalculateParams(qreal timeInterval, qreal speed1, qreal speed2 , bool engine1Break, bool engine2Break , const QPointF &rotationCenter, qreal robotAngle , const QPainterPath &robotBoundingPath) { const QVector2D direction = Geometry::directionVector(robotAngle); mReactionForce = QVector2D(); mWallsFrictionForce = QVector2D(); mForceMomentDecrement = 0; mGettingOutVector = QVector2D(); for (const items::WallItem *wall : mWorldModel.walls()) { findCollision(robotBoundingPath, wall->path(), rotationCenter); } countTractionForceAndItsMoment(speed1, speed2, engine1Break || engine2Break, rotationCenter, direction); recalculateVelocity(timeInterval); applyRotationalFrictionForce(timeInterval, direction); mPositionShift = mGettingOutVector + mVelocity * timeInterval; mRotation = mAngularVelocity * timeInterval; } void RealisticPhysicsEngine::countTractionForceAndItsMoment(qreal speed1, qreal speed2, bool breakMode , const QPointF &rotationCenter, const QVector2D &direction) { if (Math::eq(speed1, 0) && Math::eq(speed2, 0)) { const qreal realFrictionFactor = breakMode ? 5 // large value for practically immediate stop : floorFrictionCoefficient; mTractionForce = -realFrictionFactor * mVelocity; mForceMoment = 0; return; } const qreal x = rotationCenter.x(); const qreal y = rotationCenter.y(); const qreal dx = direction.x() * (robotWidth / 2); const qreal dy = direction.y() * (robotHeight / 2); const QPointF engine1Point = QPointF(x + dx + dy, y + dy - dx); const QPointF engine2Point = QPointF(x + dx - dy, y + dy + dx); const QVector2D traction1Force = direction * speed1; const QVector2D traction2Force = direction * speed2; const QVector2D friction1Force = -direction * speed1 * floorFrictionCoefficient; const QVector2D friction2Force = -direction * speed2 * floorFrictionCoefficient; const QVector2D radiusVector1 = QVector2D(engine1Point - rotationCenter); const QVector2D radiusVector2 = QVector2D(engine2Point - rotationCenter); const QVector2D realTractionForce1 = Geometry::projection(traction1Force, radiusVector1); const QVector2D realTractionForce2 = Geometry::projection(traction2Force, radiusVector2); // Parallelogram rule mTractionForce = realTractionForce1 + realTractionForce2; mTractionForce -= floorFrictionCoefficient * mVelocity; const qreal tractionForceMoment1 = Geometry::vectorProduct(traction1Force, radiusVector1); const qreal tractionForceMoment2 = Geometry::vectorProduct(traction2Force, radiusVector2); const qreal frictionForceMoment1 = Geometry::vectorProduct(friction1Force, radiusVector1); const qreal frictionForceMoment2 = Geometry::vectorProduct(friction2Force, radiusVector2); mForceMoment = -tractionForceMoment1 - tractionForceMoment2 - frictionForceMoment1 - frictionForceMoment2; mTractionForce += mReactionForce + mWallsFrictionForce; mForceMoment -= mForceMomentDecrement; } void RealisticPhysicsEngine::recalculateVelocity(qreal timeInterval) { const qreal realAngularVelocityFrictionFactor = qAbs(mAngularVelocity * angularVelocityFrictionFactor); mVelocity += mTractionForce / robotMass * timeInterval; mAngularVelocity += mForceMoment / robotInertialMoment * timeInterval; const qreal angularFriction = realAngularVelocityFrictionFactor / robotInertialMoment * timeInterval; const qreal oldAngularVelocity = mAngularVelocity; mAngularVelocity -= angularFriction * Math::sign(mAngularVelocity); if (oldAngularVelocity * mAngularVelocity <= 0) { mAngularVelocity = 0; } } void RealisticPhysicsEngine::applyRotationalFrictionForce(qreal timeInterval, const QVector2D &direction) { QVector2D rotationalFrictionForce(-direction.y(), direction.x()); rotationalFrictionForce.normalize(); const qreal sinus = Geometry::vectorProduct(mVelocity.normalized(), rotationalFrictionForce); rotationalFrictionForce *= sinus * mVelocity.length() * rotationalFrictionFactor; if (Geometry::scalarProduct(rotationalFrictionForce, mVelocity) > 0) { rotationalFrictionForce = -rotationalFrictionForce; } const QVector2D newVelocity = mVelocity + rotationalFrictionForce / robotMass * timeInterval; const qreal newProjection = Geometry::scalarProduct(newVelocity, rotationalFrictionForce); if (newProjection > 0) { const qreal oldProjection = -Geometry::scalarProduct(mVelocity, rotationalFrictionForce); const qreal incrementFactor = oldProjection / (oldProjection + newProjection); mVelocity += rotationalFrictionForce / robotMass * timeInterval * incrementFactor; } else { mVelocity = newVelocity; } } void RealisticPhysicsEngine::findCollision(const QPainterPath &robotBoundingRegion , const QPainterPath &wallBoundingRegion, const QPointF &rotationCenter) { if (!wallBoundingRegion.intersects(robotBoundingRegion)) { return; } const QPainterPath intersectionRegion = robotBoundingRegion.intersected(wallBoundingRegion).simplified(); QPointF startPoint; QPointF endPoint; const qreal lengthAtom = 1; qreal longestProjection = 0.0; QPointF mostFarPointOnRobot; qreal longestVectorNormalSlope = 0.0; QVector2D sumReaction; int contributorsCount = 0; for (int i = 0; i < intersectionRegion.elementCount(); ++i) { const QPainterPath::Element element = intersectionRegion.elementAt(i); // Walking through the segments... if (element.isMoveTo()) { endPoint = QPointF(element.x, element.y); continue; } startPoint = endPoint; endPoint = QPointF(element.x, element.y); const QLineF currentLine(startPoint, endPoint); // Checking that current segment belongs to the wall path, not the robot one if (!Geometry::belongs(currentLine, wallBoundingRegion, lowPrecision)) { continue; } const qreal currentAngle = currentLine.angle(); const QVector2D atomicVector = QVector2D(endPoint - startPoint).normalized() * lengthAtom; const qreal length = Geometry::distance(startPoint, endPoint); const int fragmentsCount = qCeil(length / lengthAtom); // If current line is too long then dividing it into small segments for (int j = 0; j <= fragmentsCount; ++j) { // Chosing points closer to center. In case of ideal 90 degrees angle between the wall and // the robot`s velocity vector resulting rotation moment must be 0 const int transitionSign = (fragmentsCount + j) % 2 ? -1 : 1; const int middleIndex = fragmentsCount / 2 + transitionSign * ((j + 1) / 2); const QPointF currentSegmentationPoint = j == fragmentsCount ? endPoint : startPoint + middleIndex * atomicVector.toPointF(); const qreal orthogonalAngle = 90 - currentAngle; const QVector2D orthogonalDirectionVector = Geometry::directionVector(orthogonalAngle); const QLineF normalLine = Geometry::veryLongLine(currentSegmentationPoint, orthogonalDirectionVector); // For each point on that segments calculating reaction force vector acting from that point const QList<QPointF> intersectionsWithRobot = Geometry::intersection(normalLine, robotBoundingRegion , lowPrecision); QList<QPointF> intersectionsWithRobotAndWall; for (const QPointF &point : intersectionsWithRobot) { if (Geometry::belongs(point, intersectionRegion, lowPrecision)) { intersectionsWithRobotAndWall << point; } } const QPointF currentMostFarPointOnRobot = Geometry::closestPointTo(intersectionsWithRobotAndWall, currentSegmentationPoint); const QVector2D currentReactionForce = QVector2D(currentSegmentationPoint - currentMostFarPointOnRobot); const QVector2D currentProjection = Geometry::projection(currentReactionForce, mVelocity); sumReaction += currentReactionForce; ++contributorsCount; // The result reaction force is maximal vector from obtained ones if (!currentMostFarPointOnRobot.isNull() && currentProjection.length() > longestProjection) { longestProjection = currentProjection.length(); mostFarPointOnRobot = currentMostFarPointOnRobot; longestVectorNormalSlope = currentAngle; } } } // Reaction force is an average between all reaction forces from small wall parts const QVector2D rawCurrentReactionForce = contributorsCount ? sumReaction / contributorsCount : QVector2D(); const QVector2D currentReactionForce = rawCurrentReactionForce / reactionForceStabilizationCoefficient; const QVector2D frictionForceDirection = Geometry::directionVector(-longestVectorNormalSlope); const QVector2D currentFrictionForce = wallFrictionCoefficient * frictionForceDirection * currentReactionForce.length(); const QVector2D radiusVector(mostFarPointOnRobot - rotationCenter); mReactionForce += currentReactionForce; mWallsFrictionForce += currentFrictionForce; mForceMomentDecrement += Geometry::vectorProduct(currentReactionForce, radiusVector); mForceMomentDecrement += Geometry::vectorProduct(currentFrictionForce, radiusVector); mGettingOutVector += rawCurrentReactionForce; }
40.88
109
0.78229
[ "geometry", "vector", "model" ]
a65f18e467596764749a3d1c75e06f3bef9f31d4
5,379
hpp
C++
include/aula/core/io/binary.hpp
amenoyoya/aula
337ad7e552a24449446c0fe567967ea372661bd7
[ "MIT" ]
null
null
null
include/aula/core/io/binary.hpp
amenoyoya/aula
337ad7e552a24449446c0fe567967ea372661bd7
[ "MIT" ]
null
null
null
include/aula/core/io/binary.hpp
amenoyoya/aula
337ad7e552a24449446c0fe567967ea372661bd7
[ "MIT" ]
null
null
null
#pragma once #include "seekfrom.hpp" namespace Aula { namespace IO { /// バイナリ管理クラス class Binary: public Object { public: /// バイナリ管理モード enum Mode { CONTROL = 1, ALLOCATE = 5, }; Binary(): Object(), ptr(nullptr), pos(0) {} explicit Binary(void *p): Object(), ptr(nullptr), pos(0) { set(p); } explicit Binary(u32 size): Object(), ptr(nullptr), pos(0) { allocate(size); } explicit Binary(const void *data, u32 size): Object(), ptr(nullptr), pos(0) { push(data, size); } explicit Binary(const std::string &data, u32 size): Object(), ptr(nullptr), pos(0) { pushString(data, size); } ~Binary(){ release(); } /// ポインタ直接制御モード(Mode.CONTROL)で対象バイナリを管理 void set(void *p); /// メモリ割り当てモード(Mode.ALLOCATE)で空のバイナリオブジェクトを生成 void allocate(u32 size); /// メモリサイズ変更 // ポインタ位置は先頭に変更される void resize(u32 size); // only Mode.ALLOCATE or NONE /// メモリ解放 void release(); /// サイズは変えず、メモリの割当てのみ行う // 追加するバイナリの大きさがある程度分かっているなら // reserveしてからpush~していく方が高速 void reserve(u32 size) { // only Mode.ALLOCATE if (_state == Mode::ALLOCATE) bin.reserve(size); } /// 指定indexの 8bit data を参照 i8& operator [](u32 i){ return ptr[i]; } /// 指定位置からのポインタ取得 const void *getPointer(u32 head = 0) const { return (const void *)(ptr + head); } /// バイナリデータを文字列型に変換 const std::string &toString() const { return bin; } /// バイナリサイズ取得 u32 getSize() const { // only Mode.ALLOCATE return _state == Mode::ALLOCATE? bin.size(): 0; } /// 現在のポインタ位置取得 const u32 &getPosition() const { return pos; } /// バイナリデータを後ろに追加 void push(const void *data, u32 size); // only Mode.ALLOCATE /// 数値をバイナリとして追加 void pushValue(i32 data, u8 size = 4) { // only Mode.ALLOCATE push(&data, size); } /// 倍精度数値をバイナリとして追加 // precision: 精度(default: 6) void pushNumber(double data, u8 precision = 6) { // only Mode.ALLOCATE pushStringData(Encoding::toString(data, precision)); } /// 文字列をバイナリとして追加 void pushString(const std::string &data, u32 size = u32(-1)) { push(data.c_str(), size == u32(-1)? data.size(): size); } /// 文字列を文字数と一緒に追加 void pushStringData(const std::string &data) { pushValue(data.size()); pushString(data); } /// バイナリの現在位置から数値を取り出す template<typename T> T getValue() { T buf = 0; memcpy(&buf, ptr + pos, sizeof(T)); seek(sizeof(T), SEEK_CUR); return buf; } i32 getI32() { return getValue<i32>(); } u32 getU32() { return getValue<u32>(); } i16 getI16() { return getValue<i16>(); } u16 getU16() { return getValue<u16>(); } i8 getI8() { return getValue<i8>(); } u8 getU8() { return getValue<u8>(); } double getNumber() { return strtod(getStringData().c_str(), nullptr); } /// バイナリの現在位置からsize分の文字列を取り出す std::string getString(u32 size); /// バイナリの現在位置からpushStrDataで入れた文字列を取り出す std::string getStringData() { u32 size = getU32(); return std::move(getString(size)); } /// バイナリの現在位置からsize文のバッファを取り出す // ポインタ位置は size 分進む const void *get(u32 size); /// 読み込み位置を変更する void seek(i32 mov, u8 mode = SeekFrom::HEAD); /// バイナリをキー文字列で簡易暗号化・復号化 // only BINARY_ALLOCATE void encode(const std::string &key, u32 keysize=16); bool decode(const std::string &key, u32 keysize=16); // 暗号化時のキーと異なるキーが指定されると失敗 /// 現在の状態を分岐取得 virtual u8 getState() const { if (_state == Mode::ALLOCATE && pos >= bin.size()) return FINISHED; return _state; } /// @static バイナリデータから4バイトのハッシュ(CRC32)を生成 // 文字列indexの検索を行う場合、文字列比較するよりCRC32ハッシュの比較を行うほうが速い // ただし偶然一致する可能性(16の8乗分の1)もある static u32 getCRC32(const Binary &buffer, u32 bufferlen, u32 crc32_start=0xffffff); private: char *ptr; std::string bin; u32 pos; }; } }
32.017857
96
0.443949
[ "object" ]
a65fd6751887486889122fb42f2f058a91a84c17
16,295
cpp
C++
pxr/imaging/rprUsd/contextHelpers.cpp
GPUOpen-LibrariesAndSDKs/RadeonProRenderUSD
c5a355a0a0c56b824657987ec38176e865ec0381
[ "Apache-2.0" ]
155
2018-08-12T17:48:09.000Z
2022-03-17T08:00:30.000Z
pxr/imaging/rprUsd/contextHelpers.cpp
GPUOpen-LibrariesAndSDKs/RadeonProRenderUSD
c5a355a0a0c56b824657987ec38176e865ec0381
[ "Apache-2.0" ]
228
2018-08-21T15:18:50.000Z
2022-03-31T10:23:50.000Z
pxr/imaging/rprUsd/contextHelpers.cpp
GPUOpen-LibrariesAndSDKs/RadeonProRenderUSD
c5a355a0a0c56b824657987ec38176e865ec0381
[ "Apache-2.0" ]
34
2018-08-22T18:41:42.000Z
2022-03-12T14:32:26.000Z
/************************************************************************ Copyright 2020 Advanced Micro Devices, Inc 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 <json.hpp> using json = nlohmann::json; #include "pxr/imaging/rprUsd/contextHelpers.h" #include "pxr/imaging/rprUsd/contextMetadata.h" #include "pxr/imaging/rprUsd/debugCodes.h" #include "pxr/imaging/rprUsd/helpers.h" #include "pxr/imaging/rprUsd/config.h" #include "pxr/imaging/rprUsd/error.h" #include "pxr/imaging/rprUsd/util.h" #include "pxr/base/arch/env.h" #include "pxr/base/tf/diagnostic.h" #include "pxr/base/tf/envSetting.h" #include <RadeonProRender.hpp> #ifdef HDRPR_ENABLE_VULKAN_INTEROP_SUPPORT #include <RadeonProRender_VK.h> #include <RadeonProRender_Baikal.h> #include <vulkan/vulkan.h> #endif // HDRPR_ENABLE_VULKAN_INTEROP_SUPPORT #ifdef __APPLE__ #include <mach-o/dyld.h> #include <mach-o/getsect.h> #include <dlfcn.h> #elif defined(__linux__) #include <link.h> #endif // __APPLE__ #include <fstream> #include <thread> #include <map> #define PRINT_CONTEXT_CREATION_DEBUG_INFO(format, ...) \ if (!TfDebug::IsEnabled(RPR_USD_DEBUG_CORE_UNSUPPORTED_ERROR)) /* empty */; else TfDebug::Helper().Msg(format, ##__VA_ARGS__) PXR_NAMESPACE_OPEN_SCOPE TF_DEFINE_ENV_SETTING(RPRUSD_ENABLE_TRACING, false, "Enable tracing of RPR core"); TF_DEFINE_ENV_SETTING(RPRUSD_TRACING_DIR, "", "Where to store RPR core tracing files. Must be a path to valid directory"); namespace { #if defined __APPLE__ const char* k_RadeonProRenderLibName = "libRadeonProRender64.dylib"; #elif defined(__linux__) const char* k_RadeonProRenderLibName = "libRadeonProRender64.so"; #endif std::string GetRprSdkPath() { #ifdef __APPLE__ uint32_t count = _dyld_image_count(); std::string pathToRpr; for (uint32_t i = 0; i < count; ++i) { const mach_header* header = _dyld_get_image_header(i); if (!header) { break; } char* code_ptr = NULL; uint64_t size; code_ptr = getsectdatafromheader_64((const mach_header_64*)header, SEG_TEXT, SECT_TEXT, &size); if (!code_ptr) { continue; } const uintptr_t slide = _dyld_get_image_vmaddr_slide(i); const uintptr_t start = (const uintptr_t)code_ptr + slide; Dl_info info; if (dladdr((const void*)start, &info)) { std::string dlpath(info.dli_fname); std::size_t found = dlpath.find(k_RadeonProRenderLibName); if (found != std::string::npos) { return dlpath.substr(0, found); } } } PRINT_CONTEXT_CREATION_DEBUG_INFO("Path to RPR SDK with %s not found", k_RadeonProRenderLibName); #elif defined(__linux__) if (auto handle = dlopen(nullptr, RTLD_NOW)) { link_map* map = nullptr; if (dlinfo(handle, RTLD_DI_LINKMAP, &map)) { const char* errorStr = "unknown reason"; if (auto error = dlerror()) { errorStr = error; } PRINT_CONTEXT_CREATION_DEBUG_INFO("Failed to query RPR SDK path: %s", errorStr); } else { for (auto head = map; head != nullptr; head = head->l_next) { if (auto dlpath = std::strstr(head->l_name, k_RadeonProRenderLibName)) { return std::string(head->l_name, dlpath - head->l_name); } } } } #endif // __APPLE__ return std::string(); } void SetupRprTracing() { if (RprUsdIsTracingEnabled()) { RPR_ERROR_CHECK(rprContextSetParameterByKey1u(nullptr, RPR_CONTEXT_TRACING_ENABLED, 1), "Failed to set context tracing parameter"); auto tracingDir = TfGetEnvSetting(RPRUSD_TRACING_DIR); if (!tracingDir.empty()) { printf("RPR tracing directory: %s\n", tracingDir.c_str()); } RPR_ERROR_CHECK(rprContextSetParameterByKeyString(nullptr, RPR_CONTEXT_TRACING_PATH, tracingDir.c_str()), "Failed to set tracing directory parameter"); } } const rpr::CreationFlags kGpuCreationFlags[] = { RPR_CREATION_FLAGS_ENABLE_GPU0, RPR_CREATION_FLAGS_ENABLE_GPU1, RPR_CREATION_FLAGS_ENABLE_GPU2, RPR_CREATION_FLAGS_ENABLE_GPU3, RPR_CREATION_FLAGS_ENABLE_GPU4, RPR_CREATION_FLAGS_ENABLE_GPU5, RPR_CREATION_FLAGS_ENABLE_GPU6, RPR_CREATION_FLAGS_ENABLE_GPU7, RPR_CREATION_FLAGS_ENABLE_GPU8, RPR_CREATION_FLAGS_ENABLE_GPU9, RPR_CREATION_FLAGS_ENABLE_GPU10, RPR_CREATION_FLAGS_ENABLE_GPU11, RPR_CREATION_FLAGS_ENABLE_GPU12, RPR_CREATION_FLAGS_ENABLE_GPU13, RPR_CREATION_FLAGS_ENABLE_GPU14, RPR_CREATION_FLAGS_ENABLE_GPU15, }; const int kMaxNumGpus = sizeof(kGpuCreationFlags) / sizeof(kGpuCreationFlags[0]); const std::map<RprUsdPluginType, const char*> kPluginLibNames = { #ifdef WIN32 {kPluginTahoe, "Tahoe64.dll"}, {kPluginNorthstar, "Northstar64.dll"}, {kPluginHybrid, "Hybrid.dll"}, {kPluginHybridPro, "HybridPro.dll"}, #elif defined __linux__ {kPluginNorthstar, "libNorthstar64.so"}, {kPluginTahoe, "libTahoe64.so"}, {kPluginHybrid, "Hybrid.so"}, #elif defined __APPLE__ {kPluginTahoe, "libTahoe64.dylib"}, {kPluginNorthstar, "libNorthstar64.dylib"}, #endif }; rpr_int GetPluginID(RprUsdPluginType pluginType) { auto pluginLibNameIter = kPluginLibNames.find(pluginType); if (pluginLibNameIter == kPluginLibNames.end()) { TF_RUNTIME_ERROR("Plugin is not supported: %d", pluginType); return -1; } auto pluginLibName = pluginLibNameIter->second; const std::string rprSdkPath = GetRprSdkPath(); const std::string pluginPath = rprSdkPath.empty() ? pluginLibName : rprSdkPath + "/" + pluginLibName; rpr_int pluginID = rprRegisterPlugin(pluginPath.c_str()); if (pluginID == -1) { TF_RUNTIME_ERROR("Failed to register %s plugin located at \"%s\"", pluginLibName, pluginPath.c_str()); return -1; } return pluginID; } std::string GetGpuName(rpr_int pluginID, rpr::CreationFlags creationFlag, rpr::ContextInfo gpuNameId, const char* cachePath) { rpr::CreationFlags additionalFlags = 0x0; #if defined(__APPLE__) additionalFlags |= RPR_CREATION_FLAGS_ENABLE_METAL; #endif try { rpr::Status status; std::unique_ptr<rpr::Context> context(rpr::Context::Create(RPR_API_VERSION, &pluginID, 1, creationFlag | additionalFlags, nullptr, cachePath, &status)); if (context) { return RprUsdGetStringInfo(context.get(), gpuNameId); } } catch (RprUsdError& e) { PRINT_CONTEXT_CREATION_DEBUG_INFO("Failed to get gpu name: %s", e.what()); } return {}; } template <typename Func> void ForEachGpu(rpr_int pluginID, const char* cachePath, Func&& func) { #define GPU_ACTION(index) \ do { \ rpr::CreationFlags gpuFlag = RPR_CREATION_FLAGS_ENABLE_GPU ## index; \ std::string name = GetGpuName(pluginID, gpuFlag, RPR_CONTEXT_GPU ## index ## _NAME, cachePath); \ func(index, gpuFlag, name); \ } while (0); GPU_ACTION(0); GPU_ACTION(1); GPU_ACTION(2); GPU_ACTION(3); GPU_ACTION(4); GPU_ACTION(5); GPU_ACTION(6); GPU_ACTION(7); GPU_ACTION(8); GPU_ACTION(9); GPU_ACTION(10); GPU_ACTION(11); GPU_ACTION(12); GPU_ACTION(13); GPU_ACTION(14); GPU_ACTION(15); #undef GPU_ACTION } struct DevicesConfiguration { int numCpuThreads; std::vector<int> gpus; }; DevicesConfiguration LoadDevicesConfiguration(RprUsdPluginType pluginType, std::string const& deviceConfigurationFilepath) { RprUsdDevicesInfo devicesInfo = RprUsdGetDevicesInfo(pluginType); if (!devicesInfo.IsValid()) { return {}; } DevicesConfiguration ret = {}; auto isLoaded = [&]() { try { std::ifstream configFile(deviceConfigurationFilepath); if (!configFile.is_open()) { return false; } json devicesConfig; configFile >> devicesConfig; auto pluginDevicesConfigIt = std::find_if(devicesConfig.begin(), devicesConfig.end(), [pluginType](json& entry) { bool foundIt; RprUsdPluginType entryPluginType = TfEnum::GetValueFromName<RprUsdPluginType>(entry["plugin_type"], &foundIt); return foundIt && entryPluginType == pluginType; } ); if (pluginDevicesConfigIt == devicesConfig.end()) { return false; } auto& pluginDevicesConfig = *pluginDevicesConfigIt; auto& cpuConfig = pluginDevicesConfig.at("cpu_config"); auto& cpuInfo = cpuConfig.at("cpu_info"); if (devicesInfo.cpu.numThreads != cpuInfo.at("num_threads").get<int>()) { return false; } cpuConfig.at("num_active_threads").get_to(ret.numCpuThreads); for (auto& gpuConfig : pluginDevicesConfig.at("gpu_configs")) { auto& configGpuInfo = gpuConfig.at("gpu_info"); RprUsdDevicesInfo::GPU gpuInfo(configGpuInfo.at("index"), configGpuInfo.at("name")); if (std::find(devicesInfo.gpus.begin(), devicesInfo.gpus.end(), gpuInfo) == devicesInfo.gpus.end()) { return false; } if (gpuConfig.at("is_enabled").get<bool>()) { ret.gpus.push_back(gpuInfo.index); } } return true; } catch (std::exception& e) { TF_RUNTIME_ERROR("Error on loading devices configurations: %s", e.what()); return false; } }(); if (!isLoaded || (ret.numCpuThreads == 0 && ret.gpus.empty())) { // Setup default configuration: either use the first GPU or, if it is not available, CPU ret = {}; if (devicesInfo.gpus.empty()) { ret.numCpuThreads = devicesInfo.cpu.numThreads; } else { ret.gpus.push_back(devicesInfo.gpus.front().index); } } return ret; } } // namespace anonymous rpr::Context* RprUsdCreateContext(RprUsdContextMetadata* metadata) { SetupRprTracing(); std::string cachePath; std::string textureCachePath; std::string deviceConfigurationFilepath; { RprUsdConfig* config; auto configLock = RprUsdConfig::GetInstance(&config); cachePath = config->GetKernelCacheDir(); textureCachePath = config->GetTextureCacheDir(); deviceConfigurationFilepath = config->GetDeviceConfigurationFilepath(); } rpr_int pluginID = GetPluginID(metadata->pluginType); if (pluginID == -1) { return nullptr; } DevicesConfiguration devicesConfiguration = LoadDevicesConfiguration(metadata->pluginType, deviceConfigurationFilepath); std::vector<rpr_context_properties> contextProperties; auto appendContextProperty = [&contextProperties](uint64_t propertyKey, void* propertyValue) { contextProperties.push_back((rpr_context_properties)propertyKey); contextProperties.push_back((rpr_context_properties)propertyValue); }; rpr::CreationFlags creationFlags = 0; for (int gpuIndex : devicesConfiguration.gpus) { if (gpuIndex >= 0 && gpuIndex < kMaxNumGpus) { creationFlags |= kGpuCreationFlags[gpuIndex]; } } if (devicesConfiguration.numCpuThreads > 0) { creationFlags |= RPR_CREATION_FLAGS_ENABLE_CPU; appendContextProperty(RPR_CONTEXT_CPU_THREAD_LIMIT, (void*)(size_t)devicesConfiguration.numCpuThreads); } if (creationFlags == 0) { return nullptr; } #if __APPLE__ if ((creationFlags & RPR_CREATION_FLAGS_ENABLE_CPU) == 0) { creationFlags |= RPR_CREATION_FLAGS_ENABLE_METAL; } #endif if (metadata->isGlInteropEnabled) { if ((creationFlags & RPR_CREATION_FLAGS_ENABLE_CPU) || RprUsdIsHybrid(metadata->pluginType)) { PRINT_CONTEXT_CREATION_DEBUG_INFO("GL interop could not be used with CPU rendering or Hybrid plugin"); metadata->isGlInteropEnabled = false; } else if (!RprUsdInitGLApi()) { PRINT_CONTEXT_CREATION_DEBUG_INFO("Failed to init GL API. Disabling GL interop"); metadata->isGlInteropEnabled = false; } } if (metadata->isGlInteropEnabled) { creationFlags |= RPR_CREATION_FLAGS_ENABLE_GL_INTEROP; } #ifdef HDRPR_ENABLE_VULKAN_INTEROP_SUPPORT if (RprUsdIsHybrid(metadata->pluginType) && metadata->interopInfo) { // Create interop context for hybrid // TODO: should not it be configurable? constexpr std::uint32_t MB = 1024u * 1024u; static std::uint32_t acc_size = 1024 * MB; static std::uint32_t vbuf_size = 1024 * MB; static std::uint32_t ibuf_size = 512 * MB; static std::uint32_t sbuf_size = 512 * MB; appendContextProperty(RPR_CONTEXT_CREATEPROP_VK_INTEROP_INFO, metadata->interopInfo); appendContextProperty(RPR_CONTEXT_CREATEPROP_HYBRID_ACC_MEMORY_SIZE, &acc_size); appendContextProperty(RPR_CONTEXT_CREATEPROP_HYBRID_VERTEX_MEMORY_SIZE, &vbuf_size); appendContextProperty(RPR_CONTEXT_CREATEPROP_HYBRID_INDEX_MEMORY_SIZE, &ibuf_size); appendContextProperty(RPR_CONTEXT_CREATEPROP_HYBRID_STAGING_MEMORY_SIZE, &sbuf_size); } #endif // HDRPR_ENABLE_VULKAN_INTEROP_SUPPORT contextProperties.push_back(nullptr); rpr::Status status; rpr::Context* context = rpr::Context::Create(RPR_API_VERSION, &pluginID, 1, creationFlags, contextProperties.data(), cachePath.c_str(), &status); if (context) { if (RPR_ERROR_CHECK(context->SetActivePlugin(pluginID), "Failed to set active plugin")) { delete context; return nullptr; } if (metadata->pluginType == kPluginHybridPro) { std::string pluginName = "Hybrid"; status = rprContextSetInternalParameterBuffer(rpr::GetRprObject(context), pluginID, "plugin.name", pluginName.c_str(), pluginName.size() + 1); } RPR_ERROR_CHECK(context->SetParameter(RPR_CONTEXT_TEXTURE_CACHE_PATH, textureCachePath.c_str()), "Failed to set texture cache path"); metadata->creationFlags = creationFlags; } else { RPR_ERROR_CHECK(status, "Failed to create RPR context"); } return context; } RprUsdDevicesInfo RprUsdGetDevicesInfo(RprUsdPluginType pluginType) { rpr_int pluginID = GetPluginID(pluginType); if (pluginID == -1) { return {}; } std::string cachePath; { RprUsdConfig* config; auto configLock = RprUsdConfig::GetInstance(&config); cachePath = config->GetKernelCacheDir(); } RprUsdDevicesInfo ret = {}; if (pluginType == kPluginHybrid) { ret.cpu.numThreads = 0; std::string name = GetGpuName(pluginID, RPR_CREATION_FLAGS_ENABLE_GPU0, RPR_CONTEXT_GPU0_NAME, cachePath.c_str()); if (!name.empty()) { ret.gpus.push_back({0, name}); } } else { ret.cpu.numThreads = std::thread::hardware_concurrency(); ForEachGpu(pluginID, cachePath.c_str(), [&ret](int index, rpr::CreationFlags, std::string const& name) { if (!name.empty()) { ret.gpus.push_back({index, name}); } } ); } return ret; } bool RprUsdIsTracingEnabled() { return TfGetEnvSetting(RPRUSD_ENABLE_TRACING); } bool RprUsdIsGpuUsed(RprUsdContextMetadata const& contextMetadata) { for (auto gpuCreationFlag : kGpuCreationFlags) { if (contextMetadata.creationFlags & gpuCreationFlag) { return true; } } return false; } PXR_NAMESPACE_CLOSE_SCOPE
34.892934
160
0.661859
[ "vector" ]
a660192edec64007a901d707e3a478c28e639608
2,807
cpp
C++
src/mir/passes/dependency_objects.cpp
neheb/meson-plus-plus
8f075012e7a12613883fa335b07c4143f5423111
[ "Apache-2.0" ]
null
null
null
src/mir/passes/dependency_objects.cpp
neheb/meson-plus-plus
8f075012e7a12613883fa335b07c4143f5423111
[ "Apache-2.0" ]
null
null
null
src/mir/passes/dependency_objects.cpp
neheb/meson-plus-plus
8f075012e7a12613883fa335b07c4143f5423111
[ "Apache-2.0" ]
null
null
null
// SPDX-license-identifier: Apache-2.0 // Copyright © 2022 Dylan Baker #include "exceptions.hpp" #include "passes.hpp" #include "private.hpp" namespace MIR::Passes { namespace { std::optional<Object> lower_found_method(const FunctionCall & f) { if (!f.pos_args.empty()) { throw Util::Exceptions::InvalidArguments( "Dependency.found() does not take any positional arguments"); } if (!f.kw_args.empty()) { throw Util::Exceptions::InvalidArguments( "Dependency.found() does not take any keyword arguments"); } return std::make_shared<Boolean>( std::get<std::shared_ptr<Dependency>>(f.holder.value())->found); } std::optional<Object> lower_version_method(const FunctionCall & f) { if (!f.pos_args.empty()) { throw Util::Exceptions::InvalidArguments( "Dependency.version() does not take any positional arguments"); } if (!f.kw_args.empty()) { throw Util::Exceptions::InvalidArguments( "Dependency.version() does not take any keyword arguments"); } return std::make_shared<String>( std::get<std::shared_ptr<Dependency>>(f.holder.value())->version); } std::optional<Object> lower_name_method(const FunctionCall & f) { if (!f.pos_args.empty()) { throw Util::Exceptions::InvalidArguments( "Dependency.name() does not take any positional arguments"); } if (!f.kw_args.empty()) { throw Util::Exceptions::InvalidArguments( "Dependency.name() does not take any keyword arguments"); } return std::make_shared<String>(std::get<std::shared_ptr<Dependency>>(f.holder.value())->name); } std::optional<Object> lower_dependency_methods_impl(const Object & obj, const State::Persistant & pstate) { if (!std::holds_alternative<std::shared_ptr<FunctionCall>>(obj)) { return std::nullopt; } const auto & f = *std::get<std::shared_ptr<FunctionCall>>(obj); if (!(f.holder.has_value() && std::holds_alternative<std::shared_ptr<Dependency>>(f.holder.value()))) { return std::nullopt; } if (!all_args_reduced(f.pos_args, f.kw_args)) { return std::nullopt; } if (f.name == "found") { return lower_found_method(f); } else if (f.name == "version") { return lower_version_method(f); } else if (f.name == "name") { return lower_name_method(f); } // XXX: Shouldn't really be able to get here... return std::nullopt; } } // namespace bool lower_dependency_objects(BasicBlock & block, State::Persistant & pstate) { return function_walker( &block, [&](const Object & obj) { return lower_dependency_methods_impl(obj, pstate); }); } } // namespace MIR::Passes
31.539326
99
0.631991
[ "object" ]
a664234375dce571300e0be06540a67e096ebece
3,586
cc
C++
src/libmv/detector/fast_detector.cc
paulinus/libmv
6656bde5aea4c715695fa98fca6e2b3417e82d76
[ "MIT" ]
1
2016-04-17T12:53:00.000Z
2016-04-17T12:53:00.000Z
src/libmv/detector/fast_detector.cc
rgkoo/libmv-blender
cdf65edbb80d8904e2df9a20116d02546df93a81
[ "MIT" ]
null
null
null
src/libmv/detector/fast_detector.cc
rgkoo/libmv-blender
cdf65edbb80d8904e2df9a20116d02546df93a81
[ "MIT" ]
null
null
null
// Copyright (c) 2009 libmv authors. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #include "libmv/detector/fast_detector.h" #include "libmv/correspondence/feature.h" #include "libmv/detector/detector.h" #include "libmv/detector/orientation_detector.h" #include "libmv/image/image.h" #include "libmv/logging/logging.h" #include "third_party/fast/fast.h" namespace libmv { namespace detector { typedef xy* (*FastDetectorCall)( const unsigned char *, int, int, int, int, int *); class FastDetector : public Detector { public: virtual ~FastDetector() {} FastDetector(FastDetectorCall detector, int threshold, int size, bool bRotationInvariant) : threshold_(threshold), size_(size), detector_(detector), bRotationInvariant_(bRotationInvariant) {} virtual void Detect(const Image &image, vector<Feature *> *features, DetectorData **data) { int num_corners = 0; ByteImage *byte_image = image.AsArray3Du(); if (byte_image) { xy* detections = detector_(byte_image->Data(), byte_image->Width(), byte_image->Height(), byte_image->Width(), threshold_, &num_corners); for (int i = 0; i < num_corners; ++i) { PointFeature *f = new PointFeature(detections[i].x, detections[i].y); f->scale = 3.0; f->orientation = 0.0; features->push_back(f); } free(detections); if (bRotationInvariant_) { fastRotationEstimation(*byte_image, *features); //gradientBoxesRotationEstimation(*byte_image,*features); } } else { LOG(ERROR) << "Invalid input image type for FAST detector"; } // FAST doesn't have a corresponding descriptor, so there's no extra data // to export. if (data) { *data = NULL; } } private: int threshold_; // Threshold called barrier in Fast paper (cf. [1]). int size_; // In pixels {9,10,11,12}. FastDetectorCall detector_; bool bRotationInvariant_; }; Detector *CreateFastDetector(int size, int threshold, bool bRotationInvariant) { FastDetectorCall detector = NULL; if (size == 9) detector = fast9_detect_nonmax; if (size == 10) detector = fast10_detect_nonmax; if (size == 11) detector = fast11_detect_nonmax; if (size == 12) detector = fast12_detect_nonmax; if (!detector) { LOG(FATAL) << "Invalid size for FAST detector: " << size; } return new FastDetector(detector, threshold, size, bRotationInvariant); } } // namespace detector } // namespace libmv
36.591837
79
0.688511
[ "vector" ]
a66531fc6603f4746fb336085cad29a56967af3f
17,169
cpp
C++
lib/replica.cpp
tenjou/replica-next
3f1255398e2f20e76fb52ead1c3595f1043e822b
[ "MIT" ]
1
2018-08-22T16:30:26.000Z
2018-08-22T16:30:26.000Z
lib/replica.cpp
tenjou/replica-next
3f1255398e2f20e76fb52ead1c3595f1043e822b
[ "MIT" ]
null
null
null
lib/replica.cpp
tenjou/replica-next
3f1255398e2f20e76fb52ead1c3595f1043e822b
[ "MIT" ]
null
null
null
#define _USE_MATH_DEFINES #define NOMINMAX #include <iostream> #include <string> #include <cmath> #include <algorithm> #include <vector> #include <windows.h> #include <gl/gl.h> #include <gl/glu.h> #include <stdio.h> #pragma comment (lib, "opengl32.lib") #pragma warning(push) #pragma warning(disable:4244) typedef ptrdiff_t GLsizeiptr; typedef ptrdiff_t GLintptr; typedef char GLchar; #ifndef APIENTRYP #define APIENTRYP APIENTRY * #endif #define GL_TEXTURE_CUBE_MAP 0x8513 #define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 #define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 #define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 #define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 #define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 #define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A #define GL_ARRAY_BUFFER 0x8892 #define GL_STATIC_DRAW 0x88E4 #define GL_DYNAMIC_DRAW 0x88E8 #define GL_UNIFORM_BUFFER 0x8A11 #define GL_FRAGMENT_SHADER 0x8B30 #define GL_VERTEX_SHADER 0x8B31 #define GL_COMPILE_STATUS 0x8B81 #define GL_LINK_STATUS 0x8B82 #define GL_VALIDATE_STATUS 0x8B83 #define GL_INFO_LOG_LENGTH 0x8B84 #define GL_INVALID_INDEX 0xFFFFFFFFu static void checkErrorOGL(const char* code, int line) { auto err = glGetError(); if(err != GL_NO_ERROR) { fprintf(stderr, "GL call failed (error=%X, line %d): %s\n", err, line, code); exit(1); } } #define GLCHK(x) x;checkErrorOGL(#x, __LINE__) typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index); typedef void (APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer); typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers); typedef void (APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers); typedef void (APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const void *data, GLenum usage); typedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const void *data); typedef void (APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader); typedef void (APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader); typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC) (void); typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC) (GLenum type); typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC) (GLuint program); typedef void (APIENTRYP PFNGLDELETESHADERPROC) (GLuint shader); typedef void (APIENTRYP PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader); typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); typedef void (APIENTRYP PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name); typedef void (APIENTRYP PFNGLLINKPROGRAMPROC) (GLuint program); typedef void (APIENTRYP PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); typedef void (APIENTRYP PFNGLUSEPROGRAMPROC) (GLuint program); typedef void (APIENTRYP PFNGLUNIFORM2FPROC) (GLint location, GLfloat v0, GLfloat v1); typedef void (APIENTRYP PFNGLUNIFORM1IPROC) (GLint location, GLint v0); typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); typedef void (APIENTRYP PFNGLVALIDATEPROGRAMPROC) (GLuint program); typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar* name); typedef void (APIENTRYP PFNGLBINDFRAGDATALOCATIONPROC) (GLuint program, GLuint color, const GLchar *name); typedef void (APIENTRYP PFNGLBINDVERTEXARRAYPROC) (GLuint array); typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSPROC) (GLsizei n, const GLuint *arrays); typedef void (APIENTRYP PFNGLGENVERTEXARRAYSPROC) (GLsizei n, GLuint *arrays); typedef GLuint (APIENTRYP PFNGLGETUNIFORMBLOCKINDEXPROC) (GLuint program, const GLchar *uniformBlockName); typedef void (APIENTRYP PFNGLUNIFORMBLOCKBINDINGPROC) (GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); typedef void (APIENTRYP PFNGLBINDBUFFERBASEPROC) (GLenum target, GLuint index, GLuint buffer); PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer; PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray; PFNGLBINDBUFFERPROC glBindBuffer; PFNGLDELETEBUFFERSPROC glDeleteBuffers; PFNGLGENBUFFERSPROC glGenBuffers; PFNGLBUFFERDATAPROC glBufferData; PFNGLBUFFERSUBDATAPROC glBufferSubData; PFNGLATTACHSHADERPROC glAttachShader; PFNGLCOMPILESHADERPROC glCompileShader; PFNGLCREATEPROGRAMPROC glCreateProgram; PFNGLCREATESHADERPROC glCreateShader; PFNGLDELETEPROGRAMPROC glDeleteProgram; PFNGLDELETESHADERPROC glDeleteShader; PFNGLDETACHSHADERPROC glDetachShader; PFNGLGETPROGRAMIVPROC glGetProgramiv; PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog; PFNGLGETSHADERIVPROC glGetShaderiv; PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog; PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation; PFNGLLINKPROGRAMPROC glLinkProgram; PFNGLSHADERSOURCEPROC glShaderSource; PFNGLUSEPROGRAMPROC glUseProgram; PFNGLUNIFORM2FPROC glUniform2f; PFNGLUNIFORM1IPROC glUniform1i; PFNGLUNIFORMMATRIX2FVPROC glUniformMatrix2fv; PFNGLUNIFORMMATRIX4FVPROC glUniformMatrix4fv; PFNGLVALIDATEPROGRAMPROC glValidateProgram; PFNGLGETATTRIBLOCATIONPROC glGetAttribLocation; static HWND hWnd = nullptr; static HDC hDC = nullptr; static HGLRC hRC = nullptr; static void(*requestAnimationFrameFunc)() = nullptr; static bool started = false; static void findAndReplace(std::string& source, std::string const& find, std::string const& replace) { for(std::string::size_type n = 0; (n = source.find(find, n)) != std::string::npos;) { source.replace(n, find.length(), replace); n += replace.length(); } } struct console { static auto log(std::string text) { std::cout << text << std::endl; } static auto error(std::string error) { std::cout << "Error: " << error << std::endl; } }; struct Math { static double min(double a, double b) { return std::min(a, b); } static double max(double a, double b) { return std::max(a, b); } static const double PI; }; const double Math::PI = M_PI; template<class T> struct Array { T* buffer; unsigned int length; Array(std::initializer_list<T> list) { this->length = list.size(); this->buffer = new T[this->length]; int count = 0; for(auto &element : list) { this->buffer[count] = element; ++count; } } T operator[](unsigned int index) { return (index > length) ? 0 : this->buffer[index]; } }; struct Float32Array { GLfloat* buffer; int length; Float32Array() { this->buffer = nullptr; this->length = 0; } Float32Array(unsigned int size) { this->buffer = new float[size]; this->length = size; } Float32Array(Array<double> src) { this->length = src.length; this->buffer = new GLfloat[src.length]; for(unsigned int n = 0; n < src.length; n++) { this->buffer[n] = static_cast<GLfloat>(src.buffer[n]); } } float& $subscript(unsigned int index) { return this->buffer[index]; } }; struct WebGLProgram { GLuint handle = 0; }; struct WebGLBuffer { GLuint handle = 0; }; struct WebGLShader { GLuint handle = 0; }; struct WebGLRenderingContext { WebGLRenderingContext() { hDC = GetDC(hWnd); PIXELFORMATDESCRIPTOR pfd; memset(&pfd, 0, sizeof(pfd)); pfd.nSize = sizeof(pfd); pfd.nVersion = 1; pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 32; pfd.cDepthBits = 32; pfd.iLayerType = PFD_MAIN_PLANE; int pf = ChoosePixelFormat(hDC, &pfd); if(pf == 0) { fprintf(stderr, "Failed to find suitable pixel format."); exit(1); } if(SetPixelFormat(hDC, pf, &pfd) == FALSE) { fprintf(stderr, "Failed to set specified pixel format."); exit(1); } DescribePixelFormat(hDC, pf, sizeof(PIXELFORMATDESCRIPTOR), &pfd); hRC = wglCreateContext(hDC); wglMakeCurrent(hDC, hRC); this->loadExtensions(); } ~WebGLRenderingContext() { wglMakeCurrent(NULL, NULL); ReleaseDC(hWnd, hDC); wglDeleteContext(hRC); } auto clearColor(float red, float green, float blue, float alpha) { GLCHK(glClearColor(red, green, blue, alpha)); } auto clearDepth(float depth) { GLCHK(glClearDepth(depth)); } auto enable(int cap) { GLCHK(glEnable(cap)); } auto depthFunc(int func) { GLCHK(glDepthFunc(func)); } auto clear(int mask) { GLCHK(glClear(mask)); } auto viewport(int x, int y, int width, int height) { GLCHK(glViewport(x, y, width, height)); } auto createProgram() { auto webglProgram = new WebGLProgram(); webglProgram->handle = glCreateProgram(); return webglProgram; } auto attachShader(WebGLProgram* program, WebGLShader* shader) { GLCHK(glAttachShader(program->handle, shader->handle)); } auto linkProgram(WebGLProgram* program) { GLCHK(glLinkProgram(program->handle)); } auto useProgram(WebGLProgram* program) { if(!program) { glUseProgram(0); } else { GLCHK(glUseProgram(program->handle)); } } double getAttribLocation(WebGLProgram* program, std::string name) { auto id = glGetAttribLocation(program->handle, name.c_str()); return glGetAttribLocation(program->handle, name.c_str()); } double getUniformLocation(WebGLProgram* program, std::string name) { return glGetUniformLocation(program->handle, name.c_str()); } auto createShader(double type) { auto webglShader = new WebGLShader(); webglShader->handle = glCreateShader(type); return webglShader; } auto deleteShader(WebGLShader* shader) { GLCHK(glDeleteShader(shader->handle)); shader->handle = 0; } auto shaderSource(WebGLShader* shader, std::string source) { findAndReplace(source, "precision highp float;", ""); findAndReplace(source, "highp", ""); const char* shaderSources[] = { source.c_str() }; GLCHK(glShaderSource(shader->handle, 1, shaderSources, nullptr)); } auto compileShader(WebGLShader* shader) { GLCHK(glCompileShader(shader->handle)); } auto getShaderParameter(WebGLShader* shader, int pname) { GLint infoLogLength; glGetShaderiv(shader->handle, GL_INFO_LOG_LENGTH, &infoLogLength); return !(infoLogLength > 0); } auto getShaderInfoLog(WebGLShader* shader) { GLint infoLogLength; glGetShaderiv(shader->handle, GL_INFO_LOG_LENGTH, &infoLogLength); std::vector<char> v(infoLogLength); glGetShaderInfoLog(shader->handle, infoLogLength, nullptr, v.data()); std::string str(begin(v), end(v)); return str; } auto createBuffer() { auto webglBuffer = new WebGLBuffer(); GLCHK(glGenBuffers(1, &webglBuffer->handle)); return webglBuffer; } auto bindBuffer(int target, WebGLBuffer* buffer) { GLCHK(glBindBuffer(target, buffer->handle)); } auto bufferData(int target, Float32Array* srcData, int usage) { GLCHK(glBufferData(target, srcData->length * sizeof(float), srcData->buffer, usage)); } auto vertexAttribPointer(double index, double size, int type, bool normalized, double stride, double offset) { GLCHK(glVertexAttribPointer(index, size, type, normalized, size * sizeof(GLfloat), (void*)0)); } auto enableVertexAttribArray(double index) { GLCHK(glEnableVertexAttribArray(index)); } auto uniformMatrix4fv(double location, bool transpose, Float32Array *buffer) { GLCHK(glUniformMatrix4fv(location, 1, GL_FALSE, buffer->buffer)); } auto drawArrays(int mode, int first, int count) { GLCHK(glDrawArrays(mode, first, count)); } static const int TRIANGLES; static const int TRIANGLE_STRIP; static const int FLOAT; static const int DEPTH_TEST; static const int LEQUAL; static const int COLOR_BUFFER_BIT; static const int DEPTH_BUFFER_BIT; static const int VERTEX_SHADER; static const int FRAGMENT_SHADER; static const int COMPILE_STATUS; static const int ARRAY_BUFFER; static const int STATIC_DRAW; private: void loadExtensions() { *(void**)&glVertexAttribPointer = wglGetProcAddress("glVertexAttribPointer"); *(void**)&glEnableVertexAttribArray = wglGetProcAddress("glEnableVertexAttribArray"); *(void**)&glBindBuffer = wglGetProcAddress("glBindBuffer"); *(void**)&glDeleteBuffers = wglGetProcAddress("glDeleteBuffers"); *(void**)&glGenBuffers = wglGetProcAddress("glGenBuffers"); *(void**)&glBufferData = wglGetProcAddress("glBufferData"); *(void**)&glBufferSubData = wglGetProcAddress("glBufferSubData"); *(void**)&glAttachShader = wglGetProcAddress("glAttachShader"); *(void**)&glCompileShader = wglGetProcAddress("glCompileShader"); *(void**)&glCreateProgram = wglGetProcAddress("glCreateProgram"); *(void**)&glCreateShader = wglGetProcAddress("glCreateShader"); *(void**)&glDeleteProgram = wglGetProcAddress("glDeleteProgram"); *(void**)&glDeleteShader = wglGetProcAddress("glDeleteShader"); *(void**)&glDetachShader = wglGetProcAddress("glDetachShader"); *(void**)&glGetProgramiv = wglGetProcAddress("glGetProgramiv"); *(void**)&glGetProgramInfoLog = wglGetProcAddress("glGetProgramInfoLog"); *(void**)&glGetShaderiv = wglGetProcAddress("glGetShaderiv"); *(void**)&glGetShaderInfoLog = wglGetProcAddress("glGetShaderInfoLog"); *(void**)&glGetUniformLocation = wglGetProcAddress("glGetUniformLocation"); *(void**)&glLinkProgram = wglGetProcAddress("glLinkProgram"); *(void**)&glShaderSource = wglGetProcAddress("glShaderSource"); *(void**)&glUseProgram = wglGetProcAddress("glUseProgram"); *(void**)&glUniform2f = wglGetProcAddress("glUniform2f"); *(void**)&glUniform1i = wglGetProcAddress("glUniform1i"); *(void**)&glUniformMatrix2fv = wglGetProcAddress("glUniformMatrix2fv"); *(void**)&glUniformMatrix4fv = wglGetProcAddress("glUniformMatrix4fv"); *(void**)&glValidateProgram = wglGetProcAddress("glValidateProgram"); *(void**)&glGetAttribLocation = wglGetProcAddress("glGetAttribLocation"); } }; const int WebGLRenderingContext::TRIANGLES = GL_TRIANGLES; const int WebGLRenderingContext::TRIANGLE_STRIP = GL_TRIANGLE_STRIP; const int WebGLRenderingContext::FLOAT = GL_FLOAT; const int WebGLRenderingContext::DEPTH_TEST = GL_DEPTH_TEST; const int WebGLRenderingContext::LEQUAL = GL_LEQUAL; const int WebGLRenderingContext::COLOR_BUFFER_BIT = GL_COLOR_BUFFER_BIT; const int WebGLRenderingContext::DEPTH_BUFFER_BIT = GL_DEPTH_BUFFER_BIT; const int WebGLRenderingContext::VERTEX_SHADER = GL_VERTEX_SHADER; const int WebGLRenderingContext::FRAGMENT_SHADER = GL_FRAGMENT_SHADER; const int WebGLRenderingContext::COMPILE_STATUS = GL_COMPILE_STATUS; const int WebGLRenderingContext::ARRAY_BUFFER = GL_ARRAY_BUFFER; const int WebGLRenderingContext::STATIC_DRAW = GL_STATIC_DRAW; LONG WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch(uMsg) { case WM_CLOSE: PostQuitMessage(0); return 0; } return DefWindowProc(hWnd, uMsg, wParam, lParam); } struct HTMLCanvasElement { int clientWidth = 800; int clientHeight = 600; HTMLCanvasElement() { HINSTANCE hInstance = GetModuleHandle(nullptr); WNDCLASSA wc; memset(&wc, 0, sizeof(wc)); wc.style = CS_OWNDC; wc.lpfnWndProc = (WNDPROC)WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = NULL; wc.lpszMenuName = NULL; wc.lpszClassName = "replica"; if(!RegisterClass(&wc)) { fprintf(stderr, "Failed to register window class"); exit(1); } RECT winRect = { 0, 0, this->clientWidth, this->clientHeight }; AdjustWindowRect(&winRect, WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_VISIBLE, FALSE); hWnd = CreateWindowA("replica", "replica", WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, winRect.right - winRect.left, winRect.bottom - winRect.top, nullptr, nullptr, hInstance, nullptr); if(!hWnd) { fprintf(stderr, "Failed to create window"); exit(1); } } ~HTMLCanvasElement() { DestroyWindow(hWnd); } auto getContext(std::string contextType) { return new WebGLRenderingContext(); } }; struct Document { auto createElement(std::string elementType) { return new HTMLCanvasElement(); } }; const auto document = new Document(); static void startMainLoop() { if(started) { return; } started = true; MSG msg; for(;;) { while(PeekMessageA(&msg, nullptr, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } if(msg.message == WM_QUIT) { break; } if(requestAnimationFrameFunc != nullptr) { requestAnimationFrameFunc(); } SwapBuffers(hDC); } } void requestAnimationFrame(void(*func)()) { requestAnimationFrameFunc = func; startMainLoop(); }
32.702857
153
0.749607
[ "vector" ]
a666e540e3ffcce6418bff9d7b028ac1e3d1540a
2,681
cpp
C++
src/catfetch.cpp
Beastwick18/catsay
1dc4f8a8c12c9a027452486db9fa703880c6f541
[ "MIT" ]
null
null
null
src/catfetch.cpp
Beastwick18/catsay
1dc4f8a8c12c9a027452486db9fa703880c6f541
[ "MIT" ]
null
null
null
src/catfetch.cpp
Beastwick18/catsay
1dc4f8a8c12c9a027452486db9fa703880c6f541
[ "MIT" ]
null
null
null
#include <iostream> #include <time.h> #include <vector> #include <string.h> #include <sstream> #include <string> using namespace std; bool dev = true; const string eyes("^O$@X-."); const string keys("hwgpdsy"); string shorten(string s, int max) { return (s.length() <= max) ? s : s.substr(0,max-3) + "..."; } char getEye(char key) { int e = key == 'r' ? (rand() % keys.length()) : keys.find(key); return e != keys.npos ? eyes[e] : 0; } void printCat(const string &sfx, const char eye, const bool yell, const int max) { string ws(max+1, ' '); system("pfetch"); cout << ws << " O _" << endl; cout << ws << " o \\`*-." << endl; cout << ws << " . ) _`-." << endl; cout << ws << " . : `. ." << endl; cout << ws << " : _ ' \\" << endl; cout << ws << " ; " << eye << "` _. `*-._" << endl; if(yell) { cout << ws << " _`-.-' `-." << endl; cout << ws << " /| ; ` `." << endl; cout << string(max-sfx.length()+6, ' ') << sfx << " :. . \\" << endl; } else { cout << ws << " `-.-' `-." << endl; cout << string(max-sfx.length()+6, ' ') << sfx << " ; ` `." << endl; cout << ws << " :. . \\" << endl; } cout << ws << " . \\ . : .-' ." << endl; cout << ws << " ' `+.; ; ' :" << endl; cout << ws << " : ' | ; ;-." << endl; cout << ws << " ; ' : :`-: _.`* ;" << endl; cout << ws << " .*' / .*' ; .*`- +' `*'" << endl; cout << ws << " `*-* `*-* `*-*'" << endl << endl; } void readArgs(int argc, char **argv, string &sfx, char &eye, bool &yell) { int i = 1; if(strlen(argv[1]) >= 2 && argv[1][0] == '-') { i = 2; if(yell = (argv[1][1] == 'Y') && strlen(argv[1]) >= 3) eye = getEye(argv[1][2]); eye = eye ?: getEye(argv[1][1]); } for(; i < argc; i++) sfx += string(argv[i]) + ' '; if(sfx.length() != 0 && !eye) eye = '*'; } void defaultChoices(string &sfx, char &eye, bool &yell) { vector<string> choices = { "nyaa", "purr", "prrrrrrrrrrrrrrrrrr", "wrrrao", "mrrowow", "meowww", "hiss" }; int choice = rand() % choices.size(); if(!eye) { eye = '*'; if(choice == 1 || choice == 2) eye = '-'; else if(choice == 0) eye = '^'; } if(choice == 6) yell = true; sfx = '*' + choices[choice] + '*'; } int main(int argc, char **argv) { srand(time(NULL)); char eye = 0; string sfx = ""; bool yell = false; if(argc > 1) readArgs(argc, argv, sfx, eye, yell); if(!sfx.length()) defaultChoices(sfx, eye, yell); int max = 10; sfx = shorten(sfx, max+6); printCat(sfx, eye, yell, max); return 0; }
27.927083
86
0.440134
[ "vector" ]
a66929bcaaf61dcfc381efda4ad2930ef53f88b5
188,335
cpp
C++
client_tools/lms/src/OPE_LMS/external/ex_canvas.cpp
operepo/ope
f1fb4e482fe7a8aae8557a3f07008ae3f6fffccd
[ "MIT" ]
9
2018-04-19T05:08:30.000Z
2021-11-23T07:36:58.000Z
client_tools/lms/src/OPE_LMS/external/ex_canvas.cpp
operepo/ope
f1fb4e482fe7a8aae8557a3f07008ae3f6fffccd
[ "MIT" ]
98
2017-11-02T19:00:44.000Z
2022-03-22T16:15:39.000Z
client_tools/lms/src/OPE_LMS/external/ex_canvas.cpp
operepo/ope
f1fb4e482fe7a8aae8557a3f07008ae3f6fffccd
[ "MIT" ]
9
2017-10-24T21:53:36.000Z
2021-11-23T07:36:59.000Z
#include "ex_canvas.h" #include "../appmodule.h" EX_Canvas::EX_Canvas(QObject *parent, APP_DB *db, QSettings *app_settings, QString localhost_url) : QObject(parent) { canvas_client_id = "1"; canvas_client_secret = "hVGyxhHAKulUTZwAExbKALBpZaHTGDBkoSS7DpsvRpY1H7yzoMfnI5NLnC6t5A0Q"; canvas_access_token = ""; canvas_url = "https://canvas.ed"; _localhost_url = localhost_url; qmlRegisterType<EX_Canvas>("com.openprisoneducation.ope", 1, 0, "Canvas"); // Store the app db we will use if (db == nullptr) { qDebug() << "ERROR - NO QSqlDatabase object provided in constructor!"; } _app_db = db; if (app_settings == nullptr) { qDebug() << "ERROR - NO QSettings object provided in constructor!"; } _app_settings = app_settings; web_request = new CM_WebRequest(this); // Connect the progress signal connect(web_request, SIGNAL(progress(qint64,qint64)), this, SLOT(downloadProgress(qint64, qint64))); } bool EX_Canvas::markItemsAsInactive() { bool ret = true; _app_db->commit(); // Hide records - re-enable them during sync QString sql = "UPDATE `users` SET is_active='false'"; QSqlQuery query; if (!query.exec(sql)) { qDebug() << "DB Error: " << query.lastError().text() << query.lastQuery(); ret = false; } // Hide courses - re-enable them during sync sql = "UPDATE courses SET is_active='false'"; if (!query.exec(sql)) { qDebug() << "DB Error: " << query.lastError().text() << query.lastQuery(); ret = false; } // Hide records - re-enable them during sync sql = "UPDATE `announcements` SET is_active='false'"; if (!query.exec(sql)) { qDebug() << "DB Error: " << query.lastError().text() << query.lastQuery(); ret = false; } // Hide records - re-enable them during sync sql = "UPDATE `assignments` SET is_active='false'"; if (!query.exec(sql)) { qDebug() << "DB Error: " << query.lastError().text() << query.lastQuery(); ret = false; } // Hide records - re-enable them during sync sql = "UPDATE `folders` SET is_active='false'"; if (!query.exec(sql)) { qDebug() << "DB Error: " << query.lastError().text() << query.lastQuery(); ret = false; } // Hide records - re-enable them during sync sql = "UPDATE `files` SET is_active='false'"; if (!query.exec(sql)) { qDebug() << "DB Error: " << query.lastError().text() << query.lastQuery(); ret = false; } // Hide records - re-enable them during sync sql = "UPDATE `pages` SET is_active='false'"; if (!query.exec(sql)) { qDebug() << "DB Error: " << query.lastError().text() << query.lastQuery(); ret = false; } // Hide records - re-enable them during sync sql = "UPDATE `conversations` SET is_active='false'"; if (!query.exec(sql)) { qDebug() << "DB Error: " << query.lastError().text() << query.lastQuery(); ret = false; } // Hide records - re-enable them during sync sql = "UPDATE `messages` SET is_active='false'"; if (!query.exec(sql)) { qDebug() << "DB Error: " << query.lastError().text() << query.lastQuery(); ret = false; } // Hide records - re-enable them during sync sql = "UPDATE `module_items` SET is_active='false'"; if (!query.exec(sql)) { qDebug() << "DB Error: " << query.lastError().text() << query.lastQuery(); ret = false; } // Hide records - re-enable them during sync sql = "UPDATE `modules` SET is_active='false'"; if (!query.exec(sql)) { qDebug() << "DB Error: " << query.lastError().text() << query.lastQuery(); ret = false; } _app_db->commit(); return ret; } bool EX_Canvas::clearInactiveItems() { bool ret = true; _app_db->commit(); // Cleanup records not active QString cleanup_sql = "DELETE FROM `files` WHERE is_active != 'true'"; QSqlQuery cleanup_query; if (!cleanup_query.exec(cleanup_sql)) { qDebug() << "DB Error: " << cleanup_query.lastError().text() << cleanup_query.lastQuery(); } // Cleanup records not active cleanup_sql = "DELETE FROM `announcements` WHERE is_active != 'true'"; if (!cleanup_query.exec(cleanup_sql)) { qDebug() << "DB Error: " << cleanup_query.lastError().text() << cleanup_query.lastQuery(); } // Cleanup records not active cleanup_sql = "DELETE FROM `assignments` WHERE is_active != 'true'"; if (!cleanup_query.exec(cleanup_sql)) { qDebug() << "DB Error: " << cleanup_query.lastError().text() << cleanup_query.lastQuery(); ret = false; } // Cleanup records not active cleanup_sql = "DELETE FROM `folders` WHERE is_active != 'true'"; if (!cleanup_query.exec(cleanup_sql)) { qDebug() << "DB Error: " << cleanup_query.lastError().text() << cleanup_query.lastQuery(); ret = false; } // Cleanup records not active cleanup_sql = "DELETE FROM `pages` WHERE is_active != 'true'"; if (!cleanup_query.exec(cleanup_sql)) { qDebug() << "DB Error: " << cleanup_query.lastError().text() << cleanup_query.lastQuery(); } // Cleanup records not active cleanup_sql = "DELETE FROM `conversations` WHERE is_active != 'true'"; if (!cleanup_query.exec(cleanup_sql)) { qDebug() << "DB Error: " << cleanup_query.lastError().text() << cleanup_query.lastQuery(); ret = false; } // Cleanup records not active cleanup_sql = "DELETE FROM `messages` WHERE is_active != 'true'"; if (!cleanup_query.exec(cleanup_sql)) { qDebug() << "DB Error: " << cleanup_query.lastError().text() << cleanup_query.lastQuery(); ret = false; } // Cleanup records not active cleanup_sql = "DELETE FROM `module_items` WHERE is_active != 'true'"; if (!cleanup_query.exec(cleanup_sql)) { qDebug() << "DB Error: " << cleanup_query.lastError().text() << cleanup_query.lastQuery(); ret = false; } // Cleanup records not active cleanup_sql = "DELETE FROM `modules` WHERE is_active != 'true'"; if (!cleanup_query.exec(cleanup_sql)) { qDebug() << "DB Error: " << cleanup_query.lastError().text() << cleanup_query.lastQuery(); ret = false; } // Cleanup records not active cleanup_sql = "DELETE FROM `users` WHERE is_active != 'true'"; if (!cleanup_query.exec(cleanup_sql)) { qDebug() << "DB Error: " << cleanup_query.lastError().text() << cleanup_query.lastQuery(); ret = false; } _app_db->commit(); return ret; } QString EX_Canvas::pullStudentInfo() { QString ret = ""; if (_app_db == nullptr) { return "ERROR - Invalid Pointer _app_db"; } // Mark items as inactive so we can tell what came in on the new sync markItemsAsInactive(); reloadCourseList(); // Get the courses table GenericTableModel *model = _app_db->getTable("users"); if (model == nullptr) { // Unable to pull the table, error with database? qDebug() << "ERROR pulling users table!!!"; return "ERROR - DB Error - getting users table"; } //qDebug() << " Trying to pull canvas student info..."; // Pull the list of classes from the server QHash<QString,QString> p; p["per_page"] = "10000"; // Cuts down number of calls significantly QJsonDocument doc = CanvasAPICall("/api/v1/users/self", "GET", &p); //qDebug() << doc.toJson(); // Loop through the users and add them to the database if (doc.isObject()) { // JSON Pulled: // {"id":26664700000000083,"name":"Smith, Bob (s777777)", // "sortable_name":"Smith, Bob (s777777)","short_name":"Smith, Bob (s777777)", // "locale":nullptr,"permissions":{"can_update_name":true,"can_update_avatar":false}} QJsonObject o = doc.object(); // Go variant first then convert to long QString id = o["id"].toString(""); QString name = o["name"].toString(""); QJsonArray permissions = o["permissions"].toArray(); if (id == "") { // Invalid user id? qDebug() << "Unable to get student information? " << doc.toJson(); //ret = "Invalid Student ID from Canvas - stopping sync!"; QJsonArray err_arr = o["errors"].toArray(); QJsonObject err_obj = err_arr.first().toObject(); ret = "ERROR - " + err_obj["message"].toString(""); return ret; } model->setFilter("id = '" + id + "'" ); model->select(); // NOTE - Make sure to fetch all or we may only get 256 records while(model->canFetchMore()) { model->fetchMore(); } QSqlRecord record; bool is_insert = false; if (model->rowCount() == 1) { // Row exists, update it with current info record = model->record(0); is_insert = false; qDebug() << "Updating student..." << name; } else { // Need to insert a record clear the filter model->setFilter(""); // Clear the filter record = model->record(); is_insert = true; qDebug() << "Importing student..." << name; } record.setValue("id", o["id"].toString("")); record.setValue("name", o["name"].toString("")); record.setValue("sortable_name", o["sortable_name"].toString("")); record.setValue("short_name", o["short_name"].toString("")); record.setValue("locale", o["locale"].toString("")); record.setValue("permissions", QJsonDocument(o["permissions"].toObject()).toJson()); record.setValue("is_active", "true"); ret = o["name"].toString(""); if(is_insert) { model->insertRecord(-1, record); } else { // Filter should be on so record 0 should still be this record model->setRecord(0, record); } // Write changes to the database if(!model->submitAll()) { qDebug() << "Error on model->submitAll()"; ret = "ERROR - Unable to write changes to database!"; return ret; } model->setFilter(""); // Clear the filter //qDebug() << "Student: " << name << " " << id; // Commit the transaction model->database().commit(); /* Don't check commit status? Transaction not started? if (!model->database().commit()) { qDebug() << "Error on commit!" << model->database().lastError(); ret = "Unable to commit changes to database!"; return ret; }*/ //qDebug() << model->lastError(); // Make sure to set the current user id and name in the registry if (_app_settings) { qDebug() << "Storing student info inthe registry..."; _app_settings->setValue("student/id", o["id"].toString("")); _app_settings->setValue("student/name", o["name"].toString("")); _app_settings->setValue("student/short_name", o["short_name"].toString("")); _app_settings->setValue("student/sortable_name", o["sortable_name"].toString("")); _app_settings->sync(); } } else { // Not an object? Invalid json response? ret = "ERROR - Invalid Json response from server: " + doc.toJson(); } return ret; } QString EX_Canvas::autoAcceptCourses() { QString ret = ""; if (!_app_settings) { QString err = "ERROR - autoAcceptCourses -- No _app_settings?"; qDebug() << err; return err; } QString student_id = _app_settings->value("student/id", "").toString(); if (student_id == "") { // No student id? Fatal error! QString err = "ERROR - No student id in settings, is app credentialed?"; qDebug() << err; return err; } // Get the list of courses for this user QHash<QString, QString> course_list; QHash<QString, QString> course_workflow_state; QString params = "?per_page=10000&state[]=unpublished&state[]=available" "&state[]=completed&enrollment_state[]=invited_or_pending" "&enrollment_state[]=active&enrollment_state[]=completed"; QString api_url = "/api/v1/users/" + student_id + "/courses?per_page=10000&state[]=all"; QJsonDocument doc = CanvasAPICall(api_url, "GET"); //qDebug() << "Json Response" << doc.toJson(); if (doc.isArray()) { QJsonArray arr = doc.array(); foreach(QJsonValue val, arr) { QJsonObject o = val.toObject(); QString course_id = o["id"].toString(""); QString course_name = o["name"].toString(""); QString course_code = o["course_code"].toString(""); QString workflow_state = o["workflow_state"].toString(""); if (course_name != "") { course_list[course_id] = course_name + " (" + course_code + ")"; course_workflow_state[course_id] = workflow_state; //qDebug() << " FOUND COURSE INFO " << course_name << workflow_state; } } } // Parameters QHash<QString,QString> p; // Get the list of pending courses api_url = "api/v1/users/" + student_id + "/enrollments" "?per_page=10000&state[]=invited&state[]=creation_pending"; doc = CanvasAPICall(api_url, "GET"); QHash<QString, QString> course_status; if (doc.isArray()) { // Loop through entries accepting each course /* JSON Pulled - list of these objects * * [{"id":999999000000448,"user_id":999999000000036,"course_id":999999000000457, * "type":"StudentEnrollment","created_at":"2019-02-02T21:18:45Z", * "updated_at":"2019-02-02T21:18:45Z","associated_user_id":null,"start_at":null, * "end_at":null,"course_section_id":999999000000424,"root_account_id":1, * "limit_privileges_to_course_section":false,"enrollment_state":"creation_pending", * "role":"StudentEnrollment","role_id":3,"last_activity_at":null, * "last_attended_at":null,"total_activity_time":0, * "grades":{"html_url":"https://canvas.ed/courses/999999000000457/grades/999999000000036", * "current_grade":null,"current_score":null,"final_grade":null,"final_score":null}, * "html_url":"https://canvas.ed/courses/999999000000457/users/999999000000036", * "user":{"id":999999000000036,"name":"Smith, Bob (s777777)","created_at":"2018-02-22T13:48:15-08:00","sortable_name":"Smith, Bob (s777777)","short_name":"Smith, Bob (s777777)","login_id":"s777777"}} * * */ QJsonArray arr = doc.array(); foreach (QJsonValue val, arr) { // Get the object QJsonObject o = val.toObject(); QString enrollment_state = o["enrollment_state"].toString(); QString enrollment_type = o["type"].toString(); QString course_id = o["course_id"].toString(); QString invitation_id = o["id"].toString(); QString workflow_state = course_workflow_state.value(course_id); // Course name not returned, would need additional queries, so just use ID for now QString course_name = course_list.value(course_id); //QString(o["name"].toString() + " ("+ o["course_code"].toString() + ")"); if (course_name == "") { course_name = course_id; } if (workflow_state == "unpublished") { // This course isn't published, we can't accept the enrollment yet qDebug() << "Course Unpublished! Students will not be able to see materials!" << course_name << course_id; course_status[course_id] = " - <span class='failed'>Not Accepted</span> " + course_name + " - Course not published!"; } else if (enrollment_type != "StudentEnrollment") { qDebug() << "Skipping AutoAcceptCourse since enrollment isn't as a student " << course_name << enrollment_type; course_status[course_id] = " - <span class='failed'>Not Accepted</span> " + course_name + " - Won't accept non student enrollment (" + enrollment_type + ")"; } else if (enrollment_state == "invited" || enrollment_state == "creation_pending") { // Hit the accept URL to make sure this course is accepted api_url = "/api/v1/courses/" + course_id + "/enrollments/" + invitation_id + "/accept"; // DEBUG //api_url = "/api/v1/courses/" + course_id + "/enrollments/debug" + invitation_id + "/accept"; p.clear(); QString err = "Accepting enrollment for pending course " + course_id + "/" + invitation_id; qDebug() << err; //ret += err; QJsonDocument accept_json = CanvasAPICall(api_url, "POST", &p); qDebug() << "Accept Response: " << course_name << course_id << accept_json.toJson(); // Should be an object if (accept_json.isObject()) { QJsonObject accept_object = accept_json.object(); bool is_success = accept_object["success"].toBool(); qDebug() << "Accepted Course " << course_name << "Success: " << is_success; if (is_success) { course_status[course_id] = " - <span class='accepted'>Accepted</span> " + course_name; } else { course_status[course_id] = " - <span class='failed'>Not Accepted</span> " + course_name + " - Is course published? (" + workflow_state + ")"; } } else { qDebug() << "Error activating course? " << course_name << course_id << accept_json.toJson(); course_status[course_id] = " - <span class='failed'>Not Accepted</span> " + course_name + " - Error accepting course, invalid Json response"; } } else { QString err = "Skipping auto accept of pending course " + course_id + " - " + invitation_id + " - " + enrollment_type + " - " + enrollment_state + " - " + student_id; qDebug() << err; //ret += err; course_status[course_id] = " - <span class='failed'>No Accepted</span> " + course_name + " - Skipping due to unknown state (" + enrollment_state + ")"; } } } else { QString err = "ERROR - Invalid JSON Response in autoAcceptCourses\n " + doc.toJson(); qDebug() << err; ret = err; } // Build up output to return if (course_status.count() > 0) { // Loop through each course listed and add output foreach (QString key, course_status.keys()) { QString course_name = key; // Translate from course id to course name if (course_list.contains(key)) { course_name = course_list[key]; } ret += course_status[key] + "\n"; } } else { // No courses found to accept ret += " - No invitations found"; } return ret; } QString EX_Canvas::pullCourses() { QString ret = ""; QString sql = ""; QSqlQuery query; if (_app_db == nullptr) { return "ERROR - No valid _app_db"; } // Get the courses table GenericTableModel *model = _app_db->getTable("courses"); if (model == nullptr) { // Unable to pull the courses table, error with database? QString err = "ERROR - pulling courses table!!!"; qDebug() << err; return err; } //qDebug() << " Trying to pull canvas courses..."; // Pull the list of classes from the server QHash<QString,QString> p; //p["per_page"] = "10000"; // Cuts down number of calls significantly // Add extra filter so we get ALL courses (even unpublished and pending) //p["state[]"] = "all"; QJsonDocument doc = CanvasAPICall("/api/v1/courses?per_page=10000&state[]=all", "GET", &p); //qDebug() << doc.toJson(); QHash<QString, QString> courses_pulled; // Loop through the courses and add them to the database if (doc.isArray()) { // JSON Pulled: // id":26664700000000082,"name":"Auto Create - CSE100","account_id":1, //"start_at":"2017-06-08T22:29:59Z","grading_standard_id":nullptr, //"is_public":nullptr,"course_code":"CSE100","default_view":"feed", //"root_account_id":1,"enrollment_term_id":1,"end_at":nullptr, //"public_syllabus":false,"public_syllabus_to_auth":false, //"storage_quota_mb":500,"is_public_to_auth_users":false, //"apply_assignment_group_weights":false, //"calendar":{"ics":"https://canvas.ed.dev/feeds/calendars/course_1DH5m9Z2FmnmKo4pvtbTilzvUkr18C0ImOD91YNl.ics"}, //"time_zone":"America/Denver","enrollments":[{"type":"student", //"role":"StudentEnrollment","role_id":3,"user_id":26664700000000083, //"enrollment_state":"active"}],"hide_final_grades":false, //"workflow_state":"available","restrict_enrollments_to_course_dates":false} QJsonArray arr = doc.array(); foreach (QJsonValue val, arr) { QJsonObject o = val.toObject(); // Go variant first then convert to long QString course_id = o["id"].toString(""); bool access_restricted_by_date = o["access_restricted_by_date"].toBool(); QString course_name = o["name"].toString(""); QJsonArray enrollments = o["enrollments"].toArray(); bool isStudent = false; bool isTA_plus = false; // marked for any other enrollment besides student bool is_active = true; // determine if course/enrollment is active QString enrollment_type = ""; QString enrollment_role = ""; QString enrollment_role_id = ""; QString enrollment_state = ""; QString workflow_state = o["workflow_state"].toString(""); // ---- this helps prevent TAs from uploading things and syncing those classes bool is_syncing = false; // Are we going to sync this course? foreach (QJsonValue enrollmentVal, enrollments) { QJsonObject enrollment = enrollmentVal.toObject(); if (enrollment["type"].toString("") == "student" && (enrollment["enrollment_state"] == "active" || enrollment["enrollment_state"] == "invited")) { isStudent = true; enrollment_type = enrollment["type"].toString(""); enrollment_role = enrollment["role"].toString(""); enrollment_role_id = enrollment["role_id"].toString(""); enrollment_state = enrollment["enrollment_state"].toString(""); qDebug() << " --> Found active student enrollment " << course_name << ":" << course_id << ":" << enrollment["type"]; } else if (enrollment["type"].toString("") == "student" && enrollment["enrollment_state"] != "active") { // Student but not active enrollment_state = enrollment["enrollment_state"].toString(""); qDebug() << " --> Found inactive student enrollment (not syncing) " << course_name << ":" << course_id << ":" << enrollment["type"]; is_active = false; isStudent = true; } else { qDebug() << " --> Found NON student enrollment (not syncing) " << course_name << ":" << course_id << ":" << enrollment["type"]; enrollment_state = enrollment["enrollment_state"].toString(""); isTA_plus = true; } } qDebug() << "ACCESS: " << access_restricted_by_date; if (access_restricted_by_date == true) { courses_pulled[course_id] = " - <span class='failed'>NOT SYNCING</span> " + course_id + " - COURSE RESTRICTED BY DATE"; qDebug() << "*** Course access restricted by date - not syncing " << course_name << ":" << course_id; } else if (workflow_state != "available") { courses_pulled[course_name] = " - <span class='failed'>NOT SYNCING</span> " + course_name + " - Course not published? (" + workflow_state + "/" + enrollment_state + ")"; qDebug() << "*** Course not published - not syncing " << course_name << ":" << course_id; }else if (isStudent == true && is_active == true && isTA_plus != true) { is_syncing = true; // Is a student, but NOT a TA or higher... do the sync. model->setFilter("id = '" + course_id + "'" ); model->select(); // NOTE - Make sure to fetch all or we may only get 256 records while(model->canFetchMore()) { model->fetchMore(); } QSqlRecord record; bool is_insert = false; if (model->rowCount() == 1) { // Row exists, update it with current info record = model->record(0); is_insert = false; qDebug() << "\tUpdating course..." << course_id << course_name; } else { // Need to insert a record clear the filter model->setFilter(""); // Clear the filter record = model->record(); is_insert = true; qDebug() << "\tImporting course..." << course_id << course_name; } record.setValue("id", o["id"].toString("")); record.setValue("name", o["name"].toString("")); record.setValue("account_id", o["account_id"].toString("")); record.setValue("start_at", o["start_at"].toString("")); record.setValue("grading_standard_id", o["grading_standard_id"].toString("")); record.setValue("is_public", o["is_public"].toBool(false)); record.setValue("course_code", o["course_code"].toString("")); record.setValue("default_view", o["default_view"].toString("")); record.setValue("root_account_id", o["root_account_id"].toString("")); record.setValue("enrollment_term_id", o["enrollment_term_id"].toString("")); record.setValue("end_at", o["end_at"].toString("")); record.setValue("public_syllabus", o["public_syllabus"].toBool(false)); record.setValue("public_syllabus_to_auth", o["public_syllabus_to_auth"].toBool(false)); record.setValue("storage_quota_mb", o["storage_quota_mb"].toString("")); record.setValue("is_public_to_auth_users", o["is_public_to_auth_users"].toBool(false)); record.setValue("apply_assignment_group_weights", o["apply_assignment_group_weights"].toBool(false)); record.setValue("calendar", QJsonDocument(o["calendar"].toObject()).toJson()); record.setValue("time_zone", o["time_zone"].toString("")); record.setValue("hide_final_grades", o["hide_final_grades"].toString("")); record.setValue("workflow_state", o["workflow_state"].toString("")); record.setValue("restrict_enrollments_to_course_dates", o["restrict_enrollments_to_course_dates"].toBool(false)); record.setValue("enrollment_type", enrollment_type); record.setValue("enrollment_role", enrollment_role); record.setValue("enrollment_role_id", enrollment_role_id); record.setValue("enrollment_state", enrollment_state); record.setValue("enrollment_user_id", o["user_id"].toString("")); record.setValue("is_active", "true"); if(is_insert) { model->insertRecord(-1, record); } else { // Filter should be on so record 0 should still be this record model->setRecord(0, record); } // Write changes to the database if(!model->submitAll()) { qDebug() << "Error submitting database changes " << model->database().lastError(); return "ERROR - Unable to submit database changes!"; } model->setFilter(""); // Clear the filter if (is_syncing) { courses_pulled[course_name] = " - <span class='accepted'>SYNCING</span> " + course_name + " (" + workflow_state + "/" + enrollment_state + ")"; } else { courses_pulled[course_name] = " - <span class='failed'>NOT SYNCING</span> " + course_name + " (" + workflow_state + "/" + enrollment_state + ")"; } }else if (isStudent == true && is_active != true) { // Log that we aren't syncing this course courses_pulled[course_name] = " - <span class='failed'>NOT SYNCING</span> " + course_name + " - Enrollment isn't active (" + workflow_state + "/" + enrollment_state + ")"; qDebug() << "*** Course enrollment isn't active, not syncing this course " << course_name << ":" << course_id; } else { // Log that we aren't syncing this course courses_pulled[course_name] = " - <span class='failed'>NOT SYNCING</span> " + course_name + " - TA+ permissions found, will only sync student access (" + workflow_state + "/" + enrollment_state + ")"; qDebug() << "*** TA+ permissions detected, not syncing this course " << course_name << ":" << course_id; } //qDebug() << "Course: " << course_name << " " << course_id << " is student " << isStudent; } // Commit the transaction model->database().commit(); //qDebug() << model->lastError(); } // Remove any courses that are not active=true QSqlQuery q; q.prepare("DELETE FROM courses WHERE is_active != 'true'"); if (!q.exec()) { qDebug() << "ERROR - SQL Query Failed: " << q.lastError(); } else { _app_db->commit(); } // Clear the dl_queue q.clear(); q.prepare("DELETE FROM canvas_dl_queue"); if (!q.exec()) { qDebug() << "ERROR - SQL Query Failed: " << q.lastError(); } else { _app_db->commit(); } // Clear the SMC media dl queue q.clear(); q.prepare("DELETE FROM smc_media_dl_queue2"); if (!q.exec()) { qDebug() << "ERROR - SQL Query Failed: " << q.lastError(); } else { _app_db->commit(); } // Clear the SMC document dl queue q.clear(); q.prepare("DELETE FROM smc_document_dl_queue2"); if (!q.exec()) { qDebug() << "ERROR - SQL Query Failed: " << q.lastError(); } else { _app_db->commit(); } // Make sure the list of courses in memory is reloaded for later use reloadCourseList(); // Return the list of courses foreach (QString key, courses_pulled.keys()) { ret += courses_pulled[key] + "\n"; } return ret; } QString EX_Canvas::pullDiscussionTopics() { // Grab discussion topics for each course in the database QString ret = ""; if (_app_db == nullptr) { return ret; } // Get the list of courses for this student GenericTableModel *courses_model = _app_db->getTable("courses"); GenericTableModel *model = _app_db->getTable("discussion_topics"); if (courses_model == nullptr || model == nullptr) { QString err = "ERROR - Unable to get models for courses or discussion topics!"; qDebug() << err; return err; } // All enteries should be for this student, so get them all courses_model->setFilter(""); courses_model->select(); // NOTE - Make sure to fetch all or we may only get 256 records while(courses_model->canFetchMore()) { courses_model->fetchMore(); } ret = true; int rowCount = courses_model->rowCount(); for (int i=0; i<rowCount; i++) { // Get modules for this course QSqlRecord course_record = courses_model->record(i); QString course_id = course_record.value("id").toString(); //qDebug() << "Retrieving modules for " << course_id; QHash<QString,QString> p; p["per_page"] = "10000"; // Cuts down number of calls significantly QJsonDocument doc = CanvasAPICall("/api/v1/courses/" + course_id + "/discussion_topics", "GET", &p); if (doc.isArray()) { qDebug() << "\tDiscussion Topics for course:"; // Should be an array of discussion topics QJsonArray arr = doc.array(); foreach(QJsonValue val, arr) { //qDebug() << "got item..."; // This should be a topic QJsonObject o = val.toObject(); QString id = o["id"].toString(""); //qDebug() << "Discussion Topic ID " << id; model->setFilter("id = " + id); model->select(); // NOTE - Make sure to fetch all or we may only get 256 records while(model->canFetchMore()) { model->fetchMore(); } QSqlRecord record; bool is_insert = false; if (model->rowCount() == 1) { // Row exists, update with current info record = model->record(0); is_insert = false; qDebug() << "\t\tUpdating discussion topic..." << id << o["title"].toString(""); } else { // Need to clear the filter to insert model->setFilter(""); record = model->record(); is_insert = true; qDebug() << "\t\tImporting discussion topic..." << id << o["title"].toString(""); } // JSON - list of objects /* // A discussion topic { // The ID of this topic. "id": 1, // The topic title. "title": "Topic 1", // The HTML content of the message body. "message": "<p>content here</p>", // The URL to the discussion topic in canvas. "html_url": "https://<canvas>/courses/1/discussion_topics/2", // The datetime the topic was posted. If it is null it hasn't been posted yet. // (see delayed_post_at) "posted_at": "2037-07-21T13:29:31Z", // The datetime for when the last reply was in the topic. "last_reply_at": "2037-07-28T19:38:31Z", // If true then a user may not respond to other replies until that user has made // an initial reply. Defaults to false. "require_initial_post": false, // Whether or not posts in this topic are visible to the user. "user_can_see_posts": true, // The count of entries in the topic. "discussion_subentry_count": 0, // The read_state of the topic for the current user, 'read' or 'unread'. "read_state": "read", // The count of unread entries of this topic for the current user. "unread_count": 0, // Whether or not the current user is subscribed to this topic. "subscribed": true, // (Optional) Why the user cannot subscribe to this topic. Only one reason will // be returned even if multiple apply. Can be one of: 'initial_post_required': // The user must post a reply first; 'not_in_group_set': The user is not in the // group set for this graded group discussion; 'not_in_group': The user is not // in this topic's group; 'topic_is_announcement': This topic is an announcement "subscription_hold": "not_in_group_set", // The unique identifier of the assignment if the topic is for grading, // otherwise null. "assignment_id": null, // The datetime to publish the topic (if not right away). "delayed_post_at": null, // Whether this discussion topic is published (true) or draft state (false) "published": true, // The datetime to lock the topic (if ever). "lock_at": null, // Whether or not the discussion is 'closed for comments'. "locked": false, // Whether or not the discussion has been 'pinned' by an instructor "pinned": false, // Whether or not this is locked for the user. "locked_for_user": true, // (Optional) Information for the user about the lock. Present when // locked_for_user is true. "lock_info": null, // (Optional) An explanation of why this is locked for the user. Present when // locked_for_user is true. "lock_explanation": "This discussion is locked until September 1 at 12:00am", // The username of the topic creator. "user_name": "User Name", // DEPRECATED An array of topic_ids for the group discussions the user is a part // of. "topic_children": [5, 7, 10], // An array of group discussions the user is a part of. Fields include: id, // group_id "group_topic_children": [{"id":5,"group_id":1}, {"id":7,"group_id":5}, {"id":10,"group_id":4}], // If the topic is for grading and a group assignment this will point to the // original topic in the course. "root_topic_id": null, // If the topic is a podcast topic this is the feed url for the current user. "podcast_url": "/feeds/topics/1/enrollment_1XAcepje4u228rt4mi7Z1oFbRpn3RAkTzuXIGOPe.rss", // The type of discussion. Values are 'side_comment', for discussions that only // allow one level of nested comments, and 'threaded' for fully threaded // discussions. "discussion_type": "side_comment", // The unique identifier of the group category if the topic is a group // discussion, otherwise null. "group_category_id": null, // Array of file attachments. "attachments": null, // The current user's permissions on this topic. "permissions": {"attach":true}, // Whether or not users can rate entries in this topic. "allow_rating": true, // Whether or not grade permissions are required to rate entries. "only_graders_can_rate": true, // Whether or not entries should be sorted by rating. "sort_by_rating": true } */ record.setValue("id", o["id"].toString("")); record.setValue("course_id", course_id); record.setValue("title", o["title"].toString("")); record.setValue("message", o["message"].toString("")); record.setValue("html_url", o["html_url"].toString("")); record.setValue("posted_at", o["posted_at"].toString("")); record.setValue("last_reply_at", o["last_reply_at"].toString("")); record.setValue("require_initial_post", o["require_initial_post"].toString("")); record.setValue("user_can_see_posts", o["user_can_see_posts"].toBool(true)); record.setValue("discussion_subentry_count", o["discussion_subentry_county"].toString("0")); record.setValue("read_state", o["read_state"].toString("unread")); record.setValue("unread_count", o["unread_count"].toString("")); record.setValue("subscribed", o["subscribed"].toBool(true)); record.setValue("subscription_hold", o["subscription_hold"].toString("not_in_group_set")); record.setValue("assignment_id", o["assignment_id"].toString("")); record.setValue("delayed_post_at", o["delayed_post_at"].toString("")); record.setValue("published", o["published"].toBool(true)); record.setValue("lock_at", o["lock_at"].toString("")); record.setValue("locked", o["locked"].toBool(false)); record.setValue("pinned", o["pinned"].toBool(false)); record.setValue("locked_for_user", o["locked_for_user"].toBool(false)); record.setValue("lock_info", o["lock_info"].toString("")); record.setValue("lock_explanation", o["lock_explanation"].toString("")); record.setValue("user_name", o["user_name"].toString("")); record.setValue("topic_children", QJsonDocument(o["topic_children"].toObject()).toJson()); record.setValue("group_topic_children", QJsonDocument(o["group_topic_children"].toObject()).toJson()); record.setValue("root_topic_id", o["root_topic_id"].toString("")); record.setValue("podcast_url", o["podcast_url"].toString("")); record.setValue("discussion_type", o["discussion_type"].toString("side_comment")); record.setValue("group_category_id", o["group_category_id"].toString("")); record.setValue("attachments", o["attachments"].toString("")); record.setValue("permissions", QJsonDocument(o["permissions"].toObject()).toJson()); record.setValue("allow_rating", o["allow_rating"].toBool(true)); record.setValue("only_graders_can_rate", o["only_graders_can_rate"].toBool(true)); record.setValue("sort_by_rating", o["sort_by_rating"].toBool(true)); record.setValue("is_active", "true"); if (is_insert) { model->insertRecord(-1, record); } else { // Filter should be set so 0 should be current record model->setRecord(0, record); } // Write changes if(!model->submitAll()) { ret = "Error saving discussion topic! "; qDebug() << "ERROR - problem saving discussion topic " << id << model->lastError(); } model->setFilter(""); // clear the filter //qDebug() << "Module " << o["name"].toString(""); model->database().commit(); //qDebug() << model->lastError(); } } } return ret; } QString EX_Canvas::pullQuizzes() { // Grab discussion topics for each course in the database QString ret = ""; if (_app_db == nullptr) { return ret; } // Get the list of courses for this student GenericTableModel *courses_model = _app_db->getTable("courses"); GenericTableModel *model = _app_db->getTable("quizzes"); if (courses_model == nullptr || model == nullptr) { QString err = "ERROR - Unable to get models for courses or quizzes!"; qDebug() << err; return err; } // All enteries should be for this student, so get them all courses_model->setFilter(""); courses_model->select(); // NOTE - Make sure to fetch all or we may only get 256 records while(courses_model->canFetchMore()) { courses_model->fetchMore(); } ret = true; int rowCount = courses_model->rowCount(); for (int i=0; i<rowCount; i++) { // Get quizzes for this course QSqlRecord course_record = courses_model->record(i); QString course_id = course_record.value("id").toString(); //qDebug() << "Retrieving quizzes for " << course_id; QHash<QString,QString> p; p["per_page"] = "10000"; // Cuts down number of calls significantly QJsonDocument doc = CanvasAPICall("/api/v1/courses/" + course_id + "/quizzes", "GET", &p); if (doc.isArray()) { qDebug() << "\tQuizzes for course: " << course_id; // Should be an array of discussion topics QJsonArray arr = doc.array(); foreach(QJsonValue val, arr) { //qDebug() << "got item..."; // This should be a quiz QJsonObject o = val.toObject(); QString id = o["id"].toString(""); //qDebug() << "Quiz ID " << id; model->setFilter("id = " + id); model->select(); // NOTE - Make sure to fetch all or we may only get 256 records while(model->canFetchMore()) { model->fetchMore(); } QSqlRecord record; bool is_insert = false; if (model->rowCount() == 1) { // Row exists, update with current info record = model->record(0); is_insert = false; qDebug() << "\t\tUpdating quiz..." << id << o["title"].toString(""); } else { // Need to clear the filter to insert model->setFilter(""); record = model->record(); is_insert = true; qDebug() << "\t\tImporting quiz..." << id << o["title"].toString(""); } ret += "\n\tProcessing Quiz: " + QString(id) + " - " + o["title"].toString(""); // JSON - list of objects /* // A quiz { // the ID of the quiz "id": 5, // the title of the quiz "title": "Hamlet Act 3 Quiz", // the HTTP/HTTPS URL to the quiz "html_url": "http://canvas.example.edu/courses/1/quizzes/2", // a url suitable for loading the quiz in a mobile webview. it will persiste // the headless session and, for quizzes in public courses, will force the user // to login "mobile_url": "http://canvas.example.edu/courses/1/quizzes/2?persist_healdess=1&force_user=1", // A url that can be visited in the browser with a POST request to preview a // quiz as the teacher. Only present when the user may grade "preview_url": "http://canvas.example.edu/courses/1/quizzes/2/take?preview=1", // the description of the quiz "description": "This is a quiz on Act 3 of Hamlet", // type of quiz possible values: 'practice_quiz', 'assignment', 'graded_survey', // 'survey' "quiz_type": "assignment", // the ID of the quiz's assignment group: "assignment_group_id": 3, // quiz time limit in minutes "time_limit": 5, // shuffle answers for students? "shuffle_answers": false, // let students see their quiz responses? possible values: null, 'always', // 'until_after_last_attempt' "hide_results": "always", // show which answers were correct when results are shown? only valid if // hide_results=null "show_correct_answers": true, // restrict the show_correct_answers option above to apply only to the last // submitted attempt of a quiz that allows multiple attempts. only valid if // show_correct_answers=true and allowed_attempts > 1 "show_correct_answers_last_attempt": true, // when should the correct answers be visible by students? only valid if // show_correct_answers=true "show_correct_answers_at": "2013-01-23T23:59:00-07:00", // prevent the students from seeing correct answers after the specified date has // passed. only valid if show_correct_answers=true "hide_correct_answers_at": "2013-01-23T23:59:00-07:00", // prevent the students from seeing their results more than once (right after // they submit the quiz) "one_time_results": true, // which quiz score to keep (only if allowed_attempts != 1) possible values: // 'keep_highest', 'keep_latest' "scoring_policy": "keep_highest", // how many times a student can take the quiz -1 = unlimited attempts "allowed_attempts": 3, // show one question at a time? "one_question_at_a_time": false, // the number of questions in the quiz "question_count": 12, // The total point value given to the quiz "points_possible": 20, // lock questions after answering? only valid if one_question_at_a_time=true "cant_go_back": false, // access code to restrict quiz access "access_code": "2beornot2be", // IP address or range that quiz access is limited to "ip_filter": "123.123.123.123", // when the quiz is due "due_at": "2013-01-23T23:59:00-07:00", // when to lock the quiz "lock_at": null, // when to unlock the quiz "unlock_at": "2013-01-21T23:59:00-07:00", // whether the quiz has a published or unpublished draft state. "published": true, // Whether the assignment's 'published' state can be changed to false. Will be // false if there are student submissions for the quiz. "unpublishable": true, // Whether or not this is locked for the user. "locked_for_user": false, // (Optional) Information for the user about the lock. Present when // locked_for_user is true. "lock_info": null, // (Optional) An explanation of why this is locked for the user. Present when // locked_for_user is true. "lock_explanation": "This quiz is locked until September 1 at 12:00am", // Link to Speed Grader for this quiz. Will not be present if quiz is // unpublished "speedgrader_url": "http://canvas.instructure.com/courses/1/speed_grader?assignment_id=1", // Link to endpoint to send extensions for this quiz. "quiz_extensions_url": "http://canvas.instructure.com/courses/1/quizzes/2/quiz_extensions", // Permissions the user has for the quiz "permissions": null, // list of due dates for the quiz "all_dates": null, // Current version number of the quiz "version_number": 3, // List of question types in the quiz "question_types": ["multiple_choice", "essay"], // Whether survey submissions will be kept anonymous (only applicable to // 'graded_survey', 'survey' quiz types) "anonymous_submissions": false } */ record.setValue("id", o["id"].toString("")); record.setValue("course_id", course_id); record.setValue("title", o["title"].toString("")); record.setValue("html_url", o["html_url"].toString("")); record.setValue("mobile_url", o["mobile_url"].toString("")); record.setValue("preview_url", o["preview_url"].toString("")); record.setValue("description", o["description"].toString("")); record.setValue("quiz_type", o["quiz_type"].toString("")); record.setValue("assignment_group_id", o["assignment_group_id"].toString("")); record.setValue("time_limit", o["time_limit"].toString("")); record.setValue("shuffle_answers", o["shuffle_answers"].toBool(false)); record.setValue("hide_results", o["hide_results"].toString("")); // always, null, until_after_last_attempt record.setValue("show_correct_answers", o["show_correct_answers"].toBool(true)); record.setValue("show_correct_answers_last_attempt", o["show_correct_answers_last_attempt"].toBool(true)); record.setValue("show_correct_answers_at", o["show_correct_answers_at"].toString("")); record.setValue("hide_correct_answers_at", o["hide_correct_answers_at"].toString("")); record.setValue("one_time_results", o["one_time_results"].toBool(true)); record.setValue("scoring_policy", o["scoring_policy"].toString("")); record.setValue("allowed_attempts", o["allowed_attempts"].toString("")); record.setValue("one_question_at_a_time", o["one_question_at_a_time"].toBool(false)); record.setValue("question_count", o["question_count"].toString("")); record.setValue("points_possible", o["points_possible"].toString("")); record.setValue("cant_go_back", o["cant_go_back"].toBool(false)); record.setValue("has_access_code", o["has_access_code"].toBool(false)); // NOTE - access code not coming down? QString access_code = o["access_code"].toString(""); if (access_code != "") { // Hash the code so students can't see it QCryptographicHash hash(QCryptographicHash::Sha256); hash.addData(access_code.toLocal8Bit()); access_code = hash.result().toHex(); } record.setValue("access_code", access_code); // Need to hash? record.setValue("ip_filter", o["ip_filter"].toString("")); record.setValue("due_at", o["due_at"].toString("")); record.setValue("lock_at", o["lock_at"].toString("")); record.setValue("unlock_at", o["unlock_at"].toString("")); record.setValue("published", o["published"].toBool(true)); record.setValue("unpublishable", o["unpublishable"].toBool(true)); record.setValue("locked_for_user", o["locked_for_user"].toBool(false)); record.setValue("lock_info", o["lock_info"].toString("")); record.setValue("lock_explanation", o["lock_explanation"].toString("")); record.setValue("speedgrader_url", o["speedgrader_url"].toString("")); record.setValue("quiz_extensions_url", o["quiz_extensions_url"].toString("")); record.setValue("permissions", QJsonDocument(o["permissions"].toObject()).toJson()); record.setValue("all_dates", QJsonDocument(o["all_dates"].toObject()).toJson()); record.setValue("version_number", o["version_number"].toString("")); record.setValue("question_types", QJsonDocument(o["question_types"].toObject()).toJson()); record.setValue("anonymous_submissions", o["anonymous_submissions"].toBool(false)); record.setValue("is_active", "true"); if (is_insert) { model->insertRecord(-1, record); } else { // Filter should be set so 0 should be current record model->setRecord(0, record); } // Write changes if(!model->submitAll()) { ret += "\n\t\tError saving quiz! " + QString(id) + " - " + o["title"].toString(""); qDebug() << "ERROR - problem saving quiz " << id << model->lastError(); } model->setFilter(""); // clear the filter //qDebug() << "Quiz " << o["name"].toString(""); model->database().commit(); //qDebug() << model->lastError(); } } } ret += "\nDone pulling quizzes"; return ret; } QString EX_Canvas::pullQuizQuestions() { // NOTE - This has to bounce through SMC since canvas doesn't give up // quizzes and answers through the API // Grab questions for each course in the database QString ret = ""; if (_app_db == nullptr) { return ret; } // Get the list of quizzes for this student GenericTableModel *quizzes_model = _app_db->getTable("quizzes"); GenericTableModel *model = _app_db->getTable("quiz_questions"); if (quizzes_model == nullptr || model == nullptr) { QString err = "ERROR - Unable to get models for quizzes or quiz_questions!"; qDebug() << err; return err; } // All enteries should be for this student, so get them all quizzes_model->setFilter(""); quizzes_model->select(); // NOTE - Make sure to fetch all or we may only get 256 records while(quizzes_model->canFetchMore()) { quizzes_model->fetchMore(); } // Get the student username/userid QString student_user = _app_settings->value("student/user_name", "").toString(); QString smc_url = _app_settings->value("student/smc_url", "https://smc.ed").toString(); if (!smc_url.endsWith("/")){ smc_url += "/"; } ret = true; int rowCount = quizzes_model->rowCount(); for (int i=0; i<rowCount; i++) { // Get quiz questions for this quiz QSqlRecord quiz_record = quizzes_model->record(i); QString quiz_id = quiz_record.value("id").toString(); QString course_id = quiz_record.value("course_id").toString(); //qDebug() << "Retrieving quiz questions for " << quiz_id; QHash<QString,QString> p; p["per_page"] = "10000"; // Cuts down number of calls significantly //QJsonDocument doc = CanvasAPICall("/api/v1/courses/" + course_id + "/quizzes/" + quiz_id + "/questions", "GET", &p); //QJsonDocument doc = SMCAPICall("/lms/get_quiz_questions/" + student_user + "/" + course_id + "/" + quiz_id + "/<auth_key>", "GET", &p); QString api_url = smc_url + "lms/get_quiz_questions_for_student/" + student_user + "/" + course_id + "/" + quiz_id + "/" + canvas_access_token; QHash<QString,QString> headers; headers["Authorization"] = "Bearer " + canvas_access_token; headers["User-Agent"] = "OPE LMS"; headers["Accept-Language"] = "en-US,en;q=0.8"; QString json = NetworkCall(api_url, "GET", &p, &headers); // Convert big id numbers to strings so they parse correctly // NOTE: qjsondocument converts ints to doubles and ends up loosing presision // find occurences of integer values in json documents and add quotes // ("\s*:\s*)(\d+\.?\d*)([^"])|([\[])(\d+\.?\d*)|([,])(\d+\.?\d*) // Was picking up digits in the body like $10,000. //QRegularExpression regex("(\"\\s*:\\s*)(\\d+\\.?\\d*)([^\"])|([\\[])(\\d+\\.?\\d*)|([,])(\\d+\\.?\\d*)"); // ":\\s*(\\d+)\\s*,"); //json = json.replace(regex, "\\1\\4\\6\"\\2\\5\\7\"\\3"); // :\"\\1\","); //qDebug() << "===================================\nParsing http data: " << json; QRegularExpression regex("(\\\"\\s*:\\s*)([0-9.]+)(\\s*[,])"); // ":\\s*(\\d+)\\s*,"); json = json.replace(regex, "\\1\"\\2\"\\3"); // :\"\\1\","); // Convert response to json QJsonParseError *err = new QJsonParseError(); QJsonDocument doc(QJsonDocument::fromJson(json.toUtf8(), err)); if (err->error != QJsonParseError::NoError) { qDebug() << "\tJSON Parse Err: " << err->errorString() << err->offset; qDebug() << "\tJSON Response: " << json; qDebug() << "\tJSON Doc: " << doc; qDebug() << "\tIs Array: " << doc.isArray(); qDebug() << "\tIs Object: " << doc.isObject(); qDebug() << "\tIs nullptr: " << doc.isNull(); } delete err; if (doc.isArray()) { qDebug() << "\tQuiz Question for Quiz: " << quiz_id; // Should be an array of quiz questions QJsonArray arr = doc.array(); foreach(QJsonValue val, arr) { //qDebug() << "got item..."; // This should be a quiz question QJsonObject o = val.toObject(); QString id = o["id"].toString(""); //qDebug() << "Quiz question ID " << id; model->setFilter("id = " + id); model->select(); // NOTE - Make sure to fetch all or we may only get 256 records while(model->canFetchMore()) { model->fetchMore(); } QSqlRecord record; bool is_insert = false; if (model->rowCount() == 1) { // Row exists, update with current info record = model->record(0); is_insert = false; qDebug() << "\t\tUpdating quiz question..." << id; } else { // Need to clear the filter to insert model->setFilter(""); record = model->record(); is_insert = true; qDebug() << "\t\tImporting quiz..." << id; } ret += "\n\tProcessing Question: " + QString(id); // JSON - list of objects /* NOTE - This comes through the SMC which grabs questions and wrapps them up. */ record.setValue("id", o["id"].toString("")); record.setValue("course_id", course_id); record.setValue("quiz_id", o["quiz_id"].toString("")); record.setValue("quiz_group_id", o["quiz_group_id"].toString("")); record.setValue("assessment_question_id", o["assessment_question_id"].toString("")); record.setValue("position", o["position"].toString("")); record.setValue("question_type", o["question_type"].toString("")); record.setValue("payload_token", o["payload_token"].toString("")); // NOTE - To decrypt payload: // sha256 hash: auth_token + course_id + quiz_id + question id + payload_token - use resulting sha256 hash as key record.setValue("question_payload", o["question_payload"].toString("")); record.setValue("is_active", "true"); if (is_insert) { model->insertRecord(-1, record); } else { // Filter should be set so 0 should be current record model->setRecord(0, record); } // Write changes if(!model->submitAll()) { ret += "\n\t\tError saving quiz! " + QString(id); qDebug() << "ERROR - problem saving quiz " << id << model->lastError(); } model->setFilter(""); // clear the filter //qDebug() << "Quiz " << o["name"].toString(""); model->database().commit(); //qDebug() << model->lastError(); } } else { QString tmp_msg = "ERROR - Unable to pull quiz questions through SMC\n\t- make sure SMC version is >= 1.9.56 and that canvas integration is properly enabled."; ret += "\n" + tmp_msg; qDebug() << tmp_msg; } } ret += "\nDone pulling quiz questions."; return ret; } bool EX_Canvas::pullModules() { // Grab modules for each course in the database bool ret = false; if (_app_db == nullptr) { return ret; } // Get the list of courses for this student GenericTableModel *courses_model = _app_db->getTable("courses"); GenericTableModel *model = _app_db->getTable("modules"); if (courses_model == nullptr || model == nullptr) { qDebug() << "Unable to get models for courses or modules!"; return false; } // All enteries should be for this student, so get them all courses_model->setFilter(""); courses_model->select(); // NOTE - Make sure to fetch all or we may only get 256 records while(courses_model->canFetchMore()) { courses_model->fetchMore(); } ret = true; int rowCount = courses_model->rowCount(); for (int i=0; i<rowCount; i++) { // Get modules for this course QSqlRecord course_record = courses_model->record(i); QString course_id = course_record.value("id").toString(); //qDebug() << "Retrieving modules for " << course_id; QHash<QString,QString> p; p["per_page"] = "10000"; // Cuts down number of calls significantly QJsonDocument doc = CanvasAPICall("/api/v1/courses/" + course_id + "/modules", "GET", &p); if (doc.isArray()) { qDebug() << "\tModules for course:"; // Should be an array of modules QJsonArray arr = doc.array(); foreach(QJsonValue val, arr) { //qDebug() << "got item..."; // This should be a module QJsonObject o = val.toObject(); QString id = o["id"].toString(""); //qDebug() << "Module ID " << id; model->setFilter("id = " + id); model->select(); // NOTE - Make sure to fetch all or we may only get 256 records while(model->canFetchMore()) { model->fetchMore(); } QSqlRecord record; bool is_insert = false; if (model->rowCount() == 1) { // Row exists, update with current info record = model->record(0); is_insert = false; qDebug() << "\t\tUpdating module..." << id << o["name"].toString(""); } else { // Need to clear the filter to insert model->setFilter(""); record = model->record(); is_insert = true; qDebug() << "\t\tImporting module..." << id << o["name"].toString(""); } // JSON - list of objects // {"id":26664700000000088,"name":"Module 1","position":1,"unlock_at":nullptr, // "require_sequential_progress":false,"publish_final_grade":false, // "prerequisite_module_ids":[],"published":false,"items_count":0, // "items_url":"https://canvas.ed.dev/api/v1/courses/26664700000000082/modules/26664700000000088/items"} record.setValue("id", o["id"].toString("")); record.setValue("name", o["name"].toString("")); record.setValue("position", o["position"].toString("")); record.setValue("unlock_at", o["unlock_at"].toString("")); record.setValue("require_sequential_progress", o["require_sequential_progress"].toBool(false)); record.setValue("publish_final_grade", o["publish_final_grade"].toBool(false)); record.setValue("prerequisite_module_ids", QJsonDocument(o["prerequisite_module_ids"].toArray()).toJson()); record.setValue("published", o["published"].toBool(false)); record.setValue("items_count", o["items_count"].toString("")); record.setValue("items_url", o["items_url"].toString("")); record.setValue("course_id", course_id); record.setValue("is_active", "true"); if (is_insert) { model->insertRecord(-1, record); } else { // Filter should be set so 0 should be current record model->setRecord(0, record); } // Write changes if(!model->submitAll()) { ret = false; } model->setFilter(""); // clear the filter //qDebug() << "Module " << o["name"].toString(""); model->database().commit(); //qDebug() << model->lastError(); } } } return ret; } bool EX_Canvas::pullModuleItems() { // Grab module items for each module in the database bool ret = false; if (_app_db == nullptr) { return ret; } // Get the list of modules for this student GenericTableModel *modules_model = _app_db->getTable("modules"); GenericTableModel *model = _app_db->getTable("module_items"); if (modules_model == nullptr || model == nullptr) { qDebug() << "Unable to get models for modules or module_items!"; return false; } // Get module items for each module modules_model->setFilter(""); modules_model->select(); // NOTE - Make sure to fetch all or we may only get 256 records while(modules_model->canFetchMore()) { modules_model->fetchMore(); } ret = true; int rowCount = modules_model->rowCount(); for (int i=0; i<rowCount; i++) { // Get module_items for this module QSqlRecord module_record = modules_model->record(i); QString module_id = module_record.value("id").toString(); QString course_id = module_record.value("course_id").toString(); //qDebug() << "Retrieving module_items for " << module_id; QHash<QString,QString> p; p["per_page"] = "10000"; // Cuts down number of calls significantly QJsonDocument doc = CanvasAPICall("/api/v1/courses/" + course_id + "/modules/" + module_id + "/items", "GET", &p ); if (doc.isArray()) { //qDebug() << "\t\t\tModule items for module:"; // Should be an array of module items QJsonArray arr = doc.array(); foreach(QJsonValue val, arr) { //qDebug() << "got item..."; // This should be a module QJsonObject o = val.toObject(); QString id = o["id"].toString(""); //qDebug() << "Module item ID " << id; model->setFilter("id = " + id); model->select(); // NOTE - Make sure to fetch all or we may only get 256 records while(model->canFetchMore()) { model->fetchMore(); } QSqlRecord record; bool is_insert = false; if (model->rowCount() == 1) { // Row exists, update with current info record = model->record(0); is_insert = false; qDebug() << "\t\t\tUpdating module item..." << id << o["title"].toString(""); } else { // Need to clear the filter to insert model->setFilter(""); record = model->record(); is_insert = true; qDebug() << "\t\t\tImporting module item..." << id << o["title"].toString(""); } // JSON - list of objects // {"id":26664700000000088,"title":"Test Page","position":1, // "indent":0,"type":"Page","module_id":26664700000000088, // "html_url":"https://canvas.ed.dev/courses/26664700000000082/modules/items/26664700000000088", // "page_url":"test-page","url":"https://canvas.ed.dev/api/v1/courses/26664700000000082/pages/test-page", // "published":false} record.setValue("id", o["id"].toString("")); record.setValue("title", o["title"].toString("")); record.setValue("position", o["position"].toString("")); record.setValue("indent", o["indent"].toString("")); record.setValue("type", o["type"].toString("")); record.setValue("module_id", o["module_id"].toString("")); record.setValue("html_url", o["html_url"].toString("")); record.setValue("page_url", o["page_url"].toString("")); record.setValue("url", o["url"].toString("")); record.setValue("published", o["published"].toBool(false)); record.setValue("content_id", o["content_id"].toString("")); record.setValue("external_url", o["external_url"].toString("")); record.setValue("new_tab", o["new_tab"].toBool(false)); // TODO - this is an array record.setValue("completion_requirement", o["completion_requirement"].toString("")); // TOOD - also an array record.setValue("content_details", o["content_details"].toString("")); record.setValue("is_active", "true"); // If this is a page item, make sure it is in the page table too if (o["type"].toString("") == "Page") { QString page_url = o["page_url"].toString(""); QSqlRecord page_record = pullSinglePage(course_id, page_url); if (page_record.isEmpty()) { ret = false; } else { // Set the content id to the page id record.setValue("content_id", page_record.value("page_id").toString()); } } else if (o["type"].toString("") == "File") { // This is a File, make sure it is queued so that it will download // even if the "Files" menu isn't QueueCanvasLinkForDownload(o["content_id"].toString(""), course_id, "", o["url"].toString("")); } if (is_insert) { model->insertRecord(-1, record); } else { // Filter should be set so 0 should be current record model->setRecord(0, record); } // Write changes if (!model->submitAll()) { ret = false; } model->setFilter(""); // clear the filter //qDebug() << "Module item " << o["title"].toString(""); model->database().commit(); //qDebug() << model->lastError(); } } } return ret; } bool EX_Canvas::pullCourseFileFolders() { // Grab a list of files for each course (Non Binaries) bool ret = false; if (_app_db == nullptr) { return ret; } // Get the list of courses for this student GenericTableModel *courses_model = _app_db->getTable("courses"); GenericTableModel *model = _app_db->getTable("folders"); if (courses_model == nullptr || model == nullptr) { qDebug() << "Unable to get models for courses or folders!"; return false; } // Pull all folder info for all courses courses_model->setFilter(""); courses_model->select(); // NOTE - Make sure to fetch all or we may only get 256 records while(courses_model->canFetchMore()) { courses_model->fetchMore(); } ret = true; int rowCount = courses_model->rowCount(); for (int i=0; i<rowCount; i++) { // Get folders for this course QSqlRecord course_record = courses_model->record(i); QString course_id = course_record.value("id").toString(); //qDebug() << "Retrieving folder info for " << course_id; QHash<QString,QString> p; p["per_page"] = "10000"; // Cuts down number of calls significantly QJsonDocument doc = CanvasAPICall("/api/v1/courses/" + course_id + "/folders", "GET", &p); if (doc.isArray()) { //qDebug() << "\tFolder info for course:"; // Should be an array of folders QJsonArray arr = doc.array(); foreach(QJsonValue val, arr) { //qDebug() << "got item..."; // This should be a module QJsonObject o = val.toObject(); QString id = o["id"].toString(""); //qDebug() << "File ID " << id; model->setFilter("id = " + id); model->select(); // NOTE - Make sure to fetch all or we may only get 256 records while(model->canFetchMore()) { model->fetchMore(); } QSqlRecord record; bool is_insert = false; if (model->rowCount() == 1) { // Row exists, update with current info record = model->record(0); is_insert = false; qDebug() << "\t\tUpdating folder info..." << id << o["full_name"].toString(""); } else { // Need to clear the filter to insert model->setFilter(""); record = model->record(); is_insert = true; qDebug() << "\t\tImporting folder info..." << id << o["full_name"].toString(""); } // JSON - list of objects // {"id":999999000000068,"name":"course files", // "full_name":"course files","context_id":999999000000068, // "context_type":"Course","parent_folder_id":nullptr, // "created_at":"2018-02-22T21:48:37Z", // "updated_at":"2018-02-22T21:48:37Z","lock_at":nullptr, // "unlock_at":nullptr,"position":nullptr,"locked":false, // "folders_url":"https://canvas.ed/api/v1/folders/999999000000068/folders", // "files_url":"https://canvas.ed/api/v1/folders/999999000000068/files", // "files_count":0,"folders_count":4,"hidden":nullptr, // "locked_for_user":false,"hidden_for_user":false, // "for_submissions":false} record.setValue("id", o["id"].toString("")); record.setValue("name", o["name"].toString("")); record.setValue("full_name", o["full_name"].toString("")); record.setValue("context_id", o["context_id"].toString("")); record.setValue("context_type", o["context_type"].toString("")); record.setValue("parent_folder_id", o["parent_folder_id"].toString("")); record.setValue("created_at", o["created_at"].toString("")); record.setValue("updated_at", o["updated_at"].toString("")); record.setValue("lock_at", o["lock_at"].toString("")); record.setValue("unlock_at", o["unlock_at"].toString("")); record.setValue("position", o["position"].toString("")); record.setValue("locked", o["locked"].toBool(false)); record.setValue("folders_url", o["folders_url"].toString("")); record.setValue("files_url", o["files_url"].toString("")); record.setValue("files_count", o["files_count"].toString("0")); record.setValue("folders_count", o["folders_count"].toString("0")); record.setValue("hidden", o["hidden"].toBool(false)); record.setValue("locked_for_user", o["locked_for_user"].toBool(false)); record.setValue("hidden_for_user", o["hidden_for_user"].toBool(false)); record.setValue("for_submissions", o["for_submissions"].toBool(false)); record.setValue("is_active", "true"); if (is_insert) { model->insertRecord(-1, record); } else { // Filter should be set so 0 should be current record model->setRecord(0, record); } // Write changes if (!model->submitAll()) { ret = false; } model->setFilter(""); // clear the filter //qDebug() << "File info " << o["display_name"].toString(""); model->database().commit(); //qDebug() << model->lastError(); } } } return ret; } bool EX_Canvas::pullCourseFilesInfo() { // Grab a list of files for each course (Non Binaries) bool ret = false; if (_app_db == nullptr) { return ret; } QSqlQuery q; // Clear out any empty file entries (no id or name?) q.prepare("DELETE FROM files WHERE id='' or filename=''"); if (!q.exec()) { qDebug() << "ERROR RUNNING DB QUERY: " << q.lastQuery() << " - " << q.lastError().text(); return false; } else { _app_db->commit(); } // Go through file dl queue - these are links found in content like pages and may not be // in the current list q.clear(); q.prepare("SELECT * FROM canvas_dl_queue"); if (!q.exec()) { qDebug() << "ERROR RUNNING DB QUERY: " << q.lastQuery() << " - " << q.lastError().text(); return false; } while (q.next()) { QString f_id = q.value(1).toString(); QString course_id = q.value(2).toString(); QString original_host = q.value(3).toString(); QString original_url = q.value(4).toString(); // This will add the file info to the files list so it can be pulled later pullSingleCourseFileInfo(f_id, course_id); } // Get the list of courses for this student GenericTableModel *courses_model = _app_db->getTable("courses"); if (courses_model == nullptr) { qCritical() << "Unable to get models for courses !"; return false; } // Mark all files as local_copy_present=4 // Do this so we can see what is left over when we are done and clear them q.prepare("UPDATE files SET local_copy_present='4'"); if (!q.exec()) { qDebug() << "ERROR RUNNING DB QUERY: " << q.lastQuery() << " - " << q.lastError().text(); return false; } // Pull all file info for all courses courses_model->setFilter(""); courses_model->select(); // NOTE - Make sure to fetch all or we may only get 256 records while(courses_model->canFetchMore()) { courses_model->fetchMore(); } ret = true; int rowCount = courses_model->rowCount(); for (int i=0; i<rowCount; i++) { // Get modules for this course QSqlRecord course_record = courses_model->record(i); QString course_id = course_record.value("id").toString(); //qDebug() << "Retrieving file info for " << course_id; QHash<QString,QString> p; p["per_page"] = "10000"; // Cuts down number of calls significantly QJsonDocument doc = CanvasAPICall("/api/v1/courses/" + course_id + "/files", "GET", &p); if (doc.isArray()) { //qDebug() << "\tFile info for course:"; // Should be an array of modules QJsonArray arr = doc.array(); foreach(QJsonValue val, arr) { //qDebug() << "got item..."; // This should be a module QJsonObject o = val.toObject(); QString id = o["id"].toString(""); //qDebug() << "File ID " << id; // Pull the file info from canvas if (!pullSingleCourseFileInfo(id, course_id)) { // If we fail, mark as false ret = false; } } } } // Clean up inactive canvas items // NOTE - this is the last step before downloading binaries clearInactiveItems(); return ret; } bool EX_Canvas::pullSingleCourseFileInfo(QString file_id, QString course_id) { // Grab the file info for this specific file bool ret = false; if (_app_db == nullptr) { return ret; } GenericTableModel *files_model = _app_db->getTable("files"); if (files_model == nullptr) { qCritical() << "Unable to get model for files!"; return false; } QHash<QString,QString> params; params["per_page"] = "10000"; // Cut down number of api calls significantly QJsonDocument doc = CanvasAPICall("/api/v1/files/" + file_id, "GET", &params); if (doc.isObject()) { // Get file object QJsonObject o = doc.object(); //qDebug() << "Got File Item " << o; QString f_id = o["id"].toString(""); if (f_id == "") { qDebug() << "pullSingleCourseFileInfo - INVALID FILE ID " << file_id << "/" << course_id << " " << o; return false; } // See if this file entry exists in the database files_model->setFilter("id=" + file_id); files_model->select(); // NOTE - Make sure to fetch all or we may only get 256 records while(files_model->canFetchMore()) { files_model->fetchMore(); } QSqlRecord record; bool is_insert = false; if (files_model->rowCount() >=1) { // Row exists - update it record = files_model->record(0); is_insert = false; qDebug() << "\t\tUpdating file info " << file_id << o["display_name"].toString(""); } else { // Inserting new record - need to clear filter files_model->setFilter(""); record = files_model->record(); is_insert = true; qDebug() << "\t\tImporting new file info " << file_id << o["display_name"].toString(""); // Set some defaults record.setValue("pull_file", ""); record.setValue("local_copy_present", "0"); } // JSON - list of objects // {"id":26664700000000097,"folder_id":26664700000000099, // "display_name":"101 uses of the quadratic equation.pdf", // "filename":"101_uses_of_the_quadratic_equation.pdf", // "content-type":"application/pdf", // "url":"https://canvas.ed.dev/files/26664700000000097/download?download_frd=1", // "size":451941,"created_at":"2017-06-21T21:44:11Z", // "updated_at":"2017-06-21T21:44:11Z","unlock_at":nullptr,"locked":false, // "hidden":false,"lock_at":nullptr,"hidden_for_user":false, // "thumbnail_url":nullptr,"modified_at":"2017-06-21T21:44:11Z", // "mime_class":"pdf","media_entry_id":nullptr,"locked_for_user":false} record.setValue("id", file_id); record.setValue("folder_id", o["folder_id"].toString("")); record.setValue("display_name", o["display_name"].toString("")); record.setValue("filename", o["filename"].toString("")); record.setValue("content_type", o["content-type"].toString("")); record.setValue("url", o["url"].toString("")); record.setValue("size", o["size"].toString("")); record.setValue("created_at", o["created_at"].toString("")); record.setValue("updated_at", o["updated_at"].toString("")); record.setValue("unlock_at", o["unlock_at"].toString("")); record.setValue("locked", o["locked"].toString("")); record.setValue("hidden", o["hidden"].toBool(false)); record.setValue("lock_at", o["lock_at"].toString("")); record.setValue("hidden_for_user", o["hidden_for_user"].toBool(false)); record.setValue("thumbnail_url", o["thumbnail_url"].toString("")); record.setValue("modified_at", o["modified_at"].toString("")); record.setValue("mime_class", o["mime_class"].toString("")); record.setValue("media_entry_id", o["media_entry_id"].toString("")); record.setValue("locked_for_user", o["locked_for_user"].toBool(false)); record.setValue("course_id", course_id); record.setValue("is_active", "true"); if (is_insert) { files_model->insertRecord(-1, record); } else { // Filter should be set so 0 should be current record files_model->setRecord(0, record); } // Write changes if (!files_model->submitAll()) { ret = false; qDebug() << "*** DB ERROR saving file info " << files_model->lastError().text(); } else { ret = true; } files_model->setFilter(""); files_model->database().commit(); } else { qDebug() << "JSON ERROR - got invalid json object " << doc; } return ret; } bool EX_Canvas::pullCourseFilesBinaries() { qDebug() << "----- PULLING CANVAS FILE BINARIES..."; // Pull binaries for files that are marked as pull bool ret = false; if (_app_db == nullptr) { return ret; } GenericTableModel *files_model = _app_db->getTable("files"); if (files_model == nullptr) { qDebug() << "Unable to get model for files"; return false; } //remove file entries if the course doesn't exist. QString sql = "delete from files where course_id not in (select id from courses)"; QSqlQuery q; q.prepare(sql); if (q.exec() != true) { qDebug() << "ERROR clearing orphaned file entries in database " << q.lastError(); _app_db->commit(); } files_model->setFilter(""); // pull_file=1 files_model->select(); // NOTE - Make sure to fetch all or we may only get 256 records while(files_model->canFetchMore()) { files_model->fetchMore(); } qDebug() << "--- Processing DL Files " << files_model->rowCount(); // Get the local cache folder QDir base_dir; base_dir.setPath(this->appDataFolder() + "/content/www_root/canvas_file_cache/"); base_dir.mkpath(base_dir.path()); ret = true; int rowCount = files_model->rowCount(); for (int i=0; i<rowCount; i++) { QSqlRecord f = files_model->record(i); QString f_id = f.value("id").toString(); QString f_filename = f.value("filename").toString(); QString f_name = f.value("display_name").toString(); QString content_type = f.value("content_type").toString(); QString f_url = f.value("url").toString(); int f_size = f.value("size").toInt(); QString f_ext = CM_MimeTypes::GetExtentionForMimeType(content_type); //QString local_path = "/" + f_id + f_ext; // f.value("pull_file").toString(); QString local_path = "/" + f_name; // f.value("pull_file").toString(); // NOTE - Don't rely on mime-type being correct. Pull extension from // the filename, and fall back to mime type if extension is empty. // FIX for application/x-msdownload - dll, exe and others are reported as // same mime-type in canvas //QFileInfo finfo(f_filename); //if (finfo.completeSuffix() != "") { // local_path = "/" + f_id + "." + finfo.completeSuffix(); //} // Get file type f.setValue("pull_file", "/canvas_file_cache" + local_path); //if (local_path == "") { // // Assign a new local path // //local_path = "/" + f_id + "_" + f_filename; // local_path = "/" + f_id; // f.setValue("pull_file", local_path); //} // See if the file already exists locally QFileInfo fi = QFileInfo(base_dir.path() + local_path); if (fi.exists() && fi.size() == f_size ) { qDebug() << "File exists " << local_path; //f_name; // Mark it as present f.setValue("local_copy_present", "1"); } else { // Download the file qDebug() << "Downloading file " << local_path; progressCurrentItem = f_filename; bool r = DownloadFile(f_url, base_dir.path() + local_path, "Canvas File: " + f_filename); if (!r) { qDebug() << "ERROR - canvas file download " << f_filename << " - " << f_url; } else { // Makre the file as present f.setValue("local_copy_present", "1"); // Make sure we save the content header /*QHash<QString, QString> headers = web_request->GetAllDownloadHeaders(); if (headers.contains("Content-Type")) { // Save a file w the mimetype QString mime_local_path = base_dir.path() + local_path + ".mime"; QString content_type = headers["Content-Type"]; QFile *mime_file = new QFile(mime_local_path); if (mime_file->open(QIODevice::WriteOnly)) { mime_file->write(content_type.toLocal8Bit()); mime_file->close(); } mime_file->deleteLater(); }*/ } } // Write changes files_model->setRecord(i, f); } files_model->submitAll(); files_model->database().commit(); // Clear out any file entries where local_copy_present is 4 //q.prepare("DELETE FROM files WHERE local_copy_present='4'"); //if (!q.exec()) { // qDebug() << "ERROR RUNNING DB QUERY: " << q.lastQuery() << " - " << q.lastError().text(); // return false; //} else { // _app_db->commit(); // } // Now go through the folder and remove any files that aren't in the file list anymore. QDir cache_dir(base_dir); qDebug() << "Removing orphaned files:"; foreach(QString f_name, cache_dir.entryList()) { if(f_name == "." || f_name == "..") { // Skip these continue; } // See if this file exists in the files database - NOTE - '' for escaped 's? files_model->setFilter("pull_file='/canvas_file_cache/" + f_name.replace("'", "''") + "'"); files_model->select(); if (files_model->rowCount() < 1) { // File isn't in the database, delete it QString local_path = base_dir.path() + "/" + f_name; qDebug() << "---- Orphaned File: " << local_path << " - deleting..."; try { QFile::remove(local_path); } catch (...) { qDebug() << "----- ERROR removing file: " << local_path; } } } // Clear old file cache folder QDir old_cache_path; old_cache_path.setPath(this->appDataFolder() + "/file_cache"); foreach(QString f_name, old_cache_path.entryList()) { if (f_name == "." || f_name == ".." || f_name == "assignment_files") { // Skip these continue; } QString local_path = old_cache_path.path() + "/" + f_name; qDebug() << "---- Orphaned File: " << local_path << " - deleting..."; try { QFile::remove(local_path); } catch (...) { qDebug() << "----- ERROR removing file: " << local_path; } } qDebug() << "----- DONE - PULLING CANVAS FILE BINARIES..."; return ret; } bool EX_Canvas::pullCoursePages() { // Grab a list of pages for each course qDebug() << "* Starting Pull Course Pages"; bool ret = false; if (_app_db == nullptr) { return ret; } // Get the list of courses for this student GenericTableModel *courses_model = _app_db->getTable("courses"); if (courses_model == nullptr) { qDebug() << "!!!Unable to get models for courses or pages!"; return false; } // Get the list of pages from canvas courses_model->setFilter(""); courses_model->select(); // NOTE - Make sure to fetch all or we may only get 256 records while(courses_model->canFetchMore()) { courses_model->fetchMore(); } ret = true; int rowCount = courses_model->rowCount(); for (int i=0; i<rowCount; i++) { // Get pages for this course QSqlRecord course_record = courses_model->record(i); QString course_id = course_record.value("id").toString(); QString course_name = course_record.value("name").toString(); qDebug() << "\tProcessing Course " << course_id << course_name; QHash<QString,QString> p; p["per_page"] = "10000"; // Cuts down number of calls significantly QJsonDocument doc = CanvasAPICall("/api/v1/courses/" + course_id + "/pages", "GET", &p); //qDebug() << "A"; if (doc.isArray()) { qDebug() << "\t\tCanvas Pages for course " << course_id << course_name; // Should be an array of pages QJsonArray arr = doc.array(); foreach(QJsonValue val, arr) { //qDebug() << "got item..."; // This should be a module QJsonObject o = val.toObject(); QString id = o["page_id"].toString(""); QString page_url = o["url"].toString(""); qDebug() << "\t\t\tFound Page - Pulling Info " << page_url << id; QSqlRecord page_record = pullSinglePage(course_id, page_url); if (page_record.isEmpty()) { // Error pulling this page? ret = false; } } } else { qDebug() << "\t\t!!! Unable to pull array of pages: " << doc; } } return ret; } bool EX_Canvas::pullMessages(QString scope) { // Pull the list of conversations, then pull each message in that conversation bool ret = false; if (_app_db == nullptr) { return ret; } if (_app_settings == nullptr) { qDebug() << "No app settings object set!"; return ret; } QString student_id = _app_settings->value("student/id", "").toString(); if (student_id == "") { qDebug() << "No student id set!!"; return ret; } // Get list of conversations, then pull the list of messages GenericTableModel *conversations_model = _app_db->getTable("conversations"); GenericTableModel *messages_model = _app_db->getTable("messages"); if (conversations_model == nullptr || messages_model == nullptr) { qDebug() << "Unable to get models for conversations or messages!"; return false; } QHash<QString,QString> p; p["per_page"] = "10000"; // Cuts down number of calls significantly p["scope"] = scope; QJsonDocument conversations_doc = CanvasAPICall("/api/v1/conversations", "GET", &p); p.remove("scope"); // Remove it so we don't end up using it later //qDebug() << "\t\tDOC " << conversations_doc; QSqlRecord record; ret = true; bool is_insert = false; // Should be an array of conversations if (conversations_doc.isArray()) { // Should have something like this: // [{"id":26664700000000089,"subject":"Next conversation", // "workflow_state":"read","last_message":"Hello", // "last_message_at":"2017-06-22T17:44:09Z", // "last_authored_message":"Is this getting through?", // "last_authored_message_at":"2017-06-22T05:24:11Z","message_count":2, // "subscribed":true,"private":false,"starred":false,"properties":[], // "audience":[1], // "audience_contexts":{"courses":{"26664700000000090":["TeacherEnrollment"]}, // "groups":{}},"avatar_url":"https://canvas.ed.dev/images/messages/avatar-50.png", // "participants":[{"id":26664700000000083,"name":"Smith, Bob (s777777)"}, // {"id":1,"name":"admin@ed"}], // "visible":true,"context_code":"course_26664700000000090", // "context_name":"TestMathCourse"}, // {"id":26664700000000088,"subject":"Email Diag","workflow_state":"read", // "last_message":"It works!!!","last_message_at":"2017-06-22T05:09:16Z", // "last_authored_message":"Diag Email.", // "last_authored_message_at":"2017-06-22T04:59:37Z", // "message_count":2,"subscribed":true,"private":false,"starred":false, // "properties":[],"audience":[1], // "audience_contexts":{"courses":{"26664700000000090":["TeacherEnrollment"]}, // "groups":{}},"avatar_url":"https://canvas.ed.dev/images/messages/avatar-50.png", // "participants":[{"id":26664700000000083,"name":"Smith, Bob (s777777)"}, // {"id":1,"name":"admin@ed"}],"visible":true, // "context_code":"course_26664700000000090","context_name":"TestMathCourse"}] // Just pull the ID, we will pull all the details after // the next call since we we get all that when we pull the message list foreach(QJsonValue val, conversations_doc.array()) { // Convert this conversation to an object QJsonObject o = val.toObject(); QString conversations_id = o["id"].toString(""); if (conversations_id == "") { qDebug() << "ERROR ERROR - Invalid conversation? " << val.toString(); continue; } // Make next API call to get list of messages QJsonDocument doc = CanvasAPICall("/api/v1/conversations/" + conversations_id, "GET", &p); // Should come back as an object if (doc.isObject()) { // Now pull info for the conversation and put it in the database o = doc.object(); // Does this conversation exist? conversations_model->setFilter("id = " + conversations_id); conversations_model->select(); // NOTE - Make sure to fetch all or we may only get 256 records while(conversations_model->canFetchMore()) { conversations_model->fetchMore(); } if (conversations_model->rowCount() >= 1) { // Exists is_insert = false; record = conversations_model->record(0); qDebug() << "\tUpdating conversation " << conversations_id; } else { // New record conversations_model->setFilter(""); record = conversations_model->record(); is_insert = true; qDebug() << "\tAdding conversation " << conversations_id; } // Set the values record.setValue("id", o["id"].toString("")); record.setValue("subject", o["subject"].toString("")); record.setValue("workflow_state", o["workflow_state"].toString("")); record.setValue("last_message", o["last_message"].toString("")); record.setValue("last_message_at", o["last_message_at"].toString("")); record.setValue("last_authored_message", o["last_authored_message"].toString("")); record.setValue("last_authored_message_at", o["last_authored_message_at"].toString("")); record.setValue("message_count", o["message_count"].toString("")); record.setValue("subscribed", o["subscribed"].toBool(false)); record.setValue("private", o["private"].toBool(false)); record.setValue("starred", o["starred"].toBool(false)); record.setValue("properties", QJsonDocument(o["properties"].toArray()).toJson()); record.setValue("audience", QJsonDocument(o["audience"].toArray()).toJson()); record.setValue("audience_contexts", QJsonDocument(o["audience_contexts"].toObject()).toJson()); record.setValue("avatar_url", o["avatar_url"].toString("")); record.setValue("participants", QJsonDocument(o["participants"].toArray()).toJson()); record.setValue("visible", o["visible"].toBool(false)); record.setValue("context_code", o["context_code"].toString("")); record.setValue("context_name", o["context_name"].toString("")); record.setValue("submissions", QJsonDocument(o["submissions"].toArray()).toJson()); record.setValue("is_active", "true"); if (is_insert) { conversations_model->insertRecord(-1, record); } else { // Filter should be set still so 0 should be current record conversations_model->setRecord(0, record); } // Write the changes if (!conversations_model->submitAll()) { ret = false; } conversations_model->setFilter(""); // clear the filter conversations_model->database().commit(); qDebug() << "Got conversation, going for messages: " << o["messages"]; // Now loop through messages and put them in the database QJsonArray messages = o["messages"].toArray(); foreach (QJsonValue m, messages) { // Store this message in the database QJsonObject mo = m.toObject(); QString m_id = mo["id"].toString(""); if (m_id == "") { qDebug() << "Invalid message id! " << m.toString(); continue; } messages_model->setFilter("id = " + m_id); messages_model->select(); // NOTE - Make sure to fetch all or we may only get 256 records while(messages_model->canFetchMore()) { messages_model->fetchMore(); } if (messages_model->rowCount() >= 1) { // Record exists is_insert = false; record = messages_model->record(0); qDebug() << "\t\tUpdating message " << m_id; } else { // New record is_insert = true; messages_model->setFilter(""); record = messages_model->record(); qDebug() << "\t\tInserting new message " << m_id; } // Set the values record.setValue("id", mo["id"].toString("")); record.setValue("author_id", mo["author_id"].toString("")); record.setValue("created_at", mo["created_at"].toString("")); record.setValue("generated", mo["generated"].toString("")); record.setValue("body", mo["body"].toString("")); record.setValue("forwarded_messages", QJsonDocument(mo["forwarded_messages"].toArray()).toJson()); record.setValue("attachments", QJsonDocument(mo["attachments"].toArray()).toJson()); record.setValue("media_comment", mo["media_comment"].toString("")); record.setValue("participating_user_ids", QJsonDocument(mo["participating_user_ids"].toArray()).toJson()); record.setValue("conversation_id", conversations_id); record.setValue("is_active", "true"); if (mo["author_id"].toString("") == student_id) { record.setValue("scope", "sent"); } else { record.setValue("scope", "inbox"); } if (is_insert) { messages_model->insertRecord(-1, record); } else { // Filter should be set so 0 is current record messages_model->setRecord(0, record); } // Write changes if (!messages_model->submitAll()) { ret = false; } messages_model->setFilter(""); //clear filter messages_model->database().commit(); if (ret == false) { qDebug() << "ERR Saving message: " << messages_model->lastError(); } } } // Commit any remaining transactions conversations_model->database().commit(); } } _app_db->commit(); return ret; } bool EX_Canvas::pullAssignments() { // Grab assignments for each course in the database bool ret = false; if (_app_db == nullptr) { return ret; } // Get a list of courses for this student GenericTableModel *courses_model = _app_db->getTable("courses"); GenericTableModel *model = _app_db->getTable("assignments"); if (courses_model == nullptr || model == nullptr) { qDebug() << "Unable to get models for courses or assignments"; return false; } // All entries should be for this student, so get them all courses_model->setFilter(""); courses_model->select(); // NOTE - Make sure to fetch all or we may only get 256 records while(courses_model->canFetchMore()) { courses_model->fetchMore(); } ret = true; int rowCount = courses_model->rowCount(); for(int i=0; i<rowCount; i++) { // Get assignments for this course QSqlRecord course_record = courses_model->record(i); QString course_id = course_record.value("id").toString(); QString course_name = course_record.value("name").toString(); qDebug() << "Retrieving assignments for " << course_id; QHash<QString, QString> p; p["per_page"] = "10000"; // cut number of calls QJsonDocument doc = CanvasAPICall("/api/v1/courses/" + course_id + "/assignments", "GET", &p); //qDebug() << "JSON Doc: " << doc; //qDebug() << "Is Array: " << doc.isArray(); //qDebug() << "Is Object: " << doc.isObject(); //qDebug() << "Is nullptr: " << doc.isnullptr(); //qDebug() << "JSON: " << doc.toJson(); if (doc.isArray()) { qDebug() << "\tAssignments for course:" << course_name; // Should be an array of assignments QJsonArray arr = doc.array(); foreach(QJsonValue val, arr) { // Should be an assignment QJsonObject o = val.toObject(); QString id = o["id"].toString(""); qDebug() << "Assignment ID " << id; model->setFilter("id = " + id); model->select(); // NOTE - Make sure to fetch all or we may only get 256 records while(model->canFetchMore()) { model->fetchMore(); } QSqlRecord record; bool is_insert = false; if (model->rowCount() == 1) { // Row exists, update w current info record = model->record(0); is_insert = false; qDebug() << "\t\tUpdating assignment..." << id << o["name"].toString(""); } else { // Need to clear the filter to insert model->setFilter(""); record = model->record(); is_insert = true; qDebug() << "\t\tImporting assignment..." << id << o["name"].toString(""); } // JSON - list of objects // {"id": 35871700000000002,"description": nullptr,"due_at": nullptr, // "unlock_at": nullptr,"lock_at": nullptr,"points_possible": nullptr, // "grading_type": "points","assignment_group_id": 35871700000000003, // "grading_standard_id": nullptr,"created_at": "2017-09-09T23:49:06Z", // "updated_at": "2017-09-09T23:49:09Z","peer_reviews": false, // "automatic_peer_reviews": false,"position": 1, // "grade_group_students_individually": false,"anonymous_peer_reviews": false, // "group_category_id": nullptr,"post_to_sis": false, // "moderated_grading": false,"omit_from_final_grade": false, // "intra_group_peer_reviews": false, // "secure_params": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsdGlfYXNzaWdubWVudF9pZCI6IjFjNTBhOTAzLWZmMWMtNDk5My1hYjg3LTY2ZWU2NWViMjY1ZiJ9.4EbPTYlKDiTZps_MxzKTlTCpXuqmzdRW7Z-q1LJX0kg", // "course_id": 35871700000000003,"name": "Test Assignment", // "submission_types": ["none"], // "has_submitted_submissions": false,"due_date_required": false, // "max_name_length": 255,"in_closed_grading_period": false, // "is_quiz_assignment": false,"muted": false, // "html_url": "https://canvas.ed/courses/35871700000000003/assignments/35871700000000002", // "has_overrides": false,"needs_grading_count": 0,"integration_id": nullptr, // "integration_data": {},"published": true,"unpublishable": true, // "only_visible_to_overrides": false,"locked_for_user": false, // "submissions_download_url": "https://canvas.ed/courses/35871700000000003/assignments/35871700000000002/submissions?zip=1" // }, QString desc = o["description"].toString(""); // Convert SMC Video/Document/Etc links to local links desc = ProcessAllLinks(desc); record.setValue("id", o["id"].toString("")); record.setValue("description", desc); record.setValue("due_at", o["due_at"].toString("")); record.setValue("unlock_at", o["unlock_at"].toString("")); record.setValue("lock_at", o["lock_at"].toString("")); record.setValue("points_possible", o["points_possible"].toString("")); record.setValue("grading_type", o["grading_type"].toString("")); record.setValue("assignment_group_id", o["assignment_group_id"].toString("")); record.setValue("grading_standard_id", o["grading_standard_id"].toString("")); record.setValue("created_at", o["created_at"].toString("")); record.setValue("updated_at", o["updated_at"].toString("")); record.setValue("peer_reviews", o["peer_reviews"].toBool(false)); record.setValue("automatic_peer_reviews", o["automatic_peer_reviews"].toBool(false)); record.setValue("position", o["position"].toString("")); record.setValue("grade_group_students_individually", o["grade_group_students_individually"].toBool(false)); record.setValue("anonymous_peer_reviews", o["anonymous_peer_reviews"].toBool(false)); record.setValue("group_category_id", o["group_category_id"].toString("")); record.setValue("post_to_sis", o["post_to_sis"].toBool(false)); record.setValue("moderated_grading", o["moderated_grading"].toBool(false)); record.setValue("omit_from_final_grade", o["omit_from_final_grade"].toBool(false)); record.setValue("intra_group_peer_reviews", o["intra_group_peer_reviews"].toBool(false)); record.setValue("secure_params", o["secure_params"].toString("")); record.setValue("course_id", o["course_id"].toString("")); record.setValue("name", o["name"].toString("")); // Submisisons is an array, convert to comma delim string QJsonArray a = o["submission_types"].toArray(); QString submission_types = ""; foreach (QVariant v, a.toVariantList() ) { if (submission_types != "") { submission_types += ","; } submission_types += v.toString(); } record.setValue("submission_types", submission_types); record.setValue("has_submitted_submissions", o["has_submitted_submissions"].toBool(false)); record.setValue("due_date_required", o["due_date_required"].toBool(false)); record.setValue("max_name_length", o["max_name_length"].toString("")); record.setValue("in_closed_grading_period", o["in_closed_grading_period"].toBool(false)); record.setValue("is_quiz_assignment", o["is_quiz_assignment"].toBool(false)); record.setValue("muted", o["muted"].toBool(false)); record.setValue("html_url", o["html_url"].toString("")); record.setValue("has_overrides", o["has_overrides"].toBool(false)); record.setValue("needs_grading_count", o["needs_grading_count"].toString("")); record.setValue("integration_id", o["integration_id"].toString("")); record.setValue("integration_data", o["integration_data"].toString("")); record.setValue("published", o["published"].toBool(false)); record.setValue("unpublishable", o["unpublishable"].toBool(false)); record.setValue("only_visible_to_overrides", o["only_visible_to_overrides"].toBool(false)); record.setValue("locked_for_user", o["locked_for_user"].toBool(false)); record.setValue("submissions_download_url", o["submissions_download_url"].toString("")); record.setValue("is_active", "true"); if (is_insert) { model->insertRecord(-1, record); } else { // Filter should be set so 0 should be current record model->setRecord(0, record); } // Write changes if (!model->submitAll()) { ret = false; } model->setFilter(""); // clear the filter model->database().commit(); } } } return ret; } bool EX_Canvas::pullAnnouncements() { // Grab a list of announcements for each course bool ret = false; if (_app_db == nullptr) { return ret; } // Get the list of courses for this student GenericTableModel *courses_model = _app_db->getTable("courses"); GenericTableModel *model = _app_db->getTable("announcements"); if (courses_model == nullptr || model == nullptr) { qDebug() << "Unable to get models for courses or announcements!"; return false; } // Pull all announcements for all courses courses_model->setFilter(""); courses_model->select(); // NOTE - Make sure to fetch all or we may only get 256 records while(courses_model->canFetchMore()) { courses_model->fetchMore(); } ret = true; int rowCount = courses_model->rowCount(); for (int i=0; i<rowCount; i++) { // Get pages for this course QSqlRecord course_record = courses_model->record(i); QString course_id = course_record.value("id").toString(); qDebug() << "Retrieving page info for " << course_id; QHash<QString,QString> p; p["per_page"] = "10000"; // Cuts down number of calls significantly p["context_codes[]"]="course_" + course_id; QJsonDocument doc = CanvasAPICall("/api/v1/announcements", "GET", &p); if (doc.isArray()) { qDebug() << "\tAnnouncements for course:"; // Should be an array of discussion topics QJsonArray arr = doc.array(); foreach(QJsonValue val, arr) { //qDebug() << "got item..."; // Got an item QJsonObject o = val.toObject(); QString id = o["id"].toString(""); model->setFilter("id = " + id); model->select(); // NOTE - Make sure to fetch all or we may only get 256 records while(model->canFetchMore()) { model->fetchMore(); } QSqlRecord record; bool is_insert = false; if (model->rowCount() == 1) { // Row exists, update with current info record = model->record(0); is_insert = false; qDebug() << "\t\tUpdating announcemnt..." << id << o["title"].toString(""); } else { // Need to clear the filter to insert model->setFilter(""); record = model->record(); is_insert = true; qDebug() << "\t\tImporting announcemnt..." << id << o["title"].toString(""); } // JSON - list of objects /* * // A discussion topic { // The ID of this topic. "id": 1, // The topic title. "title": "Topic 1", // The HTML content of the message body. "message": "<p>content here</p>", // The URL to the discussion topic in canvas. "html_url": "https://<canvas>/courses/1/discussion_topics/2", // The datetime the topic was posted. If it is nullptr it hasn't been posted yet. (see // delayed_post_at) "posted_at": "2037-07-21T13:29:31Z", // The datetime for when the last reply was in the topic. "last_reply_at": "2037-07-28T19:38:31Z", // If true then a user may not respond to other replies until that user has made an // initial reply. Defaults to false. "require_initial_post": false, // Whether or not posts in this topic are visible to the user. "user_can_see_posts": true, // The count of entries in the topic. "discussion_subentry_count": 0, // The read_state of the topic for the current user, 'read' or 'unread'. "read_state": "read", // The count of unread entries of this topic for the current user. "unread_count": 0, // Whether or not the current user is subscribed to this topic. "subscribed": true, // (Optional) Why the user cannot subscribe to this topic. Only one reason will be // returned even if multiple apply. Can be one of: 'initial_post_required': The // user must post a reply first; 'not_in_group_set': The user is not in the group // set for this graded group discussion; 'not_in_group': The user is not in this // topic's group; 'topic_is_announcement': This topic is an announcement "subscription_hold": "not_in_group_set", // The unique identifier of the assignment if the topic is for grading, otherwise // nullptr. "assignment_id": nullptr, // The datetime to publish the topic (if not right away). "delayed_post_at": nullptr, // Whether this discussion topic is published (true) or draft state (false) "published": true, // The datetime to lock the topic (if ever). "lock_at": nullptr, // Whether or not the discussion is 'closed for comments'. "locked": false, // Whether or not the discussion has been 'pinned' by an instructor "pinned": false, // Whether or not this is locked for the user. "locked_for_user": true, // (Optional) Information for the user about the lock. Present when locked_for_user // is true. "lock_info": nullptr, // (Optional) An explanation of why this is locked for the user. Present when // locked_for_user is true. "lock_explanation": "This discussion is locked until September 1 at 12:00am", // The username of the topic creator. "user_name": "User Name", // DEPRECATED An array of topic_ids for the group discussions the user is a part // of. "topic_children": [5, 7, 10], // An array of group discussions the user is a part of. Fields include: id, // group_id "group_topic_children": [{"id":5,"group_id":1}, {"id":7,"group_id":5}, {"id":10,"group_id":4}], // If the topic is for grading and a group assignment this will point to the // original topic in the course. "root_topic_id": nullptr, // If the topic is a podcast topic this is the feed url for the current user. "podcast_url": "/feeds/topics/1/enrollment_1XAcepje4u228rt4mi7Z1oFbRpn3RAkTzuXIGOPe.rss", // The type of discussion. Values are 'side_comment', for discussions that only // allow one level of nested comments, and 'threaded' for fully threaded // discussions. "discussion_type": "side_comment", // The unique identifier of the group category if the topic is a group discussion, // otherwise nullptr. "group_category_id": nullptr, // Array of file attachments. "attachments": nullptr, // The current user's permissions on this topic. "permissions": {"attach":true}, // Whether or not users can rate entries in this topic. "allow_rating": true, // Whether or not grade permissions are required to rate entries. "only_graders_can_rate": true, // Whether or not entries should be sorted by rating. "sort_by_rating": true } * */ record.setValue("id", o["id"].toString("")); record.setValue("title", o["title"].toString("")); record.setValue("message", o["message"].toString("")); record.setValue("html_url", o["html_url"].toString("")); record.setValue("posted_at", o["posted_at"].toString("")); record.setValue("last_reply_at", o["last_reply_at"].toString("")); record.setValue("require_initial_post", o["require_initial_post"].toBool(false)); record.setValue("user_can_see_posts", o["user_can_see_posts"].toBool(true)); record.setValue("discussion_subentry_count", o["discussion_subentry_count"].toString("")); record.setValue("read_state", o["read_state"].toString("")); record.setValue("unread_count", o["unread_count"].toString("")); record.setValue("subscribed", o["subscribed"].toString("")); record.setValue("subscription_hold", o["subscription_hold"].toString("")); record.setValue("assignment_id", o["assignment_id"].toString("")); record.setValue("delayed_post_at", o["delayed_post_at"].toString("")); record.setValue("published", o["published"].toBool(false)); record.setValue("lock_at", o["lock_at"].toString("")); record.setValue("locked", o["locked"].toBool(true)); record.setValue("pinned", o["pinned"].toBool(false)); record.setValue("locked_for_user", o["locked_for_user"].toBool(true)); record.setValue("lock_info", o["lock_info"].toString("")); record.setValue("lock_explanation", o["lock_explanation"].toString("")); record.setValue("user_name", o["user_name"].toString("")); // this is an array [5, 7, 10] record.setValue("topic_children", QJsonDocument(o["topic_children"].toArray()).toJson()); // Array of objects [{id:5, group_id:1},] record.setValue("group_topic_children", QJsonDocument(o["group_topic_children"].toArray()).toJson()); record.setValue("root_topic_id", o["root_topic_id"].toString("")); record.setValue("podcast_url", o["podcast_url"].toString("")); record.setValue("discussion_type", o["discussion_type"].toString("")); record.setValue("group_category_id", o["group_category_id"].toString("")); // array record.setValue("attachments", QJsonDocument(o["attachments"].toArray()).toJson()); // array record.setValue("permissions", QJsonDocument(o["permissions"].toArray()).toJson()); record.setValue("allow_rating", o["allow_rating"].toBool(true)); record.setValue("only_graders_can_rate", o["only_graders_can_rate"].toBool(true)); record.setValue("sort_by_rating", o["sort_by_rating"].toBool(true)); record.setValue("context_code", o["context_code"].toString("")); // Set this item as active record.setValue("active", "true"); record.setValue("course_id", course_id); record.setValue("is_active", "true"); if (is_insert) { model->insertRecord(-1, record); } else { // Filter should be set so 0 should be current record model->setRecord(0, record); } // Write changes if (!model->submitAll()) { ret = false; } model->setFilter(""); // clear the filter //qDebug() << "Announcement " << o["title"].toString(""); model->database().commit(); //qDebug() << model->lastError(); } } else { qDebug() << "Invalid Response for Announcement: " << doc; } } return ret; } QString EX_Canvas::pushAssignments() { // Make sure we have the list so we can do name lookups reloadAssignmentList(); // Push any submitted assignments back to canvas QString ret = ""; bool had_errors = false; QStringList error_list; if (_app_db == nullptr) { return "ERROR - No valid _app_db"; } QSqlRecord record; GenericTableModel *model = nullptr; QHash<QString,QString> assignment_push_list; // Get a list of assignments waiting to be submitted model = _app_db->getTable("assignment_submissions"); if (!model) { qDebug() << "Unable to get assignment_submissions model!"; return "ERROR - Unable to get assignment_submissions model"; } qDebug() << "-- Pushing assignment submissions..."; // Find submissions that have no sync date model->setFilter("synced_on=''"); model->select(); // NOTE - Make sure to fetch all or we may only get 256 records while(model->canFetchMore()) { model->fetchMore(); } int rowCount = model->rowCount(); for (int i=0; i < rowCount; i++) { record = model->record(i); qDebug() << "--- Submitting assignment file " << record.value("course_id").toString() << " " << record.value("assignment_id").toString() << " " << record.value("origin_url").toString() << "/" << record.value("queue_url").toString(); QString course_id = record.value("course_id").toString(); QString course_name = course_id; QString assignment_id = record.value("assignment_id").toString(); QString assignment_name = assignment_id; QString post_file = record.value("queue_url").toString(); QFileInfo post_file_info(post_file); if (_course_list.contains(course_id)) { course_name = _course_list[course_id]; } //qDebug() << "COURSE NAME: " << course_name; if (_assignment_list.contains(assignment_id)) { assignment_name = _assignment_list[assignment_id]; } QString assignment_info = post_file_info.fileName() + " (" + course_name + "/" + assignment_name + ") "; progressCurrentItem = "Pushing Assignment: " + assignment_info; emit progress(i, rowCount, progressCurrentItem); QHash<QString, QString> p; QFileInfo fi = QFileInfo(post_file); p["name"] = fi.fileName(); p["size"] = QString::number(fi.size()); // Let canvas guess the content_type //p["content_type"] = CM_MimeTypes::GetMimeType(fi.suffix()); //if (p["content_type"] == "") { // qDebug() << "UNKNOWN MIME TYPE " << fi.fileName(); // p["content_type"] = "application/octet-stream"; //} // Post to the canvas server // Get upload link QJsonDocument doc = CanvasAPICall("/api/v1/courses/" + course_id + "/assignments/" + assignment_id + "/submissions/self/files", "POST", &p); /* Should return JSON with something like this * * { * "upload_url": "https://some-bucket.s3.amazonaws.com/", * "upload_params": { * "key": "/users/1234/files/profile_pic.jpg", * <unspecified parameters; key above will not necesarily be present either> * } */ qDebug() << "$$$ SUBMIT STEP 1 RESPONSE: " << last_web_response; // Should now have the upload link if (doc.isObject()) { qDebug() << "Building SUMIT STEP 2 Response..."; p.clear(); QJsonObject o = doc.object(); if (!o.contains("upload_url") || !o.contains("upload_params")) { qDebug() << "*** ASSIGNMENT UPLOAD ERROR! missing upload_url " << assignment_id << "\n" << doc.toJson(); assignment_push_list[post_file] = " - <span class='failed'>Error></span> " + assignment_info + " - No upload_url recieved from canvas server (Step 2 failed)"; // Jump to next assignment continue; } QString next_url = o["upload_url"].toString(); QJsonObject params = o["upload_params"].toObject(); // Copy the provided parameters into the next request int order = 65; // Start at ascii a - need this to sort the keys later // or canvas will have a problem foreach(QString key, params.keys()) { p["___" + QString(order) + "_" + key] = params[key].toString(); order++; } // Do the actual file upload - NOTE - this will send back a redirect? // NOTE2 - NetworkCall will auto follow location redirect so we should // get json response from qDebug() << "Sending SUBMIT STEP 2 " << next_url; QJsonDocument doc2 = CanvasAPICall(next_url, "POST", &p, "multipart/form-data", post_file); qDebug() << "$$$ Last Web Response: " << last_web_response; if (doc2.isObject()) { // Will end up with a 201 or 301 and location header to follow // NetworkCall will see that and follow the link // Pull the file id QJsonObject o = doc2.object(); QString file_id = o["id"].toString(""); QString file_url = o["url"].toString(""); QString content_type = o["content-type"].toString(""); QString display_name = o["display_name"].toString(""); QString file_size = o["size"].toString(""); if (file_id == "") { qDebug() << "*** ERROR - No file id returned on step 2 - pushing assinment! " << assignment_name << assignment_id; assignment_push_list[post_file] = " - <span class='failed'>Error</span>" + assignment_info + " - No file id returned from canvas assignment upload! "; // Jump to next assignment continue; } // We should now have a json object with a file id, we need // to link it to the assignment so it shows up for the teacher p.clear(); // Docs here - https://canvas.instructure.com/doc/api/submissions.html p["comment[text_comment]"] = "Submitted via OPE LMS App"; p["submission[submission_type]"] = "online_upload"; p["submission[file_ids][]"] = file_id; QJsonDocument doc3 = CanvasAPICall("/api/v1/courses/" + course_id + "/assignments/" + assignment_id + "/submissions", "POST", &p); if (doc3.isObject()) { // Check if valid submission QJsonObject doc3_object = doc3.object(); QJsonArray attachments_arr = doc3_object["attachments"].toArray(); QString upload_success = attachments_arr.first().toObject()["upload_status"].toString(""); qDebug() << "Assignment pushed - TODO" << doc3.toJson(); if (upload_success == "success") { // Mark that the assignment has been synced so we don't try to // upload it again. record.setValue("synced_on", QDateTime::currentDateTime().toString()); model->setRecord(i, record); assignment_push_list[post_file] = " - <span class='accepted'>SUCCESS</span> " + assignment_info; } else { assignment_push_list[post_file] = " - <span class='failed'>FAILED</span> " + assignment_info; qDebug() << "ERROR - Final step linking assignment failed " << doc3.toJson(); had_errors = true; } } else { QString err = assignment_info + " - ERROR - Problem linking uploaded file with assignment " + assignment_id; qDebug() << err << " --- " << doc3.toJson(); assignment_push_list[post_file] = " - <span class='failed'>Error</span> " + assignment_info + " - Problem linking uploaded file with assignment " + assignment_id; had_errors = true; } } else { // Invalid response?? QString err = assignment_info + " - ERROR - *** ASSIGNMENT UPLOAD ERROR!! - Invalid response for upload link! " + assignment_id; qDebug() << err << " -- " << doc2.toJson(); had_errors = true; assignment_push_list[post_file] = " - <span class='failed'>Error</span> " + assignment_info + " - *** ASSIGNMENT UPLOAD ERROR!! - Invalid response for upload link! " + assignment_id; continue; // Jump to next assignmment } } else { QString err = assignment_info + " ERROR - ASSIGNMENT UPLOAD ERROR!!! - Invalid json object: pushAssignments " + assignment_id; qDebug() << err << " -- " << doc.toJson(); assignment_push_list[post_file] = " - <span class='failed'>Error</span> " + assignment_info + " - ASSIGNMENT UPLOAD ERROR!!! - Invalid json object: pushAssignments " + assignment_id; had_errors = true; } } bool submit_sucess = model->submitAll(); if (!submit_sucess) { qDebug() << "DB ERROR: " << model->lastError(); return "ERROR - Unable to submit changes to database!"; } // NOTE - May fail if commit not started, that is ok. model->database().commit(); foreach(QString key, assignment_push_list.keys()) { ret += assignment_push_list[key] + "\n"; } if (assignment_push_list.count() == 0) { ret += " - No assignments to push"; } if (had_errors) { ret += "\n **** <span class='failed'>Error</span> **** - One or more assignments failed to properly submit!"; } progressCurrentItem = ""; //emit progress(i, rowCount, progressCurrentItem); return ret; } bool EX_Canvas::pushMessages() { // Push any messages back to canvas - e.g. message teacher bool ret = false; return ret; } bool EX_Canvas::pushFiles() { // push any submitted files back to canvas - e.g. as message attachments bool ret = false; return ret; } bool EX_Canvas::queueAssignmentFile(QString course_id, QString assignment_id, QString submission_text, QString file_url) { if (_app_db == nullptr) { return false; } QSqlRecord record; GenericTableModel *model = nullptr; // If there is a file url, try to copy it and queue it, if not, queue the text if (course_id == "" || assignment_id == "") { return false; } if (file_url != "") { // Convert file url (file:///) to local path file_url = QUrl(file_url).toLocalFile(); submission_text = ""; // Ignore submission text if we have a file // See if the file exists if (QFile::exists(file_url)) { // Copy file to a temp location qDebug() << "Assignment file queuing up..."; // Get the temp path for saving assignments QDir cache_path; cache_path.setPath(this->appDataFolder() + "/file_cache/assignment_files"); // Make sure the base folder exists cache_path.mkpath(cache_path.path()); QFileInfo fi = QFileInfo(file_url); QString tmp_file = QString::number(QDateTime::currentSecsSinceEpoch()) + "_" +fi.fileName(); QString tmp_file_path = cache_path.absolutePath() + "/" + tmp_file; // Copy file to temp location QFile::copy(file_url, tmp_file_path); // Add the submission to the database model = _app_db->getTable("assignment_submissions"); if (model == nullptr) { qDebug() << "Unable to get model for assignment_submissions!"; return false; } // Check if this assignment already has a submission // TODO - Check if assignment has already been submitted? // Create a new record for this assignment model->setFilter(""); record = model->record(); record.setValue("assignment_type", "file"); record.setValue("submission_text", submission_text); record.setValue("queue_url", tmp_file_path); record.setValue("origin_url", file_url); record.setValue("file_size", QString::number(fi.size())); record.setValue("assignment_id", assignment_id); record.setValue("course_id", course_id); record.setValue("queued_on", QDateTime::currentDateTime().toString()); record.setValue("synced_on", ""); model->insertRecord(-1, record); if (!model->submitAll()) { qDebug() << "Error queueing assignment file in database " << model->lastError(); model->revertAll(); return false; } model->setFilter(""); model->database().commit(); return true; } else { // Invalid file submited qDebug() << "Submitted file doesn't exist! " << file_url; return false; } } else if (submission_text != "") { // Submitting a short answer/text response qDebug() << "Text answer being subbmitted"; // TODO - Store submission text return true; } else { // Invalid submission? qDebug() << "Invalid Assignment Submission!"; return false; } // If we get here, something isn't valid // return false; } bool EX_Canvas::LinkToCanvas(QString redirect_url, QString client_id) { // Redirect to canvas server to authorize this app //// TODO add purpose to key generation? &purpose=MobileLMS // Open the browser. We will get an event from the web server when it is done // https://lms.dev.domain.com/login/oauth2/auth?client_id=10&response_type=code&redirect_uri=urn:ietf:wg:oauth:2.0:oob //QString canvas_url = canvas_url; if (!canvas_url.endsWith("/login/oauth2/auth")) { // Add the path canvas_url+= "/login/oauth2/auth"; canvas_url.replace("//login", "/login"); // fix up double slashes which happens if url already ended with / } QDesktopServices::openUrl(QUrl(canvas_url + "?client_id=" + client_id + "&response_type=code&redirect_uri=" + QUrl::toPercentEncoding(redirect_url))); //https://canvas.pencollege.net/login/oauth2/auth?client_id=1&response_type=code&redirect_uri=" + QUrl::toPercentEncoding("http://localhost:8080/oauth/response")) return true; } void EX_Canvas::FinalizeLinkToCanvas(CM_HTTPRequest *request, CM_HTTPResponse *response) { // Get the URL and pull the parameters QString url = request->headers["URL"]; QStringList parts = url.split("?"); if (parts.length() < 2) { // Should be pre ? and post ?, so 2 parts. response->SetBody("<b>Invalid Query Parameters!</b>"); return; } // Split the second item on the & to get each key=value pair parts = parts[1].split("&"); QString code = ""; // Loop till we find code foreach (QString part, parts) { if (part.startsWith("code")) { parts = part.split("="); if (parts.length() >= 2) { code = parts[1]; } break; } } if (code == "") { // Didn't find the code param response->SetBody("<b>code not found!</b>"); } // Now we need to post to canvas to get the final code for the user QHash<QString,QString> headers; QHash<QString,QString> params; params["client_id"] = canvas_client_id; params["client_secret"] = canvas_client_secret; params["code"] = code; QString response_string = NetworkCall(canvas_url + "/login/oauth2/token", "POST", &params, &headers); //qDebug() << "Token JSON: " << response_string; QJsonDocument d(QJsonDocument::fromJson(response_string.toUtf8())); if (!d.isObject()) { response->SetBody("<b>Invalid canvas response!</b><br />" + response_string); return; } QJsonObject o = d.object(); canvas_access_token = o["access_token"].toString(); //qDebug() << "Access Token: " << canvas_access_token; if (canvas_access_token.length() > 5) { response->SetBody(tr("<b>App confirmed!</b><hr />Your app is now talking to canvas to download ") + tr("your materials. You can close this browser and go back to your app if ") + tr("it hasn't already done so.")); } else { // Failed to get the access token? response->SetBody(tr("<b>Failed to authenticate with Canvas!</b><hr />We were unable to ") + tr("authenticate with canvas. Please go back to your app and try again.")); } //// TODO - make the app popup and save the users info and start the canvas sync } QJsonDocument EX_Canvas::CanvasAPICall(QString api_call, QString method, QHash<QString, QString> *p, QString content_type, QString post_file, bool expect_non_json_answer) { // Network call will recursivly call the canvas api until it runs out of link headers QHash<QString,QString> headers; headers["Authorization"] = "Bearer " + canvas_access_token; headers["User-Agent"] = "OPE LMS"; headers["Accept-Language"] = "en-US,en;q=0.8"; QString call_url = api_call; // Don't append canvas server if full address is already present if (!api_call.toLower().startsWith("http")) { call_url = canvas_url; if (call_url.endsWith("/") != true) { call_url += "/"; } if (api_call.startsWith("/")) { // cut off beginning / in url api_call = api_call.mid(1); } call_url = call_url + api_call; } QString json = NetworkCall(call_url, method, p, &headers, content_type, post_file); //qDebug() << "C"; //if (call_url == "https://canvas.ed/api/v1/courses/21647000000049/pages/class-introduction") { // qDebug() << "PRE JSON RESPONSE: " << json; //} //http_reply_data = "{\"default_time_zone\":\"Pacific Time (US \u0026 Canada)\",\"id\":1,\"name\":\"Admin\",\"parent_account_id\":nullptr,\"root_account_id\":nullptr,\"default_storage_quota_mb\":5000,\"default_user_storage_quota_mb\":50}"; // Convert big id numbers to strings so they parse correctly // NOTE: qjsondocument converts ints to doubles and ends up loosing presision // find occurences of integer values in json documents and add quotes // ("\s*:\s*)(\d+\.?\d*)([^"])|([\[])(\d+\.?\d*)|([,])(\d+\.?\d*) // Was picking up digits in the body like $10,000. //QRegularExpression regex("(\"\\s*:\\s*)(\\d+\\.?\\d*)([^\"])|([\\[])(\\d+\\.?\\d*)|([,])(\\d+\\.?\\d*)"); // ":\\s*(\\d+)\\s*,"); //json = json.replace(regex, "\\1\\4\\6\"\\2\\5\\7\"\\3"); // :\"\\1\","); //qDebug() << "===================================\nParsing http data: " << json; QRegularExpression regex("(\\\"\\s*:\\s*)([0-9.]+)(\\s*[,])"); // ":\\s*(\\d+)\\s*,"); json = json.replace(regex, "\\1\"\\2\"\\3"); // :\"\\1\","); //if (call_url == "https://canvas.ed/api/v1/courses/21647000000049/pages/class-introduction") { // qDebug() << "POST JSON RESPONSE: " << json; //} // Convert response to json QJsonParseError *err = new QJsonParseError(); QJsonDocument d(QJsonDocument::fromJson(json.toUtf8(), err)); if (err->error != QJsonParseError::NoError && expect_non_json_answer != true) { qDebug() << "\tJSON Parse Err: " << err->errorString() << err->offset; qDebug() << "\tJSON Response: " << json; qDebug() << "\tJSON Doc: " << d; qDebug() << "\tIs Array: " << d.isArray(); qDebug() << "\tIs Object: " << d.isObject(); qDebug() << "\tIs nullptr: " << d.isNull(); } delete err; return d; } QString EX_Canvas::NetworkCall(QString url, QString method, QHash<QString, QString> *p, QHash<QString, QString> *headers, QString content_type, QString post_file) { QString ret; //qDebug() << "BA"; last_web_response = web_request->NetworkCall(url, method, p, headers, content_type, post_file); //qDebug() << "BB"; ret = last_web_response; //QByteArray bin_ret = web_request->NetworkCall(url, method, p, headers); //ret = QString::fromUtf8(bin_ret); // If this is a file push - canvas needs us to follow the 301. 201 response is just done // that should be set in the location header QString location_header = web_request->GetHeader("Location"); int status_code = web_request->httpStatusCode(); qDebug() << url << " - " << status_code << " " << location_header; if ((status_code == 201 || status_code >= 301 || status_code == 302 || status_code == 307 || status_code == 308 ) && (method.toUpper() == "POST" || method.toUpper() == "PUT") && location_header != "" && location_header.toLower().contains("/create_success?") ) { qDebug() << "### FOLLOWING Location Header from " << url << " to " << location_header; // Hit the next link headers->clear(); (*headers)["Authorization"] = "Bearer " + canvas_access_token; (*headers)["User-Agent"] = "OPE LMS"; (*headers)["Accept-Language"] = "en-US,en;q=0.8"; p->clear(); qDebug() << "First RET: " << ret; // Follow up changed to GET as specified in the docs under "Confirm upload success" // https://canvas.instructure.com/doc/api/file.file_uploads.html last_web_response = web_request->NetworkCall(location_header, "GET", p, headers); ret = last_web_response; qDebug() << "2nd RET: " << ret; return ret; } QString link_header = web_request->GetHeader("Link"); bool follow_link = false; // For multiple pages - we follow the link header to the next page automatically if (link_header != "") { follow_link = true; } while(follow_link == true) { // TODO - Need to keep following link until we run out of pages!!! //qDebug() << "Link header: " << link_header; QString next_url = ""; QStringList parts = link_header.split(",", QString::SkipEmptyParts); foreach (QString item, parts) { if(item.contains("rel=\"next\"")) { // Get the link QStringList parts2 = item.split(";", QString::SkipEmptyParts); next_url = parts2[0]; // Should be the first item. next_url = next_url.replace("<", "").replace(">", ""); // strip off the <> tags } } // If there is a link header, we need to call NetworkCall recursively to get the next chunk if (next_url != "") { qDebug() << "--> Nested API call: " << next_url; QString next = web_request->NetworkCall(next_url, method, p, headers, content_type, post_file); // Make sure to save the current link header for this page link_header = web_request->GetHeader("Link"); next = next.trimmed(); if (next != "" && next != "[]") { // We are combining lists, so trim off the last ] of current string, // and the first [ of the next string if (ret.trimmed().endsWith("]")) { ret = ret.remove(ret.count()-1, 1); } if (next.trimmed().startsWith("[")) { next = next.remove(0, 1); } ret.append(","); ret.append(next); } } else { // Out of next links, stop following them follow_link = false; } } return ret; } bool EX_Canvas::DownloadFile(QString url, QString local_path, QString item_name) { progressCurrentItem = item_name; emit progress(0, 0, progressCurrentItem); int count = 0; int dl_tries = 2; while (count < dl_tries) { // Try 2 times to download each file //qDebug() << " - DL Try " << count << url; if (web_request->DownloadFile(url, local_path) == true) { // DL worked, done. return true; } // DL failed, try again? count++; } qDebug() << " ***** ERROR downloading file after " << count << " tries: " << url; return false; } void EX_Canvas::downloadProgress(qint64 bytesRead, qint64 totalBytes) { if (totalBytes == 0) { _dl_progress = 0; } else { _dl_progress = bytesRead / totalBytes; } emit progress(bytesRead, totalBytes, progressCurrentItem); emit dlProgressChanged(); } void EX_Canvas::SetCanvasAccessToken(QString token) { canvas_access_token = token; } void EX_Canvas::SetCanvasURL(QString url) { canvas_url = url; } QString EX_Canvas::ProcessAllLinks(QString content) { QString ret = content; ret = ProcessDownloadLinks(ret); ret = ProcessSMCDocuments(ret); ret = ProcessSMCVideos(ret); ret = ProcessPagesLinks(ret); return ret; } QString EX_Canvas::ProcessSMCVideos(QString content) { QString ret = content; // Search content for any SMC links // <iframe width="650" height="405" src="https://smc.ed/media/player.load/6bc33efb174248c5bfff9cdd5f986ae9?autoplay=true" frameborder="0" allowfullscreen></iframe> // https://smc.ed/media/player.load/6bc33efb174248c5bfff9cdd5f986ae9 QHash<QString, QStringList> replace_urls; QRegExp rx; // Find iframes // [\"']{1}\s?((https?:\/\/[a-zA-Z\.0-9:]*)\/media\/player(\.load)?\/([a-zA-Z0-9]+)(\/)?(\?)?(autoplay=(true|false))?)\s*[\"']{1} rx.setPattern("[\\\"']{1}\\s?((https?:\\/\\/[a-zA-Z\\.0-9:]*)\\/media\\/player(\\.load)?\\/([a-zA-Z0-9]+)(\\/)?(\\?)?(autoplay=(true|false))?)\\s*[\\\"']{1}"); // rx.cap(0) = full match // 1 = full url - https://smc.ed/media/player.load/3f0s98foeu/ // 2 = server - https://smc.ed // 3 = if .load if present or empty if not // 4 = movie id //"href=http(s)://.../media/player[.load]/???..." int pos = 0; while ((pos = rx.indexIn(ret, pos)) != -1) { pos += rx.matchedLength(); // Get the full URL for this item QString full_url = rx.cap(1); // Get the host for this link QString smc_host = rx.cap(2); // Get the movie ID for this link QString movie_id = rx.cap(4); // Add to the list to be downloaded if (!_localhost_url.startsWith(smc_host)) { replace_urls[movie_id] = QStringList() << smc_host << full_url; } else { // This link already points to a local host address? qDebug() << "-- Link found w localhost address? " << full_url; } } qDebug() << "Found SMC video links"; qDebug() << replace_urls; // Queue up video to be downloaded foreach (QString movie_id, replace_urls.keys()) { QStringList values = replace_urls[movie_id]; QString original_host = values[0]; QString original_url = values[1]; QueueVideoForDownload(movie_id, original_host, original_url); } // Replace old URLs w the new ones foreach (QString movie_id, replace_urls.keys()) { QStringList values = replace_urls[movie_id]; QString original_host = values[0]; QString original_url = values[1]; QString new_url = _localhost_url; new_url += "/player.html?movie_id=" + movie_id; qDebug() << "Replacing " << original_url << " with " << new_url; ret = ret.replace(original_url, new_url, Qt::CaseInsensitive); } return ret; } QString EX_Canvas::ProcessSMCDocuments(QString content) { QString ret = content; // Search for any SMC Document links // <iframe src="https://smc.ed/smc/static/ViewerJS/index.html#/media/dl_document/4c3b4f9275bf4ff699b2dc98079f761b" width="734" height="620" allowfullscreen="allowfullscreen" webkitallowfullscreen="webkitallowfullscreen"></iframe> // https://smc.ed/media/dl_document/4c3b4f9275bf4ff699b2dc98079f761b QHash<QString, QStringList> replace_urls; QRegExp rx; // Find URLS // "((https?:\\/\\/[a-zA-Z\\.0-9:]*)((\\/smc)?\\/static\\/ViewerJS\\/index.html#)?\\/media\\/dl_document\\/([a-zA-Z0-9]+))" rx.setPattern("((https?:\\/\\/[a-zA-Z\\.0-9:]*)((\\/smc)?\\/static\\/ViewerJS\\/index.html#)?\\/media\\/dl_document\\/([a-zA-Z0-9]+))"); // rx.cap(0) = full match // 1 = https://smc.ed/media/dl_document/4c3b4f9275bf4ff699b2dc98079f761b // 2 = server - https://smc.ed // 3 = /smc/static/ViewerJS/index.html# (if exists) // 4 = /smc (if exists) // 5 = document id int pos = 0; while ((pos = rx.indexIn(ret, pos)) != -1) { pos += rx.matchedLength(); // Get the full URL for this item QString full_url = rx.cap(1); // Get the host for this item QString smc_host = rx.cap(2); // Get the document id for this item QString document_id = rx.cap(5); // Add to the list to be downloaded if (!_localhost_url.startsWith(smc_host)) { replace_urls[full_url] = QStringList() << smc_host << document_id; } else { // Link already points to a local host address, don't mess with it qDebug() << "-- Link found w localhost address? " << full_url; } } qDebug() << "Found SMC Document links"; qDebug() << replace_urls; // Queue up document to be downloaded foreach(QString original_url, replace_urls.keys()) { QStringList values = replace_urls[original_url]; QString original_host = values[0]; QString document_id = values[1]; QueueDocumentForDownload(document_id, original_host, original_url); } // Replace old URLs w the new ones foreach(QString original_url, replace_urls.keys()) { QStringList values = replace_urls[original_url]; QString original_host = values[0]; QString document_id = values[1]; QString new_url = _localhost_url; if (original_url.contains("ViewerJS")) { // Use the ViewerJS tool to display this document new_url += "/ViewerJS/index.html#/smc_document_cache/" + document_id; } else { // Not using ViewerJS - make it the direct link to the file new_url += "/smc_document_cache/" + document_id; } qDebug() << "Replacing " << original_url << " with " << new_url; ret = ret.replace(original_url, new_url, Qt::CaseInsensitive); } return ret; } QString EX_Canvas::ProcessDownloadLinks(QString content) { QString ret = content; // Search content for any file links to canvas files // Key will be full_url followed by the list of items //replace_urls[full_url] = QStringList() << file_id << course_id << canvas_host; QHash<QString, QStringList> replace_urls; QRegExp rx; // // Example link of image file embedded in this page/text // <img src="https://canvas.ed/courses/21647000000303/files/21647000019197/preview" alt="Misleading Graphs_Page_01.jpg" data-api-endpoint="https://canvas.ed/api/v1/courses/21647000000303/files/21647000019197" data-api-returntype="File" /> // Find download links // [\s>'\"]?((https?:\/\/[a-zA-Z\.0-9:]*)?(\/api\/v1)?\/courses\/([0-9]+)\/(files|modules\/items)\/([0-9]+)(\/download|\/preview)?([\?]?[;=&0-9a-zA-Z%_]+)?)[\s<'\"]? rx.setPattern("[\\s>'\\\"]?((https?:\\/\\/[a-zA-Z\\.0-9:]*)?(\\/api\\/v1)?\\/courses\\/([0-9]+)\\/(files|modules\\/items)\\/([0-9]+)(\\/download|\\/preview)?([\\?]?[;=&0-9a-zA-Z%_]+)?)[\\s<'\\\"]?"); // rx.cap(0) = full match // 1 = full url - https://smc.ed/media/player.load/3f0s98foeu/ // 2 = server - https://smc.ed // 3 = /api/v1 // 4 = course id // 5 = /files/ or modules/items // 6 = file id // 7 = /download if present // 8 = ? full query string if present int pos = 0; while ((pos = rx.indexIn(ret, pos)) != -1) { // Save the current match - use the position of the url, not the whole match // This is important so we don't loose quotes or other whitespace if it exists int start_pos = rx.pos(1); int match_len = rx.cap(1).length(); //pos += rx.matchedLength(); // Use inline replacement later, so always start at pos 0 pos = 0; // Get the full URL for this item QString full_url = rx.cap(1); qDebug() << "<<<<< FOUND URL " << full_url; // Get the host for this link QString canvas_host = rx.cap(2); if (canvas_host == "") { // For relative links - fill in current host canvas_host = canvas_url; } // Get the course id for this link QString course_id = rx.cap(4); // Get url type (files or modules/items) QString canvas_types = rx.cap(5); // Get the file id QString file_id = rx.cap(6); QString module_item_id = ""; if (canvas_types == "modules/items") { // Need to lookup the file_id, this is the module item id module_item_id = file_id; file_id = ""; QSqlQuery file_query; file_query.prepare("SELECT content_id FROM module_items WHERE id=:item_id"); file_query.bindValue(":item_id", module_item_id); if (!file_query.exec()) { qDebug() << "SQL Error - file lookup " << file_query.lastError(); } else { while(file_query.next()) { file_id = file_query.value("content_id").toString(); } } if (file_id == "") { // didn't find file, move on. qDebug() << " *** DB ERROR - couldn't pull module item for " << module_item_id << " " << file_query.lastError() << " - " << full_url; // Replace with dummy link so we can move on or we will get stuck in a loop. ret = ret.replace(start_pos, match_len, "<INVALID_MODULE_ITEM_" + module_item_id + ">"); // Jump to next item. continue; } } // Add to the list to be downloaded if (!_localhost_url.startsWith(canvas_host)) { // Add this to the download list later QueueCanvasLinkForDownload(file_id, course_id, canvas_host, full_url); // Replace this text with the place holder. // <CANVAS_FILE_???> ??? becomes the file id QString new_url = "<CANVAS_FILE_" + file_id + ">"; qDebug() << "Replacing " << full_url << " with " << new_url; ret = ret.replace(start_pos, match_len, new_url); } else { // This link already points to a local host address? qDebug() << "-- Link found w localhost address? " << full_url; } } return ret; } QString EX_Canvas::ProcessPagesLinks(QString content) { // Find links to canvas pages and change them for local links // TODO - links to pages aren't getting translated to local links QString ret = content; // Example link ot another page (maybe from assignments?) // <a id="" title="Misleading Graphs" href="https://canvas.ed/courses/21647000000303/pages/misleading-graphs" target="blank" data-api-endpoint="https://canvas.ed/api/v1/courses/21647000000303/pages/misleading-graphs" data-api-returntype="Page">Misleading Graphs</a> return ret; } bool EX_Canvas::updateDownloadLinks() { qDebug() << ">> Updating download links..."; // Replace <CANVAS_FILE_???> tags with real links QSqlQuery q; q.prepare("SELECT * FROM files"); if (!q.exec()) { qDebug() << "SQL Error!! " << q.lastError(); return false; } while(q.next()) { QString file_id = q.value("id").toString(); QString file_name = q.value("filename").toString(); QString pull_file = q.value("pull_file").toString(); QString content_type = q.value("content_type").toString(); QString f_ext = CM_MimeTypes::GetExtentionForMimeType(content_type); QString file_tag = "<CANVAS_FILE_" + file_id + ">"; //QString new_url = _localhost_url + "/canvas_file_cache/" + file_id + f_ext; // QString new_url = _localhost_url + "/canvas_file_cache/" + file_name; QString new_url = _localhost_url + pull_file; qDebug() << "Replacing " << file_tag << " with " << new_url; // Change in tables: assignments, pages QString sql = "UPDATE assignments SET description=REPLACE(description, :file_tag, :new_url)"; QSqlQuery q2; q2.prepare(sql); q2.bindValue(":file_tag", file_tag); q2.bindValue(":new_url", new_url); if (!q2.exec()) { qDebug() << "SQL Error!! " << q2.lastError() << " on " << q2.lastQuery(); } sql = "UPDATE pages SET body=REPLACE(body, :file_tag, :new_url)"; QSqlQuery q3; q3.prepare(sql); q3.bindValue(":file_tag", file_tag); q3.bindValue(":new_url", new_url); if(!q3.exec()) { qDebug() << "SQL Error!! " << q3.lastError() << " on " << q3.lastQuery(); } // Write changes to db _app_db->commit(); } return true; } bool EX_Canvas::QueueVideoForDownload(QString movie_id, QString original_host, QString original_url) { // Add the video id to the list for downloading bool ret = false; QSqlQuery q; q.prepare("SELECT count(media_id) FROM smc_media_dl_queue2 WHERE media_id = :media_id"); q.bindValue(":media_id", movie_id); if(q.exec()) { q.next(); int count = q.value(0).toInt(); if (count < 1) { // ID isn't in the list QSqlQuery q2; q2.prepare("INSERT INTO smc_media_dl_queue2 (`id`, `media_id`, `original_host`, `original_url`) VALUES (NULL, :media_id, :original_host, :original_url)"); q2.bindValue(":media_id", movie_id); q2.bindValue(":original_host", original_host); q2.bindValue(":original_url", original_url); q2.exec(); qDebug() << "New Movie ID " << movie_id; } else { // Is in the list, update it qDebug() << "Movie ID already queued " << movie_id; QSqlQuery q3; q3.prepare("UPDATE smc_media_dl_queue2 SET `original_host`=:original_host, `original_url`=:original_url WHERE `media_id`=:media_id"); q3.bindValue(":original_host", original_host); q3.bindValue(":original_url", original_url); q3.bindValue(":media_id", movie_id); q3.exec(); } ret = true; } else { // Error running query qDebug() << "ERROR RUNNING QUERY: " << q.lastError().text(); ret = false; } return ret; } bool EX_Canvas::QueueDocumentForDownload(QString document_id, QString original_host, QString original_url) { // Add the document id to the list for downloading bool ret = false; QSqlQuery q; q.prepare("SELECT count(document_id) FROM smc_document_dl_queue2 WHERE document_id = :document_id"); q.bindValue(":document_id", document_id); if(q.exec()) { q.next(); int count = q.value(0).toInt(); if (count < 1) { // ID isn't in the list QSqlQuery q2; q2.prepare("INSERT INTO smc_document_dl_queue2 (`id`, `document_id`, `original_host`, `original_url`) VALUES (NULL, :document_id, :original_host, :original_url)"); q2.bindValue(":document_id", document_id); q2.bindValue(":original_host", original_host); q2.bindValue(":original_url", original_url); q2.exec(); qDebug() << "New Document ID " << document_id; } else { qDebug() << "Document ID already queued " << document_id; } ret = true; } else { // Error running query qDebug() << "ERROR RUNNING QUERY: " << q.lastError().text(); ret = false; } return ret; } bool EX_Canvas::QueueCanvasLinkForDownload(QString file_id, QString course_id, QString original_host, QString original_url) { // Add the file id to the list for downloading bool ret = false; if (_app_db == nullptr) { qCritical() << "Invalid app DB "; return false; } QSqlQuery q; q.prepare("SELECT count(file_id) FROM canvas_dl_queue WHERE file_id = :file_id"); q.bindValue(":file_id", file_id); if(q.exec()) { q.next(); int count = q.value(0).toInt(); if (count < 1) { // ID isn't in the list QSqlQuery q2; q2.prepare("INSERT INTO canvas_dl_queue (`id`, `file_id`, `course_id`, `original_host`, `original_url`) VALUES (NULL, :file_id, :course_id, :original_host, :original_url)"); q2.bindValue(":file_id", file_id); q2.bindValue(":course_id", course_id); q2.bindValue(":original_host", original_host); q2.bindValue(":original_url", original_url); q2.exec(); qDebug() << "New File ID " << file_id; } else { QSqlQuery q2; q2.prepare("UPDATE canvas_dl_queue SET course_id=:course_id, original_host=:original_host, original_url=:original_url WHERE file_id=:file_id"); q2.bindValue(":course_id", course_id); q2.bindValue(":original_host", original_host); q2.bindValue(":original_url", original_url); q2.bindValue(":file_id", file_id); q2.exec(); qDebug() << "File ID already queued " << file_id; } ret = true; } else { // Error running query qDebug() << "ERROR RUNNING QUERY: " << q.lastError().text(); ret = false; } return ret; } bool EX_Canvas::pullSMCVideos() { bool ret = false; // Make sure our cache path exists // Get the local cache folder QDir base_dir; base_dir.setPath(this->appDataFolder() + "/content/www_root/smc_video_cache/"); base_dir.mkpath(base_dir.path()); // Get list of video IDs QSqlQuery q; q.prepare("SELECT * FROM smc_media_dl_queue2"); if(!q.exec()) { qDebug() << "ERROR RUNNING DB QUERY: " << q.lastQuery() << " - " << q.lastError().text(); return false; } while(q.next()) { // See if this file exists QString video_id = q.value(1).toString(); QString local_path = base_dir.path() + "/" + video_id + ".mp4"; QFileInfo fi = QFileInfo(local_path); if (fi.exists() && fi.size() > 1000) { qDebug() << " - SMC Video File already downloaded: " << local_path; } else { qDebug() << "** Need to download video file " << local_path; // Get the original host QString smc_url = q.value(2).toString(); //_app_settings->value("smc_url", "https://smc.ed").toString(); // Build the download url smc_url += "/media/dl_media/" + video_id + "/mp4"; bool r = DownloadFile(smc_url, local_path, "SMC Video: " + video_id); if (!r) { qDebug() << "Error downloading file " << smc_url; } } // Now pull poster image local_path = base_dir.path() + "/" + video_id + ".poster.png"; fi = QFileInfo(local_path); if (fi.exists() && fi.size() > 1000) { qDebug() << " - SMC Video Poster file already downloaded: " << local_path; } else { qDebug() << "** Need to download poster file " << local_path; QString smc_url = q.value(2).toString(); // _app_settings->value("smc_url", "https://smc.ed").toString(); // Grab the first 2 characters of the ID QString prefix = video_id.mid(0,2); smc_url += "/static/media/" + prefix + "/" + video_id + ".poster.png"; bool r = DownloadFile(smc_url, local_path, "SMC Poster: " + video_id); if (!r) { qDebug() << "Error downloading poster file " << smc_url; } } } // Now go through the folder and remove any files that aren't in the file list anymore. QDir cache_dir(base_dir); qDebug() << "Removing orphaned SMC Media files:"; foreach(QString f_name, cache_dir.entryList()) { if(f_name == "." || f_name == "..") { // Skip these continue; } // See if this file exists in the files database QFileInfo fi(f_name); QString base_name = fi.baseName(); //qDebug() << " Checknig SMC media file " << base_name; QSqlQuery q; q.prepare("select count(media_id) as cnt from smc_media_dl_queue2 where media_id=:media_id"); q.bindValue(":media_id", base_name); if (!q.exec()) { qDebug() << "DB ERROR - PullSMCVideos " << q.lastError(); } else { q.next(); QSqlRecord r = q.record(); int size = r.value(0).toInt(); //qDebug() << "------ FOUND " << size << " records"; if(size < 1) { //qDebug() << "Deleting Orphaned SMC Video " << f_name; // File isn't in the database, delete it QString local_path = base_dir.path() + "/" + f_name; qDebug() << "---- Orphaned SMC Video File: " << local_path << " - deleting..."; try { QFile::remove(local_path); } catch (...) { qDebug() << "----- ERROR removing file: " << local_path; } } } } ret = true; return ret; } bool EX_Canvas::pullSMCDocuments() { bool ret = false; // Make sure our cache path exists QDir base_dir; base_dir.setPath(this->appDataFolder() + "/content/www_root/smc_document_cache/"); base_dir.mkpath(base_dir.path()); // Get the list of document ids QSqlQuery q; q.prepare("SELECT * from smc_document_dl_queue2"); if (!q.exec()) { qDebug() << "ERROR RUNNING DB QUERY: " << q.lastQuery() << " - " << q.lastError().text(); return false; } while(q.next()) { // See if document exists QString document_id = q.value(1).toString(); QString local_path = base_dir.path() + "/" + document_id; // TODO - need file extension? QFileInfo fi = QFileInfo(local_path); if (fi.exists() && fi.size() > 10) { qDebug() << " - SMC Document file already downloaded: " << local_path; } else { qDebug() << "** Need to download document file " << local_path; QString smc_url = q.value(2).toString(); // Build dl url smc_url += "/media/dl_document/" + document_id; bool r = DownloadFile(smc_url, local_path, "SMC Document: " + document_id); if (!r) { qDebug() << "Error downloading file " << smc_url; } else { // File downloaded, get the content type header QHash<QString, QString> headers = web_request->GetAllDownloadHeaders(); if (headers.contains("Content-Type")) { // Save a file with the mime type QString mime_local_path = local_path + ".mime"; QString content_type = headers["Content-Type"]; QFile *mime_file = new QFile(mime_local_path); if (mime_file->open(QIODevice::WriteOnly)) { mime_file->write(content_type.toLocal8Bit()); mime_file->close(); } mime_file->deleteLater(); } } } } // Now go through the folder and remove any files that aren't in the file list anymore. QDir cache_dir(base_dir); qDebug() << "Removing orphaned SMC Media files:"; foreach(QString f_name, cache_dir.entryList()) { if(f_name == "." || f_name == "..") { // Skip these continue; } // See if this file exists in the files database QFileInfo fi(f_name); QString base_name = fi.baseName(); QSqlQuery q; q.prepare("SELECT COUNT(document_id) as cnt FROM smc_document_dl_queue2 where document_id=:document_id"); q.bindValue(":document_id", base_name); if (!q.exec()) { qDebug() << "DB ERROR - PullSMCDocuments " << q.lastError(); } else { q.next(); QSqlRecord r = q.record(); int size = r.value(0).toInt(); //qDebug() << "------ FOUND " << size << " records"; if(size < 1) { //qDebug() << "Deleting Orphaned SMC Document " << f_name; // File isn't in the database, delete it QString local_path = base_dir.path() + "/" + f_name; qDebug() << "---- Orphaned SMC Document File: " << local_path << " - deleting..."; try { QFile::remove(local_path); } catch (...) { qDebug() << "----- ERROR removing file: " << local_path; } } } } ret = true; return ret; } bool EX_Canvas::reloadCourseList() { // Clear and reload the course list _course_list.clear(); if (_app_db == nullptr) { qDebug() << "ERROR - No valid _app_db"; return false; } QSqlRecord record; GenericTableModel *model = nullptr; // Get the courses table model = _app_db->getTable("courses"); if (model == nullptr) { // Unable to pull the courses table, error with database? QString err = "ERROR - pulling courses table!!!"; qDebug() << err; return false; } model->setFilter(""); model->select(); // NOTE - Make sure to fetch all or we may only get 256 records while(model->canFetchMore()) { model->fetchMore(); } int rowCount = model->rowCount(); for (int i=0; i < rowCount; i++) { record = model->record(i); QString course_id = record.value("id").toString(); QString course_name = record.value("name").toString(); _course_list[course_id] = course_name; qDebug() << "ADDED COURSE TO LIST " << course_id << course_name; } return true; } bool EX_Canvas::reloadAssignmentList() { // Clear and reload the assignment list _assignment_list.clear(); if (_app_db == nullptr) { qDebug() << "ERROR - No valid _app_db"; return false; } QSqlRecord record; GenericTableModel *model = nullptr; // Get the courses table model = _app_db->getTable("assignments"); if (model == nullptr) { // Unable to pull the courses table, error with database? QString err = "ERROR - pulling assignments table!!!"; qDebug() << err; return false; } model->setFilter(""); model->select(); // NOTE - Make sure to fetch all or we may only get 256 records while(model->canFetchMore()) { model->fetchMore(); } int rowCount = model->rowCount(); for (int i=0; i < rowCount; i++) { record = model->record(i); QString assignment_id = record.value("id").toString(); QString assignment_name = record.value("name").toString(); _assignment_list[assignment_id] = assignment_name; qDebug() << "ADDED ASSIGNMENT TO LIST " << assignment_id << assignment_name; } return true; } bool EX_Canvas::setCurrentItem(QString item_text) { progressCurrentItem = item_text; return true; } QString EX_Canvas::appDataFolder() { // Cast appmodule back to its class AppModule *app_module = qobject_cast<AppModule*>(this->parent()); return app_module->appDataFolder(); } QSqlRecord EX_Canvas::pullSinglePage(QString course_id, QString page_url) { QSqlTableModel *pages_model = _app_db->getTable("pages"); if (pages_model == nullptr) { qDebug() << "Error getting model for Pages in pullSinglePage " << page_url; return QSqlRecord(); } // Pull the page from Canvas and update the database with current info QString page_body = ""; QString page_id = ""; // Need to retrieve each page body individually QHash<QString,QString> p; p["per_page"] = "10000"; // Cuts down number of calls significantly QJsonDocument page_doc = CanvasAPICall("/api/v1/courses/" + course_id + "/pages/" + page_url, "GET", &p); QJsonObject page_object; if (!page_doc.isObject()) { qDebug() << "!!!ERROR GETTING PAGE BODY - course:" << course_id << page_url << page_doc; page_body = "ERROR GETTING PAGE"; return QSqlRecord(); } else { page_object = page_doc.object(); page_body = page_object["body"].toString(""); if (page_object["locked_for_user"].toBool() == true) { page_body = page_object["lock_explanation"].toString("Page Locked - see instructor"); } } page_id = page_doc["page_id"].toString(""); if (page_id == "") { qDebug() << "** ERROR Getting Page Info for " << page_url; return QSqlRecord(); } // Convert SMC Video/Document/Etc links to local links page_body = ProcessAllLinks(page_body); pages_model->setFilter("url='" + page_url.replace("'", "''") + "' AND course_id='" + course_id.replace("'", "''") + "'"); pages_model->select(); // NOTE - Make sure to fetch all or we may only get 256 records while(pages_model->canFetchMore()) { pages_model->fetchMore(); } QSqlRecord record; bool is_insert = false; if (pages_model->rowCount() >= 1) { // Row exists, update with current info record = pages_model->record(0); is_insert = false; qDebug() << "\t\t\tUpdating page..." << page_url; } else { // Need to clear the filter to insert pages_model->setFilter(""); record = pages_model->record(); is_insert = true; qDebug() << "\t\t\tImporting page info..." << page_url; } // JSON - list of objects // {"title":"Format of the course","created_at":"2017-06-21T21:44:15Z", // "url":"format-of-the-course","editing_roles":"teachers", // "page_id":26664700000000089,"published":true,"hide_from_students":false, // "front_page":false, // "html_url":"https://canvas.ed.dev/courses/26664700000000090/pages/format-of-the-course", // "updated_at":"2017-06-21T21:44:15Z","locked_for_user":false} record.setValue("title", page_object["title"].toString("")); record.setValue("created_at", page_object["created_at"].toString("")); record.setValue("url", page_object["url"].toString("")); record.setValue("editing_roles", page_object["editing_roles"].toString("")); record.setValue("page_id", page_object["page_id"].toString("")); record.setValue("published", page_object["published"].toBool(false)); record.setValue("hide_from_students", page_object["hide_from_students"].toBool(false)); record.setValue("front_page", page_object["front_page"].toBool(false)); record.setValue("html_url", page_object["html_url"].toString("")); record.setValue("updated_at", page_object["updated_at"].toString("")); record.setValue("locked_for_user", page_object["locked_for_user"].toBool(false)); record.setValue("course_id", course_id); record.setValue("body", page_body); record.setValue("lock_info", page_object["lock_info"].toString("")); record.setValue("lock_explanation", page_object["lock_explanation"].toString("")); record.setValue("is_active", "true"); if (is_insert) { pages_model->insertRecord(-1, record); } else { // Filter should be set so 0 should be current record pages_model->setRecord(0, record); } // Write changes if (!pages_model->submitAll()) { qDebug() << "Error saving page info " << pages_model->lastError(); } pages_model->setFilter(""); // clear the filter pages_model->select(); //qDebug() << "Page " << o["title"].toString(""); pages_model->database().commit(); //qDebug() << model->lastError(); return record; } /* * * * private static string ConvertDictionaryToQueryString(Dictionary<string, object> p) { if (p == nullptr) { return ""; } StringBuilder ret = new StringBuilder(); bool first = true; foreach (string key in p.Keys) { if (key == nullptr) { continue; } if (p[key] == nullptr) { p[key] = ""; } // Put in the & between values if (!first) { ret.Append("&"); } ret.Append(HttpUtility.UrlEncode(key)); ret.Append("="); ret.Append(HttpUtility.UrlEncode(p[key].ToString())); first = false; } return ret.ToString(); } private static Dictionary<string,object> CanvasAPICall(string api_call, string method = "GET", Dictionary<string,object> p = nullptr) { string response_json = ""; Dictionary<string, object> response_items; // Don't error out on test certs ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; WebRequest wr = nullptr; string qstring = ""; if (p != nullptr && p.Count > 0 && method.ToUpper() == "GET") { qstring = ConvertDictionaryToQueryString(p); wr = WebRequest.Create(canvas_server + api_call + "?" + qstring); } else { wr = WebRequest.Create(canvas_server + api_call); } wr.Headers.Add("Authorization", "Bearer " + canvas_access_token); //wr.Headers.Add("User-Agent", "Network Admin Tool"); wr.Method = method.ToUpper(); if (p != nullptr && p.Count > 0 && (method.ToUpper() == "POST" || method.ToUpper() == "PUT")) { // Create the string boundary string boundary = "----------" + DateTime.Now.Ticks.ToString("x"); wr.ContentType = "multipart/form-data;"; // boundary=" + boundary; //wr.ContentType = "application/x-url-formencoded"; StringBuilder send = new StringBuilder(); string query = ConvertDictionaryToQueryString(p); send.Append(query); // Send the whole thing off byte[] b = Encoding.UTF8.GetBytes(send.ToString()); wr.ContentLength = b.Length; Stream st = wr.GetRequestStream(); st.Write(b, 0, b.Length); st.Close(); } WebResponse response = nullptr; try { response = wr.GetResponse(); Stream stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); response_json = reader.ReadToEnd(); } catch { } // Convert JSON response to dictionary if (response_json.Trim() == "[]") { // Empty response, return an empty dictionary response_items = new Dictionary<string,object>(); } else if (response_json.StartsWith("[{")) { // This is an array? List<Dictionary<string, object>> items = JsonConvert.DeserializeObject<List<Dictionary<string,object>>>(response_json); response_items = new Dictionary<string, object>(); for (int i=0; i<items.Count; i++) { response_items[i.ToString()] = items[i]; } } else { response_items = JsonConvert.DeserializeObject<Dictionary<string, object>>(response_json); } if (response_items == nullptr) { // Don't return a nullptr, return an empty dictionary response_items = new Dictionary<string,object>(); } return response_items; } */
43.375173
269
0.563708
[ "object", "model" ]
a6751778bf221e82e360cffa07c5d4c713a4fd41
7,613
cpp
C++
OpenGL/text_ttf/FT&glsl/text.cpp
bigov/daft-lib
7890fdba0aab800022ab9afb958946bd06779f33
[ "MIT" ]
1
2022-03-14T08:20:58.000Z
2022-03-14T08:20:58.000Z
OpenGL/text_ttf/FT&glsl/text.cpp
bigov/daft-lib
7890fdba0aab800022ab9afb958946bd06779f33
[ "MIT" ]
null
null
null
OpenGL/text_ttf/FT&glsl/text.cpp
bigov/daft-lib
7890fdba0aab800022ab9afb958946bd06779f33
[ "MIT" ]
1
2020-12-22T08:36:48.000Z
2020-12-22T08:36:48.000Z
/** * From the OpenGL Programming wikibook: http://en.wikibooks.org/wiki/Opengl::Programming * This file is in the public domain. * Contributors: Guus Sliepen, Sylvain Beucler */ #include <cstdlib> #include <iostream> using namespace std; /* Use glew.h instead of gl.h to get all the GL prototypes declared */ //#include <GL/glew.h> /* Using SDL2 for the base window and OpenGL context init */ #include <SDL2/SDL.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "shader_utils.h" #include <ft2build.h> #include FT_FREETYPE_H int screen_width=800, screen_height=600; GLuint program; GLint attribute_coord; GLint uniform_tex; GLint uniform_color; struct point { GLfloat x; GLfloat y; GLfloat s; GLfloat t; }; GLuint vbo; FT_Library ft; FT_Face face; const char *fontfilename; bool init_resources() { /* Initialize the FreeType2 library */ if (FT_Init_FreeType(&ft)) { cerr << "Could not init freetype library" << endl; return false; } /* Load a font */ int fontsize; char* font = file_read(fontfilename, &fontsize); if (font == NULL) { cerr << "Could not load font file " << fontfilename << endl; return false; } FT_Error fterr = FT_New_Memory_Face(ft, (FT_Byte*)font, fontsize, 0, &face); if (fterr != FT_Err_Ok) { cerr << "Could not init font: error 0x" << hex << fterr << endl; return false; } program = create_program("text.v.glsl", "text.f.glsl"); if(program == 0) return false; attribute_coord = get_attrib(program, "coord"); uniform_tex = get_uniform(program, "tex"); uniform_color = get_uniform(program, "color"); if(attribute_coord == -1 || uniform_tex == -1 || uniform_color == -1) return false; // Create the vertex buffer object gl::GenBuffers(1, &vbo); return true; } /** * Render text using the currently loaded font and currently set font size. * Rendering starts at coordinates (x, y), z is always 0. * The pixel coordinates that the FreeType2 library uses are scaled by (sx, sy). */ void render_text(const char *text, float x, float y, float sx, float sy) { const char *p; FT_GlyphSlot g = face->glyph; /* Create a texture that will be used to hold one "glyph" */ GLuint tex; gl::ActiveTexture(gl::TEXTURE0); gl::GenTextures(1, &tex); gl::BindTexture(gl::TEXTURE_2D, tex); gl::Uniform1i(uniform_tex, 0); /* We require 1 byte alignment when uploading texture data */ gl::PixelStorei(gl::UNPACK_ALIGNMENT, 1); /* Clamping to edges is important to prevent artifacts when scaling */ gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::CLAMP_TO_EDGE); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::CLAMP_TO_EDGE); /* Linear filtering usually looks best for text */ gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR); /* Set up the VBO for our vertex data */ gl::EnableVertexAttribArray(attribute_coord); gl::BindBuffer(gl::ARRAY_BUFFER, vbo); gl::VertexAttribPointer(attribute_coord, 4, gl::FLOAT, 0, 0, 0); /* Loop through all characters */ for (p = text; *p; p++) { /* Try to load and render the character */ if (FT_Load_Char(face, *p, FT_LOAD_RENDER)) continue; /* Upload the "bitmap", which contains an 8-bit grayscale image, as an alpha texture */ gl::TexImage2D(gl::TEXTURE_2D, 0, gl::ALPHA, g->bitmap.width, g->bitmap.rows, 0, gl::ALPHA, gl::UNSIGNED_BYTE, g->bitmap.buffer); /* Calculate the vertex and texture coordinates */ float x2 = x + g->bitmap_left * sx; float y2 = -y - g->bitmap_top * sy; float w = g->bitmap.width * sx; float h = g->bitmap.rows * sy; point box[4] = { {x2, -y2, 0, 0}, {x2 + w, -y2, 1, 0}, {x2, -y2 - h, 0, 1}, {x2 + w, -y2 - h, 1, 1}, }; /* Draw the character on the screen */ gl::BufferData(gl::ARRAY_BUFFER, sizeof box, box, gl::DYNAMIC_DRAW); gl::DrawArrays(gl::TRIANGLE_STRIP, 0, 4); /* Advance the cursor to the start of the next character */ x += (g->advance.x >> 6) * sx; y += (g->advance.y >> 6) * sy; } gl::DisableVertexAttribArray(attribute_coord); gl::DeleteTextures(1, &tex); } void render(SDL_Window* window) { float sx = 2.0 / screen_width; float sy = 2.0 / screen_height; gl::UseProgram(program); /* White background */ gl::ClearColor(1, 1, 1, 1); gl::Clear(gl::COLOR_BUFFER_BIT); /* Enable blending, necessary for our alpha texture */ gl::Enable(gl::BLEND); gl::BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA); GLfloat black[4] = { 0, 0, 0, 1 }; GLfloat red[4] = { 1, 0, 0, 1 }; GLfloat transparent_green[4] = { 0, 1, 0, 0.5 }; /* Set font size to 48 pixels, color to black */ FT_Set_Pixel_Sizes(face, 0, 48); gl::Uniform4fv(uniform_color, 1, black); /* Effects of alignment */ render_text("The Quick Brown Fox Jumps Over The Lazy Dog", -1 + 8 * sx, 1 - 50 * sy, sx, sy); render_text("The Misaligned Fox Jumps Over The Lazy Dog", -1 + 8.5 * sx, 1 - 100.5 * sy, sx, sy); /* Scaling the texture versus changing the font size */ render_text("The Small Texture Scaled Fox Jumps Over The Lazy Dog", -1 + 8 * sx, 1 - 175 * sy, sx * 0.5, sy * 0.5); FT_Set_Pixel_Sizes(face, 0, 24); render_text("The Small Font Sized Fox Jumps Over The Lazy Dog", -1 + 8 * sx, 1 - 200 * sy, sx, sy); FT_Set_Pixel_Sizes(face, 0, 48); render_text("The Tiny Texture Scaled Fox Jumps Over The Lazy Dog", -1 + 8 * sx, 1 - 235 * sy, sx * 0.25, sy * 0.25); FT_Set_Pixel_Sizes(face, 0, 12); render_text("The Tiny Font Sized Fox Jumps Over The Lazy Dog", -1 + 8 * sx, 1 - 250 * sy, sx, sy); FT_Set_Pixel_Sizes(face, 0, 48); /* Colors and transparency */ render_text("The Solid Black Fox Jumps Over The Lazy Dog", -1 + 8 * sx, 1 - 430 * sy, sx, sy); gl::Uniform4fv(uniform_color, 1, red); render_text("The Solid Red Fox Jumps Over The Lazy Dog", -1 + 8 * sx, 1 - 330 * sy, sx, sy); render_text("The Solid Red Fox Jumps Over The Lazy Dog", -1 + 28 * sx, 1 - 450 * sy, sx, sy); gl::Uniform4fv(uniform_color, 1, transparent_green); render_text("The Transparent Green Fox Jumps Over The Lazy Dog", -1 + 8 * sx, 1 - 380 * sy, sx, sy); render_text("The Transparent Green Fox Jumps Over The Lazy Dog", -1 + 18 * sx, 1 - 440 * sy, sx, sy); SDL_GL_SwapWindow(window); } void onResize(int width, int height) { screen_width = width; screen_height = height; gl::Viewport(0, 0, screen_width, screen_height); } void free_resources() { gl::DeleteProgram(program); } void mainLoop(SDL_Window* window) { while (true) { SDL_Event ev; while (SDL_PollEvent(&ev)) { if (ev.type == SDL_QUIT) return; if (ev.type == SDL_WINDOWEVENT && ev.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) onResize(ev.window.data1, ev.window.data2); } render(window); } } int main(int argc, char *argv[]) { SDL_Init(SDL_INIT_VIDEO); SDL_Window* window = SDL_CreateWindow("Basic Text", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, screen_width, screen_height, SDL_WINDOW_RESIZABLE | SDL_WINDOW_OPENGL); if (window == NULL) { cerr << "Error: can't create window: " << SDL_GetError() << endl; return EXIT_FAILURE; } SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); if (SDL_GL_CreateContext(window) == NULL) { cerr << "Error: SDL_GL_CreateContext: " << SDL_GetError() << endl; return EXIT_FAILURE; } if(!gl::sys::LoadFunctions()) { cerr << "Can't load OpenGl finctions" << endl; return EXIT_FAILURE; } if (argc > 1) fontfilename = argv[1]; else fontfilename = "FreeSans.ttf"; if (!init_resources()) return EXIT_FAILURE; mainLoop(window); free_resources(); return EXIT_SUCCESS; }
29.393822
131
0.678839
[ "render", "object", "solid" ]
a680bf08a433c5ded67e3821cb1c89233219b028
5,194
cpp
C++
program/fullyconnected-armcl-opencl-uint8/fullyconnected.cpp
hanwenzhu/ck-mlops
d9219e968222abebaf2c9634e779a1029c2da8b5
[ "Apache-2.0" ]
8
2020-11-10T12:18:06.000Z
2021-02-02T10:13:32.000Z
program/fullyconnected-armcl-opencl-uint8/fullyconnected.cpp
hanwenzhu/ck-mlops
d9219e968222abebaf2c9634e779a1029c2da8b5
[ "Apache-2.0" ]
7
2021-09-17T05:19:19.000Z
2022-03-30T11:38:50.000Z
program/fullyconnected-armcl-opencl-uint8/fullyconnected.cpp
hanwenzhu/ck-mlops
d9219e968222abebaf2c9634e779a1029c2da8b5
[ "Apache-2.0" ]
4
2021-09-17T03:51:26.000Z
2022-01-06T12:17:20.000Z
/* * Copyright (c) 2017 cTuning foundation. * See CK COPYRIGHT.txt for copyright details. * * See CK LICENSE for licensing details. * See CK COPYRIGHT for copyright details. */ #include <arm_compute/runtime/CL/functions/CLFullyConnectedLayer.h> #include "ck_nntest_armcl.h" using namespace CK; using namespace CK::armcl; using namespace arm_compute; int main() { init_test(); init_armcl(); Shape in_shape = get_input_shape_from_env(); bool transpose_weights = getenv_i("CK_TRANSPOSE_WEIGHTS", 0); bool are_weights_reshaped = getenv_i("CK_WEIGHTS_RESHAPED", 0); CK::Shape out_shape; out_shape.num = in_shape.num; out_shape.height = getenv_i("CK_OUT_SHAPE_H", 1); out_shape.width = getenv_i("CK_OUT_SHAPE_W", 1); out_shape.channels = getenv_i("CK_OUT_SHAPE_C", 1); const size_t batch_count = in_shape.num; const size_t in_batch_size = in_shape.channels * in_shape.height * in_shape.width; const size_t out_batch_size = out_shape.channels * out_shape.height * out_shape.width; CLFullyConnectedLayer layer; CLTensor input, output; CLTensor weights; CLTensor biases; measure_setup([&]() { // Init input tensor TensorShape native_in_shape(in_batch_size, batch_count); TensorInfo in_tensor_info(native_in_shape, 1, DataType::QASYMM8); float in_data_min = 0; float in_data_max = 1; init_quantization_info(in_tensor_info, in_data_min, in_data_max); print_quantization_info_info("input", in_tensor_info); input.allocator()->init(in_tensor_info); // Init weights tensor TensorShape native_weights_shape = transpose_weights ? TensorShape(in_batch_size, out_batch_size) : TensorShape(out_batch_size, in_batch_size); TensorInfo weights_tensor_info(native_weights_shape, 1, DataType::QASYMM8); float weight_min = 0; float weight_max = 1; init_quantization_info(weights_tensor_info, weight_min, weight_max); print_quantization_info_info("weights", weights_tensor_info); weights.allocator()->init(weights_tensor_info); auto input_product_scale = in_tensor_info.quantization_info().scale * weights_tensor_info.quantization_info().scale; // Init biases tensor TensorShape native_biases_shape(out_batch_size); TensorInfo biases_tensor_info(native_biases_shape, 1, DataType::S32); float bias_min = 0; float bias_max = 1.0 / 255.0; init_quantization_info(biases_tensor_info, bias_min, bias_max); print_quantization_info_info("biases", biases_tensor_info); biases.allocator()->init(biases_tensor_info); // Init output tensor TensorShape native_out_shape(out_batch_size, batch_count); TensorInfo out_tensor_info(native_out_shape, 1, DataType::QASYMM8); out_tensor_info.set_quantization_info(QuantizationInfo(input_product_scale * 1.001, 0)); print_quantization_info_info("output", out_tensor_info); output.allocator()->init(out_tensor_info); // Configure layer try { layer.configure(&input, &weights, &biases, &output, transpose_weights, are_weights_reshaped); print_tensor_shape("Configured CL shape", &output); } catch (const cl::Error &err) { printf("ArmCL exception while configure:\nwhat=%s\nerr_code=%d\n", err.what(), err.err()); abort(); } // Allocate tensors input.allocator()->allocate(); weights.allocator()->allocate(); biases.allocator()->allocate(); output.allocator()->allocate(); // Fill input data uint8_t *in_data = get_random_raw_data<uint8_t>(in_shape, 0, 50); print_input_raw_data(in_data, in_shape); copy_raw_data_to_tensor(&input, in_data, in_shape.data_count()); print_tensor_data("ArmCL native input", &input); delete[] in_data; // Fill weights data uint8_t weights_value = getenv_i("CK_IN_WEIGHTS_CONST_VALUE", 1); uint8_t *weights_data = get_const_raw_data<uint8_t>(native_weights_shape.total_size(), weights_value); copy_raw_data_to_tensor(&weights, weights_data, native_weights_shape.total_size()); delete[] weights_data; // Fill biases data int32_t biases_value = getenv_i("CK_IN_BIAS_CONST_VALUE", 0); int32_t *biases_data = get_const_raw_data<int32_t>(native_biases_shape.total_size(), biases_value); copy_raw_data_to_tensor(&biases, biases_data, native_biases_shape.total_size()); delete[] biases_data; }); measure_test([&]() { try { layer.run(); } catch (const cl::Error &err) { printf("ArmCL exception while run:\nwhat=%s\nerr_code=%d\n", err.what(), err.err()); abort(); } // Make sure all the OpenCL jobs are done executing CLScheduler::get().sync(); }); // Get and process output data print_tensor_data("ArmCL native output", &output); uint8_t *out_data = new uint8_t[out_shape.data_count()]; copy_raw_data_from_tensor(&output, out_data, out_shape.data_count()); print_output_raw_data(out_data, out_shape); dump_output_raw_data(out_data, out_shape); delete[] out_data; input.allocator()->free(); weights.allocator()->free(); biases.allocator()->free(); output.allocator()->free(); finish_test(); return 0; }
35.82069
120
0.719869
[ "shape" ]
a681346aa628686073e92b14535fdd1aa68bf034
1,587
cpp
C++
Game/Source/DeathScreen.cpp
KuronoaScarlet/PlatformerGame
94577751f1d029454c9b6c0ec5e1b30f17520188
[ "MIT" ]
null
null
null
Game/Source/DeathScreen.cpp
KuronoaScarlet/PlatformerGame
94577751f1d029454c9b6c0ec5e1b30f17520188
[ "MIT" ]
null
null
null
Game/Source/DeathScreen.cpp
KuronoaScarlet/PlatformerGame
94577751f1d029454c9b6c0ec5e1b30f17520188
[ "MIT" ]
null
null
null
#include "App.h" #include "Input.h" #include "Textures.h" #include "Audio.h" #include "Render.h" #include "Window.h" #include "Collisions.h" #include "Map.h" #include "Animation.h" #include "DeathScreen.h" #include "Scene1.h" #include "Scene2.h" #include "FadeToBlack.h" #include "EntityManager.h" #include "Defs.h" #include "Log.h" DeathScreen::DeathScreen() : Module() { name.Create("deathscreen"); } DeathScreen::~DeathScreen() { } bool DeathScreen::Awake() { LOG("Loading Screens"); bool ret = true; return ret; } // Load assets bool DeathScreen::Start() { LOG("Loading Screens assets"); bool ret = true; screen = app->tex->Load("Assets/Textures/death_screen.png"); app->audio->PlayMusic("Assets/Audio/Music/death_scene_music.ogg"); timer = 0; trans = true; return ret; } bool DeathScreen::PreUpdate() { return true; } bool DeathScreen::Update(float dt) { timer += dt; return true; } // Update: draw background bool DeathScreen::PostUpdate() { bool ret = true; // Draw everything -------------------------------------- app->render->camera.x = 0; app->render->camera.y = 0; if (app->input->GetKey(SDL_SCANCODE_SPACE) == KEY_DOWN) { app->entityManager->playerData.lives = 3; app->fade->Fade(this, (Module*)app->intro, 1); } app->render->DrawTexture(screen, 0, 0, NULL); return ret; } bool DeathScreen::CleanUp() { if (!active)return true; LOG("Freeing intro"); app->deathScreen->active = false; app->tex->UnLoad(screen); return true; }
17.633333
70
0.621928
[ "render" ]
a681ffe062c49af82314816b9be5fd3a764f5fe7
904
cpp
C++
game/src/Cub.cpp
speedy0/SoldierNo1296
bd379e9e21d6bab585c2b68c43016a1e5b6ffc59
[ "MIT" ]
null
null
null
game/src/Cub.cpp
speedy0/SoldierNo1296
bd379e9e21d6bab585c2b68c43016a1e5b6ffc59
[ "MIT" ]
null
null
null
game/src/Cub.cpp
speedy0/SoldierNo1296
bd379e9e21d6bab585c2b68c43016a1e5b6ffc59
[ "MIT" ]
null
null
null
#pragma once #include "pch.h" #include "Cub.h" Cub::Cub(glm::vec2 half_ex) : m_half_ext(half_ex){ std::vector<engine::mesh::vertex> Cub_vertices { //Creation of the Cub's vertices also known as Quad in the lab. //Position normals Texture Coordinates { {-1.f * m_half_ext.x, -1.f * m_half_ext.y, 0.0f }, { 0.0f, 0.0f, -1.0f }, { 0.f, 0.f } }, { { 1.f * m_half_ext.x, -1.f * m_half_ext.y, 0.0f }, { 0.0f, 0.0f, -1.0f }, { 1.f, 0.f } }, { { 1.f * m_half_ext.x, 1.f * m_half_ext.y, 0.0f }, { 0.0f, 0.0f, -1.0f }, { 1.f, 1.f } }, { {-1.f * m_half_ext.x, 1.f * m_half_ext.y, 0.0f }, { 0.0f, 0.0f, -1.0f }, { 0.f, 1.f } }, }; const std::vector<uint32_t> Cub_indices{ 0,1,2, 0,2,3, }; m_cub = engine::mesh::create(Cub_vertices, Cub_indices); } Cub::~Cub() {} engine::ref<Cub> Cub::create(glm::vec2 half_ext){ return std::make_shared<Cub>(half_ext); }
32.285714
97
0.565265
[ "mesh", "vector" ]
a6875d19ef4bbfb7a5168f864fced99e901bbf91
4,431
cpp
C++
src/state_manager.cpp
BadOPCode/Oblivion2-XRM
d65d9aa4b8021fc3b50b2c09edd0b19eb7baa1b9
[ "Zlib" ]
78
2015-10-08T07:14:37.000Z
2022-02-10T04:51:21.000Z
src/state_manager.cpp
BadOPCode/Oblivion2-XRM
d65d9aa4b8021fc3b50b2c09edd0b19eb7baa1b9
[ "Zlib" ]
117
2015-12-14T16:51:42.000Z
2020-02-16T07:00:36.000Z
src/state_manager.cpp
BadOPCode/Oblivion2-XRM
d65d9aa4b8021fc3b50b2c09edd0b19eb7baa1b9
[ "Zlib" ]
10
2015-12-10T16:54:24.000Z
2022-02-10T04:51:29.000Z
#include "state_manager.hpp" #include "logging.hpp" #include "utf-cpp/utf8.h" #include <cstring> #include <string> /** * @brief Removed the Current State from the session */ void StateManager::clean() { if(!m_the_state.empty()) { m_the_state.back()->onExit(); while(m_the_state.size() > 0) { m_the_state.pop_back(); } m_the_state.clear(); } } /** * @brief Parses Incoming Strings, Sepeates into single character * strings of single ASCII charactrs or UTF-8 multi-byte sequence * * Each Code point is a individual UTF8 Character * which is copied from code_point to char[5] array. */ void StateManager::update() { std::string new_string_builder = ""; bool utf_found = false; if(!m_the_state.empty()) { std::string incoming_data = std::move(m_the_state.back()->m_session_data->m_parsed_data); if(incoming_data.size() > 0) { std::string::iterator it = incoming_data.begin(); std::string::iterator line_end = incoming_data.end(); /** * This loops a string, each next should be a single character code point. */ while(it != line_end) { int byte_value = static_cast<int>((uint8_t)*it); if(byte_value < 128) { utf_found = false; *it++; // Only if ESC and next char is empty // Then we want to pass both to registed single ESC hit if(byte_value == '\x1b' && *it == '\0') { new_string_builder += '\x1b'; m_the_state.back()->update(new_string_builder, utf_found); new_string_builder = '\0'; m_the_state.back()->update(new_string_builder, utf_found); new_string_builder.erase(); continue; } new_string_builder += std::string(1, byte_value); } else { try { // Only gets here on multi-byte sequences. uint32_t code_point = utf8::next(it, line_end); unsigned char character[5] = {0, 0, 0, 0, 0}; utf8::append(code_point, character); for(int i = 0; i < 5; i++) { if(character[i] != 0) { new_string_builder += std::string(1, character[i]); } } utf_found = true; } catch(utf8::exception &ex) { Logging *log = Logging::instance(); log->xrmLog<Logging::ERROR_LOG>("Utf8 Parsing Exception=", ex.what(), __LINE__, __FILE__); } } m_the_state.back()->update(new_string_builder, utf_found); new_string_builder.erase(); } } } } /** * @brief Appends a new state then run the onEnter() */ void StateManager::pushState(state_ptr &the_state) { m_the_state.push_back(the_state); m_the_state.back()->onEnter(); } /** * @brief Runs onExit(), Then Removes the Last Added State. */ void StateManager::popState() { if(!m_the_state.empty()) { m_the_state.back()->onExit(); m_the_state.pop_back(); } m_the_state.back()->resume(); } /** * @brief Main Entertrance for Adding, Switching to new States. */ void StateManager::changeState(state_ptr &the_state) { if(!m_the_state.empty()) { if(m_the_state.back()->getStateID() == the_state->getStateID()) { return; // do nothing } m_the_state.back()->onExit(); // Rework this lateron, lets allow multiple states,, the most recent state will be active // Allowing the main state to keep all information! m_the_state.pop_back(); // Clear the Memory! std::vector<state_ptr>().swap(m_the_state); } // initialize it the_state->onEnter(); // push back our new state m_the_state.push_back(the_state); }
28.044304
114
0.501693
[ "vector" ]
a68766cdec77ffb3deee91fa20f63afedb6a5114
7,683
cpp
C++
init/init_ghost.cpp
ZephyrOS-Devices/device_motorola_ghost
c9c9f5e26c04d590f412fb113db01b4f6eed2279
[ "FTL", "Xnet", "X11" ]
22
2015-01-17T08:53:32.000Z
2020-11-14T20:44:59.000Z
init/init_ghost.cpp
AICP/device_motorola_ghost
1f18283418347c04c3d5963a483107fc0578ede7
[ "FTL", "Xnet", "X11" ]
1
2016-05-31T18:07:12.000Z
2016-05-31T18:20:13.000Z
init/init_ghost.cpp
AICP/device_motorola_ghost
1f18283418347c04c3d5963a483107fc0578ede7
[ "FTL", "Xnet", "X11" ]
82
2015-01-02T03:21:41.000Z
2022-01-03T04:28:34.000Z
/* Copyright (c) 2013, The Linux Foundation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of The Linux Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdlib.h> #include "vendor_init.h" #include "property_service.h" #include "log.h" #include "util.h" #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0])) #define ISMATCH(a, b) (!strncmp((a), (b), PROP_VALUE_MAX)) static void set_cmdline_properties() { size_t i; int rc; char prop[PROP_VALUE_MAX]; struct { const char *src_prop; const char *dest_prop; const char *def_val; } prop_map[] = { { "ro.boot.device", "ro.hw.device", "ghost", }, { "ro.boot.hwrev", "ro.hw.hwrev", "0x8300", }, { "ro.boot.radio", "ro.hw.radio", "0x1", }, }; for (i = 0; i < ARRAY_SIZE(prop_map); i++) { memset(prop, 0, PROP_VALUE_MAX); rc = property_get(prop_map[i].src_prop, prop); if (rc > 0) { property_set(prop_map[i].dest_prop, prop); } else { property_set(prop_map[i].dest_prop, prop_map[i].def_val); } } } static void gsm_properties() { property_set("ro.telephony.default_network", "9"); property_set("telephony.lteOnGsmDevice", "1"); } static void cdma_properties(const char *default_sub, const char *op_numeric, const char *op_alpha) { property_set("ro.telephony.default_cdma_sub", default_sub); property_set("ro.cdma.home.operator.numeric", op_numeric); property_set("ro.cdma.home.operator.alpha", op_alpha); property_set("persist.radio.0x9e_not_callname", "1"); property_set("persist.ril.max.crit.qmi.fails", "4"); property_set("ril.subscription.types", "NV,RUIM"); property_set("ro.cdma.subscribe_on_ruim_ready", "true"); property_set("ro.mot.ignore_csim_appid", "true"); property_set("ro.ril.svdo", "true"); property_set("ro.telephony.default_network", "10"); property_set("telephony.lteOnCdmaDevice", "1"); property_set("telephony.rilV7NeedCDMALTEPhone", "true"); } void vendor_load_properties() { char platform[PROP_VALUE_MAX]; char radio[PROP_VALUE_MAX]; char device[PROP_VALUE_MAX]; char carrier[PROP_VALUE_MAX]; char bootdevice[PROP_VALUE_MAX]; char devicename[PROP_VALUE_MAX]; int rc; rc = property_get("ro.board.platform", platform); if (!rc || !ISMATCH(platform, ANDROID_TARGET)) return; set_cmdline_properties(); property_get("ro.boot.radio", radio); property_get("ro.boot.carrier", carrier); property_get("ro.boot.device", bootdevice); if (ISMATCH(radio, "0x1")) { /* xt1058 */ property_set("ro.product.device", "ghost_retail"); property_set("ro.product.model", "Moto X"); property_set("ro.build.description", "ghost_retail-user 5.1 LPA23.12-15.5 4 release-keys"); property_set("ro.build.fingerprint", "motorola/ghost_retail/ghost:5.1/LPA23.12-15.5/4:user/release-keys"); property_set("ro.build.product", "ghost_retail"); gsm_properties(); } else if (ISMATCH(radio, "0x2")) { /* xt1060 */ property_set("ro.product.device", "ghost_verizon"); property_set("ro.product.model", "Moto X"); property_set("ro.build.description", "ghost_verizon-user 5.1 LPA23.12-39.7 7 release-keys"); property_set("ro.build.fingerprint", "motorola/ghost_verizon/ghost:5.1/LPA23.12-39.7/7:user/release-keys"); property_set("ro.build.product", "ghost_verizon"); property_set("ro.cdma.data_retry_config", "max_retries=infinite,0,0,10000,10000,100000,10000,10000,10000,10000,140000,540000,960000"); property_set("ro.gsm.data_retry_config", "default_randomization=2000,max_retries=infinite,1000,1000,80000,125000,485000,905000"); property_set("ro.gsm.2nd_data_retry_config", "max_retries=1,15000"); property_set("ro.com.google.clientidbase.ms", "android-verizon"); property_set("ro.com.google.clientidbase.am", "android-verizon"); property_set("ro.com.google.clientidbase.yt", "android-verizon"); cdma_properties("0", "311480", "Verizon"); } else if (ISMATCH(radio, "0x3")) { /* xt1052 */ property_set("ro.product.device", "ghost"); property_set("ro.product.model", "Moto X"); property_set("ro.build.description", "ghost_retde-user 5.1 LPA23.12-15.5 3 release-keys"); property_set("ro.build.fingerprint", "motorola/ghost_retde/ghost:5.1/LPA23.12-15.5/3:user/release-keys"); property_set("ro.build.product", "ghost"); gsm_properties(); } else if (ISMATCH(radio, "0x4")) { /* xt1056 */ property_set("ro.product.device", "ghost_sprint"); property_set("ro.product.model", "Moto X"); property_set("ro.build.description", "ghost_sprint-user 5.1 LPA23.12-39.10 11 release-keys"); property_set("ro.build.fingerprint", "motorola/ghost_sprint/ghost:5.1/LPA23.12-39.10/11:user/release-keys"); property_set("ro.build.product", "ghost_sprint"); cdma_properties("1", "310120", "Sprint"); } else if (ISMATCH(radio, "0x5")) { /* xt1055 */ property_set("ro.product.device", "ghost_usc"); property_set("ro.product.model", "Moto X"); property_set("ro.build.description", "ghost_usc-user 5.1 LPA23.12-21-1 1 release-keys"); property_set("ro.build.fingerprint", "motorola/ghost_usc/ghost:5.1/LPA23.12-21-1/1:user/release-keys"); property_set("ro.build.product", "ghost_usc"); cdma_properties("0", "311580", "U.S.Cellular"); } else if (ISMATCH(radio, "0x6")) { /* xt1053 */ property_set("ro.product.device", "ghost_retail"); property_set("ro.product.model", "Moto X"); property_set("ro.build.description", "ghost_retail-user 5.1 LPA23.12-15.5 4 release-keys"); property_set("ro.build.fingerprint", "motorola/ghost_retail/ghost:5.1/LPA23.12-15.5/4:user/release-keys"); property_set("ro.build.product", "ghost_retail"); gsm_properties(); } property_get("ro.product.device", device); strlcpy(devicename, device, sizeof(devicename)); INFO("Found device: %s radio id: %s carrier: %s Setting build properties for %s device\n", bootdevice, radio, carrier, devicename); }
44.668605
142
0.677079
[ "model" ]
a68bfeae6e0590f160638433e440b02af01bc381
1,603
cpp
C++
cppcheck/data/c_files/431.cpp
awsm-research/LineVul
246baf18c1932094564a10c9b81efb21914b2978
[ "MIT" ]
2
2022-03-23T12:16:20.000Z
2022-03-31T06:19:40.000Z
cppcheck/data/c_files/431.cpp
awsm-research/LineVul
246baf18c1932094564a10c9b81efb21914b2978
[ "MIT" ]
null
null
null
cppcheck/data/c_files/431.cpp
awsm-research/LineVul
246baf18c1932094564a10c9b81efb21914b2978
[ "MIT" ]
null
null
null
static zval *xml_call_handler(xml_parser *parser, zval *handler, zend_function *function_ptr, int argc, zval **argv) { int i; TSRMLS_FETCH(); if (parser && handler && !EG(exception)) { zval ***args; zval *retval; int result; zend_fcall_info fci; args = safe_emalloc(sizeof(zval **), argc, 0); for (i = 0; i < argc; i++) { args[i] = &argv[i]; } fci.size = sizeof(fci); fci.function_table = EG(function_table); fci.function_name = handler; fci.symbol_table = NULL; fci.object_ptr = parser->object; fci.retval_ptr_ptr = &retval; fci.param_count = argc; fci.params = args; fci.no_separation = 0; /*fci.function_handler_cache = &function_ptr;*/ result = zend_call_function(&fci, NULL TSRMLS_CC); if (result == FAILURE) { zval **method; zval **obj; if (Z_TYPE_P(handler) == IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler %s()", Z_STRVAL_P(handler)); } else if (zend_hash_index_find(Z_ARRVAL_P(handler), 0, (void **) &obj) == SUCCESS && zend_hash_index_find(Z_ARRVAL_P(handler), 1, (void **) &method) == SUCCESS && Z_TYPE_PP(obj) == IS_OBJECT && Z_TYPE_PP(method) == IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler %s::%s()", Z_OBJCE_PP(obj)->name, Z_STRVAL_PP(method)); } else php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler"); } for (i = 0; i < argc; i++) { zval_ptr_dtor(args[i]); } efree(args); if (result == FAILURE) { return NULL; } else { return EG(exception) ? NULL : retval; } } else { for (i = 0; i < argc; i++) { zval_ptr_dtor(&argv[i]); } return NULL; } }
26.278689
123
0.672489
[ "object" ]
a68f09cfe2504236e5e30c70a9c1bd0668858e17
4,282
hpp
C++
lib/ROVI/src/Common/LED/Effects/RunningOnOff.hpp
DanielRother/ROVI
f036148f1ae379bfb319a146eb620ce72a7fec70
[ "MIT" ]
null
null
null
lib/ROVI/src/Common/LED/Effects/RunningOnOff.hpp
DanielRother/ROVI
f036148f1ae379bfb319a146eb620ce72a7fec70
[ "MIT" ]
null
null
null
lib/ROVI/src/Common/LED/Effects/RunningOnOff.hpp
DanielRother/ROVI
f036148f1ae379bfb319a146eb620ce72a7fec70
[ "MIT" ]
null
null
null
#ifndef __LEDEFFECT_RUNNING_ONOFF__ #define __LEDEFFECT_RUNNING_ONOFF__ #include "../LEDEffect.hpp" #include <iostream> #include <algorithm> #include <vector> namespace Rovi { class RunningOnOff : public LEDEffect { public: enum class ColorModes { SINGLE, MULTI, RAINBOW, TWO_COLOR }; enum class PositionModes { LINEAR, RANDOM, MIDDLE_TO_OUT, OUT_TO_MIDDLE }; RunningOnOff(ColorModes colorMode, PositionModes positionMode, Components::LEDComponent* led, uint32_t delay_ms = 100) : LEDEffect(led, delay_ms) , colorMode(colorMode) , positionMode(positionMode) , currentPosition(0) , currentStartHue(0) , secondColorHue(180) , isTurningOn(true) , positions() { m_name = std::string{"runningFilling"}; std::cout << "RunningOnOff - delay: " << delay_ms << std::endl; } void step() { if(!led->isAdressable()) { std::cout << "Effect not available for this kind of led" << std::endl; return; } auto nbPixel = led->nbPixel(); if(positions.size() != nbPixel) { positions.resize(nbPixel); for(uint32_t pos = 0; pos <= nbPixel; ++pos) { positions[pos] = pos; } if(positionMode == PositionModes::RANDOM) { std::random_shuffle ( positions.begin(), positions.end() ); } } uint32_t currentHue; switch (colorMode) { case ColorModes::SINGLE: { std::cout << "colorMode: " << "SINGLE" << std::endl; currentHue = currentStartHue; break; } case ColorModes::MULTI: { std::cout << "colorMode: " << "MULTI" << std::endl; currentHue = random(360); break; } case ColorModes::RAINBOW: { std::cout << "colorMode: " << "RAINBOW" << std::endl; auto hueIncrement = 360.0f / (float) nbPixel; currentHue = (int32_t) ((float) currentStartHue + positions[currentPosition] * hueIncrement ) % 360; break; } case ColorModes::TWO_COLOR: { std::cout << "colorMode: " << "TWO_COLOR" << std::endl; currentHue = currentStartHue; break; } } std::cout << "pixel = " << currentPosition << "/" << nbPixel << ", position = " << positions[currentPosition] << ", isTurningOn = " << isTurningOn << ", hue = " << currentHue << std::endl; if(isTurningOn) { led->setColor(std::make_shared<HSVColor>(currentHue, 1.0f, 1.0f), positions[currentPosition]); } else { if(colorMode != ColorModes::TWO_COLOR) { led->setColor(std::make_shared<HSVColor>(currentHue, 1.0f, 0.0f), positions[currentPosition]); } else { std::cout << "Set second color instead of off" << std::endl; led->setColor(std::make_shared<HSVColor>(secondColorHue, 1.0f, 1.0f), positions[currentPosition]); } } led->show(); currentPosition = (currentPosition + 1) % nbPixel; if(currentPosition == 0) { isTurningOn = !isTurningOn; currentStartHue = random(360); secondColorHue = random(360); if(positionMode == PositionModes::RANDOM) { std::random_shuffle ( positions.begin(), positions.end() ); } } } protected: ColorModes colorMode; PositionModes positionMode; uint32_t currentPosition; uint32_t currentStartHue; uint32_t secondColorHue; bool isTurningOn; std::vector<uint32_t> positions; }; } #endif /* __LEDEFFECT_RUNNING_ONOFF__ */
33.984127
200
0.492527
[ "vector" ]
a69848ad33e66d049ba9a8f7a2f1fc14fdaf869a
6,045
hpp
C++
include/eggs/tupleware/detail/invoke.hpp
eggs-cpp/tupleware
ae54a7a82b1a3160680c069036ab3c3e1fc7cf8a
[ "BSL-1.0" ]
8
2015-04-01T12:58:31.000Z
2021-03-05T07:00:36.000Z
include/eggs/tupleware/detail/invoke.hpp
eggs-cpp/tupleware
ae54a7a82b1a3160680c069036ab3c3e1fc7cf8a
[ "BSL-1.0" ]
null
null
null
include/eggs/tupleware/detail/invoke.hpp
eggs-cpp/tupleware
ae54a7a82b1a3160680c069036ab3c3e1fc7cf8a
[ "BSL-1.0" ]
null
null
null
//! \file eggs/tupleware/detail/invoke.hpp // Eggs.Tupleware // // Copyright Agustin K-ballo Berge, Fusion Fenix 2014 // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef EGGS_TUPLEWARE_DETAIL_INVOKE_HPP #define EGGS_TUPLEWARE_DETAIL_INVOKE_HPP #include <eggs/tupleware/core.hpp> #include <eggs/tupleware/detail/at.hpp> #include <eggs/tupleware/detail/is_tuple.hpp> #include <cstddef> #include <type_traits> #include <utility> //! \cond DETAIL namespace eggs { namespace tupleware { namespace detail { namespace meta { template < typename T, typename Args , typename Enable = void > struct invoke : identity<T> {}; template <typename Function, typename ...Args> struct invoke<function<Function>, pack<Args...>> : function<Function>::template apply<Args...> {}; template <typename ...Args> struct invoke<placeholder<0>, pack<Args...>>; template <std::size_t I, typename ...Args> struct invoke<placeholder<I>, pack<Args...>> : at<I - 1, std::tuple<Args...>> {}; template < template <typename...> class Template, typename ...T , typename ...Args > struct invoke< Template<T...>, pack<Args...> , typename std::enable_if< is_placeholder_expression<Template<T...>>::value >::type > : Template<typename invoke<T, pack<Args...>>::type...> {}; template < template <typename...> class Template, typename ...T , typename ...Args > struct invoke< Template<T...>, pack<Args...> , typename std::enable_if< !is_placeholder_expression<Template<T...>>::value >::type > : identity<Template<T...>> {}; } /////////////////////////////////////////////////////////////////////////// template <typename F, typename ...Args> void invoke_overload(F const&, Args const&...); template <typename F, typename Tuple> expand_tuple_t invoke_overload(F const&, expand_tuple_t, Tuple const&); /////////////////////////////////////////////////////////////////////////// //! (t1.*f)(t2, ..., tN) when f is a pointer to a member function of a //! class T and t1 is an object of type T or a reference to an object //! of type T or a reference to an object of a type derived from T; template <typename F, typename Arg0, typename ...Args> constexpr auto invoke_impl(F&& f, Arg0&& arg0, Args&&... args) EGGS_TUPLEWARE_AUTO_RETURN( (std::forward<Arg0>(arg0).*std::forward<F>(f))( std::forward<Args>(args)...) ) //! ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of //! a class T and t1 is not one of the types described in the previous //! item; template <typename F, typename Arg0, typename ...Args> constexpr auto invoke_impl(F&& f, Arg0&& arg0, Args&&... args) EGGS_TUPLEWARE_AUTO_RETURN( ((*std::forward<Arg0>(arg0)).*std::forward<F>(f))( std::forward<Args>(args)...) ) //! t1.*f when N == 1 and f is a pointer to member data of a class T //! and t1 is an object of type T or a reference to an object of type T //! or a reference to an object of a type derived from T; template <typename F, typename Arg0> constexpr auto invoke_impl(F&& f, Arg0&& arg0) EGGS_TUPLEWARE_AUTO_RETURN( std::forward<Arg0>(arg0).*std::forward<F>(f) ) //! (*t1).*f when N == 1 and f is a pointer to member data of a class T //! and t1 is not one of the types described in the previous item; template <typename F, typename Arg0> constexpr auto invoke_impl(F&& f, Arg0&& arg0) EGGS_TUPLEWARE_AUTO_RETURN( (*std::forward<Arg0>(arg0)).*std::forward<F>(f) ) //! f(t1, t2, ..., tN) in all other cases. template <typename F, typename ...Args> constexpr auto invoke_impl(F&& f, Args&&... args) EGGS_TUPLEWARE_AUTO_RETURN( std::forward<F>(f)(std::forward<Args>(args)...) ) template < std::size_t ...Is , typename F, typename Tuple > constexpr auto invoke_expand_impl( index_sequence<Is...> , F&& f, Tuple&& tuple) EGGS_TUPLEWARE_AUTO_RETURN( invoke_impl( std::forward<F>(f) , at(meta::size_t<Is>{}, std::forward<Tuple>(tuple))...) ) /////////////////////////////////////////////////////////////////////////// template < typename F, typename ...Args , typename Enable = typename std::enable_if< !std::is_same< decltype(invoke_overload( std::declval<F>(), std::declval<Args>()...)) , expand_tuple_t >::value >::type > constexpr auto invoke(F&& f, Args&&... args) EGGS_TUPLEWARE_AUTO_RETURN( invoke_impl(std::forward<F>(f), std::forward<Args>(args)...) ) template <typename F, typename Tuple> constexpr auto invoke(F&& f, expand_tuple_t, Tuple&& tuple) EGGS_TUPLEWARE_AUTO_RETURN( invoke_expand_impl( index_sequence_for_tuple<Tuple>{} , std::forward<F>(f), std::forward<Tuple>(tuple)) ) /////////////////////////////////////////////////////////////////////// EGGS_TUPLEWARE_RESULT_OF( _result_of_invoke , ::eggs::tupleware::detail::invoke ); /////////////////////////////////////////////////////////////////////// template <typename F, typename ...Args> void _explain_invoke(F&& /*f*/, Args&&... /*args*/) { static_assert( inject_context< _result_of_invoke<F, Args...> >::value , "ill-formed invoke expression"); } }}} //! \endcond #endif /*EGGS_TUPLEWARE_DETAIL_INVOKE_HPP*/
33.39779
79
0.547064
[ "object" ]
a69a7c9c3b755c2c3dacd041ee28a3f2a7bfab55
5,269
hh
C++
k.hh
Kervius/ktr
c4f5b28bca6f153318369d4b1d8b3539a1171ba9
[ "MIT" ]
null
null
null
k.hh
Kervius/ktr
c4f5b28bca6f153318369d4b1d8b3539a1171ba9
[ "MIT" ]
null
null
null
k.hh
Kervius/ktr
c4f5b28bca6f153318369d4b1d8b3539a1171ba9
[ "MIT" ]
null
null
null
#ifndef K__________ #define K__________ #include <string> #include <vector> #include <set> #include <map> #define KTR_VERSION "v0.0.1" namespace K { struct KOpt { enum Cmd { CMD_NONE, CMD_CHECK, CMD_TEST, CMD_BUILD, CMD_CLEAN, CMD_PRINT, CMD_QUERY, CMD_DUMP, CMD_VERSION, CMD_USAGE, }; enum VerboseLevel { VL_DEAD = 0, VL_SILENT = 1, VL_INFO = 2, VL_TRACE = 3, VL_DEBUG = 4, }; Cmd command; bool check; bool force; int jobs; int verbose_level; std::vector<std::string> targets; std::string kfile; std::string kpart; KOpt() : command(CMD_NONE), check(true), force(false), jobs(1), verbose_level(VL_INFO) { kfile = "kfile"; kpart = "kpart"; } }; }; namespace K { struct Env; struct RuleInvoc; struct KFile; } typedef std::set<std::string> StringSetType; typedef std::vector<std::string> StringVecType; typedef std::vector<K::RuleInvoc *> RuleInvocVecType; void strvec_dump( FILE *f, const char *prefix, const StringVecType &v ); void strvec_dump_sl( FILE *f, const char *delim, const StringVecType &v ); std::string env_expand( const K::Env *env, const std::string &str ); void env_expand( const K::Env *env, StringVecType &v ); namespace K { struct Env { Env *parent; typedef std::map<std::string, std::string> items_type; items_type items; Env( Env *elder = NULL ) : parent(elder) { } void set( const std::string &n, const std::string &v ) { items[n] = v; }; const std::string& get( const std::string &n ) const { return items.at(n); }; std::string getd( const std::string &n, const std::string &def = std::string()) const { items_type::const_iterator p = items.find( n ); if (p != items.end()) return p->second; else if (parent) return parent->getd( n, def ); else return def; } void dump( FILE *f ) const { items_type::const_iterator II, EE; II = items.begin(); EE = items.end(); for ( ;II != EE; ++II) { fprintf( f, "var %s=%s\n", II->first.c_str(), II->second.c_str() ); } } std::string exp( const std::string &s ) const { return env_expand( this, s ); } }; struct RuleDef { enum ParamType{ RD_P_ANY = -1, RD_P_NONE = 0, }; int ptInput; int ptOutput; std::string command; std::string name; void dump( FILE *f ) const { char iii[16], ooo[16]; if (ptInput == RD_P_ANY) snprintf( iii, sizeof(iii), "%s", "any" ); else snprintf( iii, sizeof(iii), "%d", ptInput ); if (ptOutput == RD_P_ANY) snprintf( ooo, sizeof(ooo), "%s", "any" ); else snprintf( ooo, sizeof(ooo), "%d", ptOutput ); fprintf( f, "rule %s i=(%s) o=(%s) c=(%s)\n", name.c_str(), iii, ooo, command.c_str() ); } }; struct RuleInvoc { StringVecType input; StringVecType output; StringVecType deps; std::string rule_name; std::string command; RuleDef *rule; RuleInvoc() : rule(NULL) {} void dump( FILE *f ) const { fprintf( f, "do %s i=(", rule_name.c_str() ); strvec_dump_sl( f, " ", input ); fprintf( f, ") o=(" ); strvec_dump_sl( f, " ", output ); fprintf( f, ") d=(" ); strvec_dump_sl( f, " ", deps ); fprintf( f, ")\n" ); } }; struct KFile { Env env; KFile *parent; std::string basename; std::string dirname; std::string absdirname; std::vector<RuleDef *> rd; RuleInvocVecType ri; StringVecType defaults; StringVecType subdirs; std::vector<KFile *> subparts; KFile() : parent(NULL) {} void set_parent( KFile *p ) { this->parent = p; this->env.parent = p ? &p->env : NULL; } KFile *findsubfile( const std::string &name ) { for (size_t i=0; i<subdirs.size(); i++) if (subdirs[i] == name) return subparts[i]; return NULL; } RuleInvoc *find_ri_output( const std::string &name ) { for (size_t i=0; i<ri.size(); i++) for (size_t j=0; j<ri[i]->output.size(); j++) if (ri[i]->output[j] == name) return ri[i]; return NULL; } bool has_target( const std::string &name ) { return find_ri_output( name ) != NULL; } RuleDef *find_rule_def( const std::string &name ) { for (size_t i=0; i<rd.size(); i++) if (rd[i]->name == name) return rd[i]; if (parent) return parent->find_rule_def( name ); return NULL; } const Env *e() const { return &env; } Env *e() { return &env; } std::string expand_var( const std::string &str ) const { return env_expand( &this->env, str ); } }; struct InvocTree { size_t id; RuleInvoc *ri = NULL; KFile *kf = NULL; std::set<InvocTree *> prereq; std::set<InvocTree *> contrib; size_t prereq_num = 0; size_t pending_num = 0; InvocTree( RuleInvoc *ri_=NULL, KFile *kf_=NULL ) : ri(ri_), kf(kf_) {}; }; typedef std::map< std::string, InvocTree * > OutputMapType; struct InvocMap { std::vector<InvocTree *> tt; OutputMapType om; std::set<std::string> src; }; struct JobQueue { std::set<InvocTree *> visited; std::vector<InvocTree *> queue; std::map<size_t, std::set<K::InvocTree *>> jm; }; struct K { std::string root_dir; KFile *root_kfile; std::map< std::string, KFile * > kfm; InvocMap im; JobQueue jq; }; } int kmain(int argc, char **argv, K::KOpt &opts); void print_usage( FILE *f ); void kfile_dump( K::KFile *kf, FILE *f = NULL ); K::KFile *kfile_load_sub( const std::string &dir, K::KFile *parent ); #endif /* K__________ */
19.371324
90
0.626495
[ "vector" ]
a69bd671c4d181d37c6fc70cb0b466652a8118bb
13,836
cpp
C++
plugins/probe/src/TessellateBoundingBox.cpp
xge/megamol
1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b
[ "BSD-3-Clause" ]
49
2017-08-23T13:24:24.000Z
2022-03-16T09:10:58.000Z
plugins/probe/src/TessellateBoundingBox.cpp
xge/megamol
1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b
[ "BSD-3-Clause" ]
200
2018-07-20T15:18:26.000Z
2022-03-31T11:01:44.000Z
plugins/probe/src/TessellateBoundingBox.cpp
xge/megamol
1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b
[ "BSD-3-Clause" ]
31
2017-07-31T16:19:29.000Z
2022-02-14T23:41:03.000Z
/* * TessellateBoundingBox.h * Copyright (C) 2020 by MegaMol Team * Alle Rechte vorbehalten. */ #include "glm/glm.hpp" #include "TessellateBoundingBox.h" #include "mesh/Utility.h" #include "mmadios/CallADIOSData.h" #include "mmcore/param/FloatParam.h" #include "mmcore/param/IntParam.h" megamol::probe::TessellateBoundingBox::TessellateBoundingBox(void) : AbstractMeshDataSource() , _bounding_box_rhs_slot("adios", "Connect to rendering call to access bounding box") , _x_subdiv_slot("x_subdiv_param", "") , _y_subdiv_slot("y_subdiv_param", "") , _z_subdiv_slot("z_subdiv_param", "") , _padding_slot("padding_param", "") { this->_bounding_box_rhs_slot.SetCompatibleCall<adios::CallADIOSDataDescription>(); this->MakeSlotAvailable(&this->_bounding_box_rhs_slot); this->_x_subdiv_slot << new core::param::IntParam(16); this->MakeSlotAvailable(&this->_x_subdiv_slot); this->_y_subdiv_slot << new core::param::IntParam(16); this->MakeSlotAvailable(&this->_y_subdiv_slot); this->_z_subdiv_slot << new core::param::IntParam(16); this->MakeSlotAvailable(&this->_z_subdiv_slot); this->_padding_slot << new core::param::FloatParam(0.01f); this->MakeSlotAvailable(&this->_padding_slot); } megamol::probe::TessellateBoundingBox::~TessellateBoundingBox(void) { this->Release(); } bool megamol::probe::TessellateBoundingBox::create() { AbstractMeshDataSource::create(); return true; } void megamol::probe::TessellateBoundingBox::release() {} bool megamol::probe::TessellateBoundingBox::InterfaceIsDirty() { return _x_subdiv_slot.IsDirty() || _y_subdiv_slot.IsDirty() || _z_subdiv_slot.IsDirty() || _padding_slot.IsDirty(); } bool megamol::probe::TessellateBoundingBox::getMeshMetaDataCallback(core::Call& call) { auto cm = dynamic_cast<mesh::CallMesh*>(&call); if (cm == nullptr) { return false; } auto meta_data = cm->getMetaData(); adios::CallADIOSData* bboxc = this->_bounding_box_rhs_slot.CallAs<adios::CallADIOSData>(); if (bboxc != nullptr) { bboxc->setFrameIDtoLoad(meta_data.m_frame_ID); if (!(*bboxc)(1)) { return false; } meta_data.m_frame_cnt = bboxc->getFrameCount(); } meta_data.m_bboxs = _bboxs; cm->setMetaData(meta_data); return true; } bool megamol::probe::TessellateBoundingBox::getMeshDataCallback(core::Call& call) { mesh::CallMesh* lhs_mesh_call = dynamic_cast<mesh::CallMesh*>(&call); mesh::CallMesh* rhs_mesh_call = m_mesh_rhs_slot.CallAs<mesh::CallMesh>(); if (lhs_mesh_call == NULL) { return false; } syncMeshAccessCollection(lhs_mesh_call, rhs_mesh_call); // if there is a mesh connection to the right, pass on the mesh collection if (rhs_mesh_call != NULL) { if (!(*rhs_mesh_call)(0)) { return false; } if (rhs_mesh_call->hasUpdate()) { ++_version; rhs_mesh_call->getData(); } } adios::CallADIOSData* bboxc = this->_bounding_box_rhs_slot.CallAs<adios::CallADIOSData>(); if (bboxc != nullptr) { auto something_has_changed = (bboxc->getDataHash() != _old_datahash || InterfaceIsDirty()); if (something_has_changed) { ++_version; _old_datahash = bboxc->getDataHash(); _x_subdiv_slot.ResetDirty(); _y_subdiv_slot.ResetDirty(); _z_subdiv_slot.ResetDirty(); _padding_slot.ResetDirty(); auto meta_data = lhs_mesh_call->getMetaData(); //bboxc->setFrameIDtoLoad(meta_data.m_frame_ID); //if (!(*bboxc)(1)) { // return false; //} auto x_var_str = "x"; auto y_var_str = "y"; auto z_var_str = "z"; std::vector<std::string> toInq; toInq.emplace_back(x_var_str); toInq.emplace_back(y_var_str); toInq.emplace_back(z_var_str); // get data from adios for (auto var : toInq) { if (!bboxc->inquireVar(var)) { return false; } } if (!(*bboxc)(0)) { return false; } // clear mesh data for (int i = 0; i < 6; ++i) { _vertices[i].clear(); _normals[i].clear(); _faces[i].clear(); _probe_index[i].clear(); } clearMeshAccessCollection(); // compute mesh call specific update std::array<float, 6> bbox; bbox[0] = std::numeric_limits<float>::max(); // min x bbox[1] = std::numeric_limits<float>::max(); // min y bbox[2] = std::numeric_limits<float>::max(); // min z bbox[3] = std::numeric_limits<float>::min(); // max x bbox[4] = std::numeric_limits<float>::min(); // max y bbox[5] = std::numeric_limits<float>::min(); // max z if (bboxc->getData(x_var_str)->getType() == "double" && bboxc->getData(y_var_str)->getType() == "double" && bboxc->getData(z_var_str)->getType() == "double") { std::vector<double> data_x = bboxc->getData(x_var_str)->GetAsDouble(); std::vector<double> data_y = bboxc->getData(y_var_str)->GetAsDouble(); std::vector<double> data_z = bboxc->getData(z_var_str)->GetAsDouble(); for (size_t i = 0; i < data_x.size(); ++i) { bbox[0] = std::min(static_cast<float>(data_x[i]), bbox[0]); bbox[1] = std::min(static_cast<float>(data_y[i]), bbox[1]); bbox[2] = std::min(static_cast<float>(data_z[i]), bbox[2]); bbox[3] = std::max(static_cast<float>(data_x[i]), bbox[3]); bbox[4] = std::max(static_cast<float>(data_y[i]), bbox[4]); bbox[5] = std::max(static_cast<float>(data_z[i]), bbox[5]); } } else if (bboxc->getData(x_var_str)->getType() == "float" && bboxc->getData(y_var_str)->getType() == "float" && bboxc->getData(z_var_str)->getType() == "float") { std::vector<float> data_x = bboxc->getData(x_var_str)->GetAsFloat(); std::vector<float> data_y = bboxc->getData(y_var_str)->GetAsFloat(); std::vector<float> data_z = bboxc->getData(z_var_str)->GetAsFloat(); for (size_t i = 0; i < data_x.size(); ++i) { bbox[0] = std::min(data_x[i], bbox[0]); bbox[1] = std::min(data_y[i], bbox[1]); bbox[2] = std::min(data_z[i], bbox[2]); bbox[3] = std::max(data_x[i], bbox[3]); bbox[4] = std::max(data_y[i], bbox[4]); bbox[5] = std::max(data_z[i], bbox[5]); } } // apply additional padding to bounding box bbox[0] -= _padding_slot.Param<megamol::core::param::FloatParam>()->Value(); bbox[1] -= _padding_slot.Param<megamol::core::param::FloatParam>()->Value(); bbox[2] -= _padding_slot.Param<megamol::core::param::FloatParam>()->Value(); bbox[3] += _padding_slot.Param<megamol::core::param::FloatParam>()->Value(); bbox[4] += _padding_slot.Param<megamol::core::param::FloatParam>()->Value(); bbox[5] += _padding_slot.Param<megamol::core::param::FloatParam>()->Value(); _bboxs.SetBoundingBox(bbox[0], bbox[1], bbox[2], bbox[3], bbox[4], bbox[5]); // get bounding box corners glm::vec3 lbb = glm::vec3(bbox[0], bbox[1], bbox[2]); glm::vec3 rbb = glm::vec3(bbox[3], bbox[1], bbox[2]); glm::vec3 rbf = glm::vec3(bbox[3], bbox[1], bbox[5]); glm::vec3 lbf = glm::vec3(bbox[0], bbox[1], bbox[5]); glm::vec3 ltb = glm::vec3(bbox[0], bbox[4], bbox[2]); glm::vec3 rtb = glm::vec3(bbox[3], bbox[4], bbox[2]); glm::vec3 rtf = glm::vec3(bbox[3], bbox[4], bbox[5]); glm::vec3 ltf = glm::vec3(bbox[0], bbox[4], bbox[5]); // tessellate each face using VertexPositions = std::vector<std::array<float, 3>>; using VertexNormals = std::vector<std::array<float, 3>>; using QuadIndices = std::vector<std::array<uint32_t, 4>>; auto x_subdivs = _x_subdiv_slot.Param<megamol::core::param::IntParam>()->Value(); auto y_subdivs = _y_subdiv_slot.Param<megamol::core::param::IntParam>()->Value(); auto z_subdivs = _z_subdiv_slot.Param<megamol::core::param::IntParam>()->Value(); std::tuple<VertexPositions, VertexNormals, QuadIndices> face_xy_back = mesh::utility::tessellateFace(lbb, rbb, rtb, ltb, x_subdivs, y_subdivs); std::tuple<VertexPositions, VertexNormals, QuadIndices> face_xy_front = mesh::utility::tessellateFace(rbf, lbf, ltf, rtf, x_subdivs, y_subdivs); std::tuple<VertexPositions, VertexNormals, QuadIndices> face_zy_right = mesh::utility::tessellateFace(rbb, rbf, rtf, rtb, z_subdivs, y_subdivs); std::tuple<VertexPositions, VertexNormals, QuadIndices> face_zy_left = mesh::utility::tessellateFace(lbf, lbb, ltb, ltf, z_subdivs, y_subdivs); std::tuple<VertexPositions, VertexNormals, QuadIndices> face_xz_top = mesh::utility::tessellateFace(ltf, ltb, rtb, rtf, z_subdivs, x_subdivs); std::tuple<VertexPositions, VertexNormals, QuadIndices> face_xz_bottom = mesh::utility::tessellateFace(lbb, lbf, rbf, rbb, z_subdivs, x_subdivs); // copy to persistent storage _vertices[0] = std::get<0>(face_xy_back); _normals[0] = std::get<1>(face_xy_back); _faces[0] = std::get<2>(face_xy_back); _vertices[1] = std::get<0>(face_xy_front); _normals[1] = std::get<1>(face_xy_front); _faces[1] = std::get<2>(face_xy_front); _vertices[2] = std::get<0>(face_zy_right); _normals[2] = std::get<1>(face_zy_right); _faces[2] = std::get<2>(face_zy_right); _vertices[3] = std::get<0>(face_zy_left); _normals[3] = std::get<1>(face_zy_left); _faces[3] = std::get<2>(face_zy_left); _vertices[4] = std::get<0>(face_xz_top); _normals[4] = std::get<1>(face_xz_top); _faces[4] = std::get<2>(face_xz_top); _vertices[5] = std::get<0>(face_xz_bottom); _normals[5] = std::get<1>(face_xz_bottom); _faces[5] = std::get<2>(face_xz_bottom); // build accessor for this modules mesh data for (int i = 0; i < 6; ++i) { std::vector<mesh::MeshDataAccessCollection::VertexAttribute> mesh_attribs; mesh::MeshDataAccessCollection::IndexData mesh_indices; mesh::MeshDataAccessCollection::PrimitiveType mesh_type; mesh_attribs.resize(3); mesh_attribs[0].component_type = mesh::MeshDataAccessCollection::ValueType::FLOAT; mesh_attribs[0].byte_size = _vertices[i].size() * sizeof(std::array<float, 3>); mesh_attribs[0].component_cnt = 3; mesh_attribs[0].stride = sizeof(std::array<float, 3>); mesh_attribs[0].offset = 0; mesh_attribs[0].data = reinterpret_cast<uint8_t*>(_vertices[i].data()); mesh_attribs[0].semantic = mesh::MeshDataAccessCollection::POSITION; mesh_attribs[1].component_type = mesh::MeshDataAccessCollection::ValueType::FLOAT; mesh_attribs[1].byte_size = _normals[i].size() * sizeof(std::array<float, 3>); mesh_attribs[1].component_cnt = 3; mesh_attribs[1].stride = sizeof(std::array<float, 3>); mesh_attribs[1].offset = 0; mesh_attribs[1].data = reinterpret_cast<uint8_t*>(_normals[i].data()); mesh_attribs[1].semantic = mesh::MeshDataAccessCollection::NORMAL; _probe_index[i].resize(_vertices[i].size(), std::numeric_limits<int>:: max()); // allocate memory for probe ID now, but the acutal data will be written later (by probe placement) mesh_attribs[2].component_type = mesh::MeshDataAccessCollection::ValueType::INT; mesh_attribs[2].byte_size = _probe_index[i].size() * sizeof(int); mesh_attribs[2].component_cnt = 1; mesh_attribs[2].stride = sizeof(int); mesh_attribs[2].offset = 0; mesh_attribs[2].data = reinterpret_cast<uint8_t*>(_probe_index[i].data()); mesh_attribs[2].semantic = mesh::MeshDataAccessCollection::AttributeSemanticType::ID; mesh_indices.type = mesh::MeshDataAccessCollection::ValueType::UNSIGNED_INT; mesh_indices.byte_size = _faces[i].size() * sizeof(std::array<uint32_t, 4>); mesh_indices.data = reinterpret_cast<uint8_t*>(_faces[i].data()); mesh_type = mesh::MeshDataAccessCollection::PrimitiveType::QUADS; std::string identifier = std::string(FullName()) + "_mesh_" + std::to_string(i); m_mesh_access_collection.first->addMesh(identifier, mesh_attribs, mesh_indices, mesh_type); m_mesh_access_collection.second.push_back(identifier); } meta_data.m_bboxs = _bboxs; lhs_mesh_call->setMetaData(meta_data); } } lhs_mesh_call->setData(m_mesh_access_collection.first, _version); return true; }
45.215686
131
0.5829
[ "mesh", "vector" ]
a69fb0c4255396e81aed20f7e1bdb3c1d3d62a4d
21,358
hpp
C++
Source/AllProjects/CommUtils/CIDNet/CIDNet_SMTPClient.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
216
2019-03-09T06:41:28.000Z
2022-02-25T16:27:19.000Z
Source/AllProjects/CommUtils/CIDNet/CIDNet_SMTPClient.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
9
2020-09-27T08:00:52.000Z
2021-07-02T14:27:31.000Z
Source/AllProjects/CommUtils/CIDNet/CIDNet_SMTPClient.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
29
2019-03-09T10:12:24.000Z
2021-03-03T22:25:29.000Z
// // FILE NAME: CIDNet_SMTPClient.hpp // // AUTHOR: Dean Roddey // // CREATED: 01/29/2000 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2019 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This is the header for the CIDNet_SMTPClient.cpp file. This file // implements the TSMTPClient class. This class allows you to do basic client // side SMTP operations, i.e. send mail messages. // // We have a class to represent attachements, one to represent messages to // be sent, and another to represent the SMTP client. // // CAVEATS/GOTCHAS: // // 1) Because of the unfortunate decision that SMTP secure connections are not just // based on target port, we have to do some communciations at the raw level even // if we ultimately end up being secure. So, we need more than one version of // some methods. We have to be able to do EHLO and get a reply in the clear no // matter what. So we use the raw socket to do that. // // Then we set up a data source (secure or not) and do the rest. // // LOG: // // $_CIDLib_Log_$ // #pragma once #pragma CIDLIB_PACK(CIDLIBPACK) // --------------------------------------------------------------------------- // CLASS: TEmailAttachment // PREFIX: eatt // --------------------------------------------------------------------------- class CIDNETEXP TEmailAttachment { public : // ------------------------------------------------------------------- // Constructors and Destructor // ------------------------------------------------------------------- TEmailAttachment(); TEmailAttachment ( const tCIDLib::TCard4 c4BufSz , const TMemBuf& mbufData , const TString& strMIMEType , const TString& strFileName ); TEmailAttachment ( const tCIDLib::TCard4 c4BufSz , THeapBuf&& mbufData , const TString& strMIMEType , const TString& strFileName ); TEmailAttachment ( const TEmailAttachment& eattSrc ); ~TEmailAttachment(); // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- TEmailAttachment& operator= ( const TEmailAttachment& eattSrc ); // ------------------------------------------------------------------- // Public, non-virtual methods // ------------------------------------------------------------------- tCIDLib::TCard4 c4BufSz() const; const TMemBuf& mbufData() const; const TString& strFileName() const; const TString& strMIMEType() const; tCIDLib::TVoid Set ( const tCIDLib::TCard4 c4BufSz , const TMemBuf& mbufData , const TString& strMIMEType , const TString& strFileName ); private : // ------------------------------------------------------------------- // Private data members // // m_c4BufSz // The number of bytes in the attachement buffer. // // m_mbufData // The attachement data. // // m_strFileName // The suggested file name for the attachement, if any // // m_strMIMEType // The type to indicate in the transmitted message for this // attachement. // ------------------------------------------------------------------- tCIDLib::TCard4 m_c4BufSz; THeapBuf m_mbufData; TString m_strFileName; TString m_strMIMEType; }; // --------------------------------------------------------------------------- // CLASS: TEmailMsg // PREFIX: emsg // --------------------------------------------------------------------------- class CIDNETEXP TEmailMsg : public TObject { public : // ------------------------------------------------------------------- // Public class types and constants // ------------------------------------------------------------------- using TCursor = TBasicDLinkedCol<TString>::TCursor; static const tCIDLib::TCard4 c4MaxAttachements = 64; // ------------------------------------------------------------------- // Constructors and Destructor // ------------------------------------------------------------------- TEmailMsg(); TEmailMsg ( const TString& strFrom , const TString& strTo , const TString& strTopic , const TString& strMsg ); TEmailMsg ( const TEmailMsg& emsgSrc ); TEmailMsg ( TEmailMsg&& emsgSrc ); ~TEmailMsg(); // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- TEmailMsg& operator= ( const TEmailMsg& emsgSrc ); TEmailMsg& operator= ( TEmailMsg&& emsgSrc ); // ------------------------------------------------------------------- // Public, non-virtual methods // ------------------------------------------------------------------- tCIDLib::TVoid AddAttachment ( const tCIDLib::TCard4 c4BufSz , const TMemBuf& mbufData , const TString& strMIMEType , const TString& strFileName ); tCIDLib::TVoid AddAttachment ( const tCIDLib::TCard4 c4BufSz , THeapBuf&& mbufData , const TString& strMIMEType , const TString& strFileName ); tCIDLib::TVoid AddFileAttachment ( const TString& strMIMEType , const TString& strFileName ); tCIDLib::TVoid AddCCAddr ( const TString& strToAdd ); tCIDLib::TVoid AddToAddr ( const TString& strToAdd ); tCIDLib::TCard4 c4AttachmentCnt() const; TCursor cursCCList() const; TCursor cursToList() const; const TEmailAttachment& eattAt ( const tCIDLib::TCard4 c4At ) const; tCIDLib::TVoid RemoteAttachmentAt ( const tCIDLib::TCard4 c4At ); const TString& strFrom() const; const TString& strFrom ( const TString& strToSet ); const TString& strMsg() const; const TString& strMsg ( const TString& strToSet ); const TString& strTopic() const; const TString& strTopic ( const TString& strToSet ); private : // ------------------------------------------------------------------- // Private data types // ------------------------------------------------------------------- using TAttachList = TVector<TEmailAttachment>; // ------------------------------------------------------------------- // Private data members // // m_pcolAttachments // A list of attachements, faulted in upon use. It has a max which is // set as a public constant. // // m_pcolCCList // m_pcolToList // A collection of strings that hold the list of primary target // addresses, and the list of 'carbon copy' targets. These are // both lazily faulted in as required. // // m_strFrom // The address that the message is to show as from. // // m_strMsg // This is the message to send. It must be convertable to whatever // out-going encoding is set on the SMTP client object. // // m_strTopic // The topic of the message. // ------------------------------------------------------------------- mutable TAttachList* m_pcolAttachments; mutable tCIDLib::TStrBag* m_pcolCCList; mutable tCIDLib::TStrBag* m_pcolToList; TString m_strFrom; TString m_strMsg; TString m_strTopic; // ------------------------------------------------------------------- // Magic macros // ------------------------------------------------------------------- RTTIDefs(TEmailMsg,TObject) }; // --------------------------------------------------------------------------- // CLASS: TSMTPClient // PREFIX: smtp // --------------------------------------------------------------------------- class CIDNETEXP TSMTPClient : public TObject { public : // ------------------------------------------------------------------- // Constructors and Destructor // ------------------------------------------------------------------- TSMTPClient(); TSMTPClient(const TSMTPClient&) = delete; ~TSMTPClient(); // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- TSMTPClient& operator=(const TSMTPClient&) = delete; // ------------------------------------------------------------------- // Public, non-virtual methods // ------------------------------------------------------------------- tCIDLib::TVoid AddMsgToQueue ( const TEmailMsg& emsgToAdd ); tCIDLib::TVoid AddMsgToQueue ( TEmailMsg&& emsgToAdd ); tCIDLib::TVoid AddMsgToQueue ( const TString& strFrom , const TString& strTo , const TString& strTopic , const TString& strMsg ); tCIDLib::TCard4 c4ColumnWidth() const; tCIDLib::TCard4 c4ColumnWidth ( const tCIDLib::TCard4 c4ToSet ); tCIDLib::TCard4 c4MsgsInQueue() const; tCIDLib::TCard4 c4ReadTimeout() const; tCIDLib::TCard4 c4ReadTimeout ( const tCIDLib::TCard4 c4Millis ); tCIDLib::TVoid ClearQueue(); tCIDNet::EMailAuthTypes eAuthType() const; tCIDNet::EMailAuthTypes eAuthType ( const tCIDNet::EMailAuthTypes eToSet ); tCIDLib::TIPPortNum ippnToUse() const; const TString& strFromDomain() const; const TString& strPassword() const; const TString& strUserName() const; tCIDLib::TVoid SendMsgs ( const tCIDLib::TCard4 c4MaxPerMsgMSs , const tCIDLib::TBoolean bEvenIfEmpty = kCIDLib::False ); tCIDLib::TVoid SetConnInfo ( const TString& strFromDomain , const TString& strTarSrv , const tCIDLib::TIPPortNum ippnTar , const tCIDLib::TBoolean bSecure , const TString& strUser , const TString& strPassword ); tCIDLib::TVoid SetContentType ( const TString& strType , const TString& strEncoding ); private : // ------------------------------------------------------------------- // Private, non-virtual methods // ------------------------------------------------------------------- tCIDLib::TVoid Authenticate ( TCIDDataSrc& cdsSrc , const tCIDLib::TEncodedTime enctEnd ); tCIDLib::TCard4 c4CallMultiResponse ( TCIDDataSrc& cdsSrc , const TString& strCall , const tCIDLib::TEncodedTime enctEnd , const tCIDLib::TCh* const pszFunction , tCIDLib::TStrCollect& colToFill ); tCIDLib::TCard4 c4CallResponse ( TCIDDataSrc& cdsSrc , const TString& strCall , TString& strReply , const tCIDLib::TEncodedTime enctEnd ); tCIDLib::TCard4 c4GetResponse ( TCIDDataSrc& cdsSrc , TString& strReply , const tCIDLib::TEncodedTime enctEnd , const tCIDLib::TCh* const pszFunction ); tCIDLib::TCard4 c4InitConn ( TStreamSocket& sockSrc , const tCIDLib::TEncodedTime enctEnd ); tCIDLib::TCard4 c4ReadRawLine ( TStreamSocket& sockSrc , TString& strToFill , const tCIDLib::TEncodedTime enctEnd , const tCIDLib::TCh* const pszFunction , tCIDLib::TBoolean& bLast ); tCIDLib::TCard4 c4SplitLine ( TString& strOrgLine , TString& strToFill , tCIDLib::TBoolean& bLastLine ); tCIDLib::TVoid ColumnateMsg ( TCIDDataSrc& cdsSrc , const TString& strMsgText , const TString& strTextEncoding , const tCIDLib::TEncodedTime enctEnd ); tCIDLib::TVoid Hello ( TStreamSocket& sockSrc , const tCIDLib::TEncodedTime enctEnd ); tCIDLib::TVoid Hello ( TCIDDataSrc& cdsSrc , const tCIDLib::TEncodedTime enctEnd ); tCIDLib::TVoid OutputAttachments ( TCIDDataSrc& cdsSrc , const TEmailMsg& emsgSrc , const tCIDLib::TEncodedTime enctEnd ); tCIDLib::TVoid QueryServerCaps(); tCIDLib::TVoid Quit ( TCIDDataSrc& cdsSrc , const tCIDLib::TEncodedTime enctEnd ); tCIDLib::TVoid SendAccum ( TCIDDataSrc& cdsSrc , const tCIDLib::TEncodedTime enctEnd ); tCIDLib::TVoid SendAMsg ( TCIDDataSrc& cdsSrc , const TEmailMsg& emsgCur , const tCIDLib::TEncodedTime enctEnd ); tCIDLib::TVoid SendRawLine ( TStreamSocket& sockSrc , const TString& strToSend ); // ------------------------------------------------------------------- // Private data members // // m_bSecure // Indicates if we should use a secure connection or not. If secure, the // client code should have provided the correct port for such. // // m_bSupportsXX // These are flags that are set during the connection to the server. They // are really only valid during the message sending process. // // m_c4ColWidth // This is the width to which the message lines will be formatted on the // way out. It defaults to 68, which is a reasonable width that should // probably be left alone. // // m_c4MaxMsgSize // This is the maximum message size. Its defaulted to a very conservative // value, but can be set if the server supports the message size extension. // // m_eAuthType // The authorization type to use when sending messages. // // m_ippnToUse // This is the port number to use to connect to the server. We default it // to 25, and the caller must set it up otherwise if that's not appropriate. // // m_pcolQueue // This is a pointer to a collection into which added messages are placed // until the SendMsgs() method is called. // // m_strAttachEncoding // The attachements are all Base64 encoded, so we use ASCII as the text // encoding to spit out the Base64 content (when we columnate it.) So we // just pre-set this string for that purpose. // // m_strContEncoding // m_strContType // The msg body content type to indicate in the header. If not set, it is // not indicated so that the server assumes the default. And the associated // text encoding that we should use to generate text in that format. // // m_strFromDomain // This is the domain that the messages are to be indicated as coming from. // // m_strPassword // If authentication is required, then this is the password to send. // // m_strServer // This is the server that is to be connected to. The client code provides // this. // // m_strTmpRead // A temp string used to read in msgs and break them out into status and // text reply. // // m_strmFmt // In some cases we have to format first to a string, because we then need // to format that resulting data with appropriate line length. This is far // easier to do if we format out the text first and then break that text // into appropriate lengths which we then transcode and output. // // m_strmOut // This is used to format out most of the data to send to the other side. // This guy is set up for USASCII, which is fine for the commands we send // to the server and any of the 'meta' text. But it can't be used for the // message body, which can have a separate encoding if we are in a multi- // part e-mail. The body part can be separate encoded. Attachments are // effectively ASCII (base64) but would require duplicating the colunating // stuff in order to use this stream to accumulate the columned lines. So // it's not used for the attachements either. See ColumnateMsg(). // // m_strUserName // If authentication is required, then this is the user name to send. // // m_tmCurrent // There are a couple places during the creating of a message where the // current time is used. So its set here before each message is sent, and // any code that needs it just looks at this guy. // ------------------------------------------------------------------- tCIDLib::TBoolean m_bSecure; tCIDLib::TBoolean m_bSupports8BitMIME; tCIDLib::TBoolean m_bSupportsMsgSize; tCIDLib::TBoolean m_bSupportsPipelining; tCIDLib::TBoolean m_bSupportsTLS; tCIDLib::TCard4 m_c4ColWidth; tCIDLib::TCard4 m_c4MaxMsgSize; tCIDNet::EMailAuthTypes m_eAuthType; tCIDLib::TIPPortNum m_ippnToUse; TQueue<TEmailMsg>* m_pcolQueue; const TString m_strAttachEncoding; TString m_strContEncoding; TString m_strContType; TString m_strFromDomain; TString m_strPassword; TString m_strServer; TString m_strTmpRead; TString m_strUserName; TTextStringOutStream m_strmFmt; TTextMBufOutStream m_strmOut; TTime m_tmCurrent; // ------------------------------------------------------------------- // Magic macros // ------------------------------------------------------------------- RTTIDefs(TSMTPClient,TObject) }; #pragma CIDLIB_POPPACK
33.794304
89
0.437822
[ "object" ]
a6a29b24730dd8aff3711ec762f5a5f322f9b588
141
cpp
C++
Bit Manipulation/Single Number.cpp
torquecoder/InterviewBit-Solutions
7c5e2e5c904c9354f3eb213739a8dd4aaf13b7b2
[ "MIT" ]
null
null
null
Bit Manipulation/Single Number.cpp
torquecoder/InterviewBit-Solutions
7c5e2e5c904c9354f3eb213739a8dd4aaf13b7b2
[ "MIT" ]
null
null
null
Bit Manipulation/Single Number.cpp
torquecoder/InterviewBit-Solutions
7c5e2e5c904c9354f3eb213739a8dd4aaf13b7b2
[ "MIT" ]
null
null
null
int Solution::singleNumber(const vector<int> &A) { int x = 0; for (int i = 0; i < A.size(); i++) x ^= A[i]; return x; }
17.625
50
0.48227
[ "vector" ]
a6a54115161dd2db274aa8f673603e04042e730f
12,114
ipp
C++
src/core/multidim_image_platform/MultiDimImage.ipp
balintfodor/Build3D
b735129e380a414d62a1d91556f5f52674f1f6f9
[ "MIT" ]
null
null
null
src/core/multidim_image_platform/MultiDimImage.ipp
balintfodor/Build3D
b735129e380a414d62a1d91556f5f52674f1f6f9
[ "MIT" ]
5
2021-03-19T09:28:07.000Z
2022-03-12T00:09:14.000Z
src/core/multidim_image_platform/MultiDimImage.ipp
balintfodor/Build3D
b735129e380a414d62a1d91556f5f52674f1f6f9
[ "MIT" ]
1
2019-12-23T16:44:49.000Z
2019-12-23T16:44:49.000Z
template <typename T> MultiDimImage<T>::MultiDimImage(std::vector<std::size_t> dims) : m_dims(dims) { initUtilsFromDim(); std::vector<std::vector<T>> data(m_restSize, std::vector<T>(m_planeSize, T())); m_planes = std::move(data); m_type = GetType<T>(); } template <typename T> void MultiDimImage<T>::initUtilsFromDim() { int i = 0; std::size_t prodPlane = 1, prodRest = 1; for (std::size_t x : m_dims) { if (i < 2) { m_planeDims.push_back(x); m_planeDimsProducts.push_back(prodPlane); prodPlane *= x; } else { m_restDims.push_back(x); m_restDimsProducts.push_back(prodRest); prodRest *= x; } i++; } if (m_planeDims.empty()) { m_planeSize = 0; } else { m_planeSize = prodPlane; } if (m_restDims.empty() && m_planeDims.empty()) { m_restSize = 0; } else { m_restSize = prodRest; } } template <typename T> template <typename U> void MultiDimImage<T>::transformCopy(const MultiDimImage<U>& other, std::function<T(const U&)> unary) { MultiDimImage<T> newImage; newImage.m_dims = other.m_dims; newImage.initUtilsFromDim(); newImage.m_planes.reserve(newImage.m_restSize); auto itEnd = other.m_planes.end(); for (auto it = other.m_planes.begin(); it != itEnd; ++it) { newImage.m_planes.push_back(std::vector<T>()); auto& plane = newImage.m_planes.back(); plane.reserve(newImage.m_planeSize); std::transform(it->begin(), it->end(), std::back_inserter(plane), unary); } *this = std::move(newImage); } template <typename T> template <typename U> void MultiDimImage<T>::convertCopyFrom(const MultiDimImage<U>& other) { std::function<T(const U&)> f = [](const U& x) -> T { return static_cast<T>(x); }; transformCopy(other, f); } template <typename T> template <typename U> void MultiDimImage<T>::saturateCopyFrom(const MultiDimImage<U>& other, T minValue, T maxValue) { std::function<T(const U&)> f = [minValue, maxValue](const U& x) -> T { return detail::SafeLessThanCompare<T, U>::less(maxValue, x) ? maxValue : (detail::SafeLessThanCompare<T, U>::less(minValue, x) ? x : minValue); }; transformCopy(other, f); } template <typename T> template <typename U> void MultiDimImage<T>::scaledCopyFrom(const MultiDimImage<U>& other) { std::function<T(const U&)> f = detail::TypeScaleHelper<U, T>::scale; transformCopy(other, f); } template <typename T> bool MultiDimImage<T>::empty() const { return m_dims.empty() || std::any_of(m_dims.begin(), m_dims.end(), [](std::size_t x) { return x == 0; }); } template <typename T> std::size_t MultiDimImage<T>::size() const { if (m_dims.empty()) { return 0; } else { return m_planeSize * m_restSize; } } template <typename T> std::size_t MultiDimImage<T>::dims() const { return m_dims.size(); } template <typename T> std::size_t MultiDimImage<T>::dim(std::size_t d) const { if (d >= m_dims.size()) { throw std::range_error("no such dimension"); } return m_dims[d]; } template <typename T> std::vector<std::size_t> MultiDimImage<T>::dimList() const { return m_dims; } template <typename T> std::size_t MultiDimImage<T>::byteSize() const { return size() * sizeof(T); } template <typename T> Type MultiDimImage<T>::type() const { return m_type; } template <typename T> void MultiDimImage<T>::clear() { MultiDimImage<T> empty; *this = std::move(empty); } template <typename T> T& MultiDimImage<T>::at(std::vector<std::size_t> coords) { if (coords.size() != m_dims.size()) { throw std::length_error("number of coordinates not equals with the number of dimensions"); } auto itD = m_dims.begin(); auto itC = coords.begin(); for (std::size_t i = 0; i < m_dims.size(); ++i, ++itD, ++itC) { if (*itC < 0 || *itD <= *itC ) { throw std::out_of_range("out of MultiDimImage range"); } } return unsafeAt(coords); } template <typename T> std::pair<std::size_t, std::size_t> MultiDimImage<T>::planeCoordinatePair(const std::vector<std::size_t>& coords) { std::size_t second = 0; if (coords.size() > 2) { second = std::inner_product( coords.begin() + 2, coords.end(), m_restDimsProducts.begin(), 0); } return std::make_pair( std::inner_product( coords.begin(), coords.begin() + std::min((std::size_t)2, coords.size()), m_planeDimsProducts.begin(), 0), second ); } template <typename T> T& MultiDimImage<T>::unsafeAt(std::vector<std::size_t> coords) { auto c = planeCoordinatePair(coords); return m_planes[c.second][c.first]; } template <typename T> std::vector<std::vector<T>>& MultiDimImage<T>::unsafeData() { return m_planes; } template <typename T> const std::vector<std::vector<T>>& MultiDimImage<T>::unsafeData() const { return m_planes; } template <typename T> void MultiDimImage<T>::reorderDims(std::vector<std::size_t> dimOrder) { if (dimOrder.size() != m_dims.size()) { throw std::invalid_argument("number of dimensions in the argument does not match with the number of data dimensions"); } std::vector<std::size_t> identity(m_dims.size()); std::iota(identity.begin(), identity.end(), 0); std::vector<std::size_t> dimOrderSorted(dimOrder); std::sort(dimOrderSorted.begin(), dimOrderSorted.end()); if (!std::equal(dimOrderSorted.begin(), dimOrderSorted.end(), identity.begin())) { throw std::invalid_argument("bad parameters for dimension reordering"); } if (std::equal(dimOrder.begin(), dimOrder.end(), identity.begin())) { // nothing to do return; } std::vector<std::size_t> newDims(m_dims.size(), 0); for (std::size_t j = 0; j < m_dims.size(); ++j) { newDims[j] = m_dims[dimOrder[j]]; } std::size_t d = std::min((std::size_t)2, m_planeDims.size()); std::vector<std::size_t> coord(newDims.size(), 0); MultiDimImage<T> newImage(newDims); for (auto& oldPlane : m_planes) { for (auto& oldValue : oldPlane) { auto coordPair = newImage.planeCoordinatePair(detail::reorderCoords(coord, dimOrder)); newImage.m_planes[coordPair.second][coordPair.first] = oldValue; detail::stepCoords(coord.begin(), coord.begin() + d, m_planeDims.begin()); } if (m_restSize) { detail::stepCoords(coord.begin() + 2, coord.end(), m_restDims.begin()); } } *this = std::move(newImage); } template <typename T> void MultiDimImage<T>::removeDims(std::vector<std::size_t> dims) { using namespace std; sort(dims.begin(), dims.end()); vector<size_t> newDims(m_dims); size_t k = 0; for (size_t d : dims) { if (d >= m_dims.size()) { throw std::range_error("no such dimension: " + std::to_string(d)); } newDims.erase(newDims.begin() + (d - k++)); } vector<size_t> invDims(m_dims.size()); iota(invDims.begin(), invDims.end(), 0); invDims.erase(remove_if(invDims.begin(), invDims.end(), [&dims](size_t x) { return find(dims.begin(), dims.end(), x) != dims.end(); }), invDims.end()); vector<size_t> newCoord(newDims.size(), 0); vector<size_t> oldCoord(m_dims.size(), 0); MultiDimImage<T> newImage(newDims); for (auto& newPlane : newImage.m_planes) { for (auto& newValue : newPlane) { for (size_t i = 0; i < invDims.size(); ++i) { oldCoord[invDims[i]] = newCoord[i]; } auto coordPair = planeCoordinatePair(oldCoord); newValue = m_planes[coordPair.second][coordPair.first]; detail::stepCoords(newCoord.begin(), newCoord.end(), newDims.begin()); } } *this = std::move(newImage); } template <typename T> std::vector<MultiDimImage<T>> MultiDimImage<T>::splitDim(std::size_t dim) { using namespace std; if (dim >= m_dims.size()) { throw std::range_error("no such dimension: " + std::to_string(dim)); } vector<size_t> newDims(m_dims); newDims.erase(newDims.begin() + dim); vector<MultiDimImage<T>> result(m_dims[dim], MultiDimImage<T>(newDims)); vector<size_t> oldCoord(m_dims.size(), 0); vector<vector<size_t>> newCoordsList(m_dims[dim], vector<size_t>(newDims.size(), 0)); for (auto& oldPlane : m_planes) { for (auto& oldValue : oldPlane) { size_t x = oldCoord[dim]; auto coordPair = result[x].planeCoordinatePair(newCoordsList[x]); result[x].m_planes[coordPair.second][coordPair.first] = oldValue; detail::stepCoords(oldCoord.begin(), oldCoord.end(), m_dims.begin()); detail::stepCoords(newCoordsList[x].begin(), newCoordsList[x].end(), newDims.begin()); } } return result; } template <typename T> MultiDimImage<T>::~MultiDimImage() {} namespace detail { template <typename It1, typename It2> void stepCoords(It1 begin, It1 end, It2 limitsBegin) { bool c = true; auto it = begin; auto limitsIt = limitsBegin; while (c && it != end) { if (++(*it) >= *limitsIt) { *it = 0; } else { c = false; } ++it; ++limitsIt; } } template <typename X, typename Y> struct TypeScaleHelper<X, Y, true, false> { static constexpr double typeScaleParamA() { return 1.0 / ((double)std::numeric_limits<X>::max() - (double)std::numeric_limits<X>::min()); } static constexpr double typeScaleParamB() { return 0.5 -0.5 * TypeScaleHelper<X, Y>::typeScaleParamA() * ((double)std::numeric_limits<X>::min() + (double)std::numeric_limits<X>::max()); } static Y scale(X x) { const double a = TypeScaleHelper<X, Y>::typeScaleParamA(); const double b = TypeScaleHelper<X, Y>::typeScaleParamB(); return static_cast<Y>(x * a + b); } }; template <typename X, typename Y> struct TypeScaleHelper<X, Y, false, true> { static constexpr double typeScaleParamA() { return ((double)std::numeric_limits<Y>::max() - (double)std::numeric_limits<Y>::min()); } static constexpr double typeScaleParamB() { return 0.5 * ((double)std::numeric_limits<Y>::min() + (double)std::numeric_limits<Y>::max() - TypeScaleHelper<X, Y>::typeScaleParamA()); } [[deprecated("MultiDimImage - scaling a floating point type to an integral type can be numerically unstable, avoid this type of scaling")]] static Y scale(X x) { // NOTE: in cases when sizeof(X) is comparable to sizeof(Y) the division and the // multiplication precision will not be enough, it can lead false results // NOTE: using 'long double' for all calculations might solve this issue but // unfortunately msvc don't support higher precision than double, since 'long double' // is just a typedef to double in that compiler. const double a = TypeScaleHelper<X, Y>::typeScaleParamA(); const double b = TypeScaleHelper<X, Y>::typeScaleParamB(); return static_cast<Y>(x * a + b); } }; template <typename X, typename Y> struct TypeScaleHelper<X, Y, false, false> { static constexpr double typeScaleParamA() { return 1.0; } static constexpr double typeScaleParamB() { return 0.0; } static Y scale(X x) { return static_cast<Y>(x); } }; template <typename X, typename Y> Y typeScale(const X& x) { return TypeScaleHelper<X, Y>::scale(x); } }
29.618582
147
0.596995
[ "vector", "transform" ]
a6a5ff25b5740d71faaaf34cc208086e85c0df15
1,527
cpp
C++
C-Plus-Plus/heap/MergeKSortedList.cpp
yashsahay2014/NeoAlgo
4f1e5bdd6d9d899fa354de94740e0aecf5ecd2be
[ "MIT" ]
897
2020-06-25T00:12:52.000Z
2022-03-24T00:49:31.000Z
C-Plus-Plus/heap/MergeKSortedList.cpp
yashsahay2014/NeoAlgo
4f1e5bdd6d9d899fa354de94740e0aecf5ecd2be
[ "MIT" ]
5,707
2020-06-24T17:53:28.000Z
2022-01-22T05:03:15.000Z
C-Plus-Plus/heap/MergeKSortedList.cpp
yashsahay2014/NeoAlgo
4f1e5bdd6d9d899fa354de94740e0aecf5ecd2be
[ "MIT" ]
1,817
2020-06-25T03:51:05.000Z
2022-03-29T05:14:07.000Z
/* You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it. */ #include <bits/stdc++.h> #define pil pair<int,ListNode *> using namespace std; // Defining a struct of ListNode struct ListNode { int val; ListNode *next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode *next) : val(x), next(next) {} }; ListNode* mergeKLists(vector<ListNode*>& lists) { //creating a priority queue with elements in increasing order. priority_queue<pil,vector<pil>,greater<pil>> pq; //Inserting a pair of integer and ListNode head. for(auto it : lists){ if(it){ pq.push({it->val,it}); } } //Creating A New head pointer to store merged Lists. ListNode *temp = new ListNode(); ListNode *head = temp; //Iterating till priority queue gets empty. while(!pq.empty()){ // Popping the smallest element. pil top = pq.top(); pq.pop(); // Pointing head pointer to smallest element pointer. temp->next = top.second; //Checking if next element exists on current list or not. if(top.second->next){ pq.push({top.second->next->val,top.second->next}); } temp = temp->next; } return head->next; } /* Input : [ 1->4->5, 1->3->4, 2->6 ] Output : 1->1->2->3->4->4->5->6 */
24.238095
94
0.591356
[ "vector" ]
a6a7118f48348e30448e6945d3b4cecf73589589
1,355
cc
C++
certain/default/route_impl_test.cc
mehrdad-shokri/paxosstore
120ce539ef4fef18b3bef512cec28e3e0e3b241c
[ "BSD-3-Clause" ]
1,567
2017-08-30T07:58:14.000Z
2022-03-28T07:46:54.000Z
certain/default/route_impl_test.cc
tomjobs/paxosstore
120ce539ef4fef18b3bef512cec28e3e0e3b241c
[ "BSD-3-Clause" ]
21
2017-08-31T01:21:30.000Z
2021-08-31T12:55:39.000Z
certain/default/route_impl_test.cc
tomjobs/paxosstore
120ce539ef4fef18b3bef512cec28e3e0e3b241c
[ "BSD-3-Clause" ]
352
2017-08-30T15:25:40.000Z
2022-03-18T10:02:57.000Z
#include "default/route_impl.h" #include "gtest/gtest.h" #include "network/inet_addr.h" #include "utils/log.h" TEST(RouteImpl, Normal) { std::string local_addr = "127.0.0.1:13068"; std::vector<std::string> addrs; addrs.push_back("127.0.0.1:13066"); addrs.push_back("127.0.0.1:13067"); addrs.push_back("127.0.0.1:13068"); RouteImpl route(local_addr, addrs); ASSERT_STREQ(route.GetLocalAddr().c_str(), local_addr.c_str()); uint32_t acceptor_id = 0; ASSERT_EQ(route.GetLocalAcceptorId(2, &acceptor_id), 0); ASSERT_EQ(acceptor_id, 1); ASSERT_EQ(route.GetLocalAcceptorId(3, &acceptor_id), 0); ASSERT_EQ(acceptor_id, 2); ASSERT_EQ(route.GetLocalAcceptorId(4, &acceptor_id), 0); ASSERT_EQ(acceptor_id, 0); uint64_t addr_id = -1; { ASSERT_EQ(route.GetServerAddrId(4, 0, &addr_id), 0); certain::InetAddr addr(addr_id); ASSERT_STREQ(addr.ToString().c_str(), "127.0.0.1:13068"); } { ASSERT_EQ(route.GetServerAddrId(4, 1, &addr_id), 0); certain::InetAddr addr(addr_id); ASSERT_STREQ(addr.ToString().c_str(), "127.0.0.1:13066"); } { ASSERT_EQ(route.GetServerAddrId(4, 2, &addr_id), 0); certain::InetAddr addr(addr_id); ASSERT_STREQ(addr.ToString().c_str(), "127.0.0.1:13067"); } } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
28.229167
65
0.684133
[ "vector" ]
a6a79304ae06094d387f5faea92312795c42e039
2,139
hpp
C++
event.hpp
giulianopa/EventDrivenPipeline
8f871e00c36215bf6338c417fdf515efa3ef7c5f
[ "Apache-2.0" ]
null
null
null
event.hpp
giulianopa/EventDrivenPipeline
8f871e00c36215bf6338c417fdf515efa3ef7c5f
[ "Apache-2.0" ]
null
null
null
event.hpp
giulianopa/EventDrivenPipeline
8f871e00c36215bf6338c417fdf515efa3ef7c5f
[ "Apache-2.0" ]
null
null
null
#pragma once #include <vector> #include <memory> #include <typeinfo> #include <functional> #include <tuple> #include "observer.hpp" //! Abstract event. /*! Emit a message without holding any value. \date 11/21/2013 \author Giuliano Pasqualotto */ template <typename MsgType1, typename... OtherMsgType> class Event { protected: //! List of awaiting observers. mutable std::vector<Observer<MsgType1, OtherMsgType...> *> m_observers; public: //! Unique ID of the event. const EVENT_ID id; //! Event constructor. Event() : id(EventIDGenerator::createID()) {} //! Subscribe to an event /*! \param An observer which needs to be notified when the event occurs. */ EVENT_ID subscribe(Observer<MsgType1, OtherMsgType...> &ob) const { m_observers.push_back(&ob); return id; } }; //! Event ID generator class. class EventIDGenerator { static std::shared_ptr<EventIDGenerator> m_instance; EVENT_ID m_nextID; EventIDGenerator() : m_nextID(0) { } EVENT_ID next() { m_nextID++; return (m_nextID - 1); } public: static EVENT_ID createID() { if (!m_instance) m_instance = std::shared_ptr<EventIDGenerator>(new EventIDGenerator); return m_instance->next(); } }; //! Event source. /*! \date 11/21/2013 \author Giuliano Pasqualotto */ template <typename MsgType1, typename... OtherMsgType> class EventSource : public Event<MsgType1, OtherMsgType...> { public: EventSource() : Event<MsgType1, OtherMsgType...>() {} virtual ~EventSource() {} void emit(const MsgType1& msg, const OtherMsgType&... otherMsgs) { for (size_t observerId = 0; observerId < m_observers.size(); observerId++) { m_observers[observerId]->observe(id, std::forward<const MsgType1>(msg), std::forward<const OtherMsgType>(otherMsgs)...); } } void emit(const MsgType1&& msg, const OtherMsgType&&... otherMsgs) { for (size_t observerId = 0; observerId < m_observers.size(); observerId++) { m_observers[observerId]->observe(id, std::forward<const MsgType1>(msg), std::forward<const OtherMsgType>(otherMsgs)...); } } };
22.755319
124
0.672277
[ "vector" ]
16faa917c4684051eca53550eb4c6570de5a6b1c
5,430
hpp
C++
src/ivorium_graphics/Elements/Elem.hpp
ivorne/ivorium
1d876b6dcabe29b3110d3058f997e59c40cd6a2b
[ "Apache-2.0" ]
3
2021-02-26T02:59:09.000Z
2022-02-08T16:44:21.000Z
src/ivorium_graphics/Elements/Elem.hpp
ivorne/ivorium
1d876b6dcabe29b3110d3058f997e59c40cd6a2b
[ "Apache-2.0" ]
null
null
null
src/ivorium_graphics/Elements/Elem.hpp
ivorne/ivorium
1d876b6dcabe29b3110d3058f997e59c40cd6a2b
[ "Apache-2.0" ]
null
null
null
#pragma once #include "ElementRenderer.hpp" #include "../Rendering/CameraState.hpp" #include "../Rendering/FlatShader.hpp" #include <ivorium_systems/ivorium_systems.hpp> namespace iv { class Camera; /** */ class Elem : public InputNode { public: ClientMarker cm; Elem( Instance * inst ); ~Elem(); void status( iv::TableDebugView * view ); Instance * instance() const; //------------------------- element tree -------------------------------- /** */ void elem_setParent( Elem * ); /** */ Elem * elem_getParent(); /** */ virtual Camera * elem_getRoot(); /** Just used for debugging. */ virtual void elem_eachChild( std::function< void( Elem * ) > const & ){} /** */ virtual void elem_childDisconnect( Elem * ){} //------------------------- scene update traversal -------------------------------- /** Refresh synthesized parameters, from bottom to top. Also refresh everything (except childrens inherited parameters) that depends on synthesized or initialization parameters and does not depend on inherited parameters. For each child: - Call child->first_pass(). - Check changes in own initialization parameters and childs synthesized parameters. * If this change would modify own internal state or own synthesized parameters, then modify them. * Changes to internal state caused by this change can also be delayed to second pass, in which case we need to queue for that second pass. * This is useful if we realy want to avoid double recomputation of internal state that can be changed both by initialization / synthesized parameters and inherited parameters. * If this change would modify childrens inherited parameters, then queue self for second pass. * No need to queue self for second pass when own inherited parameters changed - inherited parameters are set from parent and parent calls second_pass automatically on child when this happens. */ void first_pass( ElementRenderer * ); /** Refresh inherited parameters and whatever depends on them, from top to bottom. Remove self from queue for second pass (necessary only if there is a possibility that it added self in that queue in first pass, not necessary when called from parents second_pass). Regenerate internal state and childrens inherited parameters if they depend on changed inherited parameters. Also regenerate internal states that depend on initialization or synthesized parameters and the regeneration was delayed to second pass. If we changed at leas one synthesized parameter in a child, then we need to call second_pass on that child too (this should be called once after all desired changes to that childs inherited parameters were made). */ void second_pass( ElementRenderer * ); // unsigned first_pass_frame_id(); unsigned second_pass_frame_id(); //------------------------- parameters -------------------------------- // initialization parameters /** Elements are enabled by default. Disabled Elements do not call first_pass or second_pass and therefore no children of them are processed or drawn. This also sets InputNode::inputEnabled to the same value during first pass. */ DirtyAttr< bool > attr_enabled; // inherited parameter DirtyAttr< float4x4 > modelTransform; DirtyAttr< ShaderScissor > scissor; // utility methods Elem * enabled( bool val ); /** This node being disconnected from scene tree will not be reported in ConsistencyChecks log. */ void quiet( bool ); bool quiet() const; //------------------------- utilities -------------------------------- // math over modelTransform float3 FromLocalSpaceToScreenSpace( float3 local_space ); float3 FromScreenSpaceToLocalSpace( float3 screen_space ); float2 FromScreenPlaneToLocalPlane( float2 screen_space ); // input tree utilities void Add_InputNode( InputNode * node ); void Remove_InputNode( InputNode * node ); protected: // InputNode virtual void input_childDisconnect( InputNode * ) override; virtual void input_eachChild( std::function< void( InputNode * ) > const & ) override; // Elem virtual void first_pass_impl( ElementRenderer * ) = 0; virtual void second_pass_impl( ElementRenderer * ){} private: Instance * inst; unsigned _first_pass_frame_id; unsigned _second_pass_frame_id; bool _quiet; std::vector< InputNode * > _input_children; Elem * _elem_parent; }; class Pickable { public: ClientMarker cm; Pickable( Elem * elem ); virtual bool picking_test( int2 input_pos ) = 0; Elem * elem(); Elem const * elem() const; private: Elem * _elem; }; }
37.191781
220
0.596133
[ "vector" ]
16fbc1a46d838b9c3c7dda94198ca671a741395b
2,141
cpp
C++
cpp/joi2012yo_d/main.cpp
kokosabu/atcoder
8d512587d234eb45941a2f6341c4dd003e6c9ad3
[ "Apache-2.0" ]
null
null
null
cpp/joi2012yo_d/main.cpp
kokosabu/atcoder
8d512587d234eb45941a2f6341c4dd003e6c9ad3
[ "Apache-2.0" ]
null
null
null
cpp/joi2012yo_d/main.cpp
kokosabu/atcoder
8d512587d234eb45941a2f6341c4dd003e6c9ad3
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> using namespace std; int main() { int N, K; cin >> N >> K; vector<int> A(K); vector<int> B(K); for(int i = 0; i < K; i++) { cin >> A[i] >> B[i]; B[i] -= 1; } vector<vector<int> > dp(N+1, vector<int>(9, 0)); dp[0][0] = 1; for(int i = 1; i <= N; i++) { int b = -1; for(int j = 0; j < K; j++) { if(A[j] == i) { b = B[j]; break; } } // 0 : 0 0 : from 3, 6 select 0 // 1 : 0 1 // 2 : 0 2 // 3 : 1 0 : from 1, 4, 7 // 4 : 1 1 : from 1, 7 // 5 : 1 2 // 6 : 2 0 // 7 : 2 1 // 8 : 2 2 : from 2, 5, // cout << "b : " << b << endl; if(i == 1) { // 0, 1, 2に入れる for(int j = 0; j < 3; j++) { if(b == -1) { dp[i][j] = 1; } else if(j%3 == b) { dp[i][j] = 1; } } } else if(i == 2) { for(int j = 0; j < 9; j++) { if(b != -1 && j%3 != b) { continue; } for(int k = j/3; k < 9; k += 3) { dp[i][j] += dp[i-1][k]; } } } else { for(int j = 0; j < 9; j++) { if(b != -1 && j%3 != b) { continue; } for(int k = j/3; k < 9; k += 3) { if(j != k) { dp[i][j] += dp[i-1][k]; } } } } for(int j = 0; j < 9; j++) { dp[i][j] %= 10000; } /* cout << "---- " << i << " ---" << endl; for(int j = 1; j <= i; j++) { for(int k = 0; k < 9; k++) { cout << dp[j][k] << ", "; } cout << endl; } cout << endl; */ } int sum = 0; for(int i = 0; i < 9; i++) { sum = (sum + dp[N][i]) % 10000; } cout << sum << endl; }
22.776596
52
0.245213
[ "vector" ]
16fece3a4be45adce02b9f15acbfcfcee93d5c7f
167,824
hpp
C++
Autogenerated/Bindings/CppDynamic/lib3mf_abi.hpp
alexanderoster/lib3mf
30d5c2e0e8ed7febb5c10a84dc2db9d53fee6d05
[ "BSD-2-Clause" ]
171
2015-04-30T21:54:02.000Z
2022-03-13T13:33:59.000Z
Autogenerated/Bindings/CppDynamic/lib3mf_abi.hpp
alexanderoster/lib3mf
30d5c2e0e8ed7febb5c10a84dc2db9d53fee6d05
[ "BSD-2-Clause" ]
190
2015-07-21T22:15:54.000Z
2022-03-30T15:48:37.000Z
Autogenerated/Bindings/CppDynamic/lib3mf_abi.hpp
alexanderoster/lib3mf
30d5c2e0e8ed7febb5c10a84dc2db9d53fee6d05
[ "BSD-2-Clause" ]
80
2015-04-30T22:15:54.000Z
2022-03-09T12:38:49.000Z
/*++ Copyright (C) 2019 3MF Consortium (Original Author) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This file has been generated by the Automatic Component Toolkit (ACT) version 1.6.0. Abstract: This is an autogenerated C++-Header file in order to allow an easy use of the 3MF Library Interface version: 2.2.0 */ #ifndef __LIB3MF_HEADER_CPP #define __LIB3MF_HEADER_CPP #ifdef __LIB3MF_EXPORTS #ifdef _WIN32 #define LIB3MF_DECLSPEC __declspec (dllexport) #else // _WIN32 #define LIB3MF_DECLSPEC __attribute__((visibility("default"))) #endif // _WIN32 #else // __LIB3MF_EXPORTS #define LIB3MF_DECLSPEC #endif // __LIB3MF_EXPORTS #include "lib3mf_types.hpp" extern "C" { /************************************************************************************************************************* Class definition for Base **************************************************************************************************************************/ /************************************************************************************************************************* Class definition for Writer **************************************************************************************************************************/ /** * Writes out the model as file. The file type is specified by the Model Writer class. * * @param[in] pWriter - Writer instance. * @param[in] pFilename - Filename to write into * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_writer_writetofile(Lib3MF_Writer pWriter, const char * pFilename); /** * Retrieves the size of the full 3MF file stream. * * @param[in] pWriter - Writer instance. * @param[out] pStreamSize - the stream size * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_writer_getstreamsize(Lib3MF_Writer pWriter, Lib3MF_uint64 * pStreamSize); /** * Writes out the 3MF file into a memory buffer * * @param[in] pWriter - Writer instance. * @param[in] nBufferBufferSize - Number of elements in buffer * @param[out] pBufferNeededCount - will be filled with the count of the written elements, or needed buffer size. * @param[out] pBufferBuffer - uint8 buffer of buffer to write into * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_writer_writetobuffer(Lib3MF_Writer pWriter, const Lib3MF_uint64 nBufferBufferSize, Lib3MF_uint64* pBufferNeededCount, Lib3MF_uint8 * pBufferBuffer); /** * Writes out the model and passes the data to a provided callback function. The file type is specified by the Model Writer class. * * @param[in] pWriter - Writer instance. * @param[in] pTheWriteCallback - Callback to call for writing a data chunk * @param[in] pTheSeekCallback - Callback to call for seeking in the stream * @param[in] pUserData - Userdata that is passed to the callback function * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_writer_writetocallback(Lib3MF_Writer pWriter, Lib3MF::WriteCallback pTheWriteCallback, Lib3MF::SeekCallback pTheSeekCallback, Lib3MF_pvoid pUserData); /** * Set the progress callback for calls to this writer * * @param[in] pWriter - Writer instance. * @param[in] pProgressCallback - pointer to the callback function. * @param[in] pUserData - pointer to arbitrary user data that is passed without modification to the callback. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_writer_setprogresscallback(Lib3MF_Writer pWriter, Lib3MF::ProgressCallback pProgressCallback, Lib3MF_pvoid pUserData); /** * Returns the number of digits after the decimal point to be written in each vertex coordinate-value. * * @param[in] pWriter - Writer instance. * @param[out] pDecimalPrecision - The number of digits to be written in each vertex coordinate-value after the decimal point. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_writer_getdecimalprecision(Lib3MF_Writer pWriter, Lib3MF_uint32 * pDecimalPrecision); /** * Sets the number of digits after the decimal point to be written in each vertex coordinate-value. * * @param[in] pWriter - Writer instance. * @param[in] nDecimalPrecision - The number of digits to be written in each vertex coordinate-value after the decimal point. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_writer_setdecimalprecision(Lib3MF_Writer pWriter, Lib3MF_uint32 nDecimalPrecision); /** * Activates (deactivates) the strict mode of the reader. * * @param[in] pWriter - Writer instance. * @param[in] bStrictModeActive - flag whether strict mode is active or not. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_writer_setstrictmodeactive(Lib3MF_Writer pWriter, bool bStrictModeActive); /** * Queries whether the strict mode of the reader is active or not * * @param[in] pWriter - Writer instance. * @param[out] pStrictModeActive - returns flag whether strict mode is active or not. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_writer_getstrictmodeactive(Lib3MF_Writer pWriter, bool * pStrictModeActive); /** * Returns Warning and Error Information of the read process * * @param[in] pWriter - Writer instance. * @param[in] nIndex - Index of the Warning. Valid values are 0 to WarningCount - 1 * @param[out] pErrorCode - filled with the error code of the warning * @param[in] nWarningBufferSize - size of the buffer (including trailing 0) * @param[out] pWarningNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pWarningBuffer - buffer of the message of the warning, may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_writer_getwarning(Lib3MF_Writer pWriter, Lib3MF_uint32 nIndex, Lib3MF_uint32 * pErrorCode, const Lib3MF_uint32 nWarningBufferSize, Lib3MF_uint32* pWarningNeededChars, char * pWarningBuffer); /** * Returns Warning and Error Count of the read process * * @param[in] pWriter - Writer instance. * @param[out] pCount - filled with the count of the occurred warnings. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_writer_getwarningcount(Lib3MF_Writer pWriter, Lib3MF_uint32 * pCount); /** * Registers a callback to deal with data key encryption/decryption from keystore * * @param[in] pWriter - Writer instance. * @param[in] pConsumerID - The ConsumerID to register for * @param[in] pTheCallback - The callback to be callede for wrapping and encryption key * @param[in] pUserData - Userdata that is passed to the callback function * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_writer_addkeywrappingcallback(Lib3MF_Writer pWriter, const char * pConsumerID, Lib3MF::KeyWrappingCallback pTheCallback, Lib3MF_pvoid pUserData); /** * Registers a callback to deal with encryption of content * * @param[in] pWriter - Writer instance. * @param[in] pTheCallback - The callback used to encrypt content * @param[in] pUserData - Userdata that is passed to the callback function * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_writer_setcontentencryptioncallback(Lib3MF_Writer pWriter, Lib3MF::ContentEncryptionCallback pTheCallback, Lib3MF_pvoid pUserData); /************************************************************************************************************************* Class definition for Reader **************************************************************************************************************************/ /** * Reads a model from a file. The file type is specified by the Model Reader class * * @param[in] pReader - Reader instance. * @param[in] pFilename - Filename to read from * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_reader_readfromfile(Lib3MF_Reader pReader, const char * pFilename); /** * Reads a model from a memory buffer. * * @param[in] pReader - Reader instance. * @param[in] nBufferBufferSize - Number of elements in buffer * @param[in] pBufferBuffer - uint8 buffer of Buffer to read from * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_reader_readfrombuffer(Lib3MF_Reader pReader, Lib3MF_uint64 nBufferBufferSize, const Lib3MF_uint8 * pBufferBuffer); /** * Reads a model and from the data provided by a callback function * * @param[in] pReader - Reader instance. * @param[in] pTheReadCallback - Callback to call for reading a data chunk * @param[in] nStreamSize - number of bytes the callback returns * @param[in] pTheSeekCallback - Callback to call for seeking in the stream. * @param[in] pUserData - Userdata that is passed to the callback function * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_reader_readfromcallback(Lib3MF_Reader pReader, Lib3MF::ReadCallback pTheReadCallback, Lib3MF_uint64 nStreamSize, Lib3MF::SeekCallback pTheSeekCallback, Lib3MF_pvoid pUserData); /** * Set the progress callback for calls to this writer * * @param[in] pReader - Reader instance. * @param[in] pProgressCallback - pointer to the callback function. * @param[in] pUserData - pointer to arbitrary user data that is passed without modification to the callback. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_reader_setprogresscallback(Lib3MF_Reader pReader, Lib3MF::ProgressCallback pProgressCallback, Lib3MF_pvoid pUserData); /** * Adds a relationship type which shall be read as attachment in memory while loading * * @param[in] pReader - Reader instance. * @param[in] pRelationShipType - String of the relationship type * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_reader_addrelationtoread(Lib3MF_Reader pReader, const char * pRelationShipType); /** * Removes a relationship type which shall be read as attachment in memory while loading * * @param[in] pReader - Reader instance. * @param[in] pRelationShipType - String of the relationship type * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_reader_removerelationtoread(Lib3MF_Reader pReader, const char * pRelationShipType); /** * Activates (deactivates) the strict mode of the reader. * * @param[in] pReader - Reader instance. * @param[in] bStrictModeActive - flag whether strict mode is active or not. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_reader_setstrictmodeactive(Lib3MF_Reader pReader, bool bStrictModeActive); /** * Queries whether the strict mode of the reader is active or not * * @param[in] pReader - Reader instance. * @param[out] pStrictModeActive - returns flag whether strict mode is active or not. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_reader_getstrictmodeactive(Lib3MF_Reader pReader, bool * pStrictModeActive); /** * Returns Warning and Error Information of the read process * * @param[in] pReader - Reader instance. * @param[in] nIndex - Index of the Warning. Valid values are 0 to WarningCount - 1 * @param[out] pErrorCode - filled with the error code of the warning * @param[in] nWarningBufferSize - size of the buffer (including trailing 0) * @param[out] pWarningNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pWarningBuffer - buffer of the message of the warning, may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_reader_getwarning(Lib3MF_Reader pReader, Lib3MF_uint32 nIndex, Lib3MF_uint32 * pErrorCode, const Lib3MF_uint32 nWarningBufferSize, Lib3MF_uint32* pWarningNeededChars, char * pWarningBuffer); /** * Returns Warning and Error Count of the read process * * @param[in] pReader - Reader instance. * @param[out] pCount - filled with the count of the occurred warnings. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_reader_getwarningcount(Lib3MF_Reader pReader, Lib3MF_uint32 * pCount); /** * Registers a callback to deal with key wrapping mechanism from keystore * * @param[in] pReader - Reader instance. * @param[in] pConsumerID - The ConsumerID to register for * @param[in] pTheCallback - The callback used to decrypt data key * @param[in] pUserData - Userdata that is passed to the callback function * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_reader_addkeywrappingcallback(Lib3MF_Reader pReader, const char * pConsumerID, Lib3MF::KeyWrappingCallback pTheCallback, Lib3MF_pvoid pUserData); /** * Registers a callback to deal with encryption of content * * @param[in] pReader - Reader instance. * @param[in] pTheCallback - The callback used to encrypt content * @param[in] pUserData - Userdata that is passed to the callback function * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_reader_setcontentencryptioncallback(Lib3MF_Reader pReader, Lib3MF::ContentEncryptionCallback pTheCallback, Lib3MF_pvoid pUserData); /************************************************************************************************************************* Class definition for PackagePart **************************************************************************************************************************/ /** * Returns the absolute path of this PackagePart. * * @param[in] pPackagePart - PackagePart instance. * @param[in] nPathBufferSize - size of the buffer (including trailing 0) * @param[out] pPathNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pPathBuffer - buffer of Returns the absolute path of this PackagePart, may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_packagepart_getpath(Lib3MF_PackagePart pPackagePart, const Lib3MF_uint32 nPathBufferSize, Lib3MF_uint32* pPathNeededChars, char * pPathBuffer); /** * Sets the absolute path of this PackagePart. * * @param[in] pPackagePart - PackagePart instance. * @param[in] pPath - Sets the absolute path of this PackagePart. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_packagepart_setpath(Lib3MF_PackagePart pPackagePart, const char * pPath); /************************************************************************************************************************* Class definition for Resource **************************************************************************************************************************/ /** * Retrieves the unique id of this resource within a package. This function will be removed in a later release in favor of GetUniqueResourceID * * @param[in] pResource - Resource instance. * @param[out] pUniqueResourceID - Retrieves the unique id of this resource within a package. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_resource_getresourceid(Lib3MF_Resource pResource, Lib3MF_uint32 * pUniqueResourceID); /** * Retrieves the unique id of this resource within a package. * * @param[in] pResource - Resource instance. * @param[out] pUniqueResourceID - Retrieves the unique id of this resource within a package. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_resource_getuniqueresourceid(Lib3MF_Resource pResource, Lib3MF_uint32 * pUniqueResourceID); /** * Returns the PackagePart within which this resource resides * * @param[in] pResource - Resource instance. * @param[out] pPackagePart - the PackagePart within which this resource resides. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_resource_packagepart(Lib3MF_Resource pResource, Lib3MF_PackagePart * pPackagePart); /** * Sets the new PackagePart within which this resource resides * * @param[in] pResource - Resource instance. * @param[in] pPackagePart - the new PackagePart within which this resource resides. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_resource_setpackagepart(Lib3MF_Resource pResource, Lib3MF_PackagePart pPackagePart); /** * Retrieves the id of this resource within a model. * * @param[in] pResource - Resource instance. * @param[out] pModelResourceId - Retrieves the id of this resource within a model. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_resource_getmodelresourceid(Lib3MF_Resource pResource, Lib3MF_uint32 * pModelResourceId); /************************************************************************************************************************* Class definition for ResourceIterator **************************************************************************************************************************/ /** * Iterates to the next resource in the list. * * @param[in] pResourceIterator - ResourceIterator instance. * @param[out] pHasNext - Iterates to the next resource in the list. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_resourceiterator_movenext(Lib3MF_ResourceIterator pResourceIterator, bool * pHasNext); /** * Iterates to the previous resource in the list. * * @param[in] pResourceIterator - ResourceIterator instance. * @param[out] pHasPrevious - Iterates to the previous resource in the list. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_resourceiterator_moveprevious(Lib3MF_ResourceIterator pResourceIterator, bool * pHasPrevious); /** * Returns the resource the iterator points at. * * @param[in] pResourceIterator - ResourceIterator instance. * @param[out] pResource - returns the resource instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_resourceiterator_getcurrent(Lib3MF_ResourceIterator pResourceIterator, Lib3MF_Resource * pResource); /** * Creates a new resource iterator with the same resource list. * * @param[in] pResourceIterator - ResourceIterator instance. * @param[out] pOutResourceIterator - returns the cloned Iterator instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_resourceiterator_clone(Lib3MF_ResourceIterator pResourceIterator, Lib3MF_ResourceIterator * pOutResourceIterator); /** * Returns the number of resoucres the iterator captures. * * @param[in] pResourceIterator - ResourceIterator instance. * @param[out] pCount - returns the number of resoucres the iterator captures. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_resourceiterator_count(Lib3MF_ResourceIterator pResourceIterator, Lib3MF_uint64 * pCount); /************************************************************************************************************************* Class definition for SliceStackIterator **************************************************************************************************************************/ /** * Returns the SliceStack the iterator points at. * * @param[in] pSliceStackIterator - SliceStackIterator instance. * @param[out] pResource - returns the SliceStack instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_slicestackiterator_getcurrentslicestack(Lib3MF_SliceStackIterator pSliceStackIterator, Lib3MF_SliceStack * pResource); /************************************************************************************************************************* Class definition for ObjectIterator **************************************************************************************************************************/ /** * Returns the Object the iterator points at. * * @param[in] pObjectIterator - ObjectIterator instance. * @param[out] pResource - returns the Object instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_objectiterator_getcurrentobject(Lib3MF_ObjectIterator pObjectIterator, Lib3MF_Object * pResource); /************************************************************************************************************************* Class definition for MeshObjectIterator **************************************************************************************************************************/ /** * Returns the MeshObject the iterator points at. * * @param[in] pMeshObjectIterator - MeshObjectIterator instance. * @param[out] pResource - returns the MeshObject instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobjectiterator_getcurrentmeshobject(Lib3MF_MeshObjectIterator pMeshObjectIterator, Lib3MF_MeshObject * pResource); /************************************************************************************************************************* Class definition for ComponentsObjectIterator **************************************************************************************************************************/ /** * Returns the ComponentsObject the iterator points at. * * @param[in] pComponentsObjectIterator - ComponentsObjectIterator instance. * @param[out] pResource - returns the ComponentsObject instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_componentsobjectiterator_getcurrentcomponentsobject(Lib3MF_ComponentsObjectIterator pComponentsObjectIterator, Lib3MF_ComponentsObject * pResource); /************************************************************************************************************************* Class definition for Texture2DIterator **************************************************************************************************************************/ /** * Returns the Texture2D the iterator points at. * * @param[in] pTexture2DIterator - Texture2DIterator instance. * @param[out] pResource - returns the Texture2D instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2diterator_getcurrenttexture2d(Lib3MF_Texture2DIterator pTexture2DIterator, Lib3MF_Texture2D * pResource); /************************************************************************************************************************* Class definition for BaseMaterialGroupIterator **************************************************************************************************************************/ /** * Returns the MaterialGroup the iterator points at. * * @param[in] pBaseMaterialGroupIterator - BaseMaterialGroupIterator instance. * @param[out] pResource - returns the BaseMaterialGroup instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_basematerialgroupiterator_getcurrentbasematerialgroup(Lib3MF_BaseMaterialGroupIterator pBaseMaterialGroupIterator, Lib3MF_BaseMaterialGroup * pResource); /************************************************************************************************************************* Class definition for ColorGroupIterator **************************************************************************************************************************/ /** * Returns the ColorGroup the iterator points at. * * @param[in] pColorGroupIterator - ColorGroupIterator instance. * @param[out] pResource - returns the ColorGroup instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_colorgroupiterator_getcurrentcolorgroup(Lib3MF_ColorGroupIterator pColorGroupIterator, Lib3MF_ColorGroup * pResource); /************************************************************************************************************************* Class definition for Texture2DGroupIterator **************************************************************************************************************************/ /** * Returns the Texture2DGroup the iterator points at. * * @param[in] pTexture2DGroupIterator - Texture2DGroupIterator instance. * @param[out] pResource - returns the Texture2DGroup instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2dgroupiterator_getcurrenttexture2dgroup(Lib3MF_Texture2DGroupIterator pTexture2DGroupIterator, Lib3MF_Texture2DGroup * pResource); /************************************************************************************************************************* Class definition for CompositeMaterialsIterator **************************************************************************************************************************/ /** * Returns the CompositeMaterials the iterator points at. * * @param[in] pCompositeMaterialsIterator - CompositeMaterialsIterator instance. * @param[out] pResource - returns the CompositeMaterials instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_compositematerialsiterator_getcurrentcompositematerials(Lib3MF_CompositeMaterialsIterator pCompositeMaterialsIterator, Lib3MF_CompositeMaterials * pResource); /************************************************************************************************************************* Class definition for MultiPropertyGroupIterator **************************************************************************************************************************/ /** * Returns the MultiPropertyGroup the iterator points at. * * @param[in] pMultiPropertyGroupIterator - MultiPropertyGroupIterator instance. * @param[out] pResource - returns the MultiPropertyGroup instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_multipropertygroupiterator_getcurrentmultipropertygroup(Lib3MF_MultiPropertyGroupIterator pMultiPropertyGroupIterator, Lib3MF_MultiPropertyGroup * pResource); /************************************************************************************************************************* Class definition for MetaData **************************************************************************************************************************/ /** * returns the namespace URL of the metadata * * @param[in] pMetaData - MetaData instance. * @param[in] nNameSpaceBufferSize - size of the buffer (including trailing 0) * @param[out] pNameSpaceNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pNameSpaceBuffer - buffer of the namespace URL of the metadata, may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadata_getnamespace(Lib3MF_MetaData pMetaData, const Lib3MF_uint32 nNameSpaceBufferSize, Lib3MF_uint32* pNameSpaceNeededChars, char * pNameSpaceBuffer); /** * sets a new namespace URL of the metadata * * @param[in] pMetaData - MetaData instance. * @param[in] pNameSpace - the new namespace URL of the metadata * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadata_setnamespace(Lib3MF_MetaData pMetaData, const char * pNameSpace); /** * returns the name of a metadata * * @param[in] pMetaData - MetaData instance. * @param[in] nNameBufferSize - size of the buffer (including trailing 0) * @param[out] pNameNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pNameBuffer - buffer of the name of the metadata, may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadata_getname(Lib3MF_MetaData pMetaData, const Lib3MF_uint32 nNameBufferSize, Lib3MF_uint32* pNameNeededChars, char * pNameBuffer); /** * sets a new name of a metadata * * @param[in] pMetaData - MetaData instance. * @param[in] pName - the new name of the metadata * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadata_setname(Lib3MF_MetaData pMetaData, const char * pName); /** * returns the (namespace+name) of a metadata * * @param[in] pMetaData - MetaData instance. * @param[in] nKeyBufferSize - size of the buffer (including trailing 0) * @param[out] pKeyNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pKeyBuffer - buffer of the key (namespace+name) of the metadata, may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadata_getkey(Lib3MF_MetaData pMetaData, const Lib3MF_uint32 nKeyBufferSize, Lib3MF_uint32* pKeyNeededChars, char * pKeyBuffer); /** * returns, whether a metadata must be preserved * * @param[in] pMetaData - MetaData instance. * @param[out] pMustPreserve - returns, whether a metadata must be preserved * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadata_getmustpreserve(Lib3MF_MetaData pMetaData, bool * pMustPreserve); /** * sets whether a metadata must be preserved * * @param[in] pMetaData - MetaData instance. * @param[in] bMustPreserve - a new value whether a metadata must be preserved * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadata_setmustpreserve(Lib3MF_MetaData pMetaData, bool bMustPreserve); /** * returns the type of a metadata * * @param[in] pMetaData - MetaData instance. * @param[in] nTypeBufferSize - size of the buffer (including trailing 0) * @param[out] pTypeNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pTypeBuffer - buffer of the type of the metadata, may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadata_gettype(Lib3MF_MetaData pMetaData, const Lib3MF_uint32 nTypeBufferSize, Lib3MF_uint32* pTypeNeededChars, char * pTypeBuffer); /** * sets a new type of a metadata. This must be a simple XML type * * @param[in] pMetaData - MetaData instance. * @param[in] pType - a new type of the metadata * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadata_settype(Lib3MF_MetaData pMetaData, const char * pType); /** * returns the value of the metadata * * @param[in] pMetaData - MetaData instance. * @param[in] nValueBufferSize - size of the buffer (including trailing 0) * @param[out] pValueNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pValueBuffer - buffer of the value of the metadata, may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadata_getvalue(Lib3MF_MetaData pMetaData, const Lib3MF_uint32 nValueBufferSize, Lib3MF_uint32* pValueNeededChars, char * pValueBuffer); /** * sets a new value of the metadata * * @param[in] pMetaData - MetaData instance. * @param[in] pValue - a new value of the metadata * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadata_setvalue(Lib3MF_MetaData pMetaData, const char * pValue); /************************************************************************************************************************* Class definition for MetaDataGroup **************************************************************************************************************************/ /** * returns the number of metadata in this metadatagroup * * @param[in] pMetaDataGroup - MetaDataGroup instance. * @param[out] pCount - returns the number metadata * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadatagroup_getmetadatacount(Lib3MF_MetaDataGroup pMetaDataGroup, Lib3MF_uint32 * pCount); /** * returns a metadata value within this metadatagroup * * @param[in] pMetaDataGroup - MetaDataGroup instance. * @param[in] nIndex - Index of the Metadata. * @param[out] pMetaData - an instance of the metadata * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadatagroup_getmetadata(Lib3MF_MetaDataGroup pMetaDataGroup, Lib3MF_uint32 nIndex, Lib3MF_MetaData * pMetaData); /** * returns a metadata value within this metadatagroup * * @param[in] pMetaDataGroup - MetaDataGroup instance. * @param[in] pNameSpace - the namespace of the metadata * @param[in] pName - the name of the Metadata * @param[out] pMetaData - an instance of the metadata * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadatagroup_getmetadatabykey(Lib3MF_MetaDataGroup pMetaDataGroup, const char * pNameSpace, const char * pName, Lib3MF_MetaData * pMetaData); /** * removes metadata by index from the model. * * @param[in] pMetaDataGroup - MetaDataGroup instance. * @param[in] nIndex - Index of the metadata to remove * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadatagroup_removemetadatabyindex(Lib3MF_MetaDataGroup pMetaDataGroup, Lib3MF_uint32 nIndex); /** * removes metadata from the model. * * @param[in] pMetaDataGroup - MetaDataGroup instance. * @param[in] pTheMetaData - The metadata to remove * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadatagroup_removemetadata(Lib3MF_MetaDataGroup pMetaDataGroup, Lib3MF_MetaData pTheMetaData); /** * adds a new metadata to this metadatagroup * * @param[in] pMetaDataGroup - MetaDataGroup instance. * @param[in] pNameSpace - the namespace of the metadata * @param[in] pName - the name of the metadata * @param[in] pValue - the value of the metadata * @param[in] pType - the type of the metadata * @param[in] bMustPreserve - shuold the metadata be preserved * @param[out] pMetaData - a new instance of the metadata * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_metadatagroup_addmetadata(Lib3MF_MetaDataGroup pMetaDataGroup, const char * pNameSpace, const char * pName, const char * pValue, const char * pType, bool bMustPreserve, Lib3MF_MetaData * pMetaData); /************************************************************************************************************************* Class definition for Object **************************************************************************************************************************/ /** * Retrieves an object's type * * @param[in] pObject - Object instance. * @param[out] pObjectType - returns object type enum. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_gettype(Lib3MF_Object pObject, Lib3MF::eObjectType * pObjectType); /** * Sets an object's type * * @param[in] pObject - Object instance. * @param[in] eObjectType - object type enum. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_settype(Lib3MF_Object pObject, Lib3MF::eObjectType eObjectType); /** * Retrieves an object's name * * @param[in] pObject - Object instance. * @param[in] nNameBufferSize - size of the buffer (including trailing 0) * @param[out] pNameNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pNameBuffer - buffer of returns object name., may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_getname(Lib3MF_Object pObject, const Lib3MF_uint32 nNameBufferSize, Lib3MF_uint32* pNameNeededChars, char * pNameBuffer); /** * Sets an object's name string * * @param[in] pObject - Object instance. * @param[in] pName - new object name. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_setname(Lib3MF_Object pObject, const char * pName); /** * Retrieves an object's part number * * @param[in] pObject - Object instance. * @param[in] nPartNumberBufferSize - size of the buffer (including trailing 0) * @param[out] pPartNumberNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pPartNumberBuffer - buffer of returns object part number., may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_getpartnumber(Lib3MF_Object pObject, const Lib3MF_uint32 nPartNumberBufferSize, Lib3MF_uint32* pPartNumberNeededChars, char * pPartNumberBuffer); /** * Sets an objects partnumber string * * @param[in] pObject - Object instance. * @param[in] pPartNumber - new object part number. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_setpartnumber(Lib3MF_Object pObject, const char * pPartNumber); /** * Retrieves, if an object is a mesh object * * @param[in] pObject - Object instance. * @param[out] pIsMeshObject - returns, whether the object is a mesh object * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_ismeshobject(Lib3MF_Object pObject, bool * pIsMeshObject); /** * Retrieves, if an object is a components object * * @param[in] pObject - Object instance. * @param[out] pIsComponentsObject - returns, whether the object is a components object * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_iscomponentsobject(Lib3MF_Object pObject, bool * pIsComponentsObject); /** * Retrieves, if the object is valid according to the core spec. For mesh objects, we distinguish between the type attribute of the object:In case of object type other, this always means false.In case of object type model or solidsupport, this means, if the mesh suffices all requirements of the core spec chapter 4.1.In case of object type support or surface, this always means true.A component objects is valid if and only if it contains at least one component and all child components are valid objects. * * @param[in] pObject - Object instance. * @param[out] pIsValid - returns whether the object is a valid object description * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_isvalid(Lib3MF_Object pObject, bool * pIsValid); /** * Use an existing attachment as thumbnail for this object * * @param[in] pObject - Object instance. * @param[in] pAttachment - Instance of a new or the existing thumbnailattachment object. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_setattachmentasthumbnail(Lib3MF_Object pObject, Lib3MF_Attachment pAttachment); /** * Get the attachment containing the object thumbnail. * * @param[in] pObject - Object instance. * @param[out] pAttachment - Instance of the thumbnailattachment object or NULL. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_getthumbnailattachment(Lib3MF_Object pObject, Lib3MF_Attachment * pAttachment); /** * Clears the attachment. The attachment instance is not removed from the package. * * @param[in] pObject - Object instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_clearthumbnailattachment(Lib3MF_Object pObject); /** * Returns the outbox of a build item * * @param[in] pObject - Object instance. * @param[out] pOutbox - Outbox of this build item * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_getoutbox(Lib3MF_Object pObject, Lib3MF::sBox * pOutbox); /** * Retrieves an object's uuid string (see production extension specification) * * @param[in] pObject - Object instance. * @param[out] pHasUUID - flag whether the build item has a UUID * @param[in] nUUIDBufferSize - size of the buffer (including trailing 0) * @param[out] pUUIDNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pUUIDBuffer - buffer of returns object uuid., may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_getuuid(Lib3MF_Object pObject, bool * pHasUUID, const Lib3MF_uint32 nUUIDBufferSize, Lib3MF_uint32* pUUIDNeededChars, char * pUUIDBuffer); /** * Sets a build object's uuid string (see production extension specification) * * @param[in] pObject - Object instance. * @param[in] pUUID - new object uuid string. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_setuuid(Lib3MF_Object pObject, const char * pUUID); /** * Returns the metadatagroup of this object * * @param[in] pObject - Object instance. * @param[out] pMetaDataGroup - returns an Instance of the metadatagroup of this object * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_getmetadatagroup(Lib3MF_Object pObject, Lib3MF_MetaDataGroup * pMetaDataGroup); /** * set the meshresolution of the mesh object * * @param[in] pObject - Object instance. * @param[in] eMeshResolution - meshresolution of this object * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_setslicesmeshresolution(Lib3MF_Object pObject, Lib3MF::eSlicesMeshResolution eMeshResolution); /** * get the meshresolution of the mesh object * * @param[in] pObject - Object instance. * @param[out] pMeshResolution - meshresolution of this object * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_getslicesmeshresolution(Lib3MF_Object pObject, Lib3MF::eSlicesMeshResolution * pMeshResolution); /** * returns whether the Object has a slice stack. If Recursive is true, also checks whether any references object has a slice stack * * @param[in] pObject - Object instance. * @param[in] bRecursive - check also all referenced objects? * @param[out] pHasSlices - does the object have a slice stack? * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_hasslices(Lib3MF_Object pObject, bool bRecursive, bool * pHasSlices); /** * unlinks the attached slicestack from this object. If no slice stack is attached, do noting. * * @param[in] pObject - Object instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_clearslicestack(Lib3MF_Object pObject); /** * get the Slicestack attached to the object * * @param[in] pObject - Object instance. * @param[out] pSliceStackInstance - returns the slicestack instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_getslicestack(Lib3MF_Object pObject, Lib3MF_SliceStack * pSliceStackInstance); /** * assigns a slicestack to the object * * @param[in] pObject - Object instance. * @param[in] pSliceStackInstance - the new slice stack of this Object * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_object_assignslicestack(Lib3MF_Object pObject, Lib3MF_SliceStack pSliceStackInstance); /************************************************************************************************************************* Class definition for MeshObject **************************************************************************************************************************/ /** * Returns the vertex count of a mesh object. * * @param[in] pMeshObject - MeshObject instance. * @param[out] pVertexCount - filled with the vertex count. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_getvertexcount(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 * pVertexCount); /** * Returns the triangle count of a mesh object. * * @param[in] pMeshObject - MeshObject instance. * @param[out] pVertexCount - filled with the triangle count. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_gettrianglecount(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 * pVertexCount); /** * Returns the vertex count of a mesh object. * * @param[in] pMeshObject - MeshObject instance. * @param[in] nIndex - Index of the vertex (0 to vertexcount - 1) * @param[out] pCoordinates - filled with the vertex coordinates. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_getvertex(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 nIndex, Lib3MF::sPosition * pCoordinates); /** * Sets the coordinates of a single vertex of a mesh object * * @param[in] pMeshObject - MeshObject instance. * @param[in] nIndex - Index of the vertex (0 to vertexcount - 1) * @param[in] pCoordinates - contains the vertex coordinates. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_setvertex(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 nIndex, const Lib3MF::sPosition * pCoordinates); /** * Adds a single vertex to a mesh object * * @param[in] pMeshObject - MeshObject instance. * @param[in] pCoordinates - contains the vertex coordinates. * @param[out] pNewIndex - Index of the new vertex * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_addvertex(Lib3MF_MeshObject pMeshObject, const Lib3MF::sPosition * pCoordinates, Lib3MF_uint32 * pNewIndex); /** * Obtains all vertex positions of a mesh object * * @param[in] pMeshObject - MeshObject instance. * @param[in] nVerticesBufferSize - Number of elements in buffer * @param[out] pVerticesNeededCount - will be filled with the count of the written elements, or needed buffer size. * @param[out] pVerticesBuffer - Position buffer of contains the vertex coordinates. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_getvertices(Lib3MF_MeshObject pMeshObject, const Lib3MF_uint64 nVerticesBufferSize, Lib3MF_uint64* pVerticesNeededCount, Lib3MF::sPosition * pVerticesBuffer); /** * Returns indices of a single triangle of a mesh object. * * @param[in] pMeshObject - MeshObject instance. * @param[in] nIndex - Index of the triangle (0 to trianglecount - 1) * @param[out] pIndices - filled with the triangle indices. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_gettriangle(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 nIndex, Lib3MF::sTriangle * pIndices); /** * Sets the indices of a single triangle of a mesh object. * * @param[in] pMeshObject - MeshObject instance. * @param[in] nIndex - Index of the triangle (0 to trianglecount - 1) * @param[in] pIndices - contains the triangle indices. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_settriangle(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 nIndex, const Lib3MF::sTriangle * pIndices); /** * Adds a single triangle to a mesh object * * @param[in] pMeshObject - MeshObject instance. * @param[in] pIndices - contains the triangle indices. * @param[out] pNewIndex - Index of the new triangle * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_addtriangle(Lib3MF_MeshObject pMeshObject, const Lib3MF::sTriangle * pIndices, Lib3MF_uint32 * pNewIndex); /** * Get all triangles of a mesh object * * @param[in] pMeshObject - MeshObject instance. * @param[in] nIndicesBufferSize - Number of elements in buffer * @param[out] pIndicesNeededCount - will be filled with the count of the written elements, or needed buffer size. * @param[out] pIndicesBuffer - Triangle buffer of contains the triangle indices. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_gettriangleindices(Lib3MF_MeshObject pMeshObject, const Lib3MF_uint64 nIndicesBufferSize, Lib3MF_uint64* pIndicesNeededCount, Lib3MF::sTriangle * pIndicesBuffer); /** * Sets the property at the object-level of the mesh object. * * @param[in] pMeshObject - MeshObject instance. * @param[in] nUniqueResourceID - the object-level Property UniqueResourceID. * @param[in] nPropertyID - the object-level PropertyID. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_setobjectlevelproperty(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 nUniqueResourceID, Lib3MF_uint32 nPropertyID); /** * Gets the property at the object-level of the mesh object. * * @param[in] pMeshObject - MeshObject instance. * @param[out] pUniqueResourceID - the object-level Property UniqueResourceID. * @param[out] pPropertyID - the object-level PropertyID. * @param[out] pHasObjectLevelProperty - Has an object-level property been specified? * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_getobjectlevelproperty(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 * pUniqueResourceID, Lib3MF_uint32 * pPropertyID, bool * pHasObjectLevelProperty); /** * Sets the properties of a single triangle of a mesh object. * * @param[in] pMeshObject - MeshObject instance. * @param[in] nIndex - Index of the triangle (0 to trianglecount - 1) * @param[in] pProperties - contains the triangle properties. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_settriangleproperties(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 nIndex, const Lib3MF::sTriangleProperties * pProperties); /** * Gets the properties of a single triangle of a mesh object. * * @param[in] pMeshObject - MeshObject instance. * @param[in] nIndex - Index of the triangle (0 to trianglecount - 1) * @param[out] pProperty - returns the triangle properties. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_gettriangleproperties(Lib3MF_MeshObject pMeshObject, Lib3MF_uint32 nIndex, Lib3MF::sTriangleProperties * pProperty); /** * Sets the properties of all triangles of a mesh object. Sets the object level property to the first entry of the passed triangle properties, if not yet specified. * * @param[in] pMeshObject - MeshObject instance. * @param[in] nPropertiesArrayBufferSize - Number of elements in buffer * @param[in] pPropertiesArrayBuffer - TriangleProperties buffer of contains the triangle properties array. Must have trianglecount elements. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_setalltriangleproperties(Lib3MF_MeshObject pMeshObject, Lib3MF_uint64 nPropertiesArrayBufferSize, const Lib3MF::sTriangleProperties * pPropertiesArrayBuffer); /** * Gets the properties of all triangles of a mesh object. * * @param[in] pMeshObject - MeshObject instance. * @param[in] nPropertiesArrayBufferSize - Number of elements in buffer * @param[out] pPropertiesArrayNeededCount - will be filled with the count of the written elements, or needed buffer size. * @param[out] pPropertiesArrayBuffer - TriangleProperties buffer of returns the triangle properties array. Must have trianglecount elements. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_getalltriangleproperties(Lib3MF_MeshObject pMeshObject, const Lib3MF_uint64 nPropertiesArrayBufferSize, Lib3MF_uint64* pPropertiesArrayNeededCount, Lib3MF::sTriangleProperties * pPropertiesArrayBuffer); /** * Clears all properties of this mesh object (triangle and object-level). * * @param[in] pMeshObject - MeshObject instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_clearallproperties(Lib3MF_MeshObject pMeshObject); /** * Set all triangles of a mesh object * * @param[in] pMeshObject - MeshObject instance. * @param[in] nVerticesBufferSize - Number of elements in buffer * @param[in] pVerticesBuffer - Position buffer of contains the positions. * @param[in] nIndicesBufferSize - Number of elements in buffer * @param[in] pIndicesBuffer - Triangle buffer of contains the triangle indices. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_setgeometry(Lib3MF_MeshObject pMeshObject, Lib3MF_uint64 nVerticesBufferSize, const Lib3MF::sPosition * pVerticesBuffer, Lib3MF_uint64 nIndicesBufferSize, const Lib3MF::sTriangle * pIndicesBuffer); /** * Retrieves, if an object describes a topologically oriented and manifold mesh, according to the core spec. * * @param[in] pMeshObject - MeshObject instance. * @param[out] pIsManifoldAndOriented - returns, if the object is oriented and manifold. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_ismanifoldandoriented(Lib3MF_MeshObject pMeshObject, bool * pIsManifoldAndOriented); /** * Retrieves the BeamLattice within this MeshObject. * * @param[in] pMeshObject - MeshObject instance. * @param[out] pTheBeamLattice - the BeamLattice within this MeshObject * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_meshobject_beamlattice(Lib3MF_MeshObject pMeshObject, Lib3MF_BeamLattice * pTheBeamLattice); /************************************************************************************************************************* Class definition for BeamLattice **************************************************************************************************************************/ /** * Returns the minimal length of beams for the beamlattice. * * @param[in] pBeamLattice - BeamLattice instance. * @param[out] pMinLength - minimal length of beams for the beamlattice * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_getminlength(Lib3MF_BeamLattice pBeamLattice, Lib3MF_double * pMinLength); /** * Sets the minimal length of beams for the beamlattice. * * @param[in] pBeamLattice - BeamLattice instance. * @param[in] dMinLength - minimal length of beams for the beamlattice * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_setminlength(Lib3MF_BeamLattice pBeamLattice, Lib3MF_double dMinLength); /** * Returns the clipping mode and the clipping-mesh for the beamlattice of this mesh. * * @param[in] pBeamLattice - BeamLattice instance. * @param[out] pClipMode - contains the clip mode of this mesh * @param[out] pUniqueResourceID - filled with the UniqueResourceID of the clipping mesh-object or an undefined value if pClipMode is MODELBEAMLATTICECLIPMODE_NONE * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_getclipping(Lib3MF_BeamLattice pBeamLattice, Lib3MF::eBeamLatticeClipMode * pClipMode, Lib3MF_uint32 * pUniqueResourceID); /** * Sets the clipping mode and the clipping-mesh for the beamlattice of this mesh. * * @param[in] pBeamLattice - BeamLattice instance. * @param[in] eClipMode - contains the clip mode of this mesh * @param[in] nUniqueResourceID - the UniqueResourceID of the clipping mesh-object. This mesh-object has to be defined before setting the Clipping. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_setclipping(Lib3MF_BeamLattice pBeamLattice, Lib3MF::eBeamLatticeClipMode eClipMode, Lib3MF_uint32 nUniqueResourceID); /** * Returns the representation-mesh for the beamlattice of this mesh. * * @param[in] pBeamLattice - BeamLattice instance. * @param[out] pHasRepresentation - flag whether the beamlattice has a representation mesh. * @param[out] pUniqueResourceID - filled with the UniqueResourceID of the clipping mesh-object. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_getrepresentation(Lib3MF_BeamLattice pBeamLattice, bool * pHasRepresentation, Lib3MF_uint32 * pUniqueResourceID); /** * Sets the representation-mesh for the beamlattice of this mesh. * * @param[in] pBeamLattice - BeamLattice instance. * @param[in] nUniqueResourceID - the UniqueResourceID of the representation mesh-object. This mesh-object has to be defined before setting the representation. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_setrepresentation(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint32 nUniqueResourceID); /** * Returns the ball mode and the default ball radius for the beamlattice of this mesh. * * @param[in] pBeamLattice - BeamLattice instance. * @param[out] pBallMode - contains the ball mode of this mesh * @param[out] pBallRadius - default ball radius of balls for the beamlattice * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_getballoptions(Lib3MF_BeamLattice pBeamLattice, Lib3MF::eBeamLatticeBallMode * pBallMode, Lib3MF_double * pBallRadius); /** * Sets the ball mode and thedefault ball radius for the beamlattice. * * @param[in] pBeamLattice - BeamLattice instance. * @param[in] eBallMode - contains the ball mode of this mesh * @param[in] dBallRadius - default ball radius of balls for the beamlattice * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_setballoptions(Lib3MF_BeamLattice pBeamLattice, Lib3MF::eBeamLatticeBallMode eBallMode, Lib3MF_double dBallRadius); /** * Returns the beam count of a mesh object. * * @param[in] pBeamLattice - BeamLattice instance. * @param[out] pCount - filled with the beam count. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_getbeamcount(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint32 * pCount); /** * Returns indices, radii and capmodes of a single beam of a mesh object. * * @param[in] pBeamLattice - BeamLattice instance. * @param[in] nIndex - Index of the beam (0 to beamcount - 1). * @param[out] pBeamInfo - filled with the beam indices, radii and capmodes. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_getbeam(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint32 nIndex, Lib3MF::sBeam * pBeamInfo); /** * Adds a single beam to a mesh object. * * @param[in] pBeamLattice - BeamLattice instance. * @param[in] pBeamInfo - contains the node indices, radii and capmodes. * @param[out] pIndex - filled with the new Index of the beam. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_addbeam(Lib3MF_BeamLattice pBeamLattice, const Lib3MF::sBeam * pBeamInfo, Lib3MF_uint32 * pIndex); /** * Sets the indices, radii and capmodes of a single beam of a mesh object. * * @param[in] pBeamLattice - BeamLattice instance. * @param[in] nIndex - Index of the beam (0 to beamcount - 1). * @param[in] pBeamInfo - filled with the beam indices, radii and capmodes. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_setbeam(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint32 nIndex, const Lib3MF::sBeam * pBeamInfo); /** * Sets all beam indices, radii and capmodes of a mesh object. * * @param[in] pBeamLattice - BeamLattice instance. * @param[in] nBeamInfoBufferSize - Number of elements in buffer * @param[in] pBeamInfoBuffer - Beam buffer of contains information of a number of beams * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_setbeams(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint64 nBeamInfoBufferSize, const Lib3MF::sBeam * pBeamInfoBuffer); /** * obtains all beam indices, radii and capmodes of a mesh object. * * @param[in] pBeamLattice - BeamLattice instance. * @param[in] nBeamInfoBufferSize - Number of elements in buffer * @param[out] pBeamInfoNeededCount - will be filled with the count of the written elements, or needed buffer size. * @param[out] pBeamInfoBuffer - Beam buffer of contains information of all beams * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_getbeams(Lib3MF_BeamLattice pBeamLattice, const Lib3MF_uint64 nBeamInfoBufferSize, Lib3MF_uint64* pBeamInfoNeededCount, Lib3MF::sBeam * pBeamInfoBuffer); /** * Returns the ball count of a mesh object. * * @param[in] pBeamLattice - BeamLattice instance. * @param[out] pCount - filled with the ball count. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_getballcount(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint32 * pCount); /** * Returns index and radius of a single ball of a mesh object. * * @param[in] pBeamLattice - BeamLattice instance. * @param[in] nIndex - Index of the ball (0 to ballcount - 1). * @param[out] pBallInfo - filled with the ball node index and radius. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_getball(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint32 nIndex, Lib3MF::sBall * pBallInfo); /** * Adds a single ball to a mesh object. * * @param[in] pBeamLattice - BeamLattice instance. * @param[in] pBallInfo - contains the node index and radius. * @param[out] pIndex - filled with the new Index of the ball. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_addball(Lib3MF_BeamLattice pBeamLattice, const Lib3MF::sBall * pBallInfo, Lib3MF_uint32 * pIndex); /** * Sets the index and radius of a single ball of a mesh object. * * @param[in] pBeamLattice - BeamLattice instance. * @param[in] nIndex - Index of the ball (0 to ballcount - 1). * @param[in] pBallInfo - filled with the ball node index and radius. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_setball(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint32 nIndex, const Lib3MF::sBall * pBallInfo); /** * Sets all ball indices and radii of a mesh object. * * @param[in] pBeamLattice - BeamLattice instance. * @param[in] nBallInfoBufferSize - Number of elements in buffer * @param[in] pBallInfoBuffer - Ball buffer of contains information of a number of balls * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_setballs(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint64 nBallInfoBufferSize, const Lib3MF::sBall * pBallInfoBuffer); /** * obtains all ball indices and radii of a mesh object. * * @param[in] pBeamLattice - BeamLattice instance. * @param[in] nBallInfoBufferSize - Number of elements in buffer * @param[out] pBallInfoNeededCount - will be filled with the count of the written elements, or needed buffer size. * @param[out] pBallInfoBuffer - Ball buffer of contains information of all balls * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_getballs(Lib3MF_BeamLattice pBeamLattice, const Lib3MF_uint64 nBallInfoBufferSize, Lib3MF_uint64* pBallInfoNeededCount, Lib3MF::sBall * pBallInfoBuffer); /** * Returns the number of beamsets of a mesh object. * * @param[in] pBeamLattice - BeamLattice instance. * @param[out] pCount - filled with the beamset count. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_getbeamsetcount(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint32 * pCount); /** * Adds an empty beamset to a mesh object * * @param[in] pBeamLattice - BeamLattice instance. * @param[out] pBeamSet - the new beamset * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_addbeamset(Lib3MF_BeamLattice pBeamLattice, Lib3MF_BeamSet * pBeamSet); /** * Returns a beamset of a mesh object * * @param[in] pBeamLattice - BeamLattice instance. * @param[in] nIndex - index of the requested beamset (0 ... beamsetcount-1). * @param[out] pBeamSet - the requested beamset * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamlattice_getbeamset(Lib3MF_BeamLattice pBeamLattice, Lib3MF_uint32 nIndex, Lib3MF_BeamSet * pBeamSet); /************************************************************************************************************************* Class definition for Component **************************************************************************************************************************/ /** * Returns the Resource Instance of the component. * * @param[in] pComponent - Component instance. * @param[out] pObjectResource - filled with the Resource Instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_component_getobjectresource(Lib3MF_Component pComponent, Lib3MF_Object * pObjectResource); /** * Returns the UniqueResourceID of the component. * * @param[in] pComponent - Component instance. * @param[out] pUniqueResourceID - returns the UniqueResourceID. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_component_getobjectresourceid(Lib3MF_Component pComponent, Lib3MF_uint32 * pUniqueResourceID); /** * returns, whether a component has a UUID and, if true, the component's UUID * * @param[in] pComponent - Component instance. * @param[out] pHasUUID - flag whether the component has a UUID * @param[in] nUUIDBufferSize - size of the buffer (including trailing 0) * @param[out] pUUIDNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pUUIDBuffer - buffer of the UUID as string of the form 'xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx', may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_component_getuuid(Lib3MF_Component pComponent, bool * pHasUUID, const Lib3MF_uint32 nUUIDBufferSize, Lib3MF_uint32* pUUIDNeededChars, char * pUUIDBuffer); /** * sets the component's UUID * * @param[in] pComponent - Component instance. * @param[in] pUUID - the UUID as string of the form 'xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx' * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_component_setuuid(Lib3MF_Component pComponent, const char * pUUID); /** * Returns, if the component has a different transformation than the identity matrix * * @param[in] pComponent - Component instance. * @param[out] pHasTransform - if true is returned, the transformation is not equal than the identity * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_component_hastransform(Lib3MF_Component pComponent, bool * pHasTransform); /** * Returns the transformation matrix of the component. * * @param[in] pComponent - Component instance. * @param[out] pTransform - filled with the component transformation matrix * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_component_gettransform(Lib3MF_Component pComponent, Lib3MF::sTransform * pTransform); /** * Sets the transformation matrix of the component. * * @param[in] pComponent - Component instance. * @param[in] pTransform - new transformation matrix * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_component_settransform(Lib3MF_Component pComponent, const Lib3MF::sTransform * pTransform); /************************************************************************************************************************* Class definition for ComponentsObject **************************************************************************************************************************/ /** * Adds a new component to a components object. * * @param[in] pComponentsObject - ComponentsObject instance. * @param[in] pObjectResource - object to add as component. Must not lead to circular references! * @param[in] pTransform - optional transform matrix for the component. * @param[out] pComponentInstance - new component instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_componentsobject_addcomponent(Lib3MF_ComponentsObject pComponentsObject, Lib3MF_Object pObjectResource, const Lib3MF::sTransform * pTransform, Lib3MF_Component * pComponentInstance); /** * Retrieves a component from a component object. * * @param[in] pComponentsObject - ComponentsObject instance. * @param[in] nIndex - index of the component to retrieve (0 to componentcount - 1) * @param[out] pComponentInstance - component instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_componentsobject_getcomponent(Lib3MF_ComponentsObject pComponentsObject, Lib3MF_uint32 nIndex, Lib3MF_Component * pComponentInstance); /** * Retrieves a component count of a component object. * * @param[in] pComponentsObject - ComponentsObject instance. * @param[out] pCount - returns the component count * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_componentsobject_getcomponentcount(Lib3MF_ComponentsObject pComponentsObject, Lib3MF_uint32 * pCount); /************************************************************************************************************************* Class definition for BeamSet **************************************************************************************************************************/ /** * Sets a beamset's name string * * @param[in] pBeamSet - BeamSet instance. * @param[in] pName - new name of the beamset. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamset_setname(Lib3MF_BeamSet pBeamSet, const char * pName); /** * Retrieves a beamset's name string * * @param[in] pBeamSet - BeamSet instance. * @param[in] nNameBufferSize - size of the buffer (including trailing 0) * @param[out] pNameNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pNameBuffer - buffer of returns the name of the beamset., may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamset_getname(Lib3MF_BeamSet pBeamSet, const Lib3MF_uint32 nNameBufferSize, Lib3MF_uint32* pNameNeededChars, char * pNameBuffer); /** * Sets a beamset's identifier string * * @param[in] pBeamSet - BeamSet instance. * @param[in] pIdentifier - new name of the beamset. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamset_setidentifier(Lib3MF_BeamSet pBeamSet, const char * pIdentifier); /** * Retrieves a beamset's identifier string * * @param[in] pBeamSet - BeamSet instance. * @param[in] nIdentifierBufferSize - size of the buffer (including trailing 0) * @param[out] pIdentifierNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pIdentifierBuffer - buffer of returns the identifier of the beamset., may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamset_getidentifier(Lib3MF_BeamSet pBeamSet, const Lib3MF_uint32 nIdentifierBufferSize, Lib3MF_uint32* pIdentifierNeededChars, char * pIdentifierBuffer); /** * Retrieves the reference count of a beamset * * @param[in] pBeamSet - BeamSet instance. * @param[out] pCount - returns the reference count * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamset_getreferencecount(Lib3MF_BeamSet pBeamSet, Lib3MF_uint32 * pCount); /** * Sets the references of a beamset * * @param[in] pBeamSet - BeamSet instance. * @param[in] nReferencesBufferSize - Number of elements in buffer * @param[in] pReferencesBuffer - uint32 buffer of the new indices of all beams in this beamset * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamset_setreferences(Lib3MF_BeamSet pBeamSet, Lib3MF_uint64 nReferencesBufferSize, const Lib3MF_uint32 * pReferencesBuffer); /** * Retrieves the references of a beamset * * @param[in] pBeamSet - BeamSet instance. * @param[in] nReferencesBufferSize - Number of elements in buffer * @param[out] pReferencesNeededCount - will be filled with the count of the written elements, or needed buffer size. * @param[out] pReferencesBuffer - uint32 buffer of retrieves the indices of all beams in this beamset * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamset_getreferences(Lib3MF_BeamSet pBeamSet, const Lib3MF_uint64 nReferencesBufferSize, Lib3MF_uint64* pReferencesNeededCount, Lib3MF_uint32 * pReferencesBuffer); /** * Retrieves the ball reference count of a beamset * * @param[in] pBeamSet - BeamSet instance. * @param[out] pCount - returns the ball reference count * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamset_getballreferencecount(Lib3MF_BeamSet pBeamSet, Lib3MF_uint32 * pCount); /** * Sets the ball references of a beamset * * @param[in] pBeamSet - BeamSet instance. * @param[in] nBallReferencesBufferSize - Number of elements in buffer * @param[in] pBallReferencesBuffer - uint32 buffer of the new indices of all balls in this beamset * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamset_setballreferences(Lib3MF_BeamSet pBeamSet, Lib3MF_uint64 nBallReferencesBufferSize, const Lib3MF_uint32 * pBallReferencesBuffer); /** * Retrieves the ball references of a beamset * * @param[in] pBeamSet - BeamSet instance. * @param[in] nBallReferencesBufferSize - Number of elements in buffer * @param[out] pBallReferencesNeededCount - will be filled with the count of the written elements, or needed buffer size. * @param[out] pBallReferencesBuffer - uint32 buffer of retrieves the indices of all balls in this beamset * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_beamset_getballreferences(Lib3MF_BeamSet pBeamSet, const Lib3MF_uint64 nBallReferencesBufferSize, Lib3MF_uint64* pBallReferencesNeededCount, Lib3MF_uint32 * pBallReferencesBuffer); /************************************************************************************************************************* Class definition for BaseMaterialGroup **************************************************************************************************************************/ /** * Retrieves the count of base materials in the material group. * * @param[in] pBaseMaterialGroup - BaseMaterialGroup instance. * @param[out] pCount - returns the count of base materials. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_basematerialgroup_getcount(Lib3MF_BaseMaterialGroup pBaseMaterialGroup, Lib3MF_uint32 * pCount); /** * returns all the PropertyIDs of all materials in this group * * @param[in] pBaseMaterialGroup - BaseMaterialGroup instance. * @param[in] nPropertyIDsBufferSize - Number of elements in buffer * @param[out] pPropertyIDsNeededCount - will be filled with the count of the written elements, or needed buffer size. * @param[out] pPropertyIDsBuffer - uint32 buffer of PropertyID of the material in the material group. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_basematerialgroup_getallpropertyids(Lib3MF_BaseMaterialGroup pBaseMaterialGroup, const Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer); /** * Adds a new material to the material group * * @param[in] pBaseMaterialGroup - BaseMaterialGroup instance. * @param[in] pName - new name of the base material. * @param[in] pDisplayColor - Display color of the material * @param[out] pPropertyID - returns new PropertyID of the new material in the material group. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_basematerialgroup_addmaterial(Lib3MF_BaseMaterialGroup pBaseMaterialGroup, const char * pName, const Lib3MF::sColor * pDisplayColor, Lib3MF_uint32 * pPropertyID); /** * Removes a material from the material group. * * @param[in] pBaseMaterialGroup - BaseMaterialGroup instance. * @param[in] nPropertyID - PropertyID of the material in the material group. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_basematerialgroup_removematerial(Lib3MF_BaseMaterialGroup pBaseMaterialGroup, Lib3MF_uint32 nPropertyID); /** * Returns the base material's name * * @param[in] pBaseMaterialGroup - BaseMaterialGroup instance. * @param[in] nPropertyID - PropertyID of the material in the material group. * @param[in] nNameBufferSize - size of the buffer (including trailing 0) * @param[out] pNameNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pNameBuffer - buffer of returns the name of the base material., may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_basematerialgroup_getname(Lib3MF_BaseMaterialGroup pBaseMaterialGroup, Lib3MF_uint32 nPropertyID, const Lib3MF_uint32 nNameBufferSize, Lib3MF_uint32* pNameNeededChars, char * pNameBuffer); /** * Sets a base material's name * * @param[in] pBaseMaterialGroup - BaseMaterialGroup instance. * @param[in] nPropertyID - PropertyID of the material in the material group. * @param[in] pName - new name of the base material. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_basematerialgroup_setname(Lib3MF_BaseMaterialGroup pBaseMaterialGroup, Lib3MF_uint32 nPropertyID, const char * pName); /** * Sets a base material's display color. * * @param[in] pBaseMaterialGroup - BaseMaterialGroup instance. * @param[in] nPropertyID - PropertyID of the material in the material group. * @param[in] pTheColor - The base material's display color * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_basematerialgroup_setdisplaycolor(Lib3MF_BaseMaterialGroup pBaseMaterialGroup, Lib3MF_uint32 nPropertyID, const Lib3MF::sColor * pTheColor); /** * Returns a base material's display color. * * @param[in] pBaseMaterialGroup - BaseMaterialGroup instance. * @param[in] nPropertyID - PropertyID of the material in the material group. * @param[out] pTheColor - The base material's display color * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_basematerialgroup_getdisplaycolor(Lib3MF_BaseMaterialGroup pBaseMaterialGroup, Lib3MF_uint32 nPropertyID, Lib3MF::sColor * pTheColor); /************************************************************************************************************************* Class definition for ColorGroup **************************************************************************************************************************/ /** * Retrieves the count of base materials in this Color Group. * * @param[in] pColorGroup - ColorGroup instance. * @param[out] pCount - returns the count of colors within this color group. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_colorgroup_getcount(Lib3MF_ColorGroup pColorGroup, Lib3MF_uint32 * pCount); /** * returns all the PropertyIDs of all colors within this group * * @param[in] pColorGroup - ColorGroup instance. * @param[in] nPropertyIDsBufferSize - Number of elements in buffer * @param[out] pPropertyIDsNeededCount - will be filled with the count of the written elements, or needed buffer size. * @param[out] pPropertyIDsBuffer - uint32 buffer of PropertyID of the color in the color group. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_colorgroup_getallpropertyids(Lib3MF_ColorGroup pColorGroup, const Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer); /** * Adds a new value. * * @param[in] pColorGroup - ColorGroup instance. * @param[in] pTheColor - The new color * @param[out] pPropertyID - PropertyID of the new color within this color group. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_colorgroup_addcolor(Lib3MF_ColorGroup pColorGroup, const Lib3MF::sColor * pTheColor, Lib3MF_uint32 * pPropertyID); /** * Removes a color from the color group. * * @param[in] pColorGroup - ColorGroup instance. * @param[in] nPropertyID - PropertyID of the color to be removed from the color group. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_colorgroup_removecolor(Lib3MF_ColorGroup pColorGroup, Lib3MF_uint32 nPropertyID); /** * Sets a color value. * * @param[in] pColorGroup - ColorGroup instance. * @param[in] nPropertyID - PropertyID of a color within this color group. * @param[in] pTheColor - The color * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_colorgroup_setcolor(Lib3MF_ColorGroup pColorGroup, Lib3MF_uint32 nPropertyID, const Lib3MF::sColor * pTheColor); /** * Sets a color value. * * @param[in] pColorGroup - ColorGroup instance. * @param[in] nPropertyID - PropertyID of a color within this color group. * @param[out] pTheColor - The color * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_colorgroup_getcolor(Lib3MF_ColorGroup pColorGroup, Lib3MF_uint32 nPropertyID, Lib3MF::sColor * pTheColor); /************************************************************************************************************************* Class definition for Texture2DGroup **************************************************************************************************************************/ /** * Retrieves the count of tex2coords in the Texture2DGroup. * * @param[in] pTexture2DGroup - Texture2DGroup instance. * @param[out] pCount - returns the count of tex2coords. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2dgroup_getcount(Lib3MF_Texture2DGroup pTexture2DGroup, Lib3MF_uint32 * pCount); /** * returns all the PropertyIDs of all tex2coords in this Texture2DGroup * * @param[in] pTexture2DGroup - Texture2DGroup instance. * @param[in] nPropertyIDsBufferSize - Number of elements in buffer * @param[out] pPropertyIDsNeededCount - will be filled with the count of the written elements, or needed buffer size. * @param[out] pPropertyIDsBuffer - uint32 buffer of PropertyID of the tex2coords in the Texture2DGroup. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2dgroup_getallpropertyids(Lib3MF_Texture2DGroup pTexture2DGroup, const Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer); /** * Adds a new tex2coord to the Texture2DGroup * * @param[in] pTexture2DGroup - Texture2DGroup instance. * @param[in] pUVCoordinate - The u/v-coordinate within the texture, horizontally right/vertically up from the origin in the lower left of the texture. * @param[out] pPropertyID - returns new PropertyID of the new tex2coord in the Texture2DGroup. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2dgroup_addtex2coord(Lib3MF_Texture2DGroup pTexture2DGroup, const Lib3MF::sTex2Coord * pUVCoordinate, Lib3MF_uint32 * pPropertyID); /** * Obtains a tex2coord to the Texture2DGroup * * @param[in] pTexture2DGroup - Texture2DGroup instance. * @param[in] nPropertyID - the PropertyID of the tex2coord in the Texture2DGroup. * @param[out] pUVCoordinate - The u/v-coordinate within the texture, horizontally right/vertically up from the origin in the lower left of the texture. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2dgroup_gettex2coord(Lib3MF_Texture2DGroup pTexture2DGroup, Lib3MF_uint32 nPropertyID, Lib3MF::sTex2Coord * pUVCoordinate); /** * Removes a tex2coords from the Texture2DGroup. * * @param[in] pTexture2DGroup - Texture2DGroup instance. * @param[in] nPropertyID - PropertyID of the tex2coords in the Texture2DGroup. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2dgroup_removetex2coord(Lib3MF_Texture2DGroup pTexture2DGroup, Lib3MF_uint32 nPropertyID); /** * Obtains the texture2D instance of this group. * * @param[in] pTexture2DGroup - Texture2DGroup instance. * @param[out] pTexture2DInstance - the texture2D instance of this group. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2dgroup_gettexture2d(Lib3MF_Texture2DGroup pTexture2DGroup, Lib3MF_Texture2D * pTexture2DInstance); /************************************************************************************************************************* Class definition for CompositeMaterials **************************************************************************************************************************/ /** * Retrieves the count of Composite-s in the CompositeMaterials. * * @param[in] pCompositeMaterials - CompositeMaterials instance. * @param[out] pCount - returns the count of Composite-s * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_compositematerials_getcount(Lib3MF_CompositeMaterials pCompositeMaterials, Lib3MF_uint32 * pCount); /** * returns all the PropertyIDs of all Composite-Mixing Values in this CompositeMaterials * * @param[in] pCompositeMaterials - CompositeMaterials instance. * @param[in] nPropertyIDsBufferSize - Number of elements in buffer * @param[out] pPropertyIDsNeededCount - will be filled with the count of the written elements, or needed buffer size. * @param[out] pPropertyIDsBuffer - uint32 buffer of PropertyID of the Composite-Mixing Values in the CompositeMaterials. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_compositematerials_getallpropertyids(Lib3MF_CompositeMaterials pCompositeMaterials, const Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer); /** * Obtains the BaseMaterialGroup instance of this CompositeMaterials. * * @param[in] pCompositeMaterials - CompositeMaterials instance. * @param[out] pBaseMaterialGroupInstance - returns the BaseMaterialGroup instance of this CompositeMaterials * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_compositematerials_getbasematerialgroup(Lib3MF_CompositeMaterials pCompositeMaterials, Lib3MF_BaseMaterialGroup * pBaseMaterialGroupInstance); /** * Adds a new Composite-Mixing Values to the CompositeMaterials. * * @param[in] pCompositeMaterials - CompositeMaterials instance. * @param[in] nCompositeBufferSize - Number of elements in buffer * @param[in] pCompositeBuffer - CompositeConstituent buffer of The Composite Constituents to be added as composite * @param[out] pPropertyID - returns new PropertyID of the new Composite in the CompositeMaterials. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_compositematerials_addcomposite(Lib3MF_CompositeMaterials pCompositeMaterials, Lib3MF_uint64 nCompositeBufferSize, const Lib3MF::sCompositeConstituent * pCompositeBuffer, Lib3MF_uint32 * pPropertyID); /** * Removes a Composite-Maxing Ratio from the CompositeMaterials. * * @param[in] pCompositeMaterials - CompositeMaterials instance. * @param[in] nPropertyID - PropertyID of the Composite-Mixing Values in the CompositeMaterials to be removed. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_compositematerials_removecomposite(Lib3MF_CompositeMaterials pCompositeMaterials, Lib3MF_uint32 nPropertyID); /** * Obtains a Composite-Maxing Ratio of this CompositeMaterials. * * @param[in] pCompositeMaterials - CompositeMaterials instance. * @param[in] nPropertyID - the PropertyID of the Composite-Maxing Ratio in the CompositeMaterials. * @param[in] nCompositeBufferSize - Number of elements in buffer * @param[out] pCompositeNeededCount - will be filled with the count of the written elements, or needed buffer size. * @param[out] pCompositeBuffer - CompositeConstituent buffer of The Composite-Mixing Values with the given PropertyID * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_compositematerials_getcomposite(Lib3MF_CompositeMaterials pCompositeMaterials, Lib3MF_uint32 nPropertyID, const Lib3MF_uint64 nCompositeBufferSize, Lib3MF_uint64* pCompositeNeededCount, Lib3MF::sCompositeConstituent * pCompositeBuffer); /************************************************************************************************************************* Class definition for MultiPropertyGroup **************************************************************************************************************************/ /** * Retrieves the count of MultiProperty-s in the MultiPropertyGroup. * * @param[in] pMultiPropertyGroup - MultiPropertyGroup instance. * @param[out] pCount - returns the count of MultiProperty-s * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_multipropertygroup_getcount(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, Lib3MF_uint32 * pCount); /** * returns all the PropertyIDs of all MultiProperty-s in this MultiPropertyGroup * * @param[in] pMultiPropertyGroup - MultiPropertyGroup instance. * @param[in] nPropertyIDsBufferSize - Number of elements in buffer * @param[out] pPropertyIDsNeededCount - will be filled with the count of the written elements, or needed buffer size. * @param[out] pPropertyIDsBuffer - uint32 buffer of PropertyID of the MultiProperty-s in the MultiPropertyGroup. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_multipropertygroup_getallpropertyids(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, const Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer); /** * Adds a new MultiProperty to the MultiPropertyGroup. * * @param[in] pMultiPropertyGroup - MultiPropertyGroup instance. * @param[in] nPropertyIDsBufferSize - Number of elements in buffer * @param[in] pPropertyIDsBuffer - uint32 buffer of The PropertyIDs of the new MultiProperty. * @param[out] pPropertyID - returns the PropertyID of the new MultiProperty in the MultiPropertyGroup. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_multipropertygroup_addmultiproperty(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, Lib3MF_uint64 nPropertyIDsBufferSize, const Lib3MF_uint32 * pPropertyIDsBuffer, Lib3MF_uint32 * pPropertyID); /** * Sets the PropertyIDs of a MultiProperty. * * @param[in] pMultiPropertyGroup - MultiPropertyGroup instance. * @param[in] nPropertyID - the PropertyID of the MultiProperty to be changed. * @param[in] nPropertyIDsBufferSize - Number of elements in buffer * @param[in] pPropertyIDsBuffer - uint32 buffer of The new PropertyIDs of the MultiProperty * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_multipropertygroup_setmultiproperty(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, Lib3MF_uint32 nPropertyID, Lib3MF_uint64 nPropertyIDsBufferSize, const Lib3MF_uint32 * pPropertyIDsBuffer); /** * Obtains the PropertyIDs of a MultiProperty. * * @param[in] pMultiPropertyGroup - MultiPropertyGroup instance. * @param[in] nPropertyID - the PropertyID of the MultiProperty to be queried. * @param[in] nPropertyIDsBufferSize - Number of elements in buffer * @param[out] pPropertyIDsNeededCount - will be filled with the count of the written elements, or needed buffer size. * @param[out] pPropertyIDsBuffer - uint32 buffer of The PropertyIDs of the MultiProperty * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_multipropertygroup_getmultiproperty(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, Lib3MF_uint32 nPropertyID, const Lib3MF_uint64 nPropertyIDsBufferSize, Lib3MF_uint64* pPropertyIDsNeededCount, Lib3MF_uint32 * pPropertyIDsBuffer); /** * Removes a MultiProperty from this MultiPropertyGroup. * * @param[in] pMultiPropertyGroup - MultiPropertyGroup instance. * @param[in] nPropertyID - the PropertyID of the MultiProperty to be removed. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_multipropertygroup_removemultiproperty(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, Lib3MF_uint32 nPropertyID); /** * Retrieves the number of layers of this MultiPropertyGroup. * * @param[in] pMultiPropertyGroup - MultiPropertyGroup instance. * @param[out] pCount - returns the number of layers * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_multipropertygroup_getlayercount(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, Lib3MF_uint32 * pCount); /** * Adds a MultiPropertyLayer to this MultiPropertyGroup. * * @param[in] pMultiPropertyGroup - MultiPropertyGroup instance. * @param[in] pTheLayer - The MultiPropertyLayer to add to this MultiPropertyGroup * @param[out] pLayerIndex - returns the index of this MultiPropertyLayer * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_multipropertygroup_addlayer(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, const Lib3MF::sMultiPropertyLayer * pTheLayer, Lib3MF_uint32 * pLayerIndex); /** * Obtains a MultiPropertyLayer of this MultiPropertyGroup. * * @param[in] pMultiPropertyGroup - MultiPropertyGroup instance. * @param[in] nLayerIndex - The Index of the MultiPropertyLayer queried * @param[out] pTheLayer - The MultiPropertyLayer with index LayerIndex within MultiPropertyGroup * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_multipropertygroup_getlayer(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, Lib3MF_uint32 nLayerIndex, Lib3MF::sMultiPropertyLayer * pTheLayer); /** * Removes a MultiPropertyLayer from this MultiPropertyGroup. * * @param[in] pMultiPropertyGroup - MultiPropertyGroup instance. * @param[in] nLayerIndex - The Index of the MultiPropertyLayer to be removed * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_multipropertygroup_removelayer(Lib3MF_MultiPropertyGroup pMultiPropertyGroup, Lib3MF_uint32 nLayerIndex); /************************************************************************************************************************* Class definition for Attachment **************************************************************************************************************************/ /** * Retrieves an attachment's package path. This function will be removed in a later release. * * @param[in] pAttachment - Attachment instance. * @param[in] nPathBufferSize - size of the buffer (including trailing 0) * @param[out] pPathNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pPathBuffer - buffer of returns the attachment's package path string, may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_attachment_getpath(Lib3MF_Attachment pAttachment, const Lib3MF_uint32 nPathBufferSize, Lib3MF_uint32* pPathNeededChars, char * pPathBuffer); /** * Sets an attachment's package path. This function will be removed in a later release. * * @param[in] pAttachment - Attachment instance. * @param[in] pPath - new path of the attachment. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_attachment_setpath(Lib3MF_Attachment pAttachment, const char * pPath); /** * Returns the PackagePart that is this attachment. * * @param[in] pAttachment - Attachment instance. * @param[out] pPackagePart - The PackagePart of this attachment. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_attachment_packagepart(Lib3MF_Attachment pAttachment, Lib3MF_PackagePart * pPackagePart); /** * Retrieves an attachment's relationship type * * @param[in] pAttachment - Attachment instance. * @param[in] nPathBufferSize - size of the buffer (including trailing 0) * @param[out] pPathNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pPathBuffer - buffer of returns the attachment's package relationship type string, may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_attachment_getrelationshiptype(Lib3MF_Attachment pAttachment, const Lib3MF_uint32 nPathBufferSize, Lib3MF_uint32* pPathNeededChars, char * pPathBuffer); /** * Sets an attachment's relationship type. * * @param[in] pAttachment - Attachment instance. * @param[in] pPath - new relationship type string. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_attachment_setrelationshiptype(Lib3MF_Attachment pAttachment, const char * pPath); /** * Writes out the attachment as file. * * @param[in] pAttachment - Attachment instance. * @param[in] pFileName - file to write into. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_attachment_writetofile(Lib3MF_Attachment pAttachment, const char * pFileName); /** * Reads an attachment from a file. The path of this file is only read when this attachment is being written as part of the 3MF packege, or via the WriteToFile or WriteToBuffer-methods. * * @param[in] pAttachment - Attachment instance. * @param[in] pFileName - file to read from. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_attachment_readfromfile(Lib3MF_Attachment pAttachment, const char * pFileName); /** * Reads a model and from the data provided by a callback function * * @param[in] pAttachment - Attachment instance. * @param[in] pTheReadCallback - Callback to call for reading a data chunk * @param[in] nStreamSize - number of bytes the callback returns * @param[in] pTheSeekCallback - Callback to call for seeking in the stream. * @param[in] pUserData - Userdata that is passed to the callback function * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_attachment_readfromcallback(Lib3MF_Attachment pAttachment, Lib3MF::ReadCallback pTheReadCallback, Lib3MF_uint64 nStreamSize, Lib3MF::SeekCallback pTheSeekCallback, Lib3MF_pvoid pUserData); /** * Retrieves the size of the attachment stream * * @param[in] pAttachment - Attachment instance. * @param[out] pStreamSize - the stream size * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_attachment_getstreamsize(Lib3MF_Attachment pAttachment, Lib3MF_uint64 * pStreamSize); /** * Writes out the attachment into a buffer * * @param[in] pAttachment - Attachment instance. * @param[in] nBufferBufferSize - Number of elements in buffer * @param[out] pBufferNeededCount - will be filled with the count of the written elements, or needed buffer size. * @param[out] pBufferBuffer - uint8 buffer of Buffer to write into * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_attachment_writetobuffer(Lib3MF_Attachment pAttachment, const Lib3MF_uint64 nBufferBufferSize, Lib3MF_uint64* pBufferNeededCount, Lib3MF_uint8 * pBufferBuffer); /** * Reads an attachment from a memory buffer * * @param[in] pAttachment - Attachment instance. * @param[in] nBufferBufferSize - Number of elements in buffer * @param[in] pBufferBuffer - uint8 buffer of Buffer to read from * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_attachment_readfrombuffer(Lib3MF_Attachment pAttachment, Lib3MF_uint64 nBufferBufferSize, const Lib3MF_uint8 * pBufferBuffer); /************************************************************************************************************************* Class definition for Texture2D **************************************************************************************************************************/ /** * Retrieves the attachment located at the path of the texture. * * @param[in] pTexture2D - Texture2D instance. * @param[out] pAttachment - attachment that holds the texture's image information. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2d_getattachment(Lib3MF_Texture2D pTexture2D, Lib3MF_Attachment * pAttachment); /** * Sets the texture's package path to the path of the attachment. * * @param[in] pTexture2D - Texture2D instance. * @param[in] pAttachment - attachment that holds the texture's image information. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2d_setattachment(Lib3MF_Texture2D pTexture2D, Lib3MF_Attachment pAttachment); /** * Retrieves a texture's content type. * * @param[in] pTexture2D - Texture2D instance. * @param[out] pContentType - returns content type enum. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2d_getcontenttype(Lib3MF_Texture2D pTexture2D, Lib3MF::eTextureType * pContentType); /** * Retrieves a texture's content type. * * @param[in] pTexture2D - Texture2D instance. * @param[in] eContentType - new Content Type * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2d_setcontenttype(Lib3MF_Texture2D pTexture2D, Lib3MF::eTextureType eContentType); /** * Retrieves a texture's tilestyle type. * * @param[in] pTexture2D - Texture2D instance. * @param[out] pTileStyleU - returns tilestyle type enum. * @param[out] pTileStyleV - returns tilestyle type enum. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2d_gettilestyleuv(Lib3MF_Texture2D pTexture2D, Lib3MF::eTextureTileStyle * pTileStyleU, Lib3MF::eTextureTileStyle * pTileStyleV); /** * Sets a texture's tilestyle type. * * @param[in] pTexture2D - Texture2D instance. * @param[in] eTileStyleU - new tilestyle type enum. * @param[in] eTileStyleV - new tilestyle type enum. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2d_settilestyleuv(Lib3MF_Texture2D pTexture2D, Lib3MF::eTextureTileStyle eTileStyleU, Lib3MF::eTextureTileStyle eTileStyleV); /** * Retrieves a texture's filter type. * * @param[in] pTexture2D - Texture2D instance. * @param[out] pFilter - returns filter type enum. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2d_getfilter(Lib3MF_Texture2D pTexture2D, Lib3MF::eTextureFilter * pFilter); /** * Sets a texture's filter type. * * @param[in] pTexture2D - Texture2D instance. * @param[in] eFilter - sets new filter type enum. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_texture2d_setfilter(Lib3MF_Texture2D pTexture2D, Lib3MF::eTextureFilter eFilter); /************************************************************************************************************************* Class definition for BuildItem **************************************************************************************************************************/ /** * Retrieves the object resource associated to a build item * * @param[in] pBuildItem - BuildItem instance. * @param[out] pObjectResource - returns the associated resource instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditem_getobjectresource(Lib3MF_BuildItem pBuildItem, Lib3MF_Object * pObjectResource); /** * returns, whether a build item has a UUID and, if true, the build item's UUID * * @param[in] pBuildItem - BuildItem instance. * @param[out] pHasUUID - flag whether the build item has a UUID * @param[in] nUUIDBufferSize - size of the buffer (including trailing 0) * @param[out] pUUIDNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pUUIDBuffer - buffer of the UUID as string of the form 'xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx', may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditem_getuuid(Lib3MF_BuildItem pBuildItem, bool * pHasUUID, const Lib3MF_uint32 nUUIDBufferSize, Lib3MF_uint32* pUUIDNeededChars, char * pUUIDBuffer); /** * sets the build item's UUID * * @param[in] pBuildItem - BuildItem instance. * @param[in] pUUID - the UUID as string of the form 'xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx' * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditem_setuuid(Lib3MF_BuildItem pBuildItem, const char * pUUID); /** * Retrieves the object UniqueResourceID associated to a build item * * @param[in] pBuildItem - BuildItem instance. * @param[out] pUniqueResourceID - returns the UniqueResourceID of the object * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditem_getobjectresourceid(Lib3MF_BuildItem pBuildItem, Lib3MF_uint32 * pUniqueResourceID); /** * Checks, if a build item has a non-identity transformation matrix * * @param[in] pBuildItem - BuildItem instance. * @param[out] pHasTransform - returns true, if the transformation matrix is not the identity * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditem_hasobjecttransform(Lib3MF_BuildItem pBuildItem, bool * pHasTransform); /** * Retrieves a build item's transformation matrix. * * @param[in] pBuildItem - BuildItem instance. * @param[out] pTransform - returns the transformation matrix * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditem_getobjecttransform(Lib3MF_BuildItem pBuildItem, Lib3MF::sTransform * pTransform); /** * Sets a build item's transformation matrix. * * @param[in] pBuildItem - BuildItem instance. * @param[in] pTransform - new transformation matrix * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditem_setobjecttransform(Lib3MF_BuildItem pBuildItem, const Lib3MF::sTransform * pTransform); /** * Retrieves a build item's part number string * * @param[in] pBuildItem - BuildItem instance. * @param[in] nPartNumberBufferSize - size of the buffer (including trailing 0) * @param[out] pPartNumberNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pPartNumberBuffer - buffer of Returns a build item's part number string, may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditem_getpartnumber(Lib3MF_BuildItem pBuildItem, const Lib3MF_uint32 nPartNumberBufferSize, Lib3MF_uint32* pPartNumberNeededChars, char * pPartNumberBuffer); /** * Sets a build item's part number string * * @param[in] pBuildItem - BuildItem instance. * @param[in] pSetPartnumber - new part number string for referencing parts from the outside world * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditem_setpartnumber(Lib3MF_BuildItem pBuildItem, const char * pSetPartnumber); /** * Returns the metadatagroup of this build item * * @param[in] pBuildItem - BuildItem instance. * @param[out] pMetaDataGroup - returns an Instance of the metadatagroup of this build item * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditem_getmetadatagroup(Lib3MF_BuildItem pBuildItem, Lib3MF_MetaDataGroup * pMetaDataGroup); /** * Returns the outbox of a build item * * @param[in] pBuildItem - BuildItem instance. * @param[out] pOutbox - Outbox of this build item * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditem_getoutbox(Lib3MF_BuildItem pBuildItem, Lib3MF::sBox * pOutbox); /************************************************************************************************************************* Class definition for BuildItemIterator **************************************************************************************************************************/ /** * Iterates to the next build item in the list. * * @param[in] pBuildItemIterator - BuildItemIterator instance. * @param[out] pHasNext - Iterates to the next build item in the list. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditemiterator_movenext(Lib3MF_BuildItemIterator pBuildItemIterator, bool * pHasNext); /** * Iterates to the previous build item in the list. * * @param[in] pBuildItemIterator - BuildItemIterator instance. * @param[out] pHasPrevious - Iterates to the previous build item in the list. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditemiterator_moveprevious(Lib3MF_BuildItemIterator pBuildItemIterator, bool * pHasPrevious); /** * Returns the build item the iterator points at. * * @param[in] pBuildItemIterator - BuildItemIterator instance. * @param[out] pBuildItem - returns the build item instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditemiterator_getcurrent(Lib3MF_BuildItemIterator pBuildItemIterator, Lib3MF_BuildItem * pBuildItem); /** * Creates a new build item iterator with the same build item list. * * @param[in] pBuildItemIterator - BuildItemIterator instance. * @param[out] pOutBuildItemIterator - returns the cloned Iterator instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditemiterator_clone(Lib3MF_BuildItemIterator pBuildItemIterator, Lib3MF_BuildItemIterator * pOutBuildItemIterator); /** * Returns the number of build items the iterator captures. * * @param[in] pBuildItemIterator - BuildItemIterator instance. * @param[out] pCount - returns the number of build items the iterator captures. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_builditemiterator_count(Lib3MF_BuildItemIterator pBuildItemIterator, Lib3MF_uint64 * pCount); /************************************************************************************************************************* Class definition for Slice **************************************************************************************************************************/ /** * Set all vertices of a slice. All polygons will be cleared. * * @param[in] pSlice - Slice instance. * @param[in] nVerticesBufferSize - Number of elements in buffer * @param[in] pVerticesBuffer - Position2D buffer of contains the positions. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_slice_setvertices(Lib3MF_Slice pSlice, Lib3MF_uint64 nVerticesBufferSize, const Lib3MF::sPosition2D * pVerticesBuffer); /** * Get all vertices of a slice * * @param[in] pSlice - Slice instance. * @param[in] nVerticesBufferSize - Number of elements in buffer * @param[out] pVerticesNeededCount - will be filled with the count of the written elements, or needed buffer size. * @param[out] pVerticesBuffer - Position2D buffer of contains the positions. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_slice_getvertices(Lib3MF_Slice pSlice, const Lib3MF_uint64 nVerticesBufferSize, Lib3MF_uint64* pVerticesNeededCount, Lib3MF::sPosition2D * pVerticesBuffer); /** * Get the number of vertices in a slice * * @param[in] pSlice - Slice instance. * @param[out] pCount - the number of vertices in the slice * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_slice_getvertexcount(Lib3MF_Slice pSlice, Lib3MF_uint64 * pCount); /** * Add a new polygon to this slice * * @param[in] pSlice - Slice instance. * @param[in] nIndicesBufferSize - Number of elements in buffer * @param[in] pIndicesBuffer - uint32 buffer of the new indices of the new polygon * @param[out] pIndex - the index of the new polygon * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_slice_addpolygon(Lib3MF_Slice pSlice, Lib3MF_uint64 nIndicesBufferSize, const Lib3MF_uint32 * pIndicesBuffer, Lib3MF_uint64 * pIndex); /** * Get the number of polygons in the slice * * @param[in] pSlice - Slice instance. * @param[out] pCount - the number of polygons in the slice * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_slice_getpolygoncount(Lib3MF_Slice pSlice, Lib3MF_uint64 * pCount); /** * Set all indices of a polygon * * @param[in] pSlice - Slice instance. * @param[in] nIndex - the index of the polygon to manipulate * @param[in] nIndicesBufferSize - Number of elements in buffer * @param[in] pIndicesBuffer - uint32 buffer of the new indices of the index-th polygon * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_slice_setpolygonindices(Lib3MF_Slice pSlice, Lib3MF_uint64 nIndex, Lib3MF_uint64 nIndicesBufferSize, const Lib3MF_uint32 * pIndicesBuffer); /** * Get all vertices of a slice * * @param[in] pSlice - Slice instance. * @param[in] nIndex - the index of the polygon to manipulate * @param[in] nIndicesBufferSize - Number of elements in buffer * @param[out] pIndicesNeededCount - will be filled with the count of the written elements, or needed buffer size. * @param[out] pIndicesBuffer - uint32 buffer of the indices of the index-th polygon * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_slice_getpolygonindices(Lib3MF_Slice pSlice, Lib3MF_uint64 nIndex, const Lib3MF_uint64 nIndicesBufferSize, Lib3MF_uint64* pIndicesNeededCount, Lib3MF_uint32 * pIndicesBuffer); /** * Get the number of vertices in a slice * * @param[in] pSlice - Slice instance. * @param[in] nIndex - the index of the polygon to manipulate * @param[out] pCount - the number of indices of the index-th polygon * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_slice_getpolygonindexcount(Lib3MF_Slice pSlice, Lib3MF_uint64 nIndex, Lib3MF_uint64 * pCount); /** * Get the upper Z-Coordinate of this slice. * * @param[in] pSlice - Slice instance. * @param[out] pZTop - the upper Z-Coordinate of this slice * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_slice_getztop(Lib3MF_Slice pSlice, Lib3MF_double * pZTop); /************************************************************************************************************************* Class definition for SliceStack **************************************************************************************************************************/ /** * Get the lower Z-Coordinate of the slice stack. * * @param[in] pSliceStack - SliceStack instance. * @param[out] pZBottom - the lower Z-Coordinate the slice stack * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_slicestack_getbottomz(Lib3MF_SliceStack pSliceStack, Lib3MF_double * pZBottom); /** * Returns the number of slices * * @param[in] pSliceStack - SliceStack instance. * @param[out] pCount - the number of slices * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_slicestack_getslicecount(Lib3MF_SliceStack pSliceStack, Lib3MF_uint64 * pCount); /** * Query a slice from the slice stack * * @param[in] pSliceStack - SliceStack instance. * @param[in] nSliceIndex - the index of the slice * @param[out] pTheSlice - the Slice instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_slicestack_getslice(Lib3MF_SliceStack pSliceStack, Lib3MF_uint64 nSliceIndex, Lib3MF_Slice * pTheSlice); /** * Returns the number of slices * * @param[in] pSliceStack - SliceStack instance. * @param[in] dZTop - upper Z coordinate of the slice * @param[out] pTheSlice - a new Slice instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_slicestack_addslice(Lib3MF_SliceStack pSliceStack, Lib3MF_double dZTop, Lib3MF_Slice * pTheSlice); /** * Returns the number of slice refs * * @param[in] pSliceStack - SliceStack instance. * @param[out] pCount - the number of slicereferences * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_slicestack_getslicerefcount(Lib3MF_SliceStack pSliceStack, Lib3MF_uint64 * pCount); /** * Adds another existing slicestack as sliceref in this slicestack * * @param[in] pSliceStack - SliceStack instance. * @param[in] pTheSliceStack - the slicestack to use as sliceref * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_slicestack_addslicestackreference(Lib3MF_SliceStack pSliceStack, Lib3MF_SliceStack pTheSliceStack); /** * Adds another existing slicestack as sliceref in this slicestack * * @param[in] pSliceStack - SliceStack instance. * @param[in] nSliceRefIndex - the index of the slice ref * @param[out] pTheSliceStack - the slicestack that is used as sliceref * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_slicestack_getslicestackreference(Lib3MF_SliceStack pSliceStack, Lib3MF_uint64 nSliceRefIndex, Lib3MF_SliceStack * pTheSliceStack); /** * Removes the indirection of slices via slice-refs, i.e. creates the slices of all slice refs of this SliceStack as actual slices of this SliceStack. All previously existing slices or slicerefs will be removed. * * @param[in] pSliceStack - SliceStack instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_slicestack_collapseslicereferences(Lib3MF_SliceStack pSliceStack); /** * Sets the package path where this Slice should be stored. Input an empty string to reset the path * * @param[in] pSliceStack - SliceStack instance. * @param[in] pPath - the package path where this Slice should be stored * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_slicestack_setownpath(Lib3MF_SliceStack pSliceStack, const char * pPath); /** * Obtains the package path where this Slice should be stored. Returns an empty string if the slicestack is stored within the root model. * * @param[in] pSliceStack - SliceStack instance. * @param[in] nPathBufferSize - size of the buffer (including trailing 0) * @param[out] pPathNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pPathBuffer - buffer of the package path where this Slice will be stored, may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_slicestack_getownpath(Lib3MF_SliceStack pSliceStack, const Lib3MF_uint32 nPathBufferSize, Lib3MF_uint32* pPathNeededChars, char * pPathBuffer); /************************************************************************************************************************* Class definition for Consumer **************************************************************************************************************************/ /** * Gets the consumerid * * @param[in] pConsumer - Consumer instance. * @param[in] nConsumerIDBufferSize - size of the buffer (including trailing 0) * @param[out] pConsumerIDNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pConsumerIDBuffer - buffer of A unique identifier for the consumers, may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_consumer_getconsumerid(Lib3MF_Consumer pConsumer, const Lib3MF_uint32 nConsumerIDBufferSize, Lib3MF_uint32* pConsumerIDNeededChars, char * pConsumerIDBuffer); /** * Getts the keyid * * @param[in] pConsumer - Consumer instance. * @param[in] nKeyIDBufferSize - size of the buffer (including trailing 0) * @param[out] pKeyIDNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pKeyIDBuffer - buffer of The identifier for the key of this consumer, may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_consumer_getkeyid(Lib3MF_Consumer pConsumer, const Lib3MF_uint32 nKeyIDBufferSize, Lib3MF_uint32* pKeyIDNeededChars, char * pKeyIDBuffer); /** * Gets the keyvalue associated with this consumer * * @param[in] pConsumer - Consumer instance. * @param[in] nKeyValueBufferSize - size of the buffer (including trailing 0) * @param[out] pKeyValueNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pKeyValueBuffer - buffer of The public key, when available, of this consumer, may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_consumer_getkeyvalue(Lib3MF_Consumer pConsumer, const Lib3MF_uint32 nKeyValueBufferSize, Lib3MF_uint32* pKeyValueNeededChars, char * pKeyValueBuffer); /************************************************************************************************************************* Class definition for AccessRight **************************************************************************************************************************/ /** * Gets the consumer associated with this access right * * @param[in] pAccessRight - AccessRight instance. * @param[out] pConsumer - The consumer instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_accessright_getconsumer(Lib3MF_AccessRight pAccessRight, Lib3MF_Consumer * pConsumer); /** * Gets the associated encryption algorithm * * @param[in] pAccessRight - AccessRight instance. * @param[out] pAlgorithm - The algorithm used for the key in this accessright * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_accessright_getwrappingalgorithm(Lib3MF_AccessRight pAccessRight, Lib3MF::eWrappingAlgorithm * pAlgorithm); /** * Gets the associated mask generation function algorithm * * @param[in] pAccessRight - AccessRight instance. * @param[out] pAlgorithm - The MFG1 algorithm * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_accessright_getmgfalgorithm(Lib3MF_AccessRight pAccessRight, Lib3MF::eMgfAlgorithm * pAlgorithm); /** * Gets the digest method assoicated * * @param[in] pAccessRight - AccessRight instance. * @param[out] pAlgorithm - The digest method for this accessright * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_accessright_getdigestmethod(Lib3MF_AccessRight pAccessRight, Lib3MF::eDigestMethod * pAlgorithm); /************************************************************************************************************************* Class definition for ContentEncryptionParams **************************************************************************************************************************/ /** * Returns the encryption method to be used in this encryption process * * @param[in] pContentEncryptionParams - ContentEncryptionParams instance. * @param[out] pAlgorithm - * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_contentencryptionparams_getencryptionalgorithm(Lib3MF_ContentEncryptionParams pContentEncryptionParams, Lib3MF::eEncryptionAlgorithm * pAlgorithm); /** * Gets the key for the resource associated * * @param[in] pContentEncryptionParams - ContentEncryptionParams instance. * @param[in] nByteDataBufferSize - Number of elements in buffer * @param[out] pByteDataNeededCount - will be filled with the count of the written elements, or needed buffer size. * @param[out] pByteDataBuffer - uint8 buffer of Pointer to a buffer where to place the key. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_contentencryptionparams_getkey(Lib3MF_ContentEncryptionParams pContentEncryptionParams, const Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64* pByteDataNeededCount, Lib3MF_uint8 * pByteDataBuffer); /** * Gets the IV data * * @param[in] pContentEncryptionParams - ContentEncryptionParams instance. * @param[in] nByteDataBufferSize - Number of elements in buffer * @param[out] pByteDataNeededCount - will be filled with the count of the written elements, or needed buffer size. * @param[out] pByteDataBuffer - uint8 buffer of Pointer to a buffer where to place the data. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_contentencryptionparams_getinitializationvector(Lib3MF_ContentEncryptionParams pContentEncryptionParams, const Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64* pByteDataNeededCount, Lib3MF_uint8 * pByteDataBuffer); /** * A handler descriptor that uniquely identifies the context of the resource. Each resource will be assigned a different value * * @param[in] pContentEncryptionParams - ContentEncryptionParams instance. * @param[in] nByteDataBufferSize - Number of elements in buffer * @param[out] pByteDataNeededCount - will be filled with the count of the written elements, or needed buffer size. * @param[out] pByteDataBuffer - uint8 buffer of Pointer to a buffer where to place the data. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_contentencryptionparams_getauthenticationtag(Lib3MF_ContentEncryptionParams pContentEncryptionParams, const Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64* pByteDataNeededCount, Lib3MF_uint8 * pByteDataBuffer); /** * Sets the authentication tag * * @param[in] pContentEncryptionParams - ContentEncryptionParams instance. * @param[in] nByteDataBufferSize - Number of elements in buffer * @param[in] pByteDataBuffer - uint8 buffer of The authentication tag size * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_contentencryptionparams_setauthenticationtag(Lib3MF_ContentEncryptionParams pContentEncryptionParams, Lib3MF_uint64 nByteDataBufferSize, const Lib3MF_uint8 * pByteDataBuffer); /** * A handler descriptor that uniquely identifies the context of the resource. Each resource will be assigned a different value * * @param[in] pContentEncryptionParams - ContentEncryptionParams instance. * @param[in] nByteDataBufferSize - Number of elements in buffer * @param[out] pByteDataNeededCount - will be filled with the count of the written elements, or needed buffer size. * @param[out] pByteDataBuffer - uint8 buffer of Buffer where the data will be placed * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_contentencryptionparams_getadditionalauthenticationdata(Lib3MF_ContentEncryptionParams pContentEncryptionParams, const Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64* pByteDataNeededCount, Lib3MF_uint8 * pByteDataBuffer); /** * A handler descriptor that uniquely identifies the context of the resource. Each resource will be assigned a different value * * @param[in] pContentEncryptionParams - ContentEncryptionParams instance. * @param[out] pDescriptor - * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_contentencryptionparams_getdescriptor(Lib3MF_ContentEncryptionParams pContentEncryptionParams, Lib3MF_uint64 * pDescriptor); /** * Gets the resourcedatagroup keyuuid * * @param[in] pContentEncryptionParams - ContentEncryptionParams instance. * @param[in] nUUIDBufferSize - size of the buffer (including trailing 0) * @param[out] pUUIDNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pUUIDBuffer - buffer of The resourcedatagroup keyuuid that may be use to reference an external key, may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_contentencryptionparams_getkeyuuid(Lib3MF_ContentEncryptionParams pContentEncryptionParams, const Lib3MF_uint32 nUUIDBufferSize, Lib3MF_uint32* pUUIDNeededChars, char * pUUIDBuffer); /************************************************************************************************************************* Class definition for ResourceData **************************************************************************************************************************/ /** * Gets the encrypted part path * * @param[in] pResourceData - ResourceData instance. * @param[out] pPath - The part path * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_resourcedata_getpath(Lib3MF_ResourceData pResourceData, Lib3MF_PackagePart * pPath); /** * Gets the encryption algorithm used to encrypt this ResourceData * * @param[in] pResourceData - ResourceData instance. * @param[out] pEncryptionAlgorithm - The encryption algorithm * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_resourcedata_getencryptionalgorithm(Lib3MF_ResourceData pResourceData, Lib3MF::eEncryptionAlgorithm * pEncryptionAlgorithm); /** * Tells whether this ResourceData is compressed or not * * @param[in] pResourceData - ResourceData instance. * @param[out] pCompression - The compression method * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_resourcedata_getcompression(Lib3MF_ResourceData pResourceData, Lib3MF::eCompression * pCompression); /** * Tells whether this ResourceData is compressed or not * * @param[in] pResourceData - ResourceData instance. * @param[in] nByteDataBufferSize - Number of elements in buffer * @param[out] pByteDataNeededCount - will be filled with the count of the written elements, or needed buffer size. * @param[out] pByteDataBuffer - uint8 buffer of The compression method * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_resourcedata_getadditionalauthenticationdata(Lib3MF_ResourceData pResourceData, const Lib3MF_uint64 nByteDataBufferSize, Lib3MF_uint64* pByteDataNeededCount, Lib3MF_uint8 * pByteDataBuffer); /************************************************************************************************************************* Class definition for ResourceDataGroup **************************************************************************************************************************/ /** * Sets the resourcedatagroup keyuuid * * @param[in] pResourceDataGroup - ResourceDataGroup instance. * @param[in] nUUIDBufferSize - size of the buffer (including trailing 0) * @param[out] pUUIDNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pUUIDBuffer - buffer of The new resourcedatagroup keyuuid., may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_resourcedatagroup_getkeyuuid(Lib3MF_ResourceDataGroup pResourceDataGroup, const Lib3MF_uint32 nUUIDBufferSize, Lib3MF_uint32* pUUIDNeededChars, char * pUUIDBuffer); /** * Add accessright to resourcedatagroup element * * @param[in] pResourceDataGroup - ResourceDataGroup instance. * @param[in] pConsumer - The Consumer reference * @param[in] eWrappingAlgorithm - The key wrapping algorithm to be used * @param[in] eMgfAlgorithm - The mask generation function to be used * @param[in] eDigestMethod - The digest mechanism to be used * @param[out] pTheAccessRight - The acess right instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_resourcedatagroup_addaccessright(Lib3MF_ResourceDataGroup pResourceDataGroup, Lib3MF_Consumer pConsumer, Lib3MF::eWrappingAlgorithm eWrappingAlgorithm, Lib3MF::eMgfAlgorithm eMgfAlgorithm, Lib3MF::eDigestMethod eDigestMethod, Lib3MF_AccessRight * pTheAccessRight); /** * Finds the AccessRight associated with a Consumer * * @param[in] pResourceDataGroup - ResourceDataGroup instance. * @param[in] pConsumer - The Consumer instance * @param[out] pTheAccessRight - The AcessRight instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_resourcedatagroup_findaccessrightbyconsumer(Lib3MF_ResourceDataGroup pResourceDataGroup, Lib3MF_Consumer pConsumer, Lib3MF_AccessRight * pTheAccessRight); /** * Removes access from a Consumer on this resource data group * * @param[in] pResourceDataGroup - ResourceDataGroup instance. * @param[in] pConsumer - The Consumer instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_resourcedatagroup_removeaccessright(Lib3MF_ResourceDataGroup pResourceDataGroup, Lib3MF_Consumer pConsumer); /************************************************************************************************************************* Class definition for KeyStore **************************************************************************************************************************/ /** * Adds a consumer to the keystore * * @param[in] pKeyStore - KeyStore instance. * @param[in] pConsumerID - A unique identifier for the consumer * @param[in] pKeyID - The id of the key of the consumer * @param[in] pKeyValue - The public key for this consumer in PEM format * @param[out] pConsumer - The consumer instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_addconsumer(Lib3MF_KeyStore pKeyStore, const char * pConsumerID, const char * pKeyID, const char * pKeyValue, Lib3MF_Consumer * pConsumer); /** * Gets the number of consumers in the keystore * * @param[in] pKeyStore - KeyStore instance. * @param[out] pCount - The consumer count * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_getconsumercount(Lib3MF_KeyStore pKeyStore, Lib3MF_uint64 * pCount); /** * Get a consumer from the keystore * * @param[in] pKeyStore - KeyStore instance. * @param[in] nConsumerIndex - The index of the consumer * @param[out] pConsumer - The consumer instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_getconsumer(Lib3MF_KeyStore pKeyStore, Lib3MF_uint64 nConsumerIndex, Lib3MF_Consumer * pConsumer); /** * Removes a consumer from the keystore * * @param[in] pKeyStore - KeyStore instance. * @param[in] pConsumer - The consumer instance to remove * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_removeconsumer(Lib3MF_KeyStore pKeyStore, Lib3MF_Consumer pConsumer); /** * Finds a consumer by ID * * @param[in] pKeyStore - KeyStore instance. * @param[in] pConsumerID - The ID of the consumer * @param[out] pConsumer - The consumer instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_findconsumer(Lib3MF_KeyStore pKeyStore, const char * pConsumerID, Lib3MF_Consumer * pConsumer); /** * Gets the number of resource data group in the keysore * * @param[in] pKeyStore - KeyStore instance. * @param[out] pCount - The number of resource data available * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_getresourcedatagroupcount(Lib3MF_KeyStore pKeyStore, Lib3MF_uint64 * pCount); /** * Adds a resource data group into the keystore. * * @param[in] pKeyStore - KeyStore instance. * @param[out] pResourceDataGroup - The resource data group instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_addresourcedatagroup(Lib3MF_KeyStore pKeyStore, Lib3MF_ResourceDataGroup * pResourceDataGroup); /** * Gets a resource data group * * @param[in] pKeyStore - KeyStore instance. * @param[in] nResourceDataIndex - The index of the resource data * @param[out] pResourceDataGroup - The resource data group instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_getresourcedatagroup(Lib3MF_KeyStore pKeyStore, Lib3MF_uint64 nResourceDataIndex, Lib3MF_ResourceDataGroup * pResourceDataGroup); /** * Removes a resource data group * * @param[in] pKeyStore - KeyStore instance. * @param[in] pResourceDataGroup - The resource data group instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_removeresourcedatagroup(Lib3MF_KeyStore pKeyStore, Lib3MF_ResourceDataGroup pResourceDataGroup); /** * Finds a resource data group that contains a particular resourcedata * * @param[in] pKeyStore - KeyStore instance. * @param[in] pPartPath - The target path for the resourcedata hold by the resource data group * @param[out] pResourceDataGroup - The data resource instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_findresourcedatagroup(Lib3MF_KeyStore pKeyStore, Lib3MF_PackagePart pPartPath, Lib3MF_ResourceDataGroup * pResourceDataGroup); /** * Add resourcedata to resourcedatagroup element * * @param[in] pKeyStore - KeyStore instance. * @param[in] pResourceDataGroup - The resource data group where to add this resource data * @param[in] pPartPath - The path of the part to be encrypted * @param[in] eAlgorithm - The encryption algorithm to be used to encrypt this resource * @param[in] eCompression - Whether compression should be used prior to encryption * @param[in] nAdditionalAuthenticationDataBufferSize - Number of elements in buffer * @param[in] pAdditionalAuthenticationDataBuffer - uint8 buffer of Additional data to be encrypted along the contents for better security * @param[out] pResourceData - The data resource instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_addresourcedata(Lib3MF_KeyStore pKeyStore, Lib3MF_ResourceDataGroup pResourceDataGroup, Lib3MF_PackagePart pPartPath, Lib3MF::eEncryptionAlgorithm eAlgorithm, Lib3MF::eCompression eCompression, Lib3MF_uint64 nAdditionalAuthenticationDataBufferSize, const Lib3MF_uint8 * pAdditionalAuthenticationDataBuffer, Lib3MF_ResourceData * pResourceData); /** * Removes a resource data * * @param[in] pKeyStore - KeyStore instance. * @param[in] pResourceData - The resource data to be removed * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_removeresourcedata(Lib3MF_KeyStore pKeyStore, Lib3MF_ResourceData pResourceData); /** * Finds a resource data on this resource group * * @param[in] pKeyStore - KeyStore instance. * @param[in] pResourcePath - The target path for the resourcedata * @param[out] pResourceData - The resource data instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_findresourcedata(Lib3MF_KeyStore pKeyStore, Lib3MF_PackagePart pResourcePath, Lib3MF_ResourceData * pResourceData); /** * Gets the number of resource data in the keysore * * @param[in] pKeyStore - KeyStore instance. * @param[out] pCount - The number of resource data available * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_getresourcedatacount(Lib3MF_KeyStore pKeyStore, Lib3MF_uint64 * pCount); /** * Gets a resource data * * @param[in] pKeyStore - KeyStore instance. * @param[in] nResourceDataIndex - The index of the resource data * @param[out] pResourceData - The data resource instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_getresourcedata(Lib3MF_KeyStore pKeyStore, Lib3MF_uint64 nResourceDataIndex, Lib3MF_ResourceData * pResourceData); /** * Gets the keystore UUID * * @param[in] pKeyStore - KeyStore instance. * @param[out] pHasUUID - flag whether the keystore has a UUID * @param[in] nUUIDBufferSize - size of the buffer (including trailing 0) * @param[out] pUUIDNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pUUIDBuffer - buffer of returns the keystore uuid., may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_getuuid(Lib3MF_KeyStore pKeyStore, bool * pHasUUID, const Lib3MF_uint32 nUUIDBufferSize, Lib3MF_uint32* pUUIDNeededChars, char * pUUIDBuffer); /** * Sets the keystore UUID * * @param[in] pKeyStore - KeyStore instance. * @param[in] pUUID - The new keystore uuid. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_keystore_setuuid(Lib3MF_KeyStore pKeyStore, const char * pUUID); /************************************************************************************************************************* Class definition for Model **************************************************************************************************************************/ /** * Returns the PackagePart within the OPC package that holds the root model. * * @param[in] pModel - Model instance. * @param[out] pRootModelPart - the PackagePart within the OPC package that holds the model-file * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_rootmodelpart(Lib3MF_Model pModel, Lib3MF_PackagePart * pRootModelPart); /** * Returns a new PackagePart for use within the OPC package. * * @param[in] pModel - Model instance. * @param[in] pAbsolutePath - the absolute Path (physical location) within the OPC package * @param[out] pModelPart - the new PackagePart within the OPC package * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_findorcreatepackagepart(Lib3MF_Model pModel, const char * pAbsolutePath, Lib3MF_PackagePart * pModelPart); /** * sets the units of a model. * * @param[in] pModel - Model instance. * @param[in] eUnit - Unit enum value for the model unit * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_setunit(Lib3MF_Model pModel, Lib3MF::eModelUnit eUnit); /** * returns the units of a model. * * @param[in] pModel - Model instance. * @param[out] pUnit - Unit enum value for the model unit * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getunit(Lib3MF_Model pModel, Lib3MF::eModelUnit * pUnit); /** * retrieves the language of a model * * @param[in] pModel - Model instance. * @param[in] nLanguageBufferSize - size of the buffer (including trailing 0) * @param[out] pLanguageNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pLanguageBuffer - buffer of language identifier, may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getlanguage(Lib3MF_Model pModel, const Lib3MF_uint32 nLanguageBufferSize, Lib3MF_uint32* pLanguageNeededChars, char * pLanguageBuffer); /** * sets the language of a model * * @param[in] pModel - Model instance. * @param[in] pLanguage - language identifier * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_setlanguage(Lib3MF_Model pModel, const char * pLanguage); /** * creates a model writer instance for a specific file type * * @param[in] pModel - Model instance. * @param[in] pWriterClass - string identifier for the file type * @param[out] pWriterInstance - string identifier for the file type * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_querywriter(Lib3MF_Model pModel, const char * pWriterClass, Lib3MF_Writer * pWriterInstance); /** * creates a model reader instance for a specific file type * * @param[in] pModel - Model instance. * @param[in] pReaderClass - string identifier for the file type * @param[out] pReaderInstance - string identifier for the file type * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_queryreader(Lib3MF_Model pModel, const char * pReaderClass, Lib3MF_Reader * pReaderInstance); /** * finds a model texture by its UniqueResourceID * * @param[in] pModel - Model instance. * @param[in] nUniqueResourceID - UniqueResourceID * @param[out] pTextureInstance - returns the texture2d instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_gettexture2dbyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF_Texture2D * pTextureInstance); /** * returns a Property's type * * @param[in] pModel - Model instance. * @param[in] nUniqueResourceID - Resource ID of the Property to Query * @param[out] pThePropertyType - returns a Property's type * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getpropertytypebyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF::ePropertyType * pThePropertyType); /** * finds a model base material group by its UniqueResourceID * * @param[in] pModel - Model instance. * @param[in] nUniqueResourceID - UniqueResourceID * @param[out] pBaseMaterialGroupInstance - returns the BaseMaterialGroup instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getbasematerialgroupbyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF_BaseMaterialGroup * pBaseMaterialGroupInstance); /** * finds a model texture2d group by its UniqueResourceID * * @param[in] pModel - Model instance. * @param[in] nUniqueResourceID - UniqueResourceID * @param[out] pTexture2DGroupInstance - returns the Texture2DGroup instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_gettexture2dgroupbyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF_Texture2DGroup * pTexture2DGroupInstance); /** * finds a model CompositeMaterials by its UniqueResourceID * * @param[in] pModel - Model instance. * @param[in] nUniqueResourceID - UniqueResourceID * @param[out] pCompositeMaterialsInstance - returns the CompositeMaterials instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getcompositematerialsbyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF_CompositeMaterials * pCompositeMaterialsInstance); /** * finds a model MultiPropertyGroup by its UniqueResourceID * * @param[in] pModel - Model instance. * @param[in] nUniqueResourceID - UniqueResourceID * @param[out] pMultiPropertyGroupInstance - returns the MultiPropertyGroup instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getmultipropertygroupbyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF_MultiPropertyGroup * pMultiPropertyGroupInstance); /** * finds a mesh object by its UniqueResourceID * * @param[in] pModel - Model instance. * @param[in] nUniqueResourceID - UniqueResourceID * @param[out] pMeshObjectInstance - returns the mesh object instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getmeshobjectbyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF_MeshObject * pMeshObjectInstance); /** * finds a components object by its UniqueResourceID * * @param[in] pModel - Model instance. * @param[in] nUniqueResourceID - UniqueResourceID * @param[out] pComponentsObjectInstance - returns the components object instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getcomponentsobjectbyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF_ComponentsObject * pComponentsObjectInstance); /** * finds a model color group by its UniqueResourceID * * @param[in] pModel - Model instance. * @param[in] nUniqueResourceID - UniqueResourceID * @param[out] pColorGroupInstance - returns the ColorGroup instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getcolorgroupbyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF_ColorGroup * pColorGroupInstance); /** * finds a model slicestack by its UniqueResourceID * * @param[in] pModel - Model instance. * @param[in] nUniqueResourceID - UniqueResourceID * @param[out] pSliceStacInstance - returns the slicestack instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getslicestackbyid(Lib3MF_Model pModel, Lib3MF_uint32 nUniqueResourceID, Lib3MF_SliceStack * pSliceStacInstance); /** * returns, whether a build has a UUID and, if true, the build's UUID * * @param[in] pModel - Model instance. * @param[out] pHasUUID - flag whether the build has a UUID * @param[in] nUUIDBufferSize - size of the buffer (including trailing 0) * @param[out] pUUIDNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pUUIDBuffer - buffer of the UUID as string of the form 'xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx', may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getbuilduuid(Lib3MF_Model pModel, bool * pHasUUID, const Lib3MF_uint32 nUUIDBufferSize, Lib3MF_uint32* pUUIDNeededChars, char * pUUIDBuffer); /** * sets the build's UUID * * @param[in] pModel - Model instance. * @param[in] pUUID - the UUID as string of the form 'xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx' * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_setbuilduuid(Lib3MF_Model pModel, const char * pUUID); /** * creates a build item iterator instance with all build items. * * @param[in] pModel - Model instance. * @param[out] pBuildItemIterator - returns the iterator instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getbuilditems(Lib3MF_Model pModel, Lib3MF_BuildItemIterator * pBuildItemIterator); /** * Returns the outbox of a Model * * @param[in] pModel - Model instance. * @param[out] pOutbox - Outbox of this Model * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getoutbox(Lib3MF_Model pModel, Lib3MF::sBox * pOutbox); /** * creates a resource iterator instance with all resources. * * @param[in] pModel - Model instance. * @param[out] pResourceIterator - returns the iterator instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getresources(Lib3MF_Model pModel, Lib3MF_ResourceIterator * pResourceIterator); /** * creates a resource iterator instance with all object resources. * * @param[in] pModel - Model instance. * @param[out] pResourceIterator - returns the iterator instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getobjects(Lib3MF_Model pModel, Lib3MF_ObjectIterator * pResourceIterator); /** * creates a resource iterator instance with all mesh object resources. * * @param[in] pModel - Model instance. * @param[out] pResourceIterator - returns the iterator instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getmeshobjects(Lib3MF_Model pModel, Lib3MF_MeshObjectIterator * pResourceIterator); /** * creates a resource iterator instance with all components object resources. * * @param[in] pModel - Model instance. * @param[out] pResourceIterator - returns the iterator instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getcomponentsobjects(Lib3MF_Model pModel, Lib3MF_ComponentsObjectIterator * pResourceIterator); /** * creates a Texture2DIterator instance with all texture2d resources. * * @param[in] pModel - Model instance. * @param[out] pResourceIterator - returns the iterator instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_gettexture2ds(Lib3MF_Model pModel, Lib3MF_Texture2DIterator * pResourceIterator); /** * creates a BaseMaterialGroupIterator instance with all base material resources. * * @param[in] pModel - Model instance. * @param[out] pResourceIterator - returns the iterator instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getbasematerialgroups(Lib3MF_Model pModel, Lib3MF_BaseMaterialGroupIterator * pResourceIterator); /** * creates a ColorGroupIterator instance with all ColorGroup resources. * * @param[in] pModel - Model instance. * @param[out] pResourceIterator - returns the iterator instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getcolorgroups(Lib3MF_Model pModel, Lib3MF_ColorGroupIterator * pResourceIterator); /** * creates a Texture2DGroupIterator instance with all base material resources. * * @param[in] pModel - Model instance. * @param[out] pResourceIterator - returns the iterator instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_gettexture2dgroups(Lib3MF_Model pModel, Lib3MF_Texture2DGroupIterator * pResourceIterator); /** * creates a CompositeMaterialsIterator instance with all CompositeMaterials resources. * * @param[in] pModel - Model instance. * @param[out] pResourceIterator - returns the iterator instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getcompositematerials(Lib3MF_Model pModel, Lib3MF_CompositeMaterialsIterator * pResourceIterator); /** * creates a MultiPropertyGroupsIterator instance with all MultiPropertyGroup resources. * * @param[in] pModel - Model instance. * @param[out] pResourceIterator - returns the iterator instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getmultipropertygroups(Lib3MF_Model pModel, Lib3MF_MultiPropertyGroupIterator * pResourceIterator); /** * creates a resource iterator instance with all slice stack resources. * * @param[in] pModel - Model instance. * @param[out] pResourceIterator - returns the iterator instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getslicestacks(Lib3MF_Model pModel, Lib3MF_SliceStackIterator * pResourceIterator); /** * Merges all components and objects which are referenced by a build item into a mesh. The memory is duplicated and a new model is created. * * @param[in] pModel - Model instance. * @param[out] pMergedModelInstance - returns the merged model instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_mergetomodel(Lib3MF_Model pModel, Lib3MF_Model * pMergedModelInstance); /** * adds an empty mesh object to the model. * * @param[in] pModel - Model instance. * @param[out] pMeshObjectInstance - returns the mesh object instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_addmeshobject(Lib3MF_Model pModel, Lib3MF_MeshObject * pMeshObjectInstance); /** * adds an empty component object to the model. * * @param[in] pModel - Model instance. * @param[out] pComponentsObjectInstance - returns the components object instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_addcomponentsobject(Lib3MF_Model pModel, Lib3MF_ComponentsObject * pComponentsObjectInstance); /** * creates a new model slicestack by its id * * @param[in] pModel - Model instance. * @param[in] dZBottom - Bottom Z value of the slicestack * @param[out] pSliceStackInstance - returns the new slicestack instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_addslicestack(Lib3MF_Model pModel, Lib3MF_double dZBottom, Lib3MF_SliceStack * pSliceStackInstance); /** * adds a texture2d resource to the model. Its path is given by that of an existing attachment. * * @param[in] pModel - Model instance. * @param[in] pTextureAttachment - attachment containing the image data. * @param[out] pTexture2DInstance - returns the new texture instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_addtexture2dfromattachment(Lib3MF_Model pModel, Lib3MF_Attachment pTextureAttachment, Lib3MF_Texture2D * pTexture2DInstance); /** * adds an empty BaseMaterialGroup resource to the model. * * @param[in] pModel - Model instance. * @param[out] pBaseMaterialGroupInstance - returns the new base material instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_addbasematerialgroup(Lib3MF_Model pModel, Lib3MF_BaseMaterialGroup * pBaseMaterialGroupInstance); /** * adds an empty ColorGroup resource to the model. * * @param[in] pModel - Model instance. * @param[out] pColorGroupInstance - returns the new ColorGroup instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_addcolorgroup(Lib3MF_Model pModel, Lib3MF_ColorGroup * pColorGroupInstance); /** * adds an empty Texture2DGroup resource to the model. * * @param[in] pModel - Model instance. * @param[in] pTexture2DInstance - The texture2D instance of the created Texture2DGroup. * @param[out] pTexture2DGroupInstance - returns the new Texture2DGroup instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_addtexture2dgroup(Lib3MF_Model pModel, Lib3MF_Texture2D pTexture2DInstance, Lib3MF_Texture2DGroup * pTexture2DGroupInstance); /** * adds an empty CompositeMaterials resource to the model. * * @param[in] pModel - Model instance. * @param[in] pBaseMaterialGroupInstance - The BaseMaterialGroup instance of the created CompositeMaterials. * @param[out] pCompositeMaterialsInstance - returns the new CompositeMaterials instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_addcompositematerials(Lib3MF_Model pModel, Lib3MF_BaseMaterialGroup pBaseMaterialGroupInstance, Lib3MF_CompositeMaterials * pCompositeMaterialsInstance); /** * adds an empty MultiPropertyGroup resource to the model. * * @param[in] pModel - Model instance. * @param[out] pMultiPropertyGroupInstance - returns the new MultiPropertyGroup instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_addmultipropertygroup(Lib3MF_Model pModel, Lib3MF_MultiPropertyGroup * pMultiPropertyGroupInstance); /** * adds a build item to the model. * * @param[in] pModel - Model instance. * @param[in] pObject - Object instance. * @param[in] pTransform - Transformation matrix. * @param[out] pBuildItemInstance - returns the build item instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_addbuilditem(Lib3MF_Model pModel, Lib3MF_Object pObject, const Lib3MF::sTransform * pTransform, Lib3MF_BuildItem * pBuildItemInstance); /** * removes a build item from the model * * @param[in] pModel - Model instance. * @param[in] pBuildItemInstance - Build item to remove. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_removebuilditem(Lib3MF_Model pModel, Lib3MF_BuildItem pBuildItemInstance); /** * Returns the metadata of the model as MetaDataGroup * * @param[in] pModel - Model instance. * @param[out] pTheMetaDataGroup - returns an Instance of the metadatagroup of the model * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getmetadatagroup(Lib3MF_Model pModel, Lib3MF_MetaDataGroup * pTheMetaDataGroup); /** * adds an attachment stream to the model. The OPC part will be related to the model stream with a certain relationship type. * * @param[in] pModel - Model instance. * @param[in] pURI - Path of the attachment * @param[in] pRelationShipType - Relationship type of the attachment * @param[out] pAttachmentInstance - Instance of the attachment object * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_addattachment(Lib3MF_Model pModel, const char * pURI, const char * pRelationShipType, Lib3MF_Attachment * pAttachmentInstance); /** * Removes attachment from the model. * * @param[in] pModel - Model instance. * @param[in] pAttachmentInstance - Attachment instance to remove * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_removeattachment(Lib3MF_Model pModel, Lib3MF_Attachment pAttachmentInstance); /** * retrieves an attachment stream object from the model.. * * @param[in] pModel - Model instance. * @param[in] nIndex - Index of the attachment stream * @param[out] pAttachmentInstance - Instance of the attachment object * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getattachment(Lib3MF_Model pModel, Lib3MF_uint32 nIndex, Lib3MF_Attachment * pAttachmentInstance); /** * retrieves an attachment stream object from the model. * * @param[in] pModel - Model instance. * @param[in] pURI - Path URI in the package * @param[out] pAttachmentInstance - Instance of the attachment object * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_findattachment(Lib3MF_Model pModel, const char * pURI, Lib3MF_Attachment * pAttachmentInstance); /** * retrieves the number of attachments of the model. * * @param[in] pModel - Model instance. * @param[out] pAttachmentCount - Returns the number of attachments. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getattachmentcount(Lib3MF_Model pModel, Lib3MF_uint32 * pAttachmentCount); /** * Retrieve whether the OPC package contains a package thumbnail. * * @param[in] pModel - Model instance. * @param[out] pHasThumbnail - returns whether the OPC package contains a package thumbnail * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_haspackagethumbnailattachment(Lib3MF_Model pModel, bool * pHasThumbnail); /** * Create a new or the existing package thumbnail for the OPC package. * * @param[in] pModel - Model instance. * @param[out] pAttachment - Instance of a new or the existing thumbnailattachment object. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_createpackagethumbnailattachment(Lib3MF_Model pModel, Lib3MF_Attachment * pAttachment); /** * Get the attachment to the OPC package containing the package thumbnail. * * @param[in] pModel - Model instance. * @param[out] pAttachment - Instance of the thumbnailattachment object or NULL. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getpackagethumbnailattachment(Lib3MF_Model pModel, Lib3MF_Attachment * pAttachment); /** * Remove the attachment to the OPC package containing the package thumbnail. * * @param[in] pModel - Model instance. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_removepackagethumbnailattachment(Lib3MF_Model pModel); /** * Adds a new Content Type to the model. * * @param[in] pModel - Model instance. * @param[in] pExtension - File Extension * @param[in] pContentType - Content Type Identifier * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_addcustomcontenttype(Lib3MF_Model pModel, const char * pExtension, const char * pContentType); /** * Removes a custom Content Type from the model (UTF8 version). * * @param[in] pModel - Model instance. * @param[in] pExtension - File Extension * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_removecustomcontenttype(Lib3MF_Model pModel, const char * pExtension); /** * Sets the random number generator callback for use in the library * * @param[in] pModel - Model instance. * @param[in] pTheCallback - The callback used to generate random numbers * @param[in] pUserData - Userdata to be passed to the callback function * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_setrandomnumbercallback(Lib3MF_Model pModel, Lib3MF::RandomNumberCallback pTheCallback, Lib3MF_pvoid pUserData); /** * Gets the keystore associated with this model * * @param[in] pModel - Model instance. * @param[out] pKeyStore - The package keystore * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_model_getkeystore(Lib3MF_Model pModel, Lib3MF_KeyStore * pKeyStore); /************************************************************************************************************************* Global functions **************************************************************************************************************************/ /** * retrieves the binary version of this library. * * @param[out] pMajor - returns the major version of this library * @param[out] pMinor - returns the minor version of this library * @param[out] pMicro - returns the micro version of this library * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_getlibraryversion(Lib3MF_uint32 * pMajor, Lib3MF_uint32 * pMinor, Lib3MF_uint32 * pMicro); /** * retrieves prerelease information of this library. * * @param[out] pHasPrereleaseInfo - Does the library provide prerelease version? * @param[in] nPrereleaseInfoBufferSize - size of the buffer (including trailing 0) * @param[out] pPrereleaseInfoNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pPrereleaseInfoBuffer - buffer of retrieves prerelease information of this library., may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_getprereleaseinformation(bool * pHasPrereleaseInfo, const Lib3MF_uint32 nPrereleaseInfoBufferSize, Lib3MF_uint32* pPrereleaseInfoNeededChars, char * pPrereleaseInfoBuffer); /** * retrieves build information of this library. * * @param[out] pHasBuildInfo - Does the library provide build version? * @param[in] nBuildInformationBufferSize - size of the buffer (including trailing 0) * @param[out] pBuildInformationNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pBuildInformationBuffer - buffer of retrieves build information of this library., may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_getbuildinformation(bool * pHasBuildInfo, const Lib3MF_uint32 nBuildInformationBufferSize, Lib3MF_uint32* pBuildInformationNeededChars, char * pBuildInformationBuffer); /** * retrieves whether a specification is supported, and if so, which version. * * @param[in] pSpecificationURL - URL of extension to check * @param[out] pIsSupported - returns whether this specification is supported * @param[out] pMajor - returns the major version of the extension (if IsSupported) * @param[out] pMinor - returns the minor version of the extension (if IsSupported) * @param[out] pMicro - returns the micro version of the extension (if IsSupported) * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_getspecificationversion(const char * pSpecificationURL, bool * pIsSupported, Lib3MF_uint32 * pMajor, Lib3MF_uint32 * pMinor, Lib3MF_uint32 * pMicro); /** * creates an empty model instance. * * @param[out] pModel - returns an empty model instance * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_createmodel(Lib3MF_Model * pModel); /** * releases shared ownership of an object instance * * @param[in] pInstance - the object instance to release * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_release(Lib3MF_Base pInstance); /** * acquires shared ownership of an object instance * * @param[in] pInstance - the object instance to acquire * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_acquire(Lib3MF_Base pInstance); /** * Sets the journal file path * * @param[in] pJournalPath - File name of the journal file * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_setjournal(const char * pJournalPath); /** * Retrieves the last error string of an instance * * @param[in] pInstance - Object where the error occured. * @param[in] nLastErrorStringBufferSize - size of the buffer (including trailing 0) * @param[out] pLastErrorStringNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pLastErrorStringBuffer - buffer of Last Error String, may be NULL * @param[out] pHasLastError - Returns if the instance has a last error. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_getlasterror(Lib3MF_Base pInstance, const Lib3MF_uint32 nLastErrorStringBufferSize, Lib3MF_uint32* pLastErrorStringNeededChars, char * pLastErrorStringBuffer, bool * pHasLastError); /** * Returns the address of the SymbolLookupMethod * * @param[out] pSymbolLookupMethod - Address of the SymbolAddressMethod * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_getsymbollookupmethod(Lib3MF_pvoid * pSymbolLookupMethod); /** * Return an English text for a progress identifier.|Note: this is the only function you can call from your callback function. * * @param[in] eTheProgressIdentifier - the progress identifier that is passed to the callback function * @param[in] nProgressMessageBufferSize - size of the buffer (including trailing 0) * @param[out] pProgressMessageNeededChars - will be filled with the count of the written bytes, or needed buffer size. * @param[out] pProgressMessageBuffer - buffer of English text for the progress identifier, may be NULL * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_retrieveprogressmessage(Lib3MF::eProgressIdentifier eTheProgressIdentifier, const Lib3MF_uint32 nProgressMessageBufferSize, Lib3MF_uint32* pProgressMessageNeededChars, char * pProgressMessageBuffer); /** * Creates a Color from uint8 RGBA values * * @param[in] nRed - Red value of color (0-255) * @param[in] nGreen - Green value of color (0-255) * @param[in] nBlue - Blue value of color (0-255) * @param[in] nAlpha - Alpha value of color (0-255) * @param[out] pTheColor - Assembled color * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_rgbatocolor(Lib3MF_uint8 nRed, Lib3MF_uint8 nGreen, Lib3MF_uint8 nBlue, Lib3MF_uint8 nAlpha, Lib3MF::sColor * pTheColor); /** * Creates a Color from uint8 RGBA values * * @param[in] fRed - Red value of color (0-1) * @param[in] fGreen - Green value of color (0-1) * @param[in] fBlue - Blue value of color (0-1) * @param[in] fAlpha - Alpha value of color (0-1) * @param[out] pTheColor - Assembled color * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_floatrgbatocolor(Lib3MF_single fRed, Lib3MF_single fGreen, Lib3MF_single fBlue, Lib3MF_single fAlpha, Lib3MF::sColor * pTheColor); /** * Calculates uint8-RGBA-values from a Color * * @param[in] pTheColor - Color to handle * @param[out] pRed - Red value of color (0-255) * @param[out] pGreen - Green value of color (0-255) * @param[out] pBlue - Blue value of color (0-255) * @param[out] pAlpha - Alpha value of color (0-255) * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_colortorgba(const Lib3MF::sColor * pTheColor, Lib3MF_uint8 * pRed, Lib3MF_uint8 * pGreen, Lib3MF_uint8 * pBlue, Lib3MF_uint8 * pAlpha); /** * Calculates float-RGBA-values from a Color * * @param[in] pTheColor - Color to handle * @param[out] pRed - Red value of color (0-1) * @param[out] pGreen - Green value of color (0-1) * @param[out] pBlue - Blue value of color (0-1) * @param[out] pAlpha - Alpha value of color (0-1) * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_colortofloatrgba(const Lib3MF::sColor * pTheColor, Lib3MF_single * pRed, Lib3MF_single * pGreen, Lib3MF_single * pBlue, Lib3MF_single * pAlpha); /** * Creates an identity transform * * @param[out] pTransform - Transformation matrix. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_getidentitytransform(Lib3MF::sTransform * pTransform); /** * Creates a uniform scale transform * * @param[in] fFactor - Factor in X, Y and Z * @param[out] pTransform - Transformation matrix. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_getuniformscaletransform(Lib3MF_single fFactor, Lib3MF::sTransform * pTransform); /** * Creates a scale transform * * @param[in] fFactorX - Factor in X * @param[in] fFactorY - Factor in Y * @param[in] fFactorZ - Factor in Z * @param[out] pTransform - Transformation matrix. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_getscaletransform(Lib3MF_single fFactorX, Lib3MF_single fFactorY, Lib3MF_single fFactorZ, Lib3MF::sTransform * pTransform); /** * Creates an translation transform * * @param[in] fVectorX - Translation in X * @param[in] fVectorY - Translation in Y * @param[in] fVectorZ - Translation in Z * @param[out] pTransform - Transformation matrix. * @return error code or 0 (success) */ LIB3MF_DECLSPEC Lib3MFResult lib3mf_gettranslationtransform(Lib3MF_single fVectorX, Lib3MF_single fVectorY, Lib3MF_single fVectorZ, Lib3MF::sTransform * pTransform); } #endif // __LIB3MF_HEADER_CPP
45.211207
505
0.740675
[ "mesh", "object", "model", "transform" ]
e503e600b62cfb4378c454291de2b54d51e40c07
54,259
cpp
C++
sparta/test/Pipeline/Pipeline_test.cpp
knute-sifive/map
fb25626830a56ad68ab896bcd01929023ff31c48
[ "MIT" ]
null
null
null
sparta/test/Pipeline/Pipeline_test.cpp
knute-sifive/map
fb25626830a56ad68ab896bcd01929023ff31c48
[ "MIT" ]
null
null
null
sparta/test/Pipeline/Pipeline_test.cpp
knute-sifive/map
fb25626830a56ad68ab896bcd01929023ff31c48
[ "MIT" ]
null
null
null
/** * \file Pipeline_test.cpp * \brief This is the testbench for sparta::Pipeline. * * It is intended to show all the use cases of sparta::Pipeline */ #include <iostream> #include <cstring> #include "sparta/resources/Pipeline.hpp" #include "sparta/simulation/Clock.hpp" #include "sparta/simulation/ClockManager.hpp" #include "sparta/utils/SpartaTester.hpp" TEST_INIT; #define PIPEOUT_GEN #define TEST_MANUAL_UPDATE class DummyClass { public: void stage0_PU_Handle0(void) { std::cout << " Stage[0]: handler(PortUpdate)\n"; } void stage0_F_Handle0(void) { std::cout << " Stage[0]: handler0(Flush)\n"; } void stage0_F_Handle1(void) { std::cout << " P2Stage[0]: handler1(Flush)\n"; } void stage0_T_Handle0(void) { std::cout << " Stage[0]: handler0(Tick)\n"; } void stage0_T_Handle1(void) { std::cout << " Stage[0]: handler1(Tick)\n"; } void stage0_T_Handle2(void) { std::cout << " Stage[0]: handler2(Tick)\n"; } void stage1_PU_Handle0(void) { std::cout << " Stage[1]: handler(PortUpdate)\n"; } void stage1_F_Handle0(void) { std::cout << " Stage[1]: handler0(Flush)\n"; } void stage1_F_Handle1(void) { std::cout << " P2Stage[1]: handler1(Flush)\n"; } void stage1_T_Handle0(void) { std::cout << " Stage[1]: handler0(Tick)\n"; } void stage2_PU_Handle0(void) { std::cout << " Stage[2]: handler(PortUpdate)\n"; } void stage2_F_Handle0(void) { std::cout << " Stage[2]: handler0(Flush)\n"; } void stage2_F_Handle1(void) { std::cout << " P2Stage[2]: handler1(Flush)\n"; } void stage2_T_Handle0(void) { std::cout << " Stage[2]: handler0(Tick)\n"; } void stage2_PT_Handle0(void) { std::cout << " Stage[2]: handler0(PostTick)\n"; } void stage2_PT_Handle1(void) { std::cout << " Stage[2]: handler1(PostTick)\n"; } void stage3_PU_Handle0(void) { std::cout << " Stage[3]: handler(PortUpdate)\n"; } void stage3_T_Handle0(void) { std::cout << " Stage[3]: handler0(Tick)\n"; } void stage4_PU_Handle0(void) { std::cout << " Stage[4]: handler(PortUpdate)\n"; } void stage4_F_Handle0(void) { std::cout << " Stage[4]: handler(Flush)\n"; } void stage4_T_Handle0(void) { std::cout << " Stage[4]: handler0(Tick)\n"; } void task0(void) { std::cout << " Stage[3]: producer(Tick)\n"; } void task1(void) { std::cout << " Stage[0]: producer(PortUpdate)\n"; } template<typename DataT> void task2(const DataT & dat) { std::cout << " Stage[2]: consumer(Tick, " << dat << ")\n"; } template<typename DataT> void task3(const DataT & dat) { std::cout << " Stage[4]: consumer(Flush: " << dat << ")\n"; } }; template<typename T> class DummyClass2 { public: DummyClass2() = delete; DummyClass2(sparta::Pipeline<T>* ptr) : pipeline_ptr_(ptr) {} void flushAll() { auto& pipeline = (*pipeline_ptr_); std::cout << "Flush all pipeline stages\n"; pipeline.flushAllStages(); } void flushOne() { auto& pipeline = (*pipeline_ptr_); auto iter = pipeline.begin(); auto stage_id = 0; while (iter != pipeline.end()) { if (iter.isValid()) { std::cout << "Flush pipeline stage[" << stage_id << "]\n"; pipeline.flushStage(iter); break; } ++iter; ++stage_id; } } void flushOne(const uint32_t& stage_id) { auto& pipeline = (*pipeline_ptr_); if (pipeline.isValid(stage_id)) { std::cout << "Flush pipeline stage[" << stage_id << "]\n"; pipeline.flushStage(stage_id); } } private: sparta::Pipeline<T>* pipeline_ptr_; }; class PipelineEntryObj { public: PipelineEntryObj() = default; PipelineEntryObj(const uint32_t & id, const std::string & str) : id_(id), name_(str) {} const uint32_t & getID() const { return id_; } const std::string & getName() const { return name_; } void print() const { //std::cout << "PipelineEntryObj: ID(" << id_ << "), Name(" << name_ << ")\n"; } private: uint32_t id_ = 0; std::string name_ = "default"; }; // This operator needs to be defined for pipeline collection std::ostream & operator<<(std::ostream & os, const PipelineEntryObj & obj) { obj.print(); return os; } template<typename Pipe> void runCycle(Pipe &pipe, sparta::Scheduler * sched) { #ifdef TEST_MANUAL_UPDATE pipe.update(); #endif sched->run(1, true, false); } void testPipelineContinuingEvent() { sparta::Scheduler scheduler; sparta::Clock clk("clock", &scheduler); EXPECT_TRUE(scheduler.getCurrentTick() == 1); EXPECT_TRUE(scheduler.isRunning() == 0); sparta::RootTreeNode rtn; rtn.setClock(&clk); sparta::Pipeline<uint64_t> examplePipeline1("myFirstSpartaPipeline", 5, &clk); EXPECT_EQUAL(examplePipeline1.capacity(), 5); // some opportunistic testing of the continuing feature for the pipeline unique event scheduler.finalize(); rtn.enterConfiguring(); rtn.enterFinalized(); examplePipeline1.performOwnUpdates(); //scheduler.printNextCycleEventTree(std::cerr); EXPECT_EQUAL(scheduler.getNextContinuingEventTime(), 0); EXPECT_FALSE(examplePipeline1.isAnyValid()); // make the pipeline updater event continuing, very important for some models examplePipeline1.setContinuing(true); // add an event and let it move through a couple stages, the update event should still be scheduled examplePipeline1.append(42); scheduler.run(2, true); // that update event keeps the scheduler from being finished EXPECT_FALSE(scheduler.isFinished()); // clear that event out of there scheduler.run(); // make the update event continuing now examplePipeline1.setContinuing(false); // add another event, move it one stage in examplePipeline1.append(84); scheduler.run(1, true); // verify that the update event doesn't count toward keeping the // scheduler from being finished the scheduler will tell the // pipeline that there are queued events that have the continuing // flag set EXPECT_TRUE(scheduler.isFinished()); rtn.enterTeardown(); } int main () { testPipelineContinuingEvent(); sparta::Scheduler sched; sparta::RootTreeNode rtn; sparta::ClockManager cm(&sched); sparta::Clock::Handle root_clk; root_clk = cm.makeRoot(&rtn, "root_clk"); cm.normalize(); rtn.setClock(root_clk.get()); sparta::log::Tap t2(root_clk.get()->getScheduler(), "debug", "scheduler.log.debug"); // Insert test for Pipeline from here sparta::EventSet es(&rtn); DummyClass dummyObj1; //////////////////////////////////////////////////////////////////////////////// // User-defined Event //////////////////////////////////////////////////////////////////////////////// // User Event0: Tick phase, unique event sparta::UniqueEvent<> ev_task0_tick (&es, "ev_task0_tick", CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, task0)); // User Event1: PortUpdate phase, unique event sparta::UniqueEvent<sparta::SchedulingPhase::PortUpdate> ev_task1_port (&es, "ev_task1_port", CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, task1)); // User Event2: Tick phase, payload event sparta::PayloadEvent<uint32_t> ev_task2_tick (&es, "ev_task2_tick", CREATE_SPARTA_HANDLER_WITH_DATA_WITH_OBJ(DummyClass, &dummyObj1, task2, uint32_t)); // User Event3: Flush phase, payload event sparta::PayloadEvent<std::string, sparta::SchedulingPhase::Flush> ev_task3_flush (&es, "ev_task3_flush", CREATE_SPARTA_HANDLER_WITH_DATA_WITH_OBJ(DummyClass, &dummyObj1, task3, std::string)); //////////////////////////////////////////////////////////////////////////////// // Pipeline construction //////////////////////////////////////////////////////////////////////////////// sparta::Pipeline<uint64_t> examplePipeline1("myFirstSpartaPipeline", 5, root_clk.get()); EXPECT_EQUAL(examplePipeline1.capacity(), 5); sparta::Pipeline<PipelineEntryObj> examplePipeline2("mySecondSpartaPipeline", 20, root_clk.get()); sparta::Pipeline<uint64_t> examplePipeline3("myThirdSpartaPipeline", 5, root_clk.get()); sparta::Pipeline<bool> examplePipeline4("myFourthSpartaPipeline", 5, root_clk.get()); sparta::Pipeline<uint64_t> examplePipeline5("myFifthSpartaPipeline", 5, root_clk.get()); sparta::Pipeline<uint64_t> examplePipeline6("mySixthSpartaPipeline", 5, root_clk.get()); sparta::Pipeline<uint64_t> examplePipeline7("mySeventhSpartaPipeline", 2, root_clk.get()); sparta::Pipeline<bool> stwr_pipe("STWR_Pipe", 5, root_clk.get()); DummyClass2<uint64_t> dummyObj2(&examplePipeline6); // User Event4: Flush phase, unique event sparta::UniqueEvent<sparta::SchedulingPhase::Flush> ev_flush_all (&es, "ev_flush_all", CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass2<uint64_t>, &dummyObj2, flushAll)); // User Event5: Flush phase, unique event sparta::UniqueEvent<sparta::SchedulingPhase::Flush> ev_flush_first_one (&es, "ev_flush_first_one", CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass2<uint64_t>, &dummyObj2, flushOne)); // User Event6: Flush phase, payload event sparta::PayloadEvent<uint32_t, sparta::SchedulingPhase::Flush> ev_flush_one (&es, "ev_flush_one", CREATE_SPARTA_HANDLER_WITH_DATA_WITH_OBJ(DummyClass2<uint64_t>, &dummyObj2, flushOne, uint32_t)); #ifdef PIPEOUT_GEN examplePipeline1.enableCollection<sparta::SchedulingPhase::Collection>(&rtn); examplePipeline2.enableCollection<sparta::SchedulingPhase::Update>(&rtn); examplePipeline3.enableCollection<sparta::SchedulingPhase::Collection>(&rtn); examplePipeline4.enableCollection<sparta::SchedulingPhase::Collection>(&rtn); examplePipeline5.enableCollection<sparta::SchedulingPhase::Collection>(&rtn); examplePipeline6.enableCollection<sparta::SchedulingPhase::Collection>(&rtn); examplePipeline7.enableCollection<sparta::SchedulingPhase::Collection>(&rtn); stwr_pipe.enableCollection<sparta::SchedulingPhase::Collection>(&rtn); #endif //////////////////////////////////////////////////////////////////////////////// // Pipeline stage handler registration //////////////////////////////////////////////////////////////////////////////// /* * examplePipeline1: Precedence Chain Setup per Stage * stage[0]: producer(PortUpdate) --> handler(PortUpdate) --> handler1(Tick) --> handler0(Tick) --> handler2(Tick) * stage[1]: * stage[2]: handler(Tick) --> consumer(Tick) --> handler0(PostTick) --> handler1(PostTick) * stage[3]: producer(Tick) --> handler(Tick) * stage[4]: handler(Flush) --> consumer(Flush) */ // examplePipeline1 Stage[0] handler: PortUpdate phase EXPECT_NOTHROW( examplePipeline1.registerHandlerAtStage<sparta::SchedulingPhase::PortUpdate> (0, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage0_PU_Handle0))); // examplePipeline1 Stage[0] handler: Tick phase EXPECT_NOTHROW( examplePipeline1.registerHandlerAtStage<sparta::SchedulingPhase::Tick> (0, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage0_T_Handle1))); // examplePipeline1 Stage[0] handler: Tick phase EXPECT_NOTHROW( examplePipeline1.registerHandlerAtStage<sparta::SchedulingPhase::Tick> (0, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage0_T_Handle0))); // examplePipeline1 Stage[0] handler: Tick phase EXPECT_NOTHROW( examplePipeline1.registerHandlerAtStage<sparta::SchedulingPhase::Tick> (0, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage0_T_Handle2))); // examplePipeline1 Stage[2] handler: Tick phase EXPECT_NOTHROW( examplePipeline1.registerHandlerAtStage<sparta::SchedulingPhase::Tick> (2, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage2_T_Handle0))); // examplePipeline1 Stage[2] handler: PostTick phase EXPECT_NOTHROW( examplePipeline1.registerHandlerAtStage<sparta::SchedulingPhase::PostTick> (2, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage2_PT_Handle0))); // examplePipeline1 Stage[2] handler: PostTick phase EXPECT_NOTHROW( examplePipeline1.registerHandlerAtStage<sparta::SchedulingPhase::PostTick> (2, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage2_PT_Handle1))); // examplePipeline1 Stage[3] handler: Tick phase EXPECT_NOTHROW( examplePipeline1.registerHandlerAtStage (3, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage3_T_Handle0))); // examplePipeline1 Stage[4] handler: Flush phase EXPECT_NOTHROW( examplePipeline1.registerHandlerAtStage<sparta::SchedulingPhase::Flush> (4, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage4_F_Handle0))); // Attempt to register handlers for a non-existing stage EXPECT_THROW(examplePipeline1.registerHandlerAtStage (5, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage4_F_Handle0))); /* * examplePipeline3: Precedence Chain Setup per Stage * stage[2]:handler(Flush) --> stage[1]:handler(Flush) --> stage[0]:handler(Flush) */ // examplePipeline3 Stage[0] handler: Flush phase EXPECT_NOTHROW( examplePipeline3.registerHandlerAtStage<sparta::SchedulingPhase::Flush> (0, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage0_F_Handle0))); // examplePipeline3 Stage[1] handler: Flush phase EXPECT_NOTHROW( examplePipeline3.registerHandlerAtStage<sparta::SchedulingPhase::Flush> (1, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage1_F_Handle0))); // examplePipeline3 Stage[2] handler: Flush phase EXPECT_NOTHROW( examplePipeline3.registerHandlerAtStage<sparta::SchedulingPhase::Flush> (2, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage2_F_Handle0))); /* * examplePipeline4: Precedence Chain Setup per Stage * stage[0]:handler(Flush) --> stage[1]:handler(Flush) --> stage[2]:handler(Flush) */ // examplePipeline4 Stage[0] handler: Flush phase EXPECT_NOTHROW( examplePipeline4.registerHandlerAtStage<sparta::SchedulingPhase::Flush> (0, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage0_F_Handle1))); // examplePipeline4 Stage[1] handler: Flush phase EXPECT_NOTHROW( examplePipeline4.registerHandlerAtStage<sparta::SchedulingPhase::Flush> (1, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage1_F_Handle1))); // examplePipeline4 Stage[2] handler: Flush phase EXPECT_NOTHROW( examplePipeline4.registerHandlerAtStage<sparta::SchedulingPhase::Flush> (2, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage2_F_Handle1))); /* * examplePipeline5: Precedence Chain Setup per Stage * stage[0]:handler0(Tick) * stage[1]:handler0(Tick) * stage[2]:handler0(Tick) * stage[3]:handler0(Tick) * stage[4]:handler0(Tick) */ // examplePipeline5 Stage[0] handler: Tick phase EXPECT_NOTHROW( examplePipeline5.registerHandlerAtStage<sparta::SchedulingPhase::Tick> (0, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage0_T_Handle0))); // examplePipeline5 Stage[1] handler: Tick phase EXPECT_NOTHROW( examplePipeline5.registerHandlerAtStage<sparta::SchedulingPhase::Tick> (1, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage1_T_Handle0))); // examplePipeline5 Stage[2] handler: Tick phase EXPECT_NOTHROW( examplePipeline5.registerHandlerAtStage<sparta::SchedulingPhase::Tick> (2, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage2_T_Handle0))); // examplePipeline5 Stage[3] handler: Tick phase EXPECT_NOTHROW( examplePipeline5.registerHandlerAtStage<sparta::SchedulingPhase::Tick> (3, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage3_T_Handle0))); // examplePipeline5 Stage[4] handler: Tick phase EXPECT_NOTHROW( examplePipeline5.registerHandlerAtStage<sparta::SchedulingPhase::Tick> (4, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage4_T_Handle0))); /* * examplePipeline6: Precedence Chain Setup per Stage * stage[0]: handler0(PortUpdate) --> handler0(Tick) * stage[1]: handler0(PortUpdate) --> handler0(Tick) * stage[2]: handler0(PortUpdate) --> handler0(Tick) * stage[3]: handler0(Tick) * stage[4]: handler0(Tick) */ // examplePipeline6 Stage[0] handler: PortUpdate phase EXPECT_NOTHROW( examplePipeline6.registerHandlerAtStage<sparta::SchedulingPhase::PortUpdate> (0, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage0_PU_Handle0))); // examplePipeline6 Stage[0] handler: Tick phase EXPECT_NOTHROW( examplePipeline6.registerHandlerAtStage<sparta::SchedulingPhase::Tick> (0, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage0_T_Handle0))); // examplePipeline6 Stage[1] handler: PortUpdate phase EXPECT_NOTHROW( examplePipeline6.registerHandlerAtStage<sparta::SchedulingPhase::PortUpdate> (1, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage1_PU_Handle0))); // examplePipeline6 Stage[1] handler: Tick phase EXPECT_NOTHROW( examplePipeline6.registerHandlerAtStage<sparta::SchedulingPhase::Tick> (1, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage1_T_Handle0))); // examplePipeline6 Stage[2] handler: PortUpdate phase EXPECT_NOTHROW( examplePipeline6.registerHandlerAtStage<sparta::SchedulingPhase::PortUpdate> (2, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage2_PU_Handle0))); // examplePipeline6 Stage[2] handler: Tick phase EXPECT_NOTHROW( examplePipeline6.registerHandlerAtStage<sparta::SchedulingPhase::Tick> (2, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage2_T_Handle0))); // examplePipeline6 Stage[3] handler: Tick phase EXPECT_NOTHROW( examplePipeline6.registerHandlerAtStage<sparta::SchedulingPhase::Tick> (3, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage3_T_Handle0))); // examplePipeline6 Stage[4] handler: Tick phase EXPECT_NOTHROW( examplePipeline6.registerHandlerAtStage<sparta::SchedulingPhase::Tick> (4, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage4_T_Handle0))); rtn.enterConfiguring(); rtn.enterFinalized(); #ifdef PIPEOUT_GEN sparta::collection::PipelineCollector pc("examplePipeline1", 1000000, root_clk.get(), &rtn); #endif //////////////////////////////////////////////////////////////////////////////// // Pipeline stage handling event precedence setup //////////////////////////////////////////////////////////////////////////////// EXPECT_NOTHROW(examplePipeline1.setPrecedenceBetweenStage(3, 2)); EXPECT_THROW(examplePipeline1.setPrecedenceBetweenStage(0, 0)); EXPECT_NOTHROW(examplePipeline1.setPrecedenceBetweenStage(2, 0)); EXPECT_THROW(examplePipeline1.setPrecedenceBetweenStage(0, 1)); //////////////////////////////////////////////////////////////////////////////// // Pipeline stage producer event setup //////////////////////////////////////////////////////////////////////////////// EXPECT_NOTHROW(examplePipeline1.setProducerForStage(0, ev_task1_port)); EXPECT_NOTHROW(examplePipeline1.setProducerForStage(0, ev_task2_tick)); EXPECT_NOTHROW(examplePipeline1.setProducerForStage(3, ev_task0_tick)); EXPECT_THROW(examplePipeline1.setProducerForStage(1, ev_task0_tick)); EXPECT_THROW(examplePipeline1.setProducerForStage(2, ev_task1_port)); //////////////////////////////////////////////////////////////////////////////// // Pipeline stage consumer event setup //////////////////////////////////////////////////////////////////////////////// EXPECT_NOTHROW(examplePipeline1.setConsumerForStage(2, ev_task2_tick)); EXPECT_NOTHROW(examplePipeline1.setConsumerForStage(4, ev_task3_flush)); EXPECT_THROW(examplePipeline1.setConsumerForStage(1, ev_task2_tick)); EXPECT_THROW(examplePipeline1.setConsumerForStage(3, ev_task3_flush)); //////////////////////////////////////////////////////////////////////////////// // Set precedence between two stages from diffferent Pipeline instances //////////////////////////////////////////////////////////////////////////////// EXPECT_THROW(examplePipeline3.setPrecedenceBetweenPipeline(2, examplePipeline3, 1)); EXPECT_THROW(examplePipeline3.setPrecedenceBetweenPipeline(2, examplePipeline4, 4)); EXPECT_THROW(examplePipeline3.setPrecedenceBetweenPipeline(4, examplePipeline4, 1)); EXPECT_NOTHROW(examplePipeline4.setPrecedenceBetweenPipeline(2, examplePipeline3, 2)); //////////////////////////////////////////////////////////////////////////////// // Pipeline default stage precedence setup //////////////////////////////////////////////////////////////////////////////// /* * Overall Precedence Chain Setup * stage[0]:producer(PortUpdate) --> stage[0]:handler(PortUpdate) * stage[4]:handler(Flush) --> stage[4]:consumer(Flush) * stage[2]:handler(Tick)-------------------------------> stage[0]:handler1(Tick) --> stage[0]:handler0(Tick) --> stage[0]:handler2(Tick) --> stage[3]:producer(Tick) --> stage[3]:handler(Tick) * \--> stage[2]:consumer(Tick)--/ * stage[2]:handler0(PostTick) --> stage[2]:handler1(PostTick) */ EXPECT_NOTHROW(examplePipeline1.setDefaultStagePrecedence(sparta::Pipeline<uint64_t>::Precedence::BACKWARD)); EXPECT_NOTHROW(examplePipeline3.setDefaultStagePrecedence(sparta::Pipeline<uint64_t>::Precedence::BACKWARD)); EXPECT_NOTHROW(examplePipeline4.setDefaultStagePrecedence(sparta::Pipeline<bool>::Precedence::FORWARD)); EXPECT_NOTHROW(examplePipeline5.setDefaultStagePrecedence(sparta::Pipeline<uint64_t>::Precedence::BACKWARD)); EXPECT_NOTHROW(examplePipeline6.setDefaultStagePrecedence(sparta::Pipeline<uint64_t>::Precedence::BACKWARD)); //////////////////////////////////////////////////////////////////////////////// // Registered events access //////////////////////////////////////////////////////////////////////////////// // examplePipeline7 Stage[0] handler: PortUpdate phase EXPECT_NOTHROW( examplePipeline7.registerHandlerAtStage<sparta::SchedulingPhase::PortUpdate> (0, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage0_PU_Handle0))); // examplePipeline7 Stage[1] handler: PortUpdate phase EXPECT_NOTHROW( examplePipeline7.registerHandlerAtStage<sparta::SchedulingPhase::PortUpdate> (1, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage1_PU_Handle0))); // Each of the two stages should have 1 registered event for the PortUpdate phase EXPECT_EQUAL(examplePipeline7.getEventsAtStage(0, sparta::SchedulingPhase::PortUpdate).size(), 1); EXPECT_EQUAL(examplePipeline7.getEventsAtStage(1, sparta::SchedulingPhase::PortUpdate).size(), 1); // Add a registered Tick phase event for stage 2 EXPECT_NOTHROW( examplePipeline7.registerHandlerAtStage<sparta::SchedulingPhase::Tick> (1, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage1_T_Handle0))); // Verify that stage 1 now has one Tick phase event registered uint32_t pipeline7_stage1_num_tick_events = 0; EXPECT_NOTHROW(pipeline7_stage1_num_tick_events = examplePipeline7.getEventsAtStage(1, sparta::SchedulingPhase::Tick).size()); EXPECT_EQUAL(pipeline7_stage1_num_tick_events, 1); // Add another stage 1 Tick phase event EXPECT_NOTHROW( examplePipeline7.registerHandlerAtStage<sparta::SchedulingPhase::Tick> (1, CREATE_SPARTA_HANDLER_WITH_OBJ(DummyClass, &dummyObj1, stage1_T_Handle0))); // Verify that stage 1 now has two Tick phase events registered pipeline7_stage1_num_tick_events = 0; EXPECT_NOTHROW(pipeline7_stage1_num_tick_events = examplePipeline7.getEventsAtStage(1, sparta::SchedulingPhase::Tick).size()); EXPECT_EQUAL(pipeline7_stage1_num_tick_events, 2); // Verify that we also see two Tick phase events registered when the phase is not // explicitly given (defaults to SchedulingPhase::Tick) pipeline7_stage1_num_tick_events = 0; EXPECT_NOTHROW(pipeline7_stage1_num_tick_events = examplePipeline7.getEventsAtStage(1).size()); EXPECT_EQUAL(pipeline7_stage1_num_tick_events, 2); sched.finalize(); #ifdef PIPEOUT_GEN pc.startCollection(&rtn); #endif //////////////////////////////////////////////////////////////////////////////// // Pipeline Forward Progression Test //////////////////////////////////////////////////////////////////////////////// std::cout << "\n[START] Pipeline Forward Progression Test" << std::endl; uint32_t cyc_cnt = 0; #ifndef TEST_MANUAL_UPDATE examplePipeline1.performOwnUpdates(); #endif std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; // Append Pipeline examplePipeline1.append(19); // Run Cycle-0 sched.run(1, true); EXPECT_FALSE(examplePipeline1.isValid(0)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; #ifdef TEST_MANUAL_UPDATE // Run Cycle-1(a) sched.run(1, true); examplePipeline1.update(); ev_task1_port.schedule(sparta::Clock::Cycle(0)); // Run Cycle-1(b) && Cycle-2(a) sched.run(1, true); #else // Run Cycle-1 ev_task1_port.schedule(sparta::Clock::Cycle(1)); sched.run(1, true); #endif // Test pipeline read/write using [] semantics EXPECT_EQUAL(examplePipeline1.numValid(), 1); EXPECT_TRUE(examplePipeline1.isValid(0)); EXPECT_EQUAL(examplePipeline1[0], 19); EXPECT_NOTHROW(examplePipeline1[0] -= 5); EXPECT_THROW(examplePipeline1[5] = 100); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; examplePipeline1.append(20); // Run Cycle-2(b) && Cycle-3(a) runCycle(examplePipeline1, &sched); // Test pipeline forward progression and specific stage modification EXPECT_EQUAL(examplePipeline1.numValid(), 2); EXPECT_TRUE(examplePipeline1.isValid(0)); EXPECT_EQUAL(examplePipeline1[0], 20); EXPECT_TRUE(examplePipeline1.isValid(1)); EXPECT_EQUAL(examplePipeline1[1], 14); EXPECT_NOTHROW(examplePipeline1.writeStage(0, 25)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; examplePipeline1.append(21); #ifdef TEST_MANUAL_UPDATE examplePipeline1.update(); ev_task2_tick.preparePayload(100)->schedule(sparta::Clock::Cycle(0)); // Run Cycle-3(b) && Cycle-4(a) sched.run(1, true); #else ev_task2_tick.preparePayload(100)->schedule(sparta::Clock::Cycle(1)); // Run cycle-3 sched.run(1, true); #endif // Test pipeline forward progression EXPECT_EQUAL(examplePipeline1.numValid(), 3); EXPECT_TRUE(examplePipeline1.isValid(0)); EXPECT_EQUAL(examplePipeline1[0], 21); EXPECT_TRUE(examplePipeline1.isValid(1)); EXPECT_EQUAL(examplePipeline1[1], 25); EXPECT_TRUE(examplePipeline1.isValid(2)); EXPECT_EQUAL(examplePipeline1[2], 14); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; #ifdef TEST_MANUAL_UPDATE examplePipeline1.update(); ev_task0_tick.schedule(sparta::Clock::Cycle(0)); // Run Cycle-4(b) && Cycle-5(a) sched.run(1, true); #else ev_task0_tick.schedule(sparta::Clock::Cycle(1)); // Run cycle-4 sched.run(1, true); #endif // Test pipeline forward progression EXPECT_EQUAL(examplePipeline1.numValid(), 3); EXPECT_TRUE(examplePipeline1.isValid(1)); EXPECT_EQUAL(examplePipeline1[1], 21); EXPECT_TRUE(examplePipeline1.isValid(2)); EXPECT_EQUAL(examplePipeline1[2], 25); EXPECT_TRUE(examplePipeline1.isValid(3)); EXPECT_EQUAL(examplePipeline1[3], 14); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; #ifdef TEST_MANUAL_UPDATE examplePipeline1.update(); ev_task3_flush.preparePayload("flushing")->schedule(sparta::Clock::Cycle(0)); // Run Cycle-5(b) && Cycle-6(a) sched.run(1, true); #else ev_task3_flush.preparePayload("flushing")->schedule(sparta::Clock::Cycle(1)); // Run cycle-5 sched.run(1, true); #endif // Test pipeline forward progression EXPECT_EQUAL(examplePipeline1.numValid(), 3); EXPECT_TRUE(examplePipeline1.isValid(2)); EXPECT_EQUAL(examplePipeline1[2], 21); EXPECT_TRUE(examplePipeline1.isValid(3)); EXPECT_EQUAL(examplePipeline1[3], 25); EXPECT_TRUE(examplePipeline1.isValid(4)); EXPECT_EQUAL(examplePipeline1[4], 14); while (cyc_cnt < examplePipeline1.capacity() + 3) { std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline1, &sched); } // Test pipeline forward progression EXPECT_EQUAL(examplePipeline1.numValid(), 1); EXPECT_TRUE(examplePipeline1.isLastValid()); EXPECT_EQUAL(examplePipeline1[4], 21); // Run the last cycle (i.e. drain the pipeline) std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline1, &sched); // Test pipeline draining EXPECT_FALSE(examplePipeline1.isAnyValid()); EXPECT_EQUAL(examplePipeline1.size(), 0); std::cout << "[FINISH] Pipeline Forward Progression Test" << std::endl; //////////////////////////////////////////////////////////////////////////////// // Pipeline Stage Mutation & Invalidation Test //////////////////////////////////////////////////////////////////////////////// std::cout << "\n[START] Pipeline Stage Mutation & Invalidation Test" << std::endl; cyc_cnt = 0; std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; EXPECT_NOTHROW(examplePipeline1.append(200)); EXPECT_NOTHROW(examplePipeline1.writeStage(1, 100)); EXPECT_NOTHROW(examplePipeline1.writeStage(2, 50)); runCycle(examplePipeline1, &sched); // Test pipeline append and specific stage modification EXPECT_EQUAL(examplePipeline1.numValid(), 3); EXPECT_TRUE(examplePipeline1.isValid(0)); EXPECT_TRUE(examplePipeline1.isValid(2)); EXPECT_TRUE(examplePipeline1.isValid(3)); EXPECT_THROW(examplePipeline1.isValid(5)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; EXPECT_NOTHROW(examplePipeline1.append(300)); EXPECT_NOTHROW(examplePipeline1.invalidateStage(3)); EXPECT_THROW(examplePipeline1.invalidateStage(1)); runCycle(examplePipeline1, &sched); // Test pipeline specific stage modification EXPECT_EQUAL(examplePipeline1.numValid(), 3); EXPECT_TRUE(examplePipeline1.isValid(0)); EXPECT_TRUE(examplePipeline1.isValid(1)); EXPECT_TRUE(examplePipeline1.isValid(3)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; EXPECT_NOTHROW(examplePipeline1.flushStage(3)); EXPECT_EQUAL(examplePipeline1.numValid(), 2); runCycle(examplePipeline1, &sched); // Test pipeline specific stage flushing EXPECT_EQUAL(examplePipeline1.numValid(), 2); EXPECT_TRUE(examplePipeline1.isValid(1)); EXPECT_TRUE(examplePipeline1.isValid(2)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; EXPECT_NOTHROW(examplePipeline1.flushAllStages()); EXPECT_EQUAL(examplePipeline1.numValid(), 0); runCycle(examplePipeline1, &sched); // Test whole pipeline flushing EXPECT_EQUAL(examplePipeline1.numValid(), 0); std::cout << "[FINISH] Pipeline Stage Mutation & Invalidation Test" << std::endl; //////////////////////////////////////////////////////////////////////////////// // Pipeline Stage Handling Event Activation/Deactivation Test //////////////////////////////////////////////////////////////////////////////// std::cout << "\n[START] Pipeline Stage Handling Event Activation/Deactivation Test\n"; cyc_cnt = 0; std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; // Test de-activation of pipeline stage handling events EXPECT_NOTHROW(examplePipeline1.append(1000)); EXPECT_NOTHROW(examplePipeline1.deactivateEventAtStage(0)); EXPECT_THROW(examplePipeline1.deactivateEventAtStage(1)); EXPECT_THROW(examplePipeline1.activateEventAtStage(1)); std::cout << " NOTE: Stage[0] Event Hander is de-activated!\n"; runCycle(examplePipeline1, &sched); EXPECT_EQUAL(examplePipeline1.numValid(), 1); EXPECT_TRUE(examplePipeline1.isValid(0)); // Test re-activation of pipeline stage handling events std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; EXPECT_NOTHROW(examplePipeline1.append(2000)); EXPECT_NOTHROW(examplePipeline1.activateEventAtStage(0)); std::cout << " NOTE: Stage[0] Event Hander is re-activated!\n"; runCycle(examplePipeline1, &sched); EXPECT_EQUAL(examplePipeline1.numValid(), 2); EXPECT_TRUE(examplePipeline1.isValid(0)); EXPECT_TRUE(examplePipeline1.isValid(1)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline1, &sched); EXPECT_EQUAL(examplePipeline1.numValid(), 2); EXPECT_TRUE(examplePipeline1.isValid(1)); EXPECT_TRUE(examplePipeline1.isValid(2)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; EXPECT_NOTHROW(examplePipeline1.deactivateEventAtStage(2)); std::cout << " NOTE: Stage[2] Event Hander is de-activated!\n"; runCycle(examplePipeline1, &sched); EXPECT_EQUAL(examplePipeline1.numValid(), 2); EXPECT_TRUE(examplePipeline1.isValid(2)); EXPECT_TRUE(examplePipeline1.isValid(3)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; EXPECT_NOTHROW(examplePipeline1.append(3000)); EXPECT_NOTHROW(examplePipeline1.activateEventAtStage(2)); std::cout << " NOTE: Stage[2] Event Hander is re-activated!\n"; runCycle(examplePipeline1, &sched); uint32_t offset = cyc_cnt; while (cyc_cnt < examplePipeline1.capacity() + offset) { std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline1, &sched); } EXPECT_EQUAL(examplePipeline1.numValid(), 0); std::cout << "[FINISH] Pipeline Stage Handling Event Activation/Deactivation Test\n"; //////////////////////////////////////////////////////////////////////////////// // Pipeline Iterator Test //////////////////////////////////////////////////////////////////////////////// std::cout << "\n[START] Pipeline Iterator Test" << std::endl; sparta::Pipeline<PipelineEntryObj>::const_iterator iterForStage2 = examplePipeline2.begin(); std::advance(iterForStage2, 2); cyc_cnt = 0; #ifndef TEST_MANUAL_UPDATE examplePipeline2.performOwnUpdates(); #endif examplePipeline2.append(PipelineEntryObj()); EXPECT_FALSE(iterForStage2.isValid()); #ifdef TEST_MANUAL_UPDATE // Run Cycle-0(a) sched.run(1, true); examplePipeline2.update(); // Run Cycle-0(b) && Cycle-1(a) sched.run(1, true); #else // Run Cycle-0 sched.run(1, true); #endif cyc_cnt++; EXPECT_FALSE(iterForStage2.isValid()); // Test pipeline append and forward progression with user-defined entry object for (uint32_t i = 0; i < examplePipeline2.capacity(); i++) { if (cyc_cnt%3 == 0) { examplePipeline2.append(PipelineEntryObj(i, "newPipelineObj")); EXPECT_TRUE(iterForStage2.isValid()); EXPECT_NOTHROW((*iterForStage2).getID()); } else { EXPECT_FALSE(iterForStage2.isValid()); EXPECT_THROW((*iterForStage2).getID()); } runCycle(examplePipeline2, &sched); cyc_cnt++; } // Test operator* and operator-> of pipeline iterator auto iter = examplePipeline2.begin(); uint32_t valid_cnt = 0; for (uint32_t i = 0; iter != examplePipeline2.end(); i++) { if (iter.isValid()) { std::cout << "Pipeline Stage[" << i << "]: " << "ObjectID(" << iter->getID() << "), " << "ObjectName(" << (*iter).getName() << ")\n"; valid_cnt++; } iter++; } std::cout << "[FINISH] Pipeline Iterator Test" << std::endl; //////////////////////////////////////////////////////////////////////////////// // Cross Pipeline Precedence Setup Test //////////////////////////////////////////////////////////////////////////////// std::cout << "\n[START] Cross Pipeline Precedence Setup Test" << std::endl; examplePipeline3.performOwnUpdates(); examplePipeline4.performOwnUpdates(); // Payload count is set to equal to number of registered handlers uint32_t payload_cnt = 3; for (uint32_t i = 0; i < examplePipeline3.capacity() + payload_cnt; i++) { std::cout << "Cycle[" << i << "]:\n"; if (i < payload_cnt) { examplePipeline3.append(1); examplePipeline4.append(true); } sched.run(2, true); } std::cout << "[FINISH] Cross Pipeline Precedence Setup Test" << std::endl; //////////////////////////////////////////////////////////////////////////////// // Pipeline Stall/Restart Handling Test //////////////////////////////////////////////////////////////////////////////// std::cout << "\n[START] Pipeline Stall/Restart Handling Test\n"; #ifndef TEST_MANUAL_UPDATE examplePipeline5.performOwnUpdates(); #endif cyc_cnt = 0; std::cout << "Append pipeline with data[=1000]\n"; EXPECT_NOTHROW(examplePipeline5.append(1000)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline5, &sched); EXPECT_EQUAL(examplePipeline5.numValid(), 1); EXPECT_TRUE(examplePipeline5.isValid(0)); std::cout << "Append pipeline with data[=2000]\n"; EXPECT_NOTHROW(examplePipeline5.append(2000)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline5, &sched); EXPECT_EQUAL(examplePipeline5.numValid(), 2); EXPECT_TRUE(examplePipeline5.isValid(0)); EXPECT_TRUE(examplePipeline5.isValid(1)); std::cout << "Append pipeline with data[=3000]\n"; EXPECT_NOTHROW(examplePipeline5.append(3000)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline5, &sched); EXPECT_EQUAL(examplePipeline5.numValid(), 3); EXPECT_TRUE(examplePipeline5.isValid(0)); EXPECT_TRUE(examplePipeline5.isValid(1)); EXPECT_TRUE(examplePipeline5.isValid(2)); std::cout << "Stall stage[1] for 2 cycles\n"; EXPECT_NOTHROW(examplePipeline5.stall(1, 2)); EXPECT_TRUE(examplePipeline5.isStalledOrStalling()); EXPECT_TRUE(examplePipeline5.isStalledOrStallingAtStage(0)); EXPECT_FALSE(examplePipeline5.isStalledOrStallingAtStage(2)); // Attempt to do back-to-back stall in the same cycle is forbidden EXPECT_THROW(examplePipeline5.stall(2, 2)); EXPECT_THROW(examplePipeline5.stall(0, 2)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline5, &sched); EXPECT_EQUAL(examplePipeline5.numValid(), 3); EXPECT_TRUE(examplePipeline5.isValid(0)); EXPECT_TRUE(examplePipeline5.isValid(1)); EXPECT_TRUE(examplePipeline5.isValid(3)); EXPECT_EQUAL(examplePipeline5[0], 3000); EXPECT_EQUAL(examplePipeline5[1], 2000); EXPECT_EQUAL(examplePipeline5[3], 1000); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; // Attempt to stall being stalled pipeline is forbidden EXPECT_THROW(examplePipeline5.stall(2, 2)); EXPECT_THROW(examplePipeline5.stall(0, 2)); runCycle(examplePipeline5, &sched); EXPECT_EQUAL(examplePipeline5.numValid(), 3); EXPECT_TRUE(examplePipeline5.isValid(0)); EXPECT_TRUE(examplePipeline5.isValid(1)); EXPECT_TRUE(examplePipeline5.isValid(4)); EXPECT_EQUAL(examplePipeline5[0], 3000); EXPECT_EQUAL(examplePipeline5[1], 2000); EXPECT_EQUAL(examplePipeline5[4], 1000); std::cout << "Stall stage[0] for 1 more cycles\n"; // Test stalling a stage that is about to restart EXPECT_NOTHROW(examplePipeline5.stall(0, 1)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; // Test writting into the stage that is about to restart EXPECT_NOTHROW(examplePipeline5.writeStage(1, 2500)); runCycle(examplePipeline5, &sched); EXPECT_EQUAL(examplePipeline5.numValid(), 2); EXPECT_TRUE(examplePipeline5.isValid(0)); EXPECT_TRUE(examplePipeline5.isValid(2)); EXPECT_EQUAL(examplePipeline5[0], 3000); EXPECT_EQUAL(examplePipeline5[2], 2500); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline5, &sched); EXPECT_EQUAL(examplePipeline5.numValid(), 2); EXPECT_TRUE(examplePipeline5.isValid(1)); EXPECT_TRUE(examplePipeline5.isValid(3)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline5, &sched); EXPECT_EQUAL(examplePipeline5.numValid(), 2); EXPECT_TRUE(examplePipeline5.isValid(2)); EXPECT_TRUE(examplePipeline5.isValid(4)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline5, &sched); EXPECT_EQUAL(examplePipeline5.numValid(), 1); EXPECT_TRUE(examplePipeline5.isValid(3)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline5, &sched); EXPECT_EQUAL(examplePipeline5.numValid(), 1); EXPECT_TRUE(examplePipeline5.isValid(4)); offset = cyc_cnt; while (cyc_cnt < examplePipeline5.capacity() + offset) { std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline5, &sched); } EXPECT_EQUAL(examplePipeline5.numValid(), 0); // pipeline stall with bubble crushing std::cout << "Pipeline Stall with bubble crushing Test\n"; std::cout << "Append pipeline with data[=1000]\n"; EXPECT_NOTHROW(examplePipeline5.append(1000)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline5, &sched); EXPECT_TRUE(examplePipeline5.isValid(0)); EXPECT_EQUAL(examplePipeline5.numValid(), 1); std::cout << "Append pipeline with data[=2000]\n"; EXPECT_NOTHROW(examplePipeline5.append(2000)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline5, &sched); EXPECT_TRUE(examplePipeline5.isValid(0)); EXPECT_TRUE(examplePipeline5.isValid(1)); EXPECT_EQUAL(examplePipeline5.numValid(), 2); // bubble std::cout << "Insert bubble\n"; std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline5, &sched); EXPECT_TRUE(!examplePipeline5.isValid(0)); EXPECT_TRUE(examplePipeline5.isValid(1)); EXPECT_TRUE(examplePipeline5.isValid(2)); EXPECT_EQUAL(examplePipeline5.numValid(), 2); // now stall std::cout << "Stall (insert bubble)\n"; EXPECT_NOTHROW(examplePipeline5.stall(2, 1, true)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline5, &sched); // should be unchanged EXPECT_TRUE(!examplePipeline5.isValid(0)); EXPECT_TRUE(examplePipeline5.isValid(1)); EXPECT_TRUE(examplePipeline5.isValid(2)); EXPECT_EQUAL(examplePipeline5.numValid(), 2); // push std::cout << "Append pipeline with data[=3000]\n"; EXPECT_NOTHROW(examplePipeline5.append(3000)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline5, &sched); EXPECT_TRUE(examplePipeline5.isValid(0)); EXPECT_TRUE(!examplePipeline5.isValid(1)); // bubble advances EXPECT_TRUE(examplePipeline5.isValid(2)); EXPECT_TRUE(examplePipeline5.isValid(3)); EXPECT_EQUAL(examplePipeline5.numValid(), 3); // stall again EXPECT_NOTHROW(examplePipeline5.stall(3, 1, true)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline5, &sched); EXPECT_TRUE(!examplePipeline5.isValid(0)); EXPECT_TRUE(examplePipeline5.isValid(1)); // bubble crushed EXPECT_TRUE(examplePipeline5.isValid(2)); EXPECT_TRUE(examplePipeline5.isValid(3)); EXPECT_EQUAL(examplePipeline5.numValid(), 3); // stall and push std::cout << "Stall pipeline stage 3\n"; EXPECT_NOTHROW(examplePipeline5.stall(3, 1, true)); std::cout << "Append pipeline with data[=4000]\n"; EXPECT_NOTHROW(examplePipeline5.append(4000)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline5, &sched); EXPECT_TRUE(examplePipeline5.isValid(0)); EXPECT_TRUE(examplePipeline5.isValid(1)); EXPECT_TRUE(examplePipeline5.isValid(2)); EXPECT_TRUE(examplePipeline5.isValid(3)); EXPECT_EQUAL(examplePipeline5.numValid(), 4); // allow pipeline to drain offset = cyc_cnt + 1; while (cyc_cnt < examplePipeline5.capacity() + offset) { std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline5, &sched); } EXPECT_EQUAL(examplePipeline5.numValid(), 0); // Test issue where an item is pushed to the top, then stalled at // the end, but then something new is added, bubbles crushed and // the entry seems to be valid across all pipeline stages // examplePipeline5.append(1234); for (uint32_t cnt = 0; cnt < examplePipeline5.capacity(); ++cnt) { runCycle(examplePipeline5, &sched); } EXPECT_EQUAL(examplePipeline5.numValid(), 1); EXPECT_TRUE(examplePipeline5.isLastValid()); EXPECT_EQUAL(examplePipeline5[examplePipeline5.capacity() - 1], 1234); // now stall. 1234 should remain at the last stage in the pipeline examplePipeline5.stall(examplePipeline5.capacity() - 1, 1); runCycle(examplePipeline5, &sched); EXPECT_EQUAL(examplePipeline5.numValid(), 1); EXPECT_TRUE(examplePipeline5.isLastValid()); EXPECT_EQUAL(examplePipeline5[examplePipeline5.capacity() - 1], 1234); const bool crush_bubbles = true; examplePipeline5.append(4321); examplePipeline5.stall(examplePipeline5.capacity() - 1, 1, crush_bubbles); runCycle(examplePipeline5, &sched); EXPECT_EQUAL(examplePipeline5.numValid(), 2); EXPECT_TRUE(examplePipeline5.isLastValid()); EXPECT_EQUAL(examplePipeline5[examplePipeline5.capacity() - 1], 1234); EXPECT_EQUAL(examplePipeline5[0], 4321); // Start with this: // [4321, x, x, x, 1234] // Get the pipeline to look like this: // [x, x, x, 4321, 1234] for(uint32_t i = 0; i < (examplePipeline5.capacity() - 2); ++i) { EXPECT_EQUAL(examplePipeline5[i], 4321); EXPECT_TRUE(examplePipeline5.isValid(i)); examplePipeline5.stall(examplePipeline5.capacity() - 1, 1, crush_bubbles); runCycle(examplePipeline5, &sched); EXPECT_EQUAL(examplePipeline5.numValid(), 2); EXPECT_TRUE(examplePipeline5.isLastValid()); EXPECT_EQUAL(examplePipeline5[examplePipeline5.capacity() - 1], 1234); EXPECT_FALSE(examplePipeline5.isValid(i)); } EXPECT_FALSE(examplePipeline5.isValid(0)); EXPECT_FALSE(examplePipeline5.isValid(1)); EXPECT_FALSE(examplePipeline5.isValid(2)); EXPECT_TRUE (examplePipeline5.isValid(3)); EXPECT_TRUE (examplePipeline5.isValid(4)); #ifndef TEST_MANUAL_UPDATE stwr_pipe.performOwnUpdates(); #endif std::cout << "Append stwr pipeline with data[=true]\n"; EXPECT_NOTHROW(stwr_pipe.append(true)); runCycle(stwr_pipe, &sched); runCycle(stwr_pipe, &sched); runCycle(stwr_pipe, &sched); runCycle(stwr_pipe, &sched); runCycle(stwr_pipe, &sched); stwr_pipe.stall(4, 1, true); EXPECT_NOTHROW(stwr_pipe.writeStage(0, false)); runCycle(stwr_pipe, &sched); EXPECT_TRUE(!stwr_pipe.isValid(0)); EXPECT_NOTHROW(stwr_pipe.writeStage(0, true)); // drain pipe for (uint32_t i = 0; i < stwr_pipe.capacity(); ++i) runCycle(stwr_pipe, &sched); std::cout << "[FINISH] Pipeline Stall/Restart Handling Test" << std::endl; //////////////////////////////////////////////////////////////////////////////// // Pipeline Flush Handling Test //////////////////////////////////////////////////////////////////////////////// std::cout << "\n[START] Pipeline Flush Handling Test\n"; #ifndef TEST_MANUAL_UPDATE examplePipeline6.performOwnUpdates(); #endif cyc_cnt = 0; std::cout << "Append pipeline with data[=1000]\n"; EXPECT_NOTHROW(examplePipeline6.append(1000)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline6, &sched); EXPECT_EQUAL(examplePipeline6.numValid(), 1); EXPECT_TRUE(examplePipeline6.isValid(0)); std::cout << "Append pipeline with data[=2000]\n"; EXPECT_NOTHROW(examplePipeline6.append(2000)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline6, &sched); EXPECT_EQUAL(examplePipeline6.numValid(), 2); EXPECT_TRUE(examplePipeline6.isValid(0)); EXPECT_TRUE(examplePipeline6.isValid(1)); std::cout << "Append pipeline with data[=3000]\n"; EXPECT_NOTHROW(examplePipeline6.append(3000)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline6, &sched); EXPECT_EQUAL(examplePipeline6.numValid(), 3); EXPECT_TRUE(examplePipeline6.isValid(0)); EXPECT_TRUE(examplePipeline6.isValid(1)); EXPECT_TRUE(examplePipeline6.isValid(2)); // Test flushing all pipeline stages std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; #ifdef TEST_MANUAL_UPDATE examplePipeline6.update(); EXPECT_NOTHROW(ev_flush_all.schedule(sparta::Clock::Cycle(0))); sched.run(1, true); #else EXPECT_NOTHROW(ev_flush_all.schedule(sparta::Clock::Cycle(1))); sched.run(1, true); #endif EXPECT_EQUAL(examplePipeline6.numValid(), 0); std::cout << "Append pipeline with data[=1000]\n"; EXPECT_NOTHROW(examplePipeline6.append(1000)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline6, &sched); EXPECT_EQUAL(examplePipeline6.numValid(), 1); EXPECT_TRUE(examplePipeline6.isValid(0)); std::cout << "Append pipeline with data[=2000]\n"; EXPECT_NOTHROW(examplePipeline6.append(2000)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline6, &sched); EXPECT_EQUAL(examplePipeline6.numValid(), 2); EXPECT_TRUE(examplePipeline6.isValid(0)); EXPECT_TRUE(examplePipeline6.isValid(1)); std::cout << "Append pipeline with data[=3000]\n"; EXPECT_NOTHROW(examplePipeline6.append(3000)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline6, &sched); EXPECT_EQUAL(examplePipeline6.numValid(), 3); EXPECT_TRUE(examplePipeline6.isValid(0)); EXPECT_TRUE(examplePipeline6.isValid(1)); EXPECT_TRUE(examplePipeline6.isValid(2)); std::cout << "Stall stage[1] for 2 cycles\n"; EXPECT_NOTHROW(examplePipeline6.stall(1, 2)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline6, &sched); EXPECT_EQUAL(examplePipeline6.numValid(), 3); EXPECT_TRUE(examplePipeline6.isValid(0)); EXPECT_TRUE(examplePipeline6.isValid(1)); EXPECT_TRUE(examplePipeline6.isValid(3)); // Test flushing pipeline stage before stall-causing stage; std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; #ifdef TEST_MANUAL_UPDATE examplePipeline6.update(); EXPECT_NOTHROW(ev_flush_one.preparePayload(0)->schedule(sparta::Clock::Cycle(0))); sched.run(1, true); #else EXPECT_NOTHROW(ev_flush_one.preparePayload(0)->schedule(sparta::Clock::Cycle(1))); sched.run(1, true); #endif EXPECT_EQUAL(examplePipeline6.numValid(), 2); EXPECT_FALSE(examplePipeline6.isValid(0)); EXPECT_TRUE(examplePipeline6.isValid(1)); EXPECT_TRUE(examplePipeline6.isValid(4)); std::cout << "Append pipeline with data[=1000]\n"; EXPECT_NOTHROW(examplePipeline6.append(1000)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline6, &sched); EXPECT_EQUAL(examplePipeline6.numValid(), 2); EXPECT_TRUE(examplePipeline6.isValid(0)); EXPECT_TRUE(examplePipeline6.isValid(2)); std::cout << "Append pipeline with data[=2000]\n"; EXPECT_NOTHROW(examplePipeline6.append(2000)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline6, &sched); EXPECT_EQUAL(examplePipeline6.numValid(), 3); EXPECT_TRUE(examplePipeline6.isValid(0)); EXPECT_TRUE(examplePipeline6.isValid(1)); EXPECT_TRUE(examplePipeline6.isValid(3)); std::cout << "Stall stage[1] for 3 cycles\n"; EXPECT_NOTHROW(examplePipeline6.stall(1, 3)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline6, &sched); EXPECT_EQUAL(examplePipeline6.numValid(), 3); EXPECT_TRUE(examplePipeline6.isValid(0)); EXPECT_TRUE(examplePipeline6.isValid(1)); EXPECT_TRUE(examplePipeline6.isValid(4)); // Test flushing pipeline stage which is alsp a stall-causing stage // Expect the pipeline to restart next cycle std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; #ifdef TEST_MANUAL_UPDATE examplePipeline6.update(); EXPECT_NOTHROW(ev_flush_one.preparePayload(1)->schedule(sparta::Clock::Cycle(0))); sched.run(1, true); #else EXPECT_NOTHROW(ev_flush_one.preparePayload(1)->schedule(sparta::Clock::Cycle(1))); sched.run(1, true); #endif EXPECT_EQUAL(examplePipeline6.numValid(), 1); EXPECT_TRUE(examplePipeline6.isValid(0)); EXPECT_FALSE(examplePipeline6.isValid(1)); EXPECT_EQUAL(examplePipeline6[0], 2000); std::cout << "Append pipeline with data[=3000]\n"; EXPECT_NOTHROW(examplePipeline6.append(3000)); std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline6, &sched); EXPECT_EQUAL(examplePipeline6.numValid(), 2); EXPECT_TRUE(examplePipeline6.isValid(0)); EXPECT_TRUE(examplePipeline6.isValid(1)); EXPECT_EQUAL(examplePipeline6[0], 3000); EXPECT_EQUAL(examplePipeline6[1], 2000); while (examplePipeline6.numValid()) { std::cout << "Cycle[" << cyc_cnt++ << "]:\n"; runCycle(examplePipeline6, &sched); } std::cout << "[FINISH] Pipeline Flush Handling Test\n" << std::endl; rtn.enterTeardown(); #ifdef PIPEOUT_GEN pc.destroy(); #endif // Returns error if one REPORT_ERROR; return ERROR_CODE; }
39.063355
196
0.655891
[ "object" ]
e50592f14af44fa344e901d749a8e30e1713d61d
2,611
hpp
C++
Graph.hpp
ajeseritz/projects2.0
59b4e6e9c113643d9e33156797dd183b9d726e79
[ "MIT" ]
null
null
null
Graph.hpp
ajeseritz/projects2.0
59b4e6e9c113643d9e33156797dd183b9d726e79
[ "MIT" ]
null
null
null
Graph.hpp
ajeseritz/projects2.0
59b4e6e9c113643d9e33156797dd183b9d726e79
[ "MIT" ]
null
null
null
#ifndef GRAPH_HPP #define GRAPH_HPP #include <vector> #include <iostream> struct vertex; /*This is the struct for the adjacent vertices for each vertex in the graph. */ struct Edge { vertex *v; int distance; }; /*this is the struct for each vertex in the graph. */ struct vertex { std::string name; int district; bool visited; std::vector<Edge> Edges; //stores edges to adjacent vertices }; class Graph { public: /* class constructor Purpose: perform all operations necessary to instantiate a class object Parameters: none */ Graph(); /* class destructor Purpose: free all resources that the object has aquired Parameters: none */ ~Graph(); /* Method Name: addEdge Purpose: Creates an edge between two vertices (using an adjVertex struct) Param: v1 - vertex at one end of edge Param: v2 - vertex at opposite end of edge */ void addEdge(std::string v1, std::string v2, int distance); /* Method Name: addVertex Purpose: Creates a vertex Param: name - name of the vertex (city name) */ void addVertex(std::string name); /* Method Name: displayEdges Purpose: print all edges in graph (see writeup for format) Parameters: none */ void displayEdges(); /* Method Name: assignDistricts Purpose: Iterate through the vertices, perform BFT to find connected components, and assign to district Parameters: none */ void assignDistricts(); /* Method Name: printDFS Purpose: Iterate through the vertices, perform DFS by calling the DFTraversal function Parameters: none */ void printDFS(); /* Method Name: setAllVerticesUnvisited Purpose: Iterate through the vertices, mark them unvisited. This function is called prior to calling DFS after BFS has been performed so that the nodes can revisited again when DFS is called. Parameters: None */ void setAllVerticesUnvisited(); private: std::vector<vertex> vertices; //stores vertices /* Method Name: findVertex Purpose: Find and return the vertex of the specified city Param: name - name of the city vertex to be returned returns pointer to a vertex */ vertex *findVertex(std::string name); /* Method Name: BFTraversalLabel Purpose: Call BFTraversalLabel from within assignDistricts to label the districts. This method should implement a breadth first traversal from the startingCity and assign all cities encountered the distID value Param: name - name of starting city for breadth first traversal */ void BFTraversalLabel(std::string startingCity, int distID); void DFTraversal(vertex *v); }; #endif // GRAPH_HPP
21.401639
68
0.725776
[ "object", "vector" ]
e5075f4b0c1f40c448b5a08d90a5bf3a9d57e13a
3,707
cpp
C++
control/rightclickmenudialog.cpp
realm520/ctcwallet
9c74feab5472c91869f993711a4f9ba9624d1091
[ "MIT" ]
null
null
null
control/rightclickmenudialog.cpp
realm520/ctcwallet
9c74feab5472c91869f993711a4f9ba9624d1091
[ "MIT" ]
null
null
null
control/rightclickmenudialog.cpp
realm520/ctcwallet
9c74feab5472c91869f993711a4f9ba9624d1091
[ "MIT" ]
null
null
null
#include "rightclickmenudialog.h" #include "ui_rightclickmenudialog.h" #include "../blockchain.h" #include "commondialog.h" #ifdef WIN32 #include "Windows.h" #endif #include <QDebug> #include <QClipboard> RightClickMenuDialog::RightClickMenuDialog( QString name, QWidget *parent) : QDialog(parent), accountName(name), ui(new Ui::RightClickMenuDialog) { ui->setupUi(this); setWindowFlags(Qt::Popup); ui->copyBtn->setStyleSheet("QPushButton{background-color:#ffffff;color:rgb(47,94,178);border:1px solid rgb(239,239,239);border-radius:0px;}" "QPushButton:hover{background-color:rgb(47,94,178);color:#ffffff;border-radius:0px;}" ); ui->transferBtn->setStyleSheet("QPushButton{background-color:#ffffff;color:rgb(47,94,178);border:1px solid rgb(239,239,239);border-radius:0px;}" "QPushButton:hover{background-color:rgb(47,94,178);color:#ffffff;border-radius:0px;}" ); ui->renameBtn->setStyleSheet("QPushButton{background-color:#ffffff;color:rgb(47,94,178);border:1px solid rgb(239,239,239);border-radius:0px;}" "QPushButton:hover{background-color:rgb(47,94,178);color:#ffffff;border-radius:0px;}" ); ui->exportBtn->setStyleSheet("QPushButton{background-color:#ffffff;color:rgb(47,94,178);border:1px solid rgb(239,239,239);border-radius:0px;}" "QPushButton:hover{background-color:rgb(47,94,178);color:#ffffff;border-radius:0px;}" ); ui->deleteBtn->setStyleSheet("QPushButton{background-color:#ffffff;color:rgb(47,94,178);border:1px solid rgb(239,239,239);border-radius:0px;}" "QPushButton:hover{background-color:rgb(47,94,178);color:#ffffff;border-radius:0px;}" ); if( CTC::getInstance()->registerMapValue(name) != "NO" ) // 如果是已注册账户 不显示修改账户名选项 { ui->renameBtn->hide(); ui->exportBtn->move(0,35); setGeometry(0,0,116,71); } } RightClickMenuDialog::~RightClickMenuDialog() { delete ui; } void RightClickMenuDialog::on_transferBtn_clicked() { close(); emit transferFromAccount(accountName); } void RightClickMenuDialog::on_renameBtn_clicked() { close(); emit renameAccount(accountName); } void RightClickMenuDialog::on_exportBtn_clicked() { close(); emit exportAccount(accountName); } bool RightClickMenuDialog::event(QEvent *event) { #ifdef WIN32 // class_ameneded 不能是custommenu的成员, 因为winidchange事件触发时, 类成员尚未初始化 static bool class_amended = false; if (event->type() == QEvent::WinIdChange) { HWND hwnd = reinterpret_cast<HWND>(winId()); if (class_amended == false) { class_amended = true; DWORD class_style = ::GetClassLong(hwnd, GCL_STYLE); class_style &= ~CS_DROPSHADOW; ::SetClassLong(hwnd, GCL_STYLE, class_style); // windows系统函数 } } #endif return QWidget::event(event); } void RightClickMenuDialog::on_copyBtn_clicked() { close(); QString address = CTC::getInstance()->addressMap.value(accountName).ownerAddress; QClipboard* clipBoard = QApplication::clipboard(); clipBoard->setText(address); CommonDialog commonDialog(CommonDialog::OkOnly); commonDialog.setText(tr("Copy to clipboard")); commonDialog.pop(); } void RightClickMenuDialog::on_deleteBtn_clicked() { close(); emit deleteAccount(accountName); }
34.324074
149
0.625034
[ "solid" ]
e50c804b0cca3b6b46769a1809915c53bc25d8cf
2,323
cpp
C++
example/json/req.cpp
wangxiaoshuai123456/aic_communication
070fb6c8c7a1a9f7c3b63fcc1b739411d38ea1c7
[ "MIT" ]
7
2019-01-16T14:46:12.000Z
2021-11-07T20:21:49.000Z
example/json/req.cpp
wangxiaoshuai123456/aic_communication
070fb6c8c7a1a9f7c3b63fcc1b739411d38ea1c7
[ "MIT" ]
null
null
null
example/json/req.cpp
wangxiaoshuai123456/aic_communication
070fb6c8c7a1a9f7c3b63fcc1b739411d38ea1c7
[ "MIT" ]
3
2019-11-28T13:31:30.000Z
2020-10-13T08:20:15.000Z
#include "callback.h" void requestSimulation(std::shared_ptr<AicCommuInterface> obj){ unsigned int order = 1; while(1){ //build data packet json req; req["header"]["type"] = 1; req["body"]["msg"] = "test req msg"; req["body"]["order"] = order++; std::string pack = req.dump(); bytes_ptr data = std::make_shared<bytes_vec>(pack.data(), pack.data()+pack.size()); /**method1 - send data packet,the recv packet will be returned in callback function set by 'setRecvCall', if the connection with server hasn't build,then the packet will be pushed into the send queue, it will be send to the server later when the connection is build */ obj->send(data); /**method2 - same behaviour with method1,the only difference is that the packet will be discarded if server is no connected obj->send(data,nullptr,true); */ /**method3 - send data packet,the recv packet will be returned in the lambda expression obj->send(data,[](const std::string *p_sub, bytes_ptr data_in, bytes_ptr data_out){ //do with the returned packet }); */ SLEEP(1000); } } int main() { printf("lib version:%s\n",AicCommuFactory::version().c_str()); auto obj = AicCommuFactory::newSocket(AicCommuType::CLIENT_REQUEST, "127.0.0.1", 60005, "req");//create communication object, essential obj->setPollTimeout(5000); //optional, set request timeout, default 5 seconds obj->setHeartbeatIVL(1000); //optional, set heartbeat interval, hasn't heartbeat checking default obj->setRecvCall(&req_recv_func, false); //optional, set response callback function,packet returned by server will be received in this function obj->setStatusCall(&status_func); //optional, set 'zmq socket' status callback function obj->setLogCall(&log_func, AicCommuLogLevels::DEBUG, true); //optional, set log callback function of communication library obj->setPrintPackCall(&print_pack_func); //optional, set data packet print callback functionl obj->run(); //essential, start up communication threads requestSimulation(obj); return 0; }
40.051724
150
0.637107
[ "object" ]
e51410a2fb9bfa4265e5defddbcb9b9c8b4cc704
3,915
cpp
C++
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/caches/SoGlyphCache.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/caches/SoGlyphCache.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/caches/SoGlyphCache.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
/**************************************************************************\ * * This file is part of the Coin 3D visualization library. * Copyright (C) by Kongsberg Oil & Gas Technologies. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * ("GPL") version 2 as published by the Free Software Foundation. * See the file LICENSE.GPL at the root directory of this source * distribution for additional information about the GNU GPL. * * For using Coin with software that can not be combined with the GNU * GPL, and for taking advantage of the additional benefits of our * support services, please contact Kongsberg Oil & Gas Technologies * about acquiring a Coin Professional Edition License. * * See http://www.coin3d.org/ for more information. * * Kongsberg Oil & Gas Technologies, Bygdoy Alle 5, 0257 Oslo, NORWAY. * http://www.sim.no/ sales@sim.no coin-support@coin3d.org * \**************************************************************************/ /*! \class SoGlyphCache include/Inventor/SoGlyphCache.h The SoGlyphClass is used to cache glyphs. \internal */ #include "caches/SoGlyphCache.h" #include <cassert> #include <Inventor/lists/SbList.h> #include <Inventor/elements/SoFontNameElement.h> #include <Inventor/elements/SoFontSizeElement.h> #include <Inventor/elements/SoComplexityElement.h> #include <Inventor/errors/SoDebugError.h> #include "tidbitsp.h" class SoGlyphCacheP { public: SbList <cc_glyph2d*> glyphlist2d; SbList <cc_glyph3d*> glyphlist3d; cc_font_specification * fontspec; }; #define PRIVATE(obj) ((obj)->pimpl) SoGlyphCache::SoGlyphCache(SoState * state) : SoCache(state) { PRIVATE(this) = new SoGlyphCacheP; PRIVATE(this)->fontspec = NULL; #if COIN_DEBUG if (coin_debug_caching_level() > 0) { SoDebugError::postInfo("SoGlyphCache::SoGlyphCache", "Cache constructed: %p", this); } #endif // debug } SoGlyphCache::~SoGlyphCache() { #if COIN_DEBUG if (coin_debug_caching_level() > 0) { SoDebugError::postInfo("SoGlyphCache::~SoGlyphCache", "Cache destructed: %p", this); } #endif // debug int i; this->readFontspec(NULL); for (i = 0; i < PRIVATE(this)->glyphlist2d.getLength(); i++) { cc_glyph2d_unref(PRIVATE(this)->glyphlist2d[i]); } for (i = 0; i < PRIVATE(this)->glyphlist3d.getLength(); i++) { cc_glyph3d_unref(PRIVATE(this)->glyphlist3d[i]); } delete PRIVATE(this); } /* Add a glyph that is created using cc_glyph2d_ref(). The cache will call cc_glyph2d_unref() when destructed. */ void SoGlyphCache::addGlyph(cc_glyph2d * glyph) { PRIVATE(this)->glyphlist2d.append(glyph); } /* Add a glyph that is created using cc_glyph2d_ref(). The cache will call cc_glyph2d_unref() when destructed. */ void SoGlyphCache::addGlyph(cc_glyph3d * glyph) { PRIVATE(this)->glyphlist3d.append(glyph); } /*! Read and store current fontspec. Will create cache dependencies since some elements are read. We can't read the fontspec in the constructor since we need to update SoCacheElement before reading the elements. */ void SoGlyphCache::readFontspec(SoState * state) { if (PRIVATE(this)->fontspec) { cc_fontspec_clean(PRIVATE(this)->fontspec); delete PRIVATE(this)->fontspec; PRIVATE(this)->fontspec = NULL; } if (state) { PRIVATE(this)->fontspec = new cc_font_specification; cc_fontspec_construct(PRIVATE(this)->fontspec, SoFontNameElement::get(state).getString(), SoFontSizeElement::get(state), SoComplexityElement::get(state)); } } /*! Returns the cached fontspec. */ const cc_font_specification * SoGlyphCache::getCachedFontspec(void) const { assert(PRIVATE(this)->fontspec); return PRIVATE(this)->fontspec; } #undef PRIVATE
27.1875
76
0.672797
[ "3d" ]
e5167492c00d4c7d759ce6c97e78080ef0733c42
8,405
cpp
C++
Kits/ATGTK/TextConsole.cpp
JSungMin/RenderEngine
e4a7475c6940a007a2318d13a523361441ff1dae
[ "MIT" ]
null
null
null
Kits/ATGTK/TextConsole.cpp
JSungMin/RenderEngine
e4a7475c6940a007a2318d13a523361441ff1dae
[ "MIT" ]
null
null
null
Kits/ATGTK/TextConsole.cpp
JSungMin/RenderEngine
e4a7475c6940a007a2318d13a523361441ff1dae
[ "MIT" ]
null
null
null
//-------------------------------------------------------------------------------------- // File: TextConsole.cpp // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright(c) Microsoft Corporation. All rights reserved. //-------------------------------------------------------------------------------------- #include "pch.h" #include "TextConsole.h" #include "SimpleMath.h" #include "DDSTextureLoader.h" #include "WICTextureLoader.h" #include <assert.h> using Microsoft::WRL::ComPtr; using namespace DirectX; using namespace DX; TextConsole::TextConsole() : m_textColor(1.f, 1.f, 1.f, 1.f), m_debugOutput(false) { Clear(); } TextConsole::TextConsole(ID3D11DeviceContext* context, const wchar_t* fontName) : m_textColor(1.f, 1.f, 1.f, 1.f), m_debugOutput(false) { RestoreDevice(context, fontName); Clear(); } void TextConsole::Render() { std::lock_guard<std::mutex> lock(m_mutex); float lineSpacing = m_font->GetLineSpacing(); float x = float(m_layout.left); float y = float(m_layout.top); XMVECTOR color = XMLoadFloat4(&m_textColor); m_batch->Begin(); unsigned int textLine = unsigned int(m_currentLine + 1) % m_rows; for (unsigned int line = 0; line < m_rows; ++line) { XMFLOAT2 pos(x, y + lineSpacing * float(line)); if (*m_lines[textLine]) { m_font->DrawString(m_batch.get(), m_lines[textLine], pos, color); } textLine = unsigned int(textLine + 1) % m_rows; } m_batch->End(); } void TextConsole::Clear() { std::lock_guard<std::mutex> lock(m_mutex); if (m_buffer) { memset(m_buffer.get(), 0, sizeof(wchar_t) * (m_columns + 1) * m_rows); } m_currentColumn = m_currentLine = 0; } _Use_decl_annotations_ void TextConsole::Write(const wchar_t *str) { std::lock_guard<std::mutex> lock(m_mutex); ProcessString(str); #ifndef NDEBUG if (m_debugOutput) { OutputDebugStringW(str); } #endif } _Use_decl_annotations_ void TextConsole::WriteLine(const wchar_t *str) { std::lock_guard<std::mutex> lock(m_mutex); ProcessString(str); IncrementLine(); #ifndef NDEBUG if (m_debugOutput) { OutputDebugStringW(str); OutputDebugStringW(L"\n"); } #endif } _Use_decl_annotations_ void TextConsole::Format(const wchar_t* strFormat, ...) { std::lock_guard<std::mutex> lock(m_mutex); va_list argList; va_start(argList, strFormat); size_t len = _vscwprintf(strFormat, argList) + 1; if (m_tempBuffer.size() < len) m_tempBuffer.resize(len); memset(m_tempBuffer.data(), 0, sizeof(wchar_t) * len); vswprintf_s(m_tempBuffer.data(), m_tempBuffer.size(), strFormat, argList); va_end(argList); ProcessString(m_tempBuffer.data()); #ifndef NDEBUG if (m_debugOutput) { OutputDebugStringW(m_tempBuffer.data()); } #endif } void TextConsole::SetWindow(const RECT& layout) { std::lock_guard<std::mutex> lock(m_mutex); m_layout = layout; assert(m_font != 0); float lineSpacing = m_font->GetLineSpacing(); unsigned int rows = std::max<unsigned int>(1, static_cast<unsigned int>(float(layout.bottom - layout.top) / lineSpacing)); RECT fontLayout = m_font->MeasureDrawBounds(L"X", XMFLOAT2(0,0)); unsigned int columns = std::max<unsigned int>(1, static_cast<unsigned int>(float(layout.right - layout.left) / float(fontLayout.right - fontLayout.left))); std::unique_ptr<wchar_t[]> buffer(new wchar_t[(columns + 1) * rows]); memset(buffer.get(), 0, sizeof(wchar_t) * (columns + 1) * rows); std::unique_ptr<wchar_t*[]> lines(new wchar_t*[rows]); for (unsigned int line = 0; line < rows; ++line) { lines[line] = buffer.get() + (columns + 1) * line; } if (m_lines) { unsigned int c = std::min<unsigned int>(columns, m_columns); unsigned int r = std::min<unsigned int>(rows, m_rows); for (unsigned int line = 0; line < r; ++line) { memcpy(lines[line], m_lines[line], c * sizeof(wchar_t)); } } std::swap(columns, m_columns); std::swap(rows, m_rows); std::swap(buffer, m_buffer); std::swap(lines, m_lines); if ((m_currentColumn >= m_columns) || (m_currentLine >= m_rows)) { IncrementLine(); } } void TextConsole::ReleaseDevice() { m_batch.reset(); m_font.reset(); m_context.Reset(); } void TextConsole::RestoreDevice(ID3D11DeviceContext* context, const wchar_t* fontName) { m_context = context; m_batch = std::make_unique<SpriteBatch>(context); ComPtr<ID3D11Device> device; context->GetDevice(device.GetAddressOf()); m_font = std::make_unique<SpriteFont>(device.Get(), fontName); m_font->SetDefaultCharacter(L' '); } void TextConsole::SetViewport(const D3D11_VIEWPORT& viewPort) { if (m_batch) { m_batch->SetViewport(viewPort); } } void TextConsole::SetRotation(DXGI_MODE_ROTATION rotation) { if (m_batch) { m_batch->SetRotation(rotation); } } void TextConsole::ProcessString(const wchar_t* str) { if (!m_lines) return; float width = float(m_layout.right - m_layout.left); for (const wchar_t* ch = str; *ch != 0; ++ch) { if (*ch == '\n') { IncrementLine(); continue; } bool increment = false; if (m_currentColumn >= m_columns) { increment = true; } else { m_lines[m_currentLine][m_currentColumn] = *ch; auto fontSize = m_font->MeasureString(m_lines[m_currentLine]); if (XMVectorGetX(fontSize) > width) { m_lines[m_currentLine][m_currentColumn] = L'\0'; increment = true; } } if (increment) { IncrementLine(); m_lines[m_currentLine][0] = *ch; } ++m_currentColumn; } } void TextConsole::IncrementLine() { if (!m_lines) return; m_currentLine = (m_currentLine + 1) % m_rows; m_currentColumn = 0; memset(m_lines[m_currentLine], 0, sizeof(wchar_t) * (m_columns + 1)); } //-------------------------------------------------------------------------------------- TextConsoleImage::TextConsoleImage() : TextConsole() { } TextConsoleImage::TextConsoleImage(ID3D11DeviceContext* context, const wchar_t* fontName, const wchar_t* image) : TextConsole() { RestoreDevice(context, fontName, image); } void TextConsoleImage::Render() { m_batch->Begin(); m_batch->Draw(m_background.Get(), m_fullscreen); m_batch->End(); TextConsole::Render(); } void TextConsoleImage::SetWindow(const RECT& fullscreen, bool useSafeRect) { m_fullscreen = fullscreen; if ( useSafeRect ) { TextConsole::SetWindow( SimpleMath::Viewport::ComputeTitleSafeArea(fullscreen.right - fullscreen.left, fullscreen.bottom - fullscreen.top)); } else { TextConsole::SetWindow(fullscreen); } UINT width = std::max<UINT>(fullscreen.right - fullscreen.left, 1); UINT height = std::max<UINT>(fullscreen.bottom - fullscreen.top, 1); auto vp = CD3D11_VIEWPORT(0.0f, 0.0f, static_cast<float>(width), static_cast<float>(height)); m_batch->SetViewport(vp); } void TextConsoleImage::ReleaseDevice() { TextConsole::ReleaseDevice(); m_background.Reset(); } void TextConsoleImage::RestoreDevice(ID3D11DeviceContext* context, const wchar_t* fontName, const wchar_t* image) { TextConsole::RestoreDevice(context, fontName); ComPtr<ID3D11Device> device; context->GetDevice(device.GetAddressOf()); wchar_t ext[_MAX_EXT]; _wsplitpath_s(image, nullptr, 0, nullptr, 0, nullptr, 0, ext, _MAX_EXT); if (_wcsicmp(ext, L".dds") == 0) { DX::ThrowIfFailed(CreateDDSTextureFromFile(device.Get(), image, nullptr, m_background.ReleaseAndGetAddressOf())); } else { DX::ThrowIfFailed(CreateWICTextureFromFile(device.Get(), image, nullptr, m_background.ReleaseAndGetAddressOf())); } }
22.654987
159
0.614277
[ "render" ]
e5191d4ca2d7410499911bdcc60d9701655054f3
9,265
inl
C++
applications/plugins/DEPRECATED/SofaVRPNClient/VRPNImager.inl
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
applications/plugins/DEPRECATED/SofaVRPNClient/VRPNImager.inl
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
applications/plugins/DEPRECATED/SofaVRPNClient/VRPNImager.inl
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU General Public License as published by the Free * * Software Foundation; either version 2 of the License, or (at your option) * * any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * * more details. * * * * You should have received a copy of the GNU General Public License along * * with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ /* * VRPNImager.cpp * * Created on: 14 May 2010 * Author: peterlik, olsak */ #ifndef SOFAVRPNCLIENT_VRPNIMAGER_INL_ #define SOFAVRPNCLIENT_VRPNIMAGER_INL_ #include "VRPNImager.h" #include <sofa/core/objectmodel/KeypressedEvent.h> #include <sofa/core/objectmodel/KeyreleasedEvent.h> #include <sofa/core/objectmodel/KeypressedEvent.h> #include <sofa/core/objectmodel/KeyreleasedEvent.h> #include <sofa/defaulttype/Quat.h> namespace sofavrpn { namespace client { using namespace sofa::defaulttype; template<class DataTypes> VRPNImager<DataTypes>::VRPNImager() //: f_positions( initData (&f_positions, "positions", "Positions (Vector of 3)") ) //, f_orientations( initData (&f_orientations, "orientations", "Orientations (Quaternion)") ) : f_rigidPoint( initData (&f_rigidPoint, "rigid point", "RigidPoint")), f_scale( initData (&f_scale, "scale", "Scale")) { addAlias(&f_rigidPoint,"rigidPosition"); f_scale.setValue(1.0); // = 1.0; // TODO Auto-generated constructor stub /*trackerData.data.resize(1); rg.initSeed( (long int) this );*/ } template<class DataTypes> VRPNImager<DataTypes>::~VRPNImager() { // TODO Auto-generated destructor stub } template<class DataTypes> bool VRPNImager<DataTypes>::connectToServer() { std::cout << "Connecting to imager server..." << std::endl; g_imager = new vrpn_Imager_Remote(deviceURL.c_str()); imagerData.remote_imager = g_imager; g_imager->register_description_handler((void*) &imagerData, handle_description_message); g_imager->register_discarded_frames_handler((void*) &imagerData , handle_discarded_frames); g_imager->register_end_frame_handler((void*) &imagerData, handle_end_of_frame); g_imager->register_region_handler((void*) &imagerData, handle_region_change); std::cout << "Waiting to hear the image dimensions..." << std::endl; while (!imagerData.got_dimensions) { g_imager->mainloop(); vrpn_SleepMsecs(1); } std::cout << "Connection established, dimensions " << imagerData.Xdim << " " << imagerData.Ydim << std::endl; g_imager->connectionPtr()->Jane_stop_this_crazy_thing(50); // Allocate memory for the image and clear it, so that things that don't get filled in will be black. if ( (imagerData.image = new unsigned char[imagerData.Xdim * imagerData.Ydim * 3]) == NULL) { std::cout << "Out of memory when allocating image!" << std::endl; return -1; } for (unsigned int i = 0; i < (unsigned)(imagerData.Xdim * imagerData.Ydim * 3); i++) { imagerData.image[i] = 0; } imagerData.ready_for_region = true; glGenTextures(1, &imageTextureID); return true; } template<class DataTypes> void VRPNImager<DataTypes>::update() { g_imager->mainloop(); Point x; for (unsigned i=0; i < x.size(); i++) x[i] = imagerData.rigidPointData[i]; //float temp = x[1]; x[0]*= f_scale.getValue(); x[1]= -x[1]*f_scale.getValue(); x[2]= -x[2]*f_scale.getValue(); if (x.size() > 3) { // process quaternion //x[0] *= 1; //x[1] *= -1; //x[2] *= -1; //x[2]; x[2]=temp; /*temp=x[5]; x[5]=x[6]; x[6]=temp;*/ /*x[3] = 0; x[4] = 0; x[5] = 0; x[6] = 1;*/ //x[3] = imagerData.rigidPointData[ std::cout << "PointData = " << f_rigidPoint.getValue() << std::endl; Quat qt(x[3], x[4], x[5], x[6]); Vec3 currentAxisRotation; Real currentAngleRotation; qt.quatToAxis(currentAxisRotation, currentAngleRotation); //Quat qt2(currentAxisRotation*(-1), currentAngleRotation); currentAxisRotation[1] *= -1; currentAxisRotation[2] *= -1; /*Real ttemp; ttemp = currentAxisRotation[0]; currentAxisRotation[0]=currentAxisRotation[2]; currentAxisRotation[2]=ttemp;*/ Quat qt2(currentAxisRotation, currentAngleRotation); x[3] = qt2[0]; x[4] = qt2[1]; x[5] = qt2[2]; x[6] = qt2[3]; } //std::cout << "Quat = " << qt << std::endl; //std::cout << "Euler = " << qt.toEulerVector() << std::endl; f_rigidPoint.setValue(x); /*sofa::helper::WriteAccessor< Data< VecCoord > > points = f_points; std::cout << "read tracker " << this->getName() << std::endl; if (tkr) { //get infos trackerData.modified = false; tkr->mainloop(); VRPNTrackerData copyTrackerData(trackerData); if(copyTrackerData.modified) { points.clear(); //if (points.size() < trackerData.data.size()) points.resize(copyTrackerData.data.size()); for (unsigned int i=0 ; i<copyTrackerData.data.size() ;i++) { Coord pos; pos[0] = (copyTrackerData.data[i].pos[0])*p_scale.getValue() + p_dx.getValue(); pos[1] = (copyTrackerData.data[i].pos[1])*p_scale.getValue() + p_dy.getValue(); pos[2] = (copyTrackerData.data[i].pos[2])*p_scale.getValue() + p_dz.getValue(); Coord p(pos); points[i] = p; } } }*/ } template<class DataTypes> void VRPNImager<DataTypes>::draw() { glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); glDisable(GL_CULL_FACE); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, imageTextureID); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, g_imager->nCols(), g_imager->nRows(), 0, GL_BGR, GL_UNSIGNED_BYTE, imagerData.image); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glBegin(GL_QUADS); glTexCoord2i(0, 0); glVertex4f(-1, -1, 0, 1); glTexCoord2i(1, 0); glVertex4f(1, -1, 0, 1); glTexCoord2i(1, 1); glVertex4f(1, 1, 0, 1); glTexCoord2i(0, 1); glVertex4f(-1, 1, 0, 1); glEnd(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glDisable(GL_TEXTURE_2D); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); } template<class DataTypes> void VRPNImager<DataTypes>::handleEvent(sofa::core::objectmodel::Event* /*event*/) { update(); /*if (sofa::core::objectmodel::KeypressedEvent* ev = dynamic_cast<sofa::core::objectmodel::KeypressedEvent*>(event)) { double nb = 10.0; switch(ev->getKey()) { case 'A': case 'a': angleX -= M_PI/nb; break; case 'Q': case 'q': angleX += M_PI/nb; break; case 'Z': case 'z': angleY -= M_PI/nb; break; case 'S': case 's': angleY += M_PI/nb; break; case 'E': case 'e': angleZ -= M_PI/nb; break; case 'D': case 'd': angleZ += M_PI/nb; break; } }*/ } } } #endif /* SOFAVRPNCLIENT_VRPNIMAGER_INL_ */
31.729452
128
0.556827
[ "vector" ]
e52846a208a4a0c2f36eaef5c482f148772cfbd9
7,716
hpp
C++
ocs2_thirdparty/include/cppad/cg/dae_index_reduction/soares_secchi.hpp
grizzi/ocs2
4b78c4825deb8b2efc992fdbeef6fdb1fcca2345
[ "BSD-3-Clause" ]
126
2021-07-13T13:59:12.000Z
2022-03-31T02:52:18.000Z
ocs2_thirdparty/include/cppad/cg/dae_index_reduction/soares_secchi.hpp
grizzi/ocs2
4b78c4825deb8b2efc992fdbeef6fdb1fcca2345
[ "BSD-3-Clause" ]
27
2021-07-14T12:14:04.000Z
2022-03-30T16:27:52.000Z
ocs2_thirdparty/include/cppad/cg/dae_index_reduction/soares_secchi.hpp
grizzi/ocs2
4b78c4825deb8b2efc992fdbeef6fdb1fcca2345
[ "BSD-3-Clause" ]
55
2021-07-14T07:08:47.000Z
2022-03-31T15:54:30.000Z
#ifndef CPPAD_CG_SOARES_SECCHI_HPP #define CPPAD_CG_SOARES_SECCHI_HPP /* -------------------------------------------------------------------------- * CppADCodeGen: C++ Algorithmic Differentiation with Source Code Generation: * Copyright (C) 2016 Ciengis * Copyright (C) 2018 Joao Leal * * CppADCodeGen is distributed under multiple licenses: * * - Eclipse Public License Version 1.0 (EPL1), and * - GNU General Public License Version 3 (GPL3). * * EPL1 terms and conditions can be found in the file "epl-v10.txt", while * terms and conditions for the GPL3 can be found in the file "gpl3.txt". * ---------------------------------------------------------------------------- * Author: Joao Leal */ #include <cppad/cg/dae_index_reduction/dae_structural_index_reduction.hpp> #include <cppad/cg/dae_index_reduction/augment_path_depth_lookahead.hpp> #include <cppad/cg/dae_index_reduction/augment_path_depth_lookahead_a.hpp> namespace CppAD { namespace cg { /** * Soares Secchi method for DAE structural index reduction */ template<class Base> class SoaresSecchi : public DaeStructuralIndexReduction<Base> { protected: using CGBase = CppAD::cg::CG<Base>; using ADCG = CppAD::AD<CGBase>; protected: // avoids having to type this->graph_ using DaeStructuralIndexReduction<Base>::graph_; // typical values used to avoid NaNs in the tape validation by CppAD std::vector<Base> x_; /** * the last equations added to graph * (equations used to create the ODE or DAE with index 1) */ std::set<Enode<Base>*> lastAddEq_; // whether or not reduceIndex() has been called bool reduced_; // AugmentPathDepthLookahead<Base> defaultAugmentPath_; AugmentPathDepthLookaheadA<Base> defaultAugmentPathA_; AugmentPath<Base>* augmentPath_; AugmentPath<Base>* augmentPathA_; public: /** * Creates the DAE index reduction algorithm that implements the * Soares Secchi method. * * @param fun The original model (potentially high index) * @param varInfo The DAE system variable information (in the same order * as in the tape) * @param eqName Equation names (it can be an empty vector) * @param x typical variable values (used to avoid NaNs in CppAD checks) */ SoaresSecchi(ADFun<CG<Base> >& fun, const std::vector<DaeVarInfo>& varInfo, const std::vector<std::string>& eqName, const std::vector<Base>& x) : DaeStructuralIndexReduction<Base>(fun, varInfo, eqName), x_(x), reduced_(false), augmentPath_(&defaultAugmentPath_), augmentPathA_(&defaultAugmentPathA_){ } SoaresSecchi(const SoaresSecchi& p) = delete; SoaresSecchi& operator=(const SoaresSecchi& p) = delete; virtual ~SoaresSecchi() { } AugmentPath<Base>& getAugmentPath() const { return *augmentPath_; } void setAugmentPath(AugmentPath<Base>& a) const { augmentPath_ = &a; } /** * Defines whether or not original names saved by using * CppAD::PrintFor(0, "", val, name) * should be kept by also adding PrintFor operations in the reduced model. */ inline void setPreserveNames(bool p) { graph_.setPreserveNames(p); } /** * Whether or not original names saved by using * CppAD::PrintFor(0, "", val, name) * should be kept by also adding PrintFor operations in the reduced model. */ inline bool isPreserveNames() const { return graph_.isPreserveNames(); } /** * Performs the DAE differentiation index reductions * * @param newVarInfo Variable related information of the reduced index * model * @param equationInfo Equation related information of the reduced index * model * @return the reduced index model (must be deleted by user) * @throws CGException on failure */ inline std::unique_ptr<ADFun<CG<Base>>> reduceIndex(std::vector<DaeVarInfo>& newVarInfo, std::vector<DaeEquationInfo>& equationInfo) override { if (reduced_) throw CGException("reduceIndex() can only be called once!"); if (this->verbosity_ >= Verbosity::High) log() << "######## Soares Secchi method ########\n"; augmentPath_->setLogger(*this); augmentPathA_->setLogger(*this); reduced_ = true; // detects which equations have to be differentiated to get an ODE detectSubset2Dif(); // we want an index 1 DAE (ignore the last equations added to the graph) for(const Enode<Base>* i: lastAddEq_) { graph_.remove(*i); } if (this->verbosity_ >= Verbosity::Low) { graph_.printResultInfo("Soares Secchi"); log() << "Structural index: " << graph_.getStructuralIndex() << std::endl; } std::unique_ptr<ADFun<CGBase>> reducedFun(graph_.generateNewModel(newVarInfo, equationInfo, x_)); return reducedFun; } /** * Provides the differentiation index. It can only be called after * reduceIndex(). * * @return the DAE differentiation index. * @throws CGException */ inline size_t getStructuralIndex() const { return graph_.getStructuralIndex(); } protected: using DaeStructuralIndexReduction<Base>::log; /** * */ inline void detectSubset2Dif() { auto& vnodes = graph_.variables(); auto& enodes = graph_.equations(); std::set<Enode<Base>*> marked; std::set<Enode<Base>*> lastMarked; if (this->verbosity_ >= Verbosity::High) graph_.printDot(this->log()); while (true) { // augment the matching one by one for (size_t k = 0; k < enodes.size(); k++) { Enode<Base>* i = enodes[k]; if (this->verbosity_ >= Verbosity::High) log() << "Outer loop: equation k = " << *i << "\n"; if (i->assignmentVariable() != nullptr) { continue; } bool pathFound = augmentPathA_->augmentPath(*i); if (!pathFound) { for (Enode<Base>* ii: enodes) { // mark colored equations to be differentiated if (ii->isColored() && ii->derivative() == nullptr) { marked.insert(ii); // uncolor equations ii->uncolor(); } } pathFound = augmentPath_->augmentPath(*i); if (!pathFound) { throw CGException("Singular system detected."); } for (auto* jj: vnodes) jj->uncolor(); } else { for (auto* ii: enodes) ii->uncolor(); } } if (marked.empty()) break; // diff all MARKED equations for (Enode<Base>* i: marked) { graph_.createDerivate(*i, false); } if (this->verbosity_ >= Verbosity::High) graph_.printDot(this->log()); lastMarked.swap(marked); marked.clear(); } lastAddEq_.clear(); for (const Enode<Base>* i: lastMarked) { lastAddEq_.insert(i->derivative()); } } }; } // END cg namespace } // END CppAD namespace #endif
31.622951
110
0.565837
[ "vector", "model" ]
e529ce046b54f83888bef14a77499e52f5f1001b
703
cpp
C++
ODE/src/rk.cpp
milindasf/Dendro-GR
1bc3104fb546267d9fb32c05595a564cb2a57338
[ "MIT" ]
27
2018-06-19T14:45:43.000Z
2022-02-18T22:04:51.000Z
ODE/src/rk.cpp
milindasf/Dendro-GR
1bc3104fb546267d9fb32c05595a564cb2a57338
[ "MIT" ]
1
2019-11-06T22:17:32.000Z
2019-11-07T20:23:44.000Z
ODE/src/rk.cpp
milindasf/Dendro-GR
1bc3104fb546267d9fb32c05595a564cb2a57338
[ "MIT" ]
10
2018-06-19T22:01:09.000Z
2021-10-03T07:02:07.000Z
// // Created by milinda on 5/25/17. /** *@author Milinda Fernando *School of Computing, University of Utah *@brief */ // #include "rk.h" namespace ode { namespace solver { RK::RK(ot::Mesh *pMesh, double pTBegin, double pTEnd,double pTh) { m_uiMesh=pMesh; m_uiComm=m_uiMesh->getMPIGlobalCommunicator(); m_uiOrder=pMesh->getElementOrder(); m_uiTimeBegin=pTBegin; m_uiTimeEnd=pTEnd; m_uiT_h=pTh; m_uiT_h_prev=m_uiT_h; m_uiCurrentStep=0; m_uiCurrentTime=m_uiTimeBegin; m_uiNrp=m_uiOrder+1; } RK::~RK() { } } }
14.645833
72
0.539118
[ "mesh" ]
e52a118319042a18746c554029848e3a7e6ecdff
23,051
hpp
C++
include/UnityEngine/UI/RectMask2D.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/UnityEngine/UI/RectMask2D.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/UnityEngine/UI/RectMask2D.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: UnityEngine.EventSystems.UIBehaviour #include "UnityEngine/EventSystems/UIBehaviour.hpp" // Including type: UnityEngine.UI.IClipper #include "UnityEngine/UI/IClipper.hpp" // Including type: UnityEngine.ICanvasRaycastFilter #include "UnityEngine/ICanvasRaycastFilter.hpp" // Including type: UnityEngine.Rect #include "UnityEngine/Rect.hpp" // Including type: UnityEngine.Vector4 #include "UnityEngine/Vector4.hpp" // Including type: UnityEngine.Vector2Int #include "UnityEngine/Vector2Int.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine::UI namespace UnityEngine::UI { // Forward declaring type: RectangularVertexClipper class RectangularVertexClipper; // Forward declaring type: MaskableGraphic class MaskableGraphic; // Forward declaring type: IClippable class IClippable; } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: RectTransform class RectTransform; // Forward declaring type: Canvas class Canvas; // Skipping declaration: Vector2 because it is already included! // Forward declaring type: Camera class Camera; } // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: HashSet`1<T> template<typename T> class HashSet_1; // Forward declaring type: List`1<T> template<typename T> class List_1; } // Completed forward declares // Type namespace: UnityEngine.UI namespace UnityEngine::UI { // Size: 0x88 #pragma pack(push, 1) // Autogenerated type: UnityEngine.UI.RectMask2D // [TokenAttribute] Offset: FFFFFFFF // [AddComponentMenu] Offset: DEADE4 // [ExecuteAlways] Offset: FFFFFFFF // [DisallowMultipleComponent] Offset: FFFFFFFF // [RequireComponent] Offset: DEADE4 class RectMask2D : public UnityEngine::EventSystems::UIBehaviour/*, public UnityEngine::UI::IClipper, public UnityEngine::ICanvasRaycastFilter*/ { public: // private readonly UnityEngine.UI.RectangularVertexClipper m_VertexClipper // Size: 0x8 // Offset: 0x18 UnityEngine::UI::RectangularVertexClipper* m_VertexClipper; // Field size check static_assert(sizeof(UnityEngine::UI::RectangularVertexClipper*) == 0x8); // private UnityEngine.RectTransform m_RectTransform // Size: 0x8 // Offset: 0x20 UnityEngine::RectTransform* m_RectTransform; // Field size check static_assert(sizeof(UnityEngine::RectTransform*) == 0x8); // private System.Collections.Generic.HashSet`1<UnityEngine.UI.MaskableGraphic> m_MaskableTargets // Size: 0x8 // Offset: 0x28 System::Collections::Generic::HashSet_1<UnityEngine::UI::MaskableGraphic*>* m_MaskableTargets; // Field size check static_assert(sizeof(System::Collections::Generic::HashSet_1<UnityEngine::UI::MaskableGraphic*>*) == 0x8); // private System.Collections.Generic.HashSet`1<UnityEngine.UI.IClippable> m_ClipTargets // Size: 0x8 // Offset: 0x30 System::Collections::Generic::HashSet_1<UnityEngine::UI::IClippable*>* m_ClipTargets; // Field size check static_assert(sizeof(System::Collections::Generic::HashSet_1<UnityEngine::UI::IClippable*>*) == 0x8); // private System.Boolean m_ShouldRecalculateClipRects // Size: 0x1 // Offset: 0x38 bool m_ShouldRecalculateClipRects; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: m_ShouldRecalculateClipRects and: m_Clippers char __padding4[0x7] = {}; // private System.Collections.Generic.List`1<UnityEngine.UI.RectMask2D> m_Clippers // Size: 0x8 // Offset: 0x40 System::Collections::Generic::List_1<UnityEngine::UI::RectMask2D*>* m_Clippers; // Field size check static_assert(sizeof(System::Collections::Generic::List_1<UnityEngine::UI::RectMask2D*>*) == 0x8); // private UnityEngine.Rect m_LastClipRectCanvasSpace // Size: 0x10 // Offset: 0x48 UnityEngine::Rect m_LastClipRectCanvasSpace; // Field size check static_assert(sizeof(UnityEngine::Rect) == 0x10); // private System.Boolean m_ForceClip // Size: 0x1 // Offset: 0x58 bool m_ForceClip; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: m_ForceClip and: m_Padding char __padding7[0x3] = {}; // private UnityEngine.Vector4 m_Padding // Size: 0x10 // Offset: 0x5C UnityEngine::Vector4 m_Padding; // Field size check static_assert(sizeof(UnityEngine::Vector4) == 0x10); // private UnityEngine.Vector2Int m_Softness // Size: 0x8 // Offset: 0x6C UnityEngine::Vector2Int m_Softness; // Field size check static_assert(sizeof(UnityEngine::Vector2Int) == 0x8); // Padding between fields: m_Softness and: m_Canvas char __padding9[0x4] = {}; // private UnityEngine.Canvas m_Canvas // Size: 0x8 // Offset: 0x78 UnityEngine::Canvas* m_Canvas; // Field size check static_assert(sizeof(UnityEngine::Canvas*) == 0x8); // private UnityEngine.Vector3[] m_Corners // Size: 0x8 // Offset: 0x80 ::Array<UnityEngine::Vector3>* m_Corners; // Field size check static_assert(sizeof(::Array<UnityEngine::Vector3>*) == 0x8); // Creating value type constructor for type: RectMask2D RectMask2D(UnityEngine::UI::RectangularVertexClipper* m_VertexClipper_ = {}, UnityEngine::RectTransform* m_RectTransform_ = {}, System::Collections::Generic::HashSet_1<UnityEngine::UI::MaskableGraphic*>* m_MaskableTargets_ = {}, System::Collections::Generic::HashSet_1<UnityEngine::UI::IClippable*>* m_ClipTargets_ = {}, bool m_ShouldRecalculateClipRects_ = {}, System::Collections::Generic::List_1<UnityEngine::UI::RectMask2D*>* m_Clippers_ = {}, UnityEngine::Rect m_LastClipRectCanvasSpace_ = {}, bool m_ForceClip_ = {}, UnityEngine::Vector4 m_Padding_ = {}, UnityEngine::Vector2Int m_Softness_ = {}, UnityEngine::Canvas* m_Canvas_ = {}, ::Array<UnityEngine::Vector3>* m_Corners_ = {}) noexcept : m_VertexClipper{m_VertexClipper_}, m_RectTransform{m_RectTransform_}, m_MaskableTargets{m_MaskableTargets_}, m_ClipTargets{m_ClipTargets_}, m_ShouldRecalculateClipRects{m_ShouldRecalculateClipRects_}, m_Clippers{m_Clippers_}, m_LastClipRectCanvasSpace{m_LastClipRectCanvasSpace_}, m_ForceClip{m_ForceClip_}, m_Padding{m_Padding_}, m_Softness{m_Softness_}, m_Canvas{m_Canvas_}, m_Corners{m_Corners_} {} // Creating interface conversion operator: operator UnityEngine::UI::IClipper operator UnityEngine::UI::IClipper() noexcept { return *reinterpret_cast<UnityEngine::UI::IClipper*>(this); } // Creating interface conversion operator: operator UnityEngine::ICanvasRaycastFilter operator UnityEngine::ICanvasRaycastFilter() noexcept { return *reinterpret_cast<UnityEngine::ICanvasRaycastFilter*>(this); } // Deleting conversion operator: operator System::IntPtr constexpr operator System::IntPtr() const noexcept = delete; // Get instance field reference: private readonly UnityEngine.UI.RectangularVertexClipper m_VertexClipper UnityEngine::UI::RectangularVertexClipper*& dyn_m_VertexClipper(); // Get instance field reference: private UnityEngine.RectTransform m_RectTransform UnityEngine::RectTransform*& dyn_m_RectTransform(); // Get instance field reference: private System.Collections.Generic.HashSet`1<UnityEngine.UI.MaskableGraphic> m_MaskableTargets System::Collections::Generic::HashSet_1<UnityEngine::UI::MaskableGraphic*>*& dyn_m_MaskableTargets(); // Get instance field reference: private System.Collections.Generic.HashSet`1<UnityEngine.UI.IClippable> m_ClipTargets System::Collections::Generic::HashSet_1<UnityEngine::UI::IClippable*>*& dyn_m_ClipTargets(); // Get instance field reference: private System.Boolean m_ShouldRecalculateClipRects bool& dyn_m_ShouldRecalculateClipRects(); // Get instance field reference: private System.Collections.Generic.List`1<UnityEngine.UI.RectMask2D> m_Clippers System::Collections::Generic::List_1<UnityEngine::UI::RectMask2D*>*& dyn_m_Clippers(); // Get instance field reference: private UnityEngine.Rect m_LastClipRectCanvasSpace UnityEngine::Rect& dyn_m_LastClipRectCanvasSpace(); // Get instance field reference: private System.Boolean m_ForceClip bool& dyn_m_ForceClip(); // Get instance field reference: private UnityEngine.Vector4 m_Padding UnityEngine::Vector4& dyn_m_Padding(); // Get instance field reference: private UnityEngine.Vector2Int m_Softness UnityEngine::Vector2Int& dyn_m_Softness(); // Get instance field reference: private UnityEngine.Canvas m_Canvas UnityEngine::Canvas*& dyn_m_Canvas(); // Get instance field reference: private UnityEngine.Vector3[] m_Corners ::Array<UnityEngine::Vector3>*& dyn_m_Corners(); // public UnityEngine.Vector4 get_padding() // Offset: 0x19DAB98 UnityEngine::Vector4 get_padding(); // public System.Void set_padding(UnityEngine.Vector4 value) // Offset: 0x19DABA4 void set_padding(UnityEngine::Vector4 value); // public UnityEngine.Vector2Int get_softness() // Offset: 0x19DABB0 UnityEngine::Vector2Int get_softness(); // public System.Void set_softness(UnityEngine.Vector2Int value) // Offset: 0x19DABB8 void set_softness(UnityEngine::Vector2Int value); // private UnityEngine.Canvas get_Canvas() // Offset: 0x19DAC90 UnityEngine::Canvas* get_Canvas(); // public UnityEngine.Rect get_canvasRect() // Offset: 0x19DADC8 UnityEngine::Rect get_canvasRect(); // public UnityEngine.RectTransform get_rectTransform() // Offset: 0x19DAE14 UnityEngine::RectTransform* get_rectTransform(); // private UnityEngine.Rect get_rootCanvasRect() // Offset: 0x19DB33C UnityEngine::Rect get_rootCanvasRect(); // public System.Boolean IsRaycastLocationValid(UnityEngine.Vector2 sp, UnityEngine.Camera eventCamera) // Offset: 0x19DB244 bool IsRaycastLocationValid(UnityEngine::Vector2 sp, UnityEngine::Camera* eventCamera); // public System.Void PerformClipping() // Offset: 0x19DB470 void PerformClipping(); // public System.Void UpdateClipSoftness() // Offset: 0x19DBBB0 void UpdateClipSoftness(); // public System.Void AddClippable(UnityEngine.UI.IClippable clippable) // Offset: 0x19D944C void AddClippable(UnityEngine::UI::IClippable* clippable); // public System.Void RemoveClippable(UnityEngine.UI.IClippable clippable) // Offset: 0x19D92C4 void RemoveClippable(UnityEngine::UI::IClippable* clippable); // protected System.Void .ctor() // Offset: 0x19DAFFC // Implemented from: UnityEngine.EventSystems.UIBehaviour // Base method: System.Void UIBehaviour::.ctor() // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static RectMask2D* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::UI::RectMask2D::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<RectMask2D*, creationType>())); } // protected override System.Void OnEnable() // Offset: 0x19DB160 // Implemented from: UnityEngine.EventSystems.UIBehaviour // Base method: System.Void UIBehaviour::OnEnable() void OnEnable(); // protected override System.Void OnDisable() // Offset: 0x19DB19C // Implemented from: UnityEngine.EventSystems.UIBehaviour // Base method: System.Void UIBehaviour::OnDisable() void OnDisable(); // protected override System.Void OnTransformParentChanged() // Offset: 0x19DBE64 // Implemented from: UnityEngine.EventSystems.UIBehaviour // Base method: System.Void UIBehaviour::OnTransformParentChanged() void OnTransformParentChanged(); // protected override System.Void OnCanvasHierarchyChanged() // Offset: 0x19DBE90 // Implemented from: UnityEngine.EventSystems.UIBehaviour // Base method: System.Void UIBehaviour::OnCanvasHierarchyChanged() void OnCanvasHierarchyChanged(); }; // UnityEngine.UI.RectMask2D #pragma pack(pop) static check_size<sizeof(RectMask2D), 128 + sizeof(::Array<UnityEngine::Vector3>*)> __UnityEngine_UI_RectMask2DSizeCheck; static_assert(sizeof(RectMask2D) == 0x88); } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::UI::RectMask2D*, "UnityEngine.UI", "RectMask2D"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: UnityEngine::UI::RectMask2D::get_padding // Il2CppName: get_padding template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::Vector4 (UnityEngine::UI::RectMask2D::*)()>(&UnityEngine::UI::RectMask2D::get_padding)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::RectMask2D*), "get_padding", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::RectMask2D::set_padding // Il2CppName: set_padding template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::RectMask2D::*)(UnityEngine::Vector4)>(&UnityEngine::UI::RectMask2D::set_padding)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector4")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::RectMask2D*), "set_padding", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: UnityEngine::UI::RectMask2D::get_softness // Il2CppName: get_softness template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::Vector2Int (UnityEngine::UI::RectMask2D::*)()>(&UnityEngine::UI::RectMask2D::get_softness)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::RectMask2D*), "get_softness", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::RectMask2D::set_softness // Il2CppName: set_softness template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::RectMask2D::*)(UnityEngine::Vector2Int)>(&UnityEngine::UI::RectMask2D::set_softness)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector2Int")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::RectMask2D*), "set_softness", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: UnityEngine::UI::RectMask2D::get_Canvas // Il2CppName: get_Canvas template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::Canvas* (UnityEngine::UI::RectMask2D::*)()>(&UnityEngine::UI::RectMask2D::get_Canvas)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::RectMask2D*), "get_Canvas", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::RectMask2D::get_canvasRect // Il2CppName: get_canvasRect template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::Rect (UnityEngine::UI::RectMask2D::*)()>(&UnityEngine::UI::RectMask2D::get_canvasRect)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::RectMask2D*), "get_canvasRect", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::RectMask2D::get_rectTransform // Il2CppName: get_rectTransform template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::RectTransform* (UnityEngine::UI::RectMask2D::*)()>(&UnityEngine::UI::RectMask2D::get_rectTransform)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::RectMask2D*), "get_rectTransform", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::RectMask2D::get_rootCanvasRect // Il2CppName: get_rootCanvasRect template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::Rect (UnityEngine::UI::RectMask2D::*)()>(&UnityEngine::UI::RectMask2D::get_rootCanvasRect)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::RectMask2D*), "get_rootCanvasRect", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::RectMask2D::IsRaycastLocationValid // Il2CppName: IsRaycastLocationValid template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::UI::RectMask2D::*)(UnityEngine::Vector2, UnityEngine::Camera*)>(&UnityEngine::UI::RectMask2D::IsRaycastLocationValid)> { static const MethodInfo* get() { static auto* sp = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector2")->byval_arg; static auto* eventCamera = &::il2cpp_utils::GetClassFromName("UnityEngine", "Camera")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::RectMask2D*), "IsRaycastLocationValid", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{sp, eventCamera}); } }; // Writing MetadataGetter for method: UnityEngine::UI::RectMask2D::PerformClipping // Il2CppName: PerformClipping template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::RectMask2D::*)()>(&UnityEngine::UI::RectMask2D::PerformClipping)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::RectMask2D*), "PerformClipping", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::RectMask2D::UpdateClipSoftness // Il2CppName: UpdateClipSoftness template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::RectMask2D::*)()>(&UnityEngine::UI::RectMask2D::UpdateClipSoftness)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::RectMask2D*), "UpdateClipSoftness", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::RectMask2D::AddClippable // Il2CppName: AddClippable template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::RectMask2D::*)(UnityEngine::UI::IClippable*)>(&UnityEngine::UI::RectMask2D::AddClippable)> { static const MethodInfo* get() { static auto* clippable = &::il2cpp_utils::GetClassFromName("UnityEngine.UI", "IClippable")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::RectMask2D*), "AddClippable", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{clippable}); } }; // Writing MetadataGetter for method: UnityEngine::UI::RectMask2D::RemoveClippable // Il2CppName: RemoveClippable template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::RectMask2D::*)(UnityEngine::UI::IClippable*)>(&UnityEngine::UI::RectMask2D::RemoveClippable)> { static const MethodInfo* get() { static auto* clippable = &::il2cpp_utils::GetClassFromName("UnityEngine.UI", "IClippable")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::RectMask2D*), "RemoveClippable", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{clippable}); } }; // Writing MetadataGetter for method: UnityEngine::UI::RectMask2D::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: UnityEngine::UI::RectMask2D::OnEnable // Il2CppName: OnEnable template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::RectMask2D::*)()>(&UnityEngine::UI::RectMask2D::OnEnable)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::RectMask2D*), "OnEnable", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::RectMask2D::OnDisable // Il2CppName: OnDisable template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::RectMask2D::*)()>(&UnityEngine::UI::RectMask2D::OnDisable)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::RectMask2D*), "OnDisable", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::RectMask2D::OnTransformParentChanged // Il2CppName: OnTransformParentChanged template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::RectMask2D::*)()>(&UnityEngine::UI::RectMask2D::OnTransformParentChanged)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::RectMask2D*), "OnTransformParentChanged", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::RectMask2D::OnCanvasHierarchyChanged // Il2CppName: OnCanvasHierarchyChanged template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::UI::RectMask2D::*)()>(&UnityEngine::UI::RectMask2D::OnCanvasHierarchyChanged)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::RectMask2D*), "OnCanvasHierarchyChanged", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
56.636364
1,105
0.732463
[ "object", "vector" ]
e5399aefc866188fbdff47821e30ab6369a0124d
3,865
cpp
C++
Project/Dev_class11_handout/Motor2D/Particle_Firework.cpp
Guille1406/Project-II
af954426efce06937671f02ac0a5840e5faefb0e
[ "Apache-2.0" ]
null
null
null
Project/Dev_class11_handout/Motor2D/Particle_Firework.cpp
Guille1406/Project-II
af954426efce06937671f02ac0a5840e5faefb0e
[ "Apache-2.0" ]
null
null
null
Project/Dev_class11_handout/Motor2D/Particle_Firework.cpp
Guille1406/Project-II
af954426efce06937671f02ac0a5840e5faefb0e
[ "Apache-2.0" ]
null
null
null
#include "Particle_Firework.h" #include "Particle.h" /* P_Firework::P_Firework(SceneElement* element, iPoint* object, iPoint position_static, SDL_Rect initial_rect, iPoint timelife_, fPoint speed_particle, Part_Direction p_direction, int num_particles, int num_textures, iPoint next_textture_, iPoint last_textures_) { if (element != nullptr) { pos.x = element->position.x; pos.y = element->position.y; arrow_to_follow = element; object = nullptr; } else if (object != nullptr) { pos.x = object->x; pos.y = object->y; object_follow = object; arrow_to_follow = nullptr; } else { pos.x = position_static.x; pos.y = position_static.y; object_follow = nullptr; arrow_to_follow = nullptr; } speed = speed_particle; i_rect = initial_rect; next_textures = next_textture_; last_textures = last_textures_; // timelife = timelife_; number_particles = num_particles; number_multifirework = num_particles; godelete = false; n_textures = num_textures; size_rect = initial_rect.w; for (int i = 0; i < 1; i++)// { Particle* temp = new Particle(pos, iPoint(0, 0), timelife, speed, p_direction, initial_rect, size_rect, n_textures, true); particle.push_back(temp); } } P_Firework::~P_Firework() { } bool P_Firework::Update(float dt) { MoveParticles(); return true; } bool P_Firework::PostUpdate() { if (particle.size() == 1) { render(particle[0]->GetPosition()); } else { render(pos); } return true; } void P_Firework::render(fPoint pos) { if (particle.size() == 1) { if (particle[0]->isDead()) { timelife.y += 1; for (int i = 1; i < number_particles; i++) { speed.x = 100; speed.y = 100; Particle* temp = new Particle(pos, iPoint(0, 0), timelife, speed, Part_Direction::Part_Direc_RANDOM_FIREWORK, i_rect, size_rect, n_textures, true, Wind::Part_Wind_NULL, next_textures); particle.push_back(temp); } timelife.y -= 1; } } else { for (int i = 1; i < number_particles; i++) { if (particle[i]->isDead() && particle[i]->GetRepeat()) { particle[i]->SetRepeat(false); for (int k = 0; k < MULITFIREWORK; k++) { speed.x = 100; speed.y = 100; Particle* temp = new Particle(particle[i]->GetPosition(), iPoint(0, 0), timelife, speed, Part_Direction::Part_Direc_RANDOM_FIREWORK, i_rect, size_rect, n_textures, true, Wind::Part_Wind_NULL, last_textures); particle.push_back(temp); number_multifirework++; } } } } if (particle.size() == 1) { //Draw particles for (int i = 0; i < 1; i++) { particle[i]->render(); } } else if (particle.size() == number_particles) { //Draw particles for (int i = 0; i < number_particles; i++) { particle[i]->render(); } } else // number_multifirework; { //Draw particles for (int i = 0; i < number_multifirework; i++) { particle[i]->render(); } } } void P_Firework::MoveParticles() { if (particle.size() == 1) { for (int i = 0; i < 1; i++) { particle[i]->SetSpeedGreavity(fPoint(0, 5)); } for (int i = 0; i < 1; i++) { float temp = App->GetDT(); particle[i]->Move(fPoint(particle[i]->GetSpeed().x * temp, particle[i]->GetSpeed().y * temp)); } } else if (particle.size() == number_particles) { for (int i = 1; i < number_particles; i++) { particle[i]->SetSpeedGreavity(fPoint(0, 5)); } for (int i = 1; i < number_particles; i++) { float temp = App->GetDT(); particle[i]->Move(fPoint(particle[i]->GetSpeed().x * temp, particle[i]->GetSpeed().y * temp)); } } else { for (int i = number_particles; i < number_multifirework; i++) { particle[i]->SetSpeedGreavity(fPoint(0, 5)); } for (int i = number_particles; i < number_multifirework; i++) { float temp = App->GetDT(); particle[i]->Move(fPoint(particle[i]->GetSpeed().x * temp, particle[i]->GetSpeed().y * temp)); } } } */
21.236264
260
0.638292
[ "render", "object" ]
e53fa83699c8700950267759041e2cb21e683cde
7,376
cpp
C++
camera/SensorListener.cpp
TaichiN/android_device_amazon_omap4-common
686cfa27699b5eedccccbd8c3b76decc21287bea
[ "FTL" ]
2
2015-02-16T19:40:17.000Z
2015-02-17T15:42:35.000Z
ti/omap4-aah/camera/SensorListener.cpp
Keneral/ahardware
9a8a025f7c9471444c9e271bbe7f48182741d710
[ "Unlicense" ]
null
null
null
ti/omap4-aah/camera/SensorListener.cpp
Keneral/ahardware
9a8a025f7c9471444c9e271bbe7f48182741d710
[ "Unlicense" ]
1
2018-02-24T19:09:04.000Z
2018-02-24T19:09:04.000Z
/* * Copyright (C) Texas Instruments - http://www.ti.com/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file SensorListener.cpp * * This file listens and propogates sensor events to CameraHal. * */ #include "SensorListener.h" #include <stdint.h> #include <math.h> #include <sys/types.h> namespace Ti { namespace Camera { /*** static declarations ***/ static const float RADIANS_2_DEG = (float) (180 / M_PI); // measured values on device...might need tuning static const int DEGREES_90_THRESH = 50; static const int DEGREES_180_THRESH = 170; static const int DEGREES_270_THRESH = 250; static int sensor_events_listener(int fd, int events, void* data) { SensorListener* listener = (SensorListener*) data; ssize_t num_sensors; ASensorEvent sen_events[8]; while ((num_sensors = listener->mSensorEventQueue->read(sen_events, 8)) > 0) { for (int i = 0; i < num_sensors; i++) { if (sen_events[i].type == android::Sensor::TYPE_ACCELEROMETER) { float x = sen_events[i].vector.azimuth; float y = sen_events[i].vector.pitch; float z = sen_events[i].vector.roll; float radius = 0; int tilt = 0, orient = 0; CAMHAL_LOGVA("ACCELEROMETER EVENT"); CAMHAL_LOGVB(" azimuth = %f pitch = %f roll = %f", sen_events[i].vector.azimuth, sen_events[i].vector.pitch, sen_events[i].vector.roll); // see http://en.wikipedia.org/wiki/Spherical_coordinate_system#Cartesian_coordinates // about conversion from cartesian to spherical for orientation calculations radius = (float) sqrt(x * x + y * y + z * z); tilt = (int) asinf(z / radius) * RADIANS_2_DEG; orient = (int) atan2f(-x, y) * RADIANS_2_DEG; if (orient < 0) { orient += 360; } if (orient >= DEGREES_270_THRESH) { orient = 270; } else if (orient >= DEGREES_180_THRESH) { orient = 180; } else if (orient >= DEGREES_90_THRESH) { orient = 90; } else { orient = 0; } listener->handleOrientation(orient, tilt); CAMHAL_LOGVB(" tilt = %d orientation = %d", tilt, orient); } else if (sen_events[i].type == android::Sensor::TYPE_GYROSCOPE) { CAMHAL_LOGVA("GYROSCOPE EVENT"); } } } if (num_sensors < 0 && num_sensors != -EAGAIN) { CAMHAL_LOGEB("reading events failed: %s", strerror(-num_sensors)); } return 1; } /****** public - member functions ******/ SensorListener::SensorListener() { LOG_FUNCTION_NAME; sensorsEnabled = 0; mOrientationCb = NULL; mSensorEventQueue = NULL; mSensorLooperThread = NULL; LOG_FUNCTION_NAME_EXIT; } SensorListener::~SensorListener() { LOG_FUNCTION_NAME; CAMHAL_LOGDA("Kill looper thread"); if (mSensorLooperThread.get()) { // 1. Request exit // 2. Wake up looper which should be polling for an event // 3. Wait for exit mSensorLooperThread->requestExit(); mSensorLooperThread->wake(); mSensorLooperThread->join(); mSensorLooperThread.clear(); mSensorLooperThread = NULL; } CAMHAL_LOGDA("Kill looper"); if (mLooper.get()) { mLooper->removeFd(mSensorEventQueue->getFd()); mLooper.clear(); mLooper = NULL; } CAMHAL_LOGDA("SensorListener destroyed"); LOG_FUNCTION_NAME_EXIT; } status_t SensorListener::initialize() { status_t ret = NO_ERROR; android::SensorManager& mgr(android::SensorManager::getInstance()); LOG_FUNCTION_NAME; android::sp<android::Looper> mLooper; mSensorEventQueue = mgr.createEventQueue(); if (mSensorEventQueue == NULL) { CAMHAL_LOGEA("createEventQueue returned NULL"); ret = NO_INIT; goto out; } mLooper = new android::Looper(false); mLooper->addFd(mSensorEventQueue->getFd(), 0, ALOOPER_EVENT_INPUT, sensor_events_listener, this); if (mSensorLooperThread.get() == NULL) mSensorLooperThread = new SensorLooperThread(mLooper.get()); if (mSensorLooperThread.get() == NULL) { CAMHAL_LOGEA("Couldn't create sensor looper thread"); ret = NO_MEMORY; goto out; } ret = mSensorLooperThread->run("sensor looper thread", android::PRIORITY_URGENT_DISPLAY); if (ret == INVALID_OPERATION){ CAMHAL_LOGDA("thread already running ?!?"); } else if (ret != NO_ERROR) { CAMHAL_LOGEA("couldn't run thread"); goto out; } out: LOG_FUNCTION_NAME_EXIT; return ret; } void SensorListener::setCallbacks(orientation_callback_t orientation_cb, void *cookie) { LOG_FUNCTION_NAME; if (orientation_cb) { mOrientationCb = orientation_cb; } mCbCookie = cookie; LOG_FUNCTION_NAME_EXIT; } void SensorListener::handleOrientation(uint32_t orientation, uint32_t tilt) { LOG_FUNCTION_NAME; android::AutoMutex lock(&mLock); if (mOrientationCb && (sensorsEnabled & SENSOR_ORIENTATION)) { mOrientationCb(orientation, tilt, mCbCookie); } LOG_FUNCTION_NAME_EXIT; } void SensorListener::enableSensor(sensor_type_t type) { android::Sensor const* sensor; android::SensorManager& mgr(android::SensorManager::getInstance()); LOG_FUNCTION_NAME; android::AutoMutex lock(&mLock); if ((type & SENSOR_ORIENTATION) && !(sensorsEnabled & SENSOR_ORIENTATION)) { sensor = mgr.getDefaultSensor(android::Sensor::TYPE_ACCELEROMETER); if(sensor) { CAMHAL_LOGDB("orientation = %p (%s)", sensor, sensor->getName().string()); mSensorEventQueue->enableSensor(sensor); mSensorEventQueue->setEventRate(sensor, ms2ns(100)); sensorsEnabled |= SENSOR_ORIENTATION; } else { CAMHAL_LOGDB("not enabling absent orientation sensor"); } } LOG_FUNCTION_NAME_EXIT; } void SensorListener::disableSensor(sensor_type_t type) { android::Sensor const* sensor; android::SensorManager& mgr(android::SensorManager::getInstance()); LOG_FUNCTION_NAME; android::AutoMutex lock(&mLock); if ((type & SENSOR_ORIENTATION) && (sensorsEnabled & SENSOR_ORIENTATION)) { sensor = mgr.getDefaultSensor(android::Sensor::TYPE_ACCELEROMETER); CAMHAL_LOGDB("orientation = %p (%s)", sensor, sensor->getName().string()); mSensorEventQueue->disableSensor(sensor); sensorsEnabled &= ~SENSOR_ORIENTATION; } LOG_FUNCTION_NAME_EXIT; } } // namespace Camera } // namespace Ti
31.122363
101
0.627305
[ "vector" ]
e540ecc3aae57012bd62a145e5c9d00595b12763
2,070
cpp
C++
src/Prostopadloscian.cpp
lukasz-pawlos/Dron
27d0a0d5c30e7dd0bb3d74dd8bdf940bca96d430
[ "MIT" ]
null
null
null
src/Prostopadloscian.cpp
lukasz-pawlos/Dron
27d0a0d5c30e7dd0bb3d74dd8bdf940bca96d430
[ "MIT" ]
null
null
null
src/Prostopadloscian.cpp
lukasz-pawlos/Dron
27d0a0d5c30e7dd0bb3d74dd8bdf940bca96d430
[ "MIT" ]
null
null
null
#include "Prostopadloscian.hh" Prostopadloscian::Prostopadloscian() {} Prostopadloscian::Prostopadloscian(double bok_A, double bok_B, double bok_C){ if (bok_A < 0){ cout << "Bok nie moze byc liczba ujemna" << endl; exit(1); } if (bok_B < 0){ cout << "Bok nie moze byc liczba ujemna" << endl; exit(1); } if (bok_C < 0){ cout << "Bok nie moze byc liczba ujemna" << endl; exit(1); } A = bok_A; B = bok_B; C = bok_C; } void Prostopadloscian::Orient_wektor(SWektor<double,3> &W)const { W= Orientacja * W; } void Prostopadloscian::Wspolrzedne(SWektor<double,3> *wsp)const { SWektor<double,3> przesX(A,0,0); SWektor<double,3> przesY(0,B,0); SWektor<double,3> przesZ(0,0,C); (*this).Orient_wektor(przesX); (*this).Orient_wektor(przesY); (*this).Orient_wektor(przesZ); wsp[0] = Srodek + przesX + przesY + przesZ; wsp[1] = Srodek + przesX - przesY + przesZ; wsp[2] = Srodek - przesX - przesY + przesZ; wsp[3] = Srodek - przesX + przesY + przesZ; wsp[4] = Srodek + przesX + przesY - przesZ; wsp[5] = Srodek + przesX - przesY - przesZ; wsp[6] = Srodek - przesX - przesY - przesZ; wsp[7] = Srodek - przesX + przesY - przesZ; } void Prostopadloscian::ustaw_pozycje(const SWektor<double,3> &Wektor) { Srodek = Wektor; } void Prostopadloscian::ustaw_orientacje(const MacierzOb &Macierz) { Orientacja = Macierz; } void Prostopadloscian::ustaw_srodek(double X, double Y, double Z){ Srodek[0] = X; Srodek[1] = Y; Srodek[2] = Z; } void Prostopadloscian::Rysuj() { SWektor<double,3> tab[8]; (*this).Wspolrzedne(tab); if (ID != -1) api->erase_shape(ID); ID = api ->draw_polyhedron(vector<vector<Point3D> > {{ drawNS::Point3D(tab[0][0],tab[0][1],tab[0][2]),drawNS::Point3D(tab[1][0],tab[1][1],tab[1][2]),drawNS::Point3D(tab[2][0],tab[2][1],tab[2][2]),drawNS::Point3D(tab[3][0],tab[3][1],tab[3][2]) },{ drawNS::Point3D(tab[4][0],tab[4][1],tab[4][2]),drawNS::Point3D(tab[5][0],tab[5][1],tab[5][2]),drawNS::Point3D(tab[6][0],tab[6][1],tab[6][2]),drawNS::Point3D(tab[7][0],tab[7][1],tab[7][2]) } }, "red"); }
19.528302
191
0.641063
[ "vector" ]
e54343b9adb181df7e96b2fd60a2a5e757980eb9
11,314
hxx
C++
Modules/Applications/AppClassification/include/otbTrainSVM.hxx
kikislater/OTB
8271c62b5891d3da9cb2e9ba3a2706a26de8c323
[ "Apache-2.0" ]
1
2019-09-12T00:53:05.000Z
2019-09-12T00:53:05.000Z
Modules/Applications/AppClassification/include/otbTrainSVM.hxx
ThomasWangWeiHong/OTB
569686e40f0ae146e726bd3cfd253e67ec2b4533
[ "Apache-2.0" ]
null
null
null
Modules/Applications/AppClassification/include/otbTrainSVM.hxx
ThomasWangWeiHong/OTB
569686e40f0ae146e726bd3cfd253e67ec2b4533
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef otbTrainSVM_hxx #define otbTrainSVM_hxx #include "otbLearningApplicationBase.h" #include "otbSVMMachineLearningModel.h" namespace otb { namespace Wrapper { template <class TInputValue, class TOutputValue> void LearningApplicationBase<TInputValue,TOutputValue> ::InitSVMParams() { AddChoice("classifier.svm", "SVM classifier (OpenCV)"); SetParameterDescription("classifier.svm", "http://docs.opencv.org/modules/ml/doc/support_vector_machines.html"); AddParameter(ParameterType_Choice, "classifier.svm.m", "SVM Model Type"); SetParameterDescription("classifier.svm.m", "Type of SVM formulation."); if (this->m_RegressionFlag) { AddChoice("classifier.svm.m.epssvr", "Epsilon Support Vector Regression"); AddChoice("classifier.svm.m.nusvr", "Nu Support Vector Regression"); SetParameterString("classifier.svm.m", "epssvr"); } else { AddChoice("classifier.svm.m.csvc", "C support vector classification"); AddChoice("classifier.svm.m.nusvc", "Nu support vector classification"); AddChoice("classifier.svm.m.oneclass", "Distribution estimation (One Class SVM)"); SetParameterString("classifier.svm.m", "csvc"); } AddParameter(ParameterType_Choice, "classifier.svm.k", "SVM Kernel Type"); AddChoice("classifier.svm.k.linear", "Linear"); AddChoice("classifier.svm.k.rbf", "Gaussian radial basis function"); AddChoice("classifier.svm.k.poly", "Polynomial"); AddChoice("classifier.svm.k.sigmoid", "Sigmoid"); SetParameterString("classifier.svm.k", "linear"); SetParameterDescription("classifier.svm.k", "SVM Kernel Type."); AddParameter(ParameterType_Float, "classifier.svm.c", "Cost parameter C"); SetParameterFloat("classifier.svm.c",1.0); SetParameterDescription("classifier.svm.c", "SVM models have a cost parameter C (1 by default) to control the trade-off" " between training errors and forcing rigid margins."); AddParameter(ParameterType_Float, "classifier.svm.nu", "Parameter nu of a SVM optimization problem (NU_SVC / ONE_CLASS)"); SetParameterFloat("classifier.svm.nu",0.0); SetParameterDescription("classifier.svm.nu", "Parameter nu of a SVM optimization problem."); if (this->m_RegressionFlag) { AddParameter(ParameterType_Float, "classifier.svm.p", "Parameter epsilon of a SVM optimization problem (EPS_SVR)"); SetParameterFloat("classifier.svm.p",1.0); SetParameterDescription("classifier.svm.p", "Parameter epsilon of a SVM optimization problem (EPS_SVR)."); AddParameter(ParameterType_Choice, "classifier.svm.term", "Termination criteria"); SetParameterDescription("classifier.svm.term", "Termination criteria for iterative algorithm"); AddChoice("classifier.svm.term.iter", "Stops when maximum iteration is reached."); AddChoice("classifier.svm.term.eps", "Stops when accuracy is lower than epsilon."); AddChoice("classifier.svm.term.all", "Stops when either iteration or epsilon criteria is true"); AddParameter(ParameterType_Float, "classifier.svm.iter", "Maximum iteration"); SetParameterFloat("classifier.svm.iter",1000); SetParameterDescription("classifier.svm.iter", "Maximum number of iterations (corresponds to the termination criteria 'iter')."); AddParameter(ParameterType_Float, "classifier.svm.eps", "Epsilon accuracy threshold"); SetParameterFloat("classifier.svm.eps",FLT_EPSILON); SetParameterDescription("classifier.svm.eps", "Epsilon accuracy (corresponds to the termination criteria 'eps')."); } AddParameter(ParameterType_Float, "classifier.svm.coef0", "Parameter coef0 of a kernel function (POLY / SIGMOID)"); SetParameterFloat("classifier.svm.coef0",0.0); SetParameterDescription("classifier.svm.coef0", "Parameter coef0 of a kernel function (POLY / SIGMOID)."); AddParameter(ParameterType_Float, "classifier.svm.gamma", "Parameter gamma of a kernel function (POLY / RBF / SIGMOID)"); SetParameterFloat("classifier.svm.gamma",1.0); SetParameterDescription("classifier.svm.gamma", "Parameter gamma of a kernel function (POLY / RBF / SIGMOID)."); AddParameter(ParameterType_Float, "classifier.svm.degree", "Parameter degree of a kernel function (POLY)"); SetParameterFloat("classifier.svm.degree",1.0); SetParameterDescription("classifier.svm.degree", "Parameter degree of a kernel function (POLY)."); AddParameter(ParameterType_Bool, "classifier.svm.opt", "Parameters optimization"); SetParameterDescription("classifier.svm.opt", "SVM parameters optimization flag.\n" "-If set to True, then the optimal SVM parameters will be estimated. " "Parameters are considered optimal by OpenCV when the cross-validation estimate of " "the test set error is minimal. Finally, the SVM training process is computed " "10 times with these optimal parameters over subsets corresponding to 1/10th of " "the training samples using the k-fold cross-validation (with k = 10).\n-If set " "to False, the SVM classification process will be computed once with the " "currently set input SVM parameters over the training samples.\n-Thus, even " "with identical input SVM parameters and a similar random seed, the output " "SVM models will be different according to the method used (optimized or not) " "because the samples are not identically processed within OpenCV."); } template <class TInputValue, class TOutputValue> void LearningApplicationBase<TInputValue,TOutputValue> ::TrainSVM(typename ListSampleType::Pointer trainingListSample, typename TargetListSampleType::Pointer trainingLabeledListSample, std::string modelPath) { typedef otb::SVMMachineLearningModel<InputValueType, OutputValueType> SVMType; typename SVMType::Pointer SVMClassifier = SVMType::New(); SVMClassifier->SetRegressionMode(this->m_RegressionFlag); SVMClassifier->SetInputListSample(trainingListSample); SVMClassifier->SetTargetListSample(trainingLabeledListSample); switch (GetParameterInt("classifier.svm.k")) { case 0: // LINEAR SVMClassifier->SetKernelType(CvSVM::LINEAR); std::cout << "CvSVM::LINEAR = " << CvSVM::LINEAR << std::endl; break; case 1: // RBF SVMClassifier->SetKernelType(CvSVM::RBF); std::cout << "CvSVM::RBF = " << CvSVM::RBF << std::endl; break; case 2: // POLY SVMClassifier->SetKernelType(CvSVM::POLY); std::cout << "CvSVM::POLY = " << CvSVM::POLY << std::endl; break; case 3: // SIGMOID SVMClassifier->SetKernelType(CvSVM::SIGMOID); std::cout << "CvSVM::SIGMOID = " << CvSVM::SIGMOID << std::endl; break; default: // DEFAULT = LINEAR SVMClassifier->SetKernelType(CvSVM::LINEAR); std::cout << "CvSVM::LINEAR = " << CvSVM::LINEAR << std::endl; break; } if (this->m_RegressionFlag) { switch (GetParameterInt("classifier.svm.m")) { case 0: // EPS_SVR SVMClassifier->SetSVMType(CvSVM::EPS_SVR); std::cout<<"CvSVM::EPS_SVR = "<<CvSVM::EPS_SVR<<std::endl; break; case 1: // NU_SVR SVMClassifier->SetSVMType(CvSVM::NU_SVR); std::cout<<"CvSVM::NU_SVR = "<<CvSVM::NU_SVR<<std::endl; break; default: // DEFAULT = EPS_SVR SVMClassifier->SetSVMType(CvSVM::EPS_SVR); std::cout << "CvSVM::EPS_SVR = " << CvSVM::EPS_SVR << std::endl; break; } } else { switch (GetParameterInt("classifier.svm.m")) { case 0: // C_SVC SVMClassifier->SetSVMType(CvSVM::C_SVC); std::cout << "CvSVM::C_SVC = " << CvSVM::C_SVC << std::endl; break; case 1: // NU_SVC SVMClassifier->SetSVMType(CvSVM::NU_SVC); std::cout << "CvSVM::NU_SVC = " << CvSVM::NU_SVC << std::endl; break; case 2: // ONE_CLASS SVMClassifier->SetSVMType(CvSVM::ONE_CLASS); std::cout << "CvSVM::ONE_CLASS = " << CvSVM::ONE_CLASS << std::endl; break; default: // DEFAULT = C_SVC SVMClassifier->SetSVMType(CvSVM::C_SVC); std::cout << "CvSVM::C_SVC = " << CvSVM::C_SVC << std::endl; break; } } SVMClassifier->SetC(GetParameterFloat("classifier.svm.c")); SVMClassifier->SetNu(GetParameterFloat("classifier.svm.nu")); if (this->m_RegressionFlag) { SVMClassifier->SetP(GetParameterFloat("classifier.svm.p")); switch (GetParameterInt("classifier.svm.term")) { case 0: // ITER SVMClassifier->SetTermCriteriaType(CV_TERMCRIT_ITER); break; case 1: // EPS SVMClassifier->SetTermCriteriaType(CV_TERMCRIT_EPS); break; case 2: // ITER+EPS SVMClassifier->SetTermCriteriaType(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS); break; default: SVMClassifier->SetTermCriteriaType(CV_TERMCRIT_ITER); break; } SVMClassifier->SetMaxIter(GetParameterInt("classifier.svm.iter")); SVMClassifier->SetEpsilon(GetParameterFloat("classifier.svm.eps")); } SVMClassifier->SetCoef0(GetParameterFloat("classifier.svm.coef0")); SVMClassifier->SetGamma(GetParameterFloat("classifier.svm.gamma")); SVMClassifier->SetDegree(GetParameterFloat("classifier.svm.degree")); SVMClassifier->SetParameterOptimization(GetParameterInt("classifier.svm.opt")); SVMClassifier->Train(); SVMClassifier->Save(modelPath); // Update the displayed parameters in the GUI after the training process, for further use of them SetParameterFloat("classifier.svm.c",static_cast<float> (SVMClassifier->GetOutputC())); SetParameterFloat("classifier.svm.nu",static_cast<float> (SVMClassifier->GetOutputNu())); if (this->m_RegressionFlag) { SetParameterFloat("classifier.svm.p",static_cast<float> (SVMClassifier->GetOutputP())); } SetParameterFloat("classifier.svm.coef0",static_cast<float> (SVMClassifier->GetOutputCoef0())); SetParameterFloat("classifier.svm.gamma",static_cast<float> (SVMClassifier->GetOutputGamma())); SetParameterFloat("classifier.svm.degree",static_cast<float> (SVMClassifier->GetOutputDegree())); } } //end namespace wrapper } //end namespace otb #endif
45.256
121
0.676772
[ "vector", "model" ]
e546a5a860efac24791d127d038d1a674a487576
8,563
cpp
C++
sdl2/starfighter/src/player.cpp
pdpdds/SDLGameProgramming
3af68e2133296f3e7bc3d7454d9301141bca2d5a
[ "BSD-2-Clause" ]
null
null
null
sdl2/starfighter/src/player.cpp
pdpdds/SDLGameProgramming
3af68e2133296f3e7bc3d7454d9301141bca2d5a
[ "BSD-2-Clause" ]
null
null
null
sdl2/starfighter/src/player.cpp
pdpdds/SDLGameProgramming
3af68e2133296f3e7bc3d7454d9301141bca2d5a
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (C) 2003 Parallel Realities Copyright (C) 2011, 2012, 2013 Guus Sliepen Copyright (C) 2012, 2015-2017 Julie Marchant <onpon4@riseup.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "SDL2/SDL.h" #include "defs.h" #include "structs.h" #include "alien.h" #include "audio.h" #include "engine.h" #include "game.h" #include "gfx.h" #include "screen.h" #include "weapons.h" #include "window.h" Object player; int player_chargerFired = 0; /* Initialises the player for a new game. */ void player_init() { player.active = 1; player.x = screen->w / 2; player.y = screen->h / 2; player.speed = 2; player.systemPower = player.maxShield; player.face = 0; player.image[0] = gfx_shipSprites[SS_FIREFLY]; player.image[1] = gfx_shipSprites[SS_FIREFLY_L]; player.engineX = player.image[0]->w; player.engineY = (player.image[0]->h / 2); player.owner = &player; player.flags = FL_FRIEND; player.weaponType[0] = W_PLAYER_WEAPON; if (weapons[W_PLAYER_WEAPON].ammo[0] < game.minPlasmaOutput) weapons[W_PLAYER_WEAPON].ammo[0] = game.minPlasmaOutput; if (weapons[W_PLAYER_WEAPON].damage < game.minPlasmaDamage) weapons[W_PLAYER_WEAPON].damage = game.minPlasmaDamage; if (weapons[W_PLAYER_WEAPON].reload[0] > rate2reload[game.minPlasmaRate]) weapons[W_PLAYER_WEAPON].reload[0] = rate2reload[game.minPlasmaRate]; player.hit = 0; engine.lowShield = (player.maxShield >= 3) ? (player.maxShield / 3) : 1; engine.averageShield = engine.lowShield + engine.lowShield; if ((player.weaponType[1] == W_CHARGER) || (player.weaponType[1] == W_LASER)) player.ammo[1] = 0; } void player_setTarget(int index) { engine.targetIndex = index; engine.targetShield = 85; engine.targetShield /= aliens[index].shield; } void player_checkShockDamage(float x, float y) { float distX = fabsf(x - player.x); float distY = fabsf(y - player.y); // Don't let the player be hurt by an explosion after they have completed // all the mission Objectives. That would be *really* annoying! if ((engine.cheatShield) || (engine.missionCompleteTimer != 0)) return; if ((distX <= 50) && (distY <= 50)) { if (distX >= 1) distX /= 5; if (distY >= 1) distY /= 5; player.shield -= (int)(10 - distX); player.shield -= (int)(10 - distY); LIMIT(player.shield, 0, player.maxShield); player.hit = 10; } } void player_exit() { player_chargerFired = 0; if ((player.weaponType[1] == W_CHARGER) || (player.weaponType[1] == W_LASER)) player.ammo[1] = 0; } void player_flushInput() { for (int i = 0; i < KEY_LAST; i++) engine.keyState[i] = 0; while (SDL_PollEvent(&engine.event)){} } static enum keys mapkey(int code) { switch (code) { case SDLK_UP: case SDLK_KP_8: return KEY_UP; case SDLK_DOWN: case SDLK_KP_2: case SDLK_KP_5: return KEY_DOWN; case SDLK_LEFT: case SDLK_KP_4: return KEY_LEFT; case SDLK_RIGHT: case SDLK_KP_6: return KEY_RIGHT; case SDLK_LCTRL: case SDLK_RCTRL: case SDLK_RETURN: case SDLK_z: case SDLK_y: case SDLK_c: case SDLK_a: case SDLK_d: case SDLK_f: case SDLK_SLASH: case SDLK_COMMA: case SDLK_1: case SDLK_3: case SDLK_KP_0: case SDLK_HOME: case SDLK_END: return KEY_FIRE; case SDLK_SPACE: case SDLK_x: case SDLK_s: case SDLK_PERIOD: case SDLK_2: case SDLK_KP_1: case SDLK_PAGEUP: case SDLK_PAGEDOWN: return KEY_ALTFIRE; case SDLK_LSHIFT: case SDLK_RSHIFT: case SDLK_LALT: case SDLK_RALT: case SDLK_KP_7: case SDLK_KP_9: return KEY_SWITCH; case SDLK_p: case SDLK_PAUSE: return KEY_PAUSE; case SDLK_ESCAPE: case SDLK_q: case SDLK_BACKSPACE: case SDLK_DELETE: return KEY_ESCAPE; case SDLK_F11: return KEY_FULLSCREEN; default: return KEY_DUMMY; } } void player_getInput() { while (SDL_PollEvent(&engine.event)) { switch (engine.event.type) { case SDL_QUIT: exit(0); break; case SDL_MOUSEBUTTONDOWN: if (engine.gameSection == SECTION_INTERMISSION) { if (engine.event.button.button == SDL_BUTTON_LEFT) engine.keyState[KEY_FIRE] = 1; if (engine.event.button.button == SDL_BUTTON_RIGHT) engine.keyState[KEY_ALTFIRE] = 1; } break; case SDL_KEYDOWN: engine.keyState[mapkey(engine.event.key.keysym.sym)] = 1; if (engine.gameSection != SECTION_GAME) engine.paused = 0; break; case SDL_KEYUP: if (engine.event.key.keysym.sym != SDLK_p) engine.keyState[mapkey(engine.event.key.keysym.sym)] = 0; break; case SDL_JOYBUTTONDOWN: case SDL_JOYBUTTONUP: switch (engine.event.jbutton.button) { case 0: case 3: engine.keyState[KEY_ALTFIRE] = engine.event.jbutton.state; break; case 1: case 2: engine.keyState[KEY_FIRE] = engine.event.jbutton.state; break; case 4: case 6: engine.keyState[KEY_ESCAPE] = engine.event.jbutton.state; break; case 5: case 7: case 8: engine.keyState[KEY_SWITCH] = engine.event.jbutton.state; break; case 9: if (engine.event.jbutton.state) engine.keyState[KEY_PAUSE] = 1; break; } break; case SDL_JOYHATMOTION: engine.keyState[KEY_UP] = engine.event.jhat.value & SDL_HAT_UP; engine.keyState[KEY_DOWN] = engine.event.jhat.value & SDL_HAT_DOWN; engine.keyState[KEY_LEFT] = engine.event.jhat.value & SDL_HAT_LEFT; engine.keyState[KEY_RIGHT] = engine.event.jhat.value & SDL_HAT_RIGHT; break; case SDL_JOYAXISMOTION: static int prevjoyup, prevjoydown, prevjoyleft, prevjoyright; if (engine.event.jaxis.axis & 1) { int joyup = engine.event.jaxis.value < -16384; int joydown = engine.event.jaxis.value >= 16384; if(joyup != prevjoyup) engine.keyState[KEY_UP] = prevjoyup = joyup; if(joydown != prevjoydown) engine.keyState[KEY_DOWN] = prevjoydown = joydown; } else { int joyleft = engine.event.jaxis.value < -16384; int joyright = engine.event.jaxis.value >= 16384; if(joyleft != prevjoyleft) engine.keyState[KEY_LEFT] = prevjoyleft = joyleft; if(joyright != prevjoyright) engine.keyState[KEY_RIGHT] = prevjoyright = joyright; } break; case SDL_WINDOWEVENT: if (engine.autoPause && (engine.event.window.event == SDL_WINDOWEVENT_FOCUS_LOST)) engine.paused = 1; break; } if (engine.keyState[KEY_FULLSCREEN]) { engine.fullScreen = !engine.fullScreen; SDL_SetWindowFullscreen(window, engine.fullScreen ? FULLSCREEN : 0); engine.keyState[KEY_FULLSCREEN] = 0; } } if (engine.gameSection == SECTION_INTERMISSION) { // Get the current mouse position static int px = -1, py = -1; int x, y, w, h; SDL_GetMouseState(&x, &y); SDL_GetWindowSize(window, &w, &h); x = screen->w * x / w; y = screen->h * y / h; if (px == x && py == y) { if(engine.keyState[KEY_UP] && engine.cursor_y > 0) engine.cursor_y -= 4; if(engine.keyState[KEY_DOWN] && engine.cursor_y < screen->h - 4) engine.cursor_y += 4; if(engine.keyState[KEY_LEFT] && engine.cursor_x > 0) engine.cursor_x -= 4; if(engine.keyState[KEY_RIGHT] && engine.cursor_x < screen->w - 4) engine.cursor_x += 4; } else { engine.cursor_x = px = x; engine.cursor_y = py = y; } } } void player_leaveSector() { engine.keyState[KEY_UP] = 0; engine.keyState[KEY_DOWN] = 0; engine.keyState[KEY_LEFT] = 0; engine.keyState[KEY_RIGHT] = 0; engine.keyState[KEY_FIRE] = 0; engine.keyState[KEY_ALTFIRE] = 0; if (engine.done == 0) engine.done = 3; if (engine.done == 3) { player.face = 0; if (player.x > -100) { player.x += engine.ssx; engine.ssx -= 1; if (player.y > screen->h / 2) player.y--; if (player.y < screen->h / 2) player.y++; } if (player.x <= -100) { engine.done = 2; audio_playSound(SFX_FLY, screen->w / 2, screen->h / 2); } } if (engine.done == 2) { player.face = 0; player.x += 12; engine.ssx -= 0.2; if (player.x > (2 * screen->w)) engine.done = 1; } }
24.121127
90
0.672895
[ "object" ]
e553efbf1f18e4c66332538c0b33ad6e9125a6aa
21,850
cpp
C++
src/gfx/mg_bitmap_font.cpp
Magnutic/mg-engine
09862497bf99198281acc8227b135777491c58d3
[ "BSD-3-Clause" ]
null
null
null
src/gfx/mg_bitmap_font.cpp
Magnutic/mg-engine
09862497bf99198281acc8227b135777491c58d3
[ "BSD-3-Clause" ]
null
null
null
src/gfx/mg_bitmap_font.cpp
Magnutic/mg-engine
09862497bf99198281acc8227b135777491c58d3
[ "BSD-3-Clause" ]
null
null
null
//************************************************************************************************** // This file is part of Mg Engine. Copyright (c) 2020, Magnus Bergsten. // Mg Engine is made available under the terms of the 3-Clause BSD License. // See LICENSE.txt in the project's root directory. //************************************************************************************************** #include "mg/gfx/mg_bitmap_font.h" #include "mg/containers/mg_array.h" #include "mg/containers/mg_flat_map.h" #include "mg/containers/mg_small_vector.h" #include "mg/core/mg_log.h" #include "mg/core/mg_runtime_error.h" #include "mg/mg_unicode.h" #include "mg/resource_cache/mg_resource_access_guard.h" #include "mg/resources/mg_font_resource.h" #include "mg/utils/mg_file_io.h" #include "mg/utils/mg_math_utils.h" #include "mg/utils/mg_stl_helpers.h" #include "mg/utils/mg_string_utils.h" #include "opengl/mg_glad.h" // TODO temp //-------------------------------------------------------------------------------------------------- // Include stb_truetype. // We do this in a slightly evil manner: // To avoid risk of symbol conflict in the not-too-unlikely case of linking with another object that // also uses stb_truetype, we wrap the #include in a custom namespace. // For this to work, we must ensure the stb headers themselves do not include any standard library // headers. // As long as we provide implementation macros for all functions used by the stb headers, this will // work. #include <assert.h> // NOLINT(modernize-deprecated-headers) #include <math.h> // NOLINT(modernize-deprecated-headers) #include <stdlib.h> // NOLINT(modernize-deprecated-headers) #include <string.h> // NOLINT(modernize-deprecated-headers) // Definitions for stb_rect_pack #define STBRP_SORT qsort // NOLINT #define STBRP_ASSERT assert // NOLINT // Definitions for stb_truetype #define STBTT_ifloor(x) ((int)::floor(x)) // NOLINT #define STBTT_iceil(x) ((int)::ceil(x)) // NOLINT #define STBTT_sqrt(x) ::sqrt(x) // NOLINT #define STBTT_pow(x, y) ::pow(x, y) // NOLINT #define STBTT_fmod(x, y) ::fmod(x, y) // NOLINT #define STBTT_cos(x) ::cos(x) // NOLINT #define STBTT_acos(x) ::acos(x) // NOLINT #define STBTT_fabs(x) ::fabs(x) // NOLINT #define STBTT_malloc(x, u) ((void)(u), ::malloc(x)) // NOLINT #define STBTT_free(x, u) ((void)(u), ::free(x)) // NOLINT #define STBTT_assert(x) assert(x) // NOLINT #define STBTT_strlen(x) ::strlen(x) // NOLINT #define STBTT_memcpy ::memcpy // NOLINT #define STBTT_memset ::memset // NOLINT #define STBTT_STATIC 1 // NOLINT #define STB_TRUETYPE_IMPLEMENTATION 1 // NOLINT #define STB_RECT_PACK_IMPLEMENTATION 1 // NOLINT // Namespace stb-library definitions to avoid potential symbol conflicts. namespace Mg::stb { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wsign-conversion" // Note: stb_rect_pack must be included before truetype, as the latter will use a fallback if the // former is not included. #include <stb_rect_pack.h> #include <stb_truetype.h> #pragma GCC diagnostic pop } // namespace Mg::stb using namespace Mg::stb; //-------------------------------------------------------------------------------------------------- #include <fmt/core.h> #include <glm/vec2.hpp> #include <atomic> #include <numeric> #include <string> #include <vector> namespace Mg::gfx { struct BitmapFontData { // Texture with packed glyph rasters. TextureHandle::Owner texture; int texture_width = 0; int texture_height = 0; // Font size (letter height) in pixels. int font_size_pixels = 0; // Indexable array of data describing where in texture a glyph resides Array<stbtt_packedchar> packed_chars; // The range of unicode code points represented in texture and packed_chars. small_vector<UnicodeRange, 5> unicode_ranges; }; //-------------------------------------------------------------------------------------------------- // Private definitions //-------------------------------------------------------------------------------------------------- namespace { // Initial size of rasterized font textures. They grow as needed to fit requested glyphs. constexpr int k_initial_font_texture_width = 128; constexpr int k_initial_font_texture_height = 128; // Character to substitute when trying to display an unsupported codepoint. constexpr char32_t k_substitution_character = U'\U0000FFFD'; Opt<int32_t> get_packedchar_index(const BitmapFontData& font, char32_t codepoint) { int32_t result = 0; for (const UnicodeRange& range : font.unicode_ranges) { if (contains_codepoint(range, codepoint)) { result += narrow<int>(codepoint - range.start); return result; } result += narrow<int32_t>(range.length); } return nullopt; } class FontPacker { public: void pack(ResourceHandle<FontResource> font_resource, span<const UnicodeRange> unicode_ranges, const int font_size_pixels, BitmapFontData& font) { // Set initial texture size. m_texture_width = k_initial_font_texture_width; m_texture_height = k_initial_font_texture_height; // Load font data. ResourceAccessGuard resource_access{ font_resource }; auto merged_ranges = merge_overlapping_ranges(unicode_ranges); { // Ensure the substitution character is present in merged_ranges. auto contains_subsistution_char = [](UnicodeRange r) { return contains_codepoint(r, k_substitution_character); }; const bool has_substitution_char = count_if(merged_ranges, contains_subsistution_char) == 1; if (!has_substitution_char) { merged_ranges.push_back({ k_substitution_character, 1 }); } } // Pack into a texture. pack_impl(resource_access->data(), merged_ranges, font_size_pixels, font); log.verbose("Packed font {}:{} into {}x{} texture.", font_resource.resource_id().str_view(), font_size_pixels, m_texture_width, m_texture_height); } private: void pack_impl(const span<const std::byte>& font_data, const span<const UnicodeRange>& unicode_ranges, const int font_size_pixels, BitmapFontData& font) { { auto texture_data = Array<uint8_t>::make_for_overwrite( narrow<size_t>(m_texture_width * m_texture_height)); stbtt_pack_context pack_context; std::copy(unicode_ranges.begin(), unicode_ranges.end(), std::back_inserter(font.unicode_ranges)); const size_t num_packed_chars = std::accumulate(unicode_ranges.begin(), unicode_ranges.end(), size_t(0), [](size_t acc, UnicodeRange range) { return acc + range.length; }); font.packed_chars = Array<stbtt_packedchar>::make_for_overwrite(num_packed_chars); const int stride_in_bytes = 0; const int padding = 1; void* const alloc_context = nullptr; if (0 == stbtt_PackBegin(&pack_context, texture_data.data(), m_texture_width, m_texture_height, stride_in_bytes, padding, alloc_context)) { log.error("Failed to initiate STBTT font packing context."); throw RuntimeError{}; } const auto font_index = 0; const auto font_size = static_cast<float>(font_size_pixels); bool packing_succeeded = true; size_t packed_char_offset = 0; for (UnicodeRange unicode_range : unicode_ranges) { const auto first_codepoint = narrow<int>(unicode_range.start); const auto num_codepoints = narrow<int>(unicode_range.length); const auto* font_data_ptr = reinterpret_cast<const uint8_t*>(font_data.data()); auto* chardata_for_range = &font.packed_chars[packed_char_offset]; const auto pack_result = stbtt_PackFontRange(&pack_context, font_data_ptr, font_index, font_size, first_codepoint, num_codepoints, chardata_for_range); if (pack_result == 0) { packing_succeeded = false; break; } packed_char_offset += unicode_range.length; } stbtt_PackEnd(&pack_context); if (packing_succeeded) { font.texture = make_texture(pack_context); font.texture_width = m_texture_width; font.texture_height = m_texture_height; return; } } // If failed, try again recursively with larger texture. grow_texture(); pack_impl(font_data, unicode_ranges, font_size_pixels, font); } // Create texture for the given font data. TextureHandle::Owner make_texture(stbtt_pack_context& context) const { // Upload rasterized font texture to GPU. GLuint gl_texture_id = 0; glGenTextures(1, &gl_texture_id); glBindTexture(GL_TEXTURE_2D, gl_texture_id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, m_texture_width, m_texture_height, 0, GL_RED, GL_UNSIGNED_BYTE, context.pixels); return TextureHandle::Owner{ gl_texture_id }; } void grow_texture() { int& side = (m_texture_width <= m_texture_height) ? m_texture_width : m_texture_height; side *= 2; } int m_texture_width = 0; int m_texture_height = 0; }; } // namespace //-------------------------------------------------------------------------------------------------- // PreparedText //-------------------------------------------------------------------------------------------------- PreparedText::~PreparedText() { const auto vbo_id = m_gpu_data.vertex_buffer.as_gl_id(); const auto vao_id = m_gpu_data.vertex_array.as_gl_id(); glDeleteBuffers(1, &vbo_id); glDeleteVertexArrays(1, &vao_id); } //-------------------------------------------------------------------------------------------------- // BitmapFont //-------------------------------------------------------------------------------------------------- BitmapFont::BitmapFont(ResourceHandle<FontResource> font, const int font_size_pixels, span<const UnicodeRange> unicode_ranges) { impl().font_size_pixels = font_size_pixels; FontPacker packer; packer.pack(font, unicode_ranges, font_size_pixels, impl()); } BitmapFont::~BitmapFont() = default; // Implementation of BitmapFont::prepare_text namespace { struct BreakLinesResult { Array<stbtt_aligned_quad> char_quads; float width; float height; size_t num_lines; }; // Break text into multiple lines at '\n'-codepoints and wherever the line would exceed // `max_width_pixels`. BreakLinesResult break_lines(const std::u32string_view& text_codepoints, span<const stbtt_aligned_quad> single_line_quads, const Opt<int32_t> max_width_pixels, const float line_height, const float line_spacing_factor) { MG_ASSERT(text_codepoints.size() == single_line_quads.size()); auto result_quads = Array<stbtt_aligned_quad>::make_copy(single_line_quads); float width = 0.0f; size_t num_lines = 1; // Index of the quad where the current lines starts. size_t line_start_index = 0; // Index of the most recent whitespace glyph quad. We always break at whitespace boundaries here // (no hyphenation of forced line breaks). size_t last_whitespace_index = 0; // The single_line_quads include the glyph quads' vertex positions arranged in a single line. We // will split into multiple lines by modifying these positions. Hence, we track the accumulated // offset caused by line breaks in the x and y axes and apply to each position. Every time we // break a line, we add the line height to the y_offset and subtract the width of the line to // make sure the next line starts where it should. float x_offset = 0.0f; float y_offset = 0.0f; // Whether this glyph should be the start of a new line. bool start_new_line = false; size_t i = 0; while (i < single_line_quads.size()) { if (is_whitespace(text_codepoints[i])) { last_whitespace_index = i; // Skip leading whitespace after line break unless it is another line break. if (start_new_line && text_codepoints[i] != '\n') { ++i; continue; } } const stbtt_aligned_quad& q = single_line_quads[i]; if (start_new_line) { start_new_line = false; line_start_index = i; // Accumulate offset to move the following quads to down and inward. x_offset = -q.x0; y_offset += line_height * line_spacing_factor; ++num_lines; } if (text_codepoints[i] == '\n') { start_new_line = true; ++i; continue; } const bool is_first_char_of_line = i == line_start_index; const bool is_past_width_limit = max_width_pixels.has_value() && (q.x1 + x_offset) > static_cast<float>(max_width_pixels.value()); if (!is_first_char_of_line && is_past_width_limit) { if (last_whitespace_index > line_start_index) { i = last_whitespace_index + 1; } start_new_line = true; continue; } // Apply accumulated offsets. result_quads[i].x0 = q.x0 + x_offset; result_quads[i].x1 = q.x1 + x_offset; result_quads[i].y0 = q.y0 + y_offset; result_quads[i].y1 = q.y1 + y_offset; // Track the maximum horizontal extents of the text after adding line breaks. width = max(width, q.x1); ++i; } const float height = line_height + y_offset; return { std::move(result_quads), width, height, num_lines }; }; // Convert to UTF32 and filter out unprintable characters. std::u32string convert_and_filter(std::string_view text) { // Convert to codepoints. bool utf8_error = false; std::u32string codepoints = utf8_to_utf32(text, &utf8_error); if (utf8_error) { auto msg = fmt::format("FontHandler::prepare_text: invalid UTF-8 in string '{}'.", text); log.warning(msg); } // Filter out ASCII control characters, except for tabs, which we will turn into four spaces, // and line feeds, which are later handled by break_lines. auto is_ascii_ctrl_code = [](const char32_t c) { return (c != 10 && c < 32) || c == 127; }; const bool should_be_filtered = std::find_if(codepoints.begin(), codepoints.end(), is_ascii_ctrl_code) != codepoints.end(); if (should_be_filtered) { std::u32string filtered_text; for (const char32_t c : codepoints) { if (!is_ascii_ctrl_code(c)) { filtered_text += c; } else if (c == '\t') { filtered_text += U" "; } } codepoints = filtered_text; } return codepoints; } } // namespace PreparedText BitmapFont::prepare_text(std::string_view text_utf8, const TypeSetting& typesetting) const { // Convert text to sequence of code points (while filtering out unprintable characters). const std::u32string text_codepoints = convert_and_filter(text_utf8); const auto line_height = static_cast<float>(font_size_pixels()); // Get texture for font. MG_ASSERT(impl().texture.handle != TextureHandle::null_handle()); // Get quads for each codepoint in the string. auto char_quads = Array<stbtt_aligned_quad>::make_for_overwrite(text_codepoints.size()); { float x = 0.0f; float y = line_height; for (size_t i = 0; i < text_codepoints.size(); ++i) { auto codepoint = text_codepoints[i]; stbtt_aligned_quad& quad = char_quads[i]; // Do not try to print newline characters, but put a space instead to ensure one-to-one // relationship between char_quads and text_codepoints. codepoint = (codepoint == '\n' ? ' ' : codepoint); // Get index of packedchar corresponding to codepoint, or that of the substituition if // not present. const auto packedchar_index = get_packedchar_index(impl(), codepoint) .value_or(get_packedchar_index(impl(), k_substitution_character).value()); constexpr int align_to_integer = 0; stbtt_GetPackedQuad(impl().packed_chars.data(), impl().texture_width, impl().texture_height, packedchar_index, &x, &y, &quad, align_to_integer); } } // Break quads into multiple lines. BreakLinesResult break_lines_result = break_lines(text_codepoints, char_quads, typesetting.max_width_pixels, line_height, typesetting.line_spacing_factor); char_quads = std::move(break_lines_result.char_quads); const float width = break_lines_result.width; const float height = break_lines_result.height; // Prepare vertex data. struct Vertex { glm::vec2 position; glm::vec2 tex_coord; }; static_assert(sizeof(Vertex) == 2u * sizeof(glm::vec2)); // Assert no padding. static constexpr size_t verts_per_char = 6u; auto vertices = Array<Vertex>::make_for_overwrite(text_codepoints.size() * verts_per_char); for (size_t i = 0; i < char_quads.size(); ++i) { const stbtt_aligned_quad& q = char_quads[i]; const size_t offset = i * verts_per_char; // Normalize vertex positions into [0.0, 1.0] to simplify transformations (width and height // is stored along with the text so that it can be scaled appropriately in the vertex // shader). // Flipped Y-axis compared with what stb_truetype expects. const float x0 = q.x0 / width; const float x1 = q.x1 / width; const float y0 = 1.0f - q.y0 / height; const float y1 = 1.0f - q.y1 / height; vertices[offset + 0] = { { x0, y1 }, { q.s0, q.t1 } }; vertices[offset + 1] = { { x1, y1 }, { q.s1, q.t1 } }; vertices[offset + 2] = { { x1, y0 }, { q.s1, q.t0 } }; vertices[offset + 3] = { { x0, y1 }, { q.s0, q.t1 } }; vertices[offset + 4] = { { x1, y0 }, { q.s1, q.t0 } }; vertices[offset + 5] = { { x0, y0 }, { q.s0, q.t0 } }; } // Create OpenGL buffers. // TODO move into GL-specific private header. GLuint gl_vertex_array_id = 0; glGenVertexArrays(1, &gl_vertex_array_id); glBindVertexArray(gl_vertex_array_id); GLuint gl_buffer_id = 0; glGenBuffers(1, &gl_buffer_id); glBindBuffer(GL_ARRAY_BUFFER, gl_buffer_id); glBufferData(GL_ARRAY_BUFFER, narrow<GLsizei>(sizeof(Vertex) * vertices.size()), static_cast<const GLvoid*>(vertices.data()), GL_STATIC_DRAW); const auto stride = narrow<GLsizei>(sizeof(Vertex)); const GLvoid* position_offset = nullptr; const auto* texcoord_offset = reinterpret_cast<const GLvoid*>(sizeof(glm::vec2)); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, stride, position_offset); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, stride, texcoord_offset); glEnableVertexAttribArray(1); glBindVertexArray(0); PreparedText::GpuData gpu_data; gpu_data.texture = impl().texture.handle; gpu_data.vertex_buffer = BufferHandle(gl_buffer_id); gpu_data.vertex_array = VertexArrayHandle(gl_vertex_array_id); return PreparedText(gpu_data, width, height, text_codepoints.size()); } span<const UnicodeRange> BitmapFont::contained_ranges() const { return impl().unicode_ranges; } int BitmapFont::font_size_pixels() const { return impl().font_size_pixels; } } // namespace Mg::gfx
38.066202
100
0.573547
[ "object", "vector" ]
e556d78d55355fd20245b95b4ad0184a27c9c4c2
62,396
cpp
C++
packages/utility/distribution/test/tstUnitBaseTwoDGridPolicy.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
10
2019-11-14T19:58:30.000Z
2021-04-04T17:44:09.000Z
packages/utility/distribution/test/tstUnitBaseTwoDGridPolicy.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
43
2020-03-03T19:59:20.000Z
2021-09-08T03:36:08.000Z
packages/utility/distribution/test/tstUnitBaseTwoDGridPolicy.cpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
6
2020-02-12T17:37:07.000Z
2020-09-08T18:59:51.000Z
//---------------------------------------------------------------------------// //! //! \file tstUnitBaseTwoDGridPolicy.cpp //! \author Luke Kersting //! \brief The UnitBase two-dimensional sampling policy unit tests //! //---------------------------------------------------------------------------// // Std Lib Includes #include <iostream> #include <sstream> #include <memory> // Boost Includes #include <boost/units/systems/cgs.hpp> #include <boost/units/io.hpp> // FRENSIE Includes #include "Utility_TwoDGridPolicy.hpp" #include "Utility_UnitTestHarnessWithMain.hpp" #include "Utility_DynamicOutputFormatter.hpp" #include "Utility_InterpolatedFullyTabularBasicBivariateDistribution.hpp" #include "Utility_DeltaDistribution.hpp" #include "Utility_UniformDistribution.hpp" #include "Utility_ExponentialDistribution.hpp" #include "Utility_ElectronVoltUnit.hpp" #include "Utility_BarnUnit.hpp" using boost::units::quantity; using Utility::Units::MegaElectronVolt; using Utility::Units::MeV; using Utility::Units::Barn; using Utility::Units::barn; using Utility::Units::barns; namespace cgs = boost::units::cgs; //---------------------------------------------------------------------------// // Testing Typenames //---------------------------------------------------------------------------// using XIndepType = Utility::UnitTraits<MegaElectronVolt>::template GetQuantityType<double>::type; using YIndepType = Utility::UnitTraits<cgs::length>::template GetQuantityType<double>::type; using ZDepType = Utility::UnitTraits<Barn>::template GetQuantityType<double>::type; using DistributionType = std::vector<std::pair<double,std::shared_ptr<const Utility::TabularUnivariateDistribution > > >; using UnitAwareDistributionType = std::vector<std::pair<Utility::UnitTraits<MegaElectronVolt>::template GetQuantityType<double>::type,std::shared_ptr<const Utility::UnitAwareTabularUnivariateDistribution<cgs::length,Barn> > > >; //---------------------------------------------------------------------------// // Testing Variables //---------------------------------------------------------------------------// std::shared_ptr<DistributionType> distribution; std::shared_ptr<UnitAwareDistributionType> unit_aware_distribution; std::function<double(const Utility::TabularUnivariateDistribution&)> functor; std::function<double(const Utility::TabularUnivariateDistribution&, const double)> threshold_functor; std::function<YIndepType(const Utility::UnitAwareTabularUnivariateDistribution<cgs::length,Barn>&)> ua_functor; std::function<YIndepType(const Utility::UnitAwareTabularUnivariateDistribution<cgs::length,Barn>&, const double)> ua_threshold_functor; std::function<double (double)> min_func, max_func; std::function<YIndepType(const XIndepType)> ua_min_func, ua_max_func; DistributionType::const_iterator bin, lower_bin, upper_bin, sampled_bin, start_bin; UnitAwareDistributionType::const_iterator ua_bin, ua_lower_bin, ua_upper_bin, ua_sampled_bin, ua_start_bin; //---------------------------------------------------------------------------// // Tests. //---------------------------------------------------------------------------// // Check that the distribution is tabular in the primary dimension FRENSIE_UNIT_TEST( UnitBase, name ) { std::string name = Utility::UnitBase<Utility::LinLinLin>::name(); FRENSIE_CHECK( name == "Unit-base" ); name = Utility::UnitBase<Utility::LinLinLin>::TwoDInterpPolicy::name(); FRENSIE_CHECK( name == "LinLinLin" ); } //---------------------------------------------------------------------------// // Check that the Y lower bound can be calculated FRENSIE_UNIT_TEST( UnitBase, calculateLowerBound ) { lower_bin = distribution->begin(); upper_bin = lower_bin; ++upper_bin; // On the first bin boundary double x_value = 0.0; double bound = Utility::UnitBase<Utility::LinLinLin>::calculateLowerBound<double>( x_value, lower_bin, upper_bin ); FRENSIE_CHECK_EQUAL( bound, 0.0 ); // In the first bin x_value = 0.5; bound = Utility::UnitBase<Utility::LinLinLin>::calculateLowerBound<double>( x_value, lower_bin, upper_bin ); FRENSIE_CHECK_EQUAL( bound, 1.25 ); // On the second bin boundary ++lower_bin; ++upper_bin; x_value = 1.0; bound = Utility::UnitBase<Utility::LinLinLin>::calculateLowerBound<double>( x_value, lower_bin, upper_bin ); FRENSIE_CHECK_EQUAL( bound, 2.5 ); // In the second bin x_value = 1.5; bound = Utility::UnitBase<Utility::LinLinLin>::calculateLowerBound<double>( x_value, lower_bin, upper_bin ); FRENSIE_CHECK_EQUAL( bound, 1.25 ); // On the upper bin boundary x_value = 2.0; bound = Utility::UnitBase<Utility::LinLinLin>::calculateLowerBound<double>( x_value, lower_bin, upper_bin ); FRENSIE_CHECK_EQUAL( bound, 0.0 ); } //---------------------------------------------------------------------------// // Check that the Y lower bound can be calculated FRENSIE_UNIT_TEST( UnitBase, calculateUpperBound ) { lower_bin = distribution->begin(); upper_bin = lower_bin; ++upper_bin; // On the first bin boundary double x_value = 0.0; double bound = Utility::UnitBase<Utility::LinLinLin>::calculateUpperBound<double>( x_value, lower_bin, upper_bin ); FRENSIE_CHECK_EQUAL( bound, 10.0 ); // In the first bin x_value = 0.5; bound = Utility::UnitBase<Utility::LinLinLin>::calculateUpperBound<double>( x_value, lower_bin, upper_bin ); FRENSIE_CHECK_EQUAL( bound, 8.75 ); // On the second bin boundary ++lower_bin; ++upper_bin; x_value = 1.0; bound = Utility::UnitBase<Utility::LinLinLin>::calculateUpperBound<double>( x_value, lower_bin, upper_bin ); FRENSIE_CHECK_EQUAL( bound, 7.5 ); // In the second bin x_value = 1.5; bound = Utility::UnitBase<Utility::LinLinLin>::calculateUpperBound<double>( x_value, lower_bin, upper_bin ); FRENSIE_CHECK_EQUAL( bound, 8.75 ); // On the upper bin boundary x_value = 2.0; bound = Utility::UnitBase<Utility::LinLinLin>::calculateUpperBound<double>( x_value, lower_bin, upper_bin ); FRENSIE_CHECK_EQUAL( bound, 10.0 ); } //---------------------------------------------------------------------------// // Check that the distribution can be evaluated FRENSIE_UNIT_TEST( UnitBase, evaluatePDF ) { std::function<double(double,double)> evaluate = [&min_func, &max_func, &lower_bin, &upper_bin](double x_value, double y_value) { return Utility::UnitBase<Utility::LinLinLin>::evaluatePDF<Utility::TabularUnivariateDistribution,double,double,double>( x_value, y_value, min_func, max_func, &Utility::TabularUnivariateDistribution::evaluate, lower_bin, upper_bin ); }; lower_bin = distribution->begin(); upper_bin = lower_bin; ++upper_bin; double x_value = 0.0; min_func = [](double x){return 0.0;}; max_func = [](double x){return 10.0;};; // On the first bin boundary FRENSIE_CHECK_EQUAL( evaluate( 0.0, -1.0 ), 0.0 ); FRENSIE_CHECK_EQUAL( evaluate( 0.0, 0.0 ), 1.0 ); FRENSIE_CHECK_EQUAL( evaluate( 0.0, 5.0 ), 1.0 ); FRENSIE_CHECK_EQUAL( evaluate( 0.0, 10.0 ), 1.0 ); FRENSIE_CHECK_EQUAL( evaluate( 0.0, 11.0 ), 0.0 ); // In the first bin min_func = [](double x){return 1.25;}; max_func = [](double x){return 8.75;}; FRENSIE_CHECK_EQUAL( evaluate( 0.5, 1.0 ), 0.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( evaluate( 0.5, 1.25 ), 0.7, 1e-15 ); FRENSIE_CHECK_FLOATING_EQUALITY( evaluate( 0.5, 5.0 ), 1.0, 1e-6 ); FRENSIE_CHECK_FLOATING_EQUALITY( evaluate( 0.5, 8.75 ), 5.0/6.0, 1e-15 ); FRENSIE_CHECK_EQUAL( evaluate( 0.5, 9.0 ), 0.0 ); // On the second bin boundary ++lower_bin; ++upper_bin; min_func = [](double x){return 2.5;}; max_func = [](double x){return 7.5;}; FRENSIE_CHECK_EQUAL( evaluate( 1.0, 2.0 ), 0.0 ); FRENSIE_CHECK_EQUAL( evaluate( 1.0, 2.5 ), 0.1 ); FRENSIE_CHECK_EQUAL( evaluate( 1.0, 5.0 ), 1.0 ); FRENSIE_CHECK_EQUAL( evaluate( 1.0, 7.5 ), 0.5 ); FRENSIE_CHECK_EQUAL( evaluate( 1.0, 8.0 ), 0.0 ); // In the second bin min_func = [](double x){return 1.25;}; max_func = [](double x){return 8.75;}; FRENSIE_CHECK_EQUAL( evaluate( 1.5, 1.0 ), 0.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( evaluate( 1.5, 1.25 ), 0.1, 1e-15 ); FRENSIE_CHECK_FLOATING_EQUALITY( evaluate( 1.5, 5.0 ), 0.4, 1e-6 ); FRENSIE_CHECK_FLOATING_EQUALITY( evaluate( 1.5, 8.75 ), 7.0/30.0, 1e-15 ); FRENSIE_CHECK_EQUAL( evaluate( 1.5, 9.0 ), 0.0 ); // On the upper bin boundary min_func = [](double x){return 0.0;}; max_func = [](double x){return 10.0;}; FRENSIE_CHECK_EQUAL( evaluate( 2.0, -1.0 ), 0.0 ); FRENSIE_CHECK_EQUAL( evaluate( 2.0, 0.0 ), 0.1 ); FRENSIE_CHECK_EQUAL( evaluate( 2.0, 5.0 ), 0.1 ); FRENSIE_CHECK_EQUAL( evaluate( 2.0, 10.0 ), 0.1 ); FRENSIE_CHECK_EQUAL( evaluate( 2.0, 11.0 ), 0.0 ); } //---------------------------------------------------------------------------// // Check that the unit-aware distribution can be evaluated FRENSIE_UNIT_TEST( UnitAwareUnitBase, evaluatePDF ) { std::function<ZDepType(XIndepType,YIndepType)> evaluate = [&ua_min_func, &ua_max_func, &ua_lower_bin, &ua_upper_bin](XIndepType x_value, YIndepType y_value) { return Utility::UnitBase<Utility::LinLinLin>::evaluatePDF<Utility::UnitAwareTabularUnivariateDistribution<cgs::length,Barn>,XIndepType,YIndepType,ZDepType>( x_value, y_value, ua_min_func, ua_max_func, &Utility::UnitAwareTabularUnivariateDistribution<cgs::length,Barn>::evaluate, ua_lower_bin, ua_upper_bin ); }; ua_lower_bin = unit_aware_distribution->begin(); ua_upper_bin = ua_lower_bin; ++ua_upper_bin; ua_min_func = [](XIndepType x){return 0.0*cgs::centimeter;}; ua_max_func = [](XIndepType x){return 10.0*cgs::centimeter;}; // On the first bin boundary FRENSIE_CHECK_EQUAL( evaluate( 0.0*MeV, -1.0*cgs::centimeter ), 0.0*barn ); FRENSIE_CHECK_EQUAL( evaluate( 0.0*MeV, 0.0*cgs::centimeter ), 1.0*barn ); FRENSIE_CHECK_EQUAL( evaluate( 0.0*MeV, 5.0*cgs::centimeter ), 1.0*barn ); FRENSIE_CHECK_EQUAL( evaluate( 0.0*MeV, 10.0*cgs::centimeter ), 1.0*barn ); FRENSIE_CHECK_EQUAL( evaluate( 0.0*MeV, 11.0*cgs::centimeter ), 0.0*barn ); // In the first bin ua_min_func = [](XIndepType x){return 1.25*cgs::centimeter;}; ua_max_func = [](XIndepType x){return 8.75*cgs::centimeter;}; FRENSIE_CHECK_EQUAL( evaluate( 0.5*MeV, 1.0*cgs::centimeter ), 0.0*barn ); FRENSIE_CHECK_FLOATING_EQUALITY( evaluate( 0.5*MeV, 1.25*cgs::centimeter ), 0.7*barn, 1e-15 ); FRENSIE_CHECK_FLOATING_EQUALITY( evaluate( 0.5*MeV, 5.0*cgs::centimeter ), 1.0*barn, 1e-6 ); FRENSIE_CHECK_FLOATING_EQUALITY( evaluate( 0.5*MeV, 8.75*cgs::centimeter ), 5.0/6.0*barn, 1e-15 ); FRENSIE_CHECK_EQUAL( evaluate( 0.5*MeV, 9.0*cgs::centimeter ), 0.0*barn ); // On the second bin boundary ++ua_lower_bin; ++ua_upper_bin; ua_min_func = [](XIndepType x){return 2.5*cgs::centimeter;}; ua_max_func = [](XIndepType x){return 7.5*cgs::centimeter;}; FRENSIE_CHECK_EQUAL( evaluate( 1.0*MeV, 2.0*cgs::centimeter ), 0.0*barn ); FRENSIE_CHECK_EQUAL( evaluate( 1.0*MeV, 2.5*cgs::centimeter ), 0.1*barn ); FRENSIE_CHECK_EQUAL( evaluate( 1.0*MeV, 5.0*cgs::centimeter ), 1.0*barn ); FRENSIE_CHECK_EQUAL( evaluate( 1.0*MeV, 7.5*cgs::centimeter ), 0.5*barn ); FRENSIE_CHECK_EQUAL( evaluate( 1.0*MeV, 8.0*cgs::centimeter ), 0.0*barn ); // In the second bin ua_min_func = [](XIndepType x){return 1.25*cgs::centimeter;}; ua_max_func = [](XIndepType x){return 8.75*cgs::centimeter;}; FRENSIE_CHECK_EQUAL( evaluate( 1.5*MeV, 1.0*cgs::centimeter ), 0.0*barn ); FRENSIE_CHECK_FLOATING_EQUALITY( evaluate( 1.5*MeV, 1.25*cgs::centimeter ), 0.1*barn, 1e-15 ); FRENSIE_CHECK_FLOATING_EQUALITY( evaluate( 1.5*MeV, 5.0*cgs::centimeter ), 0.4*barn, 1e-6 ); FRENSIE_CHECK_FLOATING_EQUALITY( evaluate( 1.5*MeV, 8.75*cgs::centimeter ), 7.0/30.0*barn, 1e-15 ); FRENSIE_CHECK_EQUAL( evaluate( 1.5*MeV, 9.0*cgs::centimeter ), 0.0*barn ); // On the upper bin boundary ua_min_func = [](XIndepType x){return 0.0*cgs::centimeter;}; ua_max_func = [](XIndepType x){return 10.0*cgs::centimeter;}; FRENSIE_CHECK_EQUAL( evaluate( 2.0*MeV, -1.0*cgs::centimeter ), 0.0*barn ); FRENSIE_CHECK_EQUAL( evaluate( 2.0*MeV, 0.0*cgs::centimeter ), 0.1*barn ); FRENSIE_CHECK_EQUAL( evaluate( 2.0*MeV, 5.0*cgs::centimeter ), 0.1*barn ); FRENSIE_CHECK_EQUAL( evaluate( 2.0*MeV, 10.0*cgs::centimeter ), 0.1*barn ); FRENSIE_CHECK_EQUAL( evaluate( 2.0*MeV, 11.0*cgs::centimeter ), 0.0*barn ); } //---------------------------------------------------------------------------// // Check that the distribution can be evaluated FRENSIE_UNIT_TEST( UnitBase, evaluateCDF ) { std::function<double(double,double)> evaluate = [&min_func, &max_func, &lower_bin, &upper_bin](double x_value, double y_value) { return Utility::UnitBase<Utility::LinLinLin>::evaluateCDF<Utility::TabularUnivariateDistribution,double,double>( x_value, y_value, min_func, max_func, &Utility::TabularUnivariateDistribution::evaluateCDF, lower_bin, upper_bin ); }; lower_bin = distribution->begin(); upper_bin = lower_bin; ++upper_bin; double x_value = 0.0; min_func = [](double x){return 0.0;}; max_func = [](double x){return 10.0;};; // On the first bin boundary FRENSIE_CHECK_EQUAL( evaluate( 0.0, -1.0 ), 0.0 ); FRENSIE_CHECK_EQUAL( evaluate( 0.0, 0.0 ), 0.0 ); FRENSIE_CHECK_EQUAL( evaluate( 0.0, 5.0 ), 0.5 ); FRENSIE_CHECK_EQUAL( evaluate( 0.0, 10.0 ), 1.0 ); FRENSIE_CHECK_EQUAL( evaluate( 0.0, 11.0 ), 1.0 ); // In the first bin min_func = [](double x){return 1.25;}; max_func = [](double x){return 8.75;}; FRENSIE_CHECK_EQUAL( evaluate( 0.5, 1.0 ), 0.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( evaluate( 0.5, 1.25 ), 0.0, 1e-15 ); FRENSIE_CHECK_FLOATING_EQUALITY( evaluate( 0.5, 5.0 ), 4.6153846153846156e-01, 1e-6 ); FRENSIE_CHECK_FLOATING_EQUALITY( evaluate( 0.5, 8.75 ), 1.0, 1e-15 ); FRENSIE_CHECK_EQUAL( evaluate( 0.5, 9.0 ), 1.0 ); // On the second bin boundary ++lower_bin; ++upper_bin; min_func = [](double x){return 2.5;}; max_func = [](double x){return 7.5;}; FRENSIE_CHECK_EQUAL( evaluate( 1.0, 2.0 ), 0.0 ); FRENSIE_CHECK_EQUAL( evaluate( 1.0, 2.5 ), 0.0 ); FRENSIE_CHECK_EQUAL( evaluate( 1.0, 5.0 ), 4.23076923076923128e-01 ); FRENSIE_CHECK_EQUAL( evaluate( 1.0, 7.5 ), 1.0 ); FRENSIE_CHECK_EQUAL( evaluate( 1.0, 8.0 ), 1.0 ); // In the second bin min_func = [](double x){return 1.25;}; max_func = [](double x){return 8.75;}; FRENSIE_CHECK_EQUAL( evaluate( 1.5, 1.0 ), 0.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( evaluate( 1.5, 1.25 ), 0.0, 1e-15 ); FRENSIE_CHECK_FLOATING_EQUALITY( evaluate( 1.5, 5.0 ), 4.6153846153846156e-01, 1e-6 ); FRENSIE_CHECK_FLOATING_EQUALITY( evaluate( 1.5, 8.75 ), 1.0, 1e-15 ); FRENSIE_CHECK_EQUAL( evaluate( 1.5, 9.0 ), 1.0 ); // On the upper bin boundary min_func = [](double x){return 0.0;}; max_func = [](double x){return 10.0;}; FRENSIE_CHECK_EQUAL( evaluate( 2.0, -1.0 ), 0.0 ); FRENSIE_CHECK_EQUAL( evaluate( 2.0, 0.0 ), 0.0 ); FRENSIE_CHECK_EQUAL( evaluate( 2.0, 5.0 ), 0.5 ); FRENSIE_CHECK_EQUAL( evaluate( 2.0, 10.0 ), 1.0 ); FRENSIE_CHECK_EQUAL( evaluate( 2.0, 11.0 ), 1.0 ); } //---------------------------------------------------------------------------// // Check that the unit-aware distribution can be evaluated FRENSIE_UNIT_TEST( UnitAwareUnitBase, evaluateCDF ) { std::function<double(XIndepType,YIndepType)> evaluate = [&ua_min_func, &ua_max_func, &ua_lower_bin, &ua_upper_bin](XIndepType x_value, YIndepType y_value) { return Utility::UnitBase<Utility::LinLinLin>::evaluateCDF<Utility::UnitAwareTabularUnivariateDistribution<cgs::length,Barn>,XIndepType,YIndepType>( x_value, y_value, ua_min_func, ua_max_func, &Utility::UnitAwareTabularUnivariateDistribution<cgs::length,Barn>::evaluateCDF, ua_lower_bin, ua_upper_bin ); }; ua_lower_bin = unit_aware_distribution->begin(); ua_upper_bin = ua_lower_bin; ++ua_upper_bin; ua_min_func = [](XIndepType x){return 0.0*cgs::centimeter;}; ua_max_func = [](XIndepType x){return 10.0*cgs::centimeter;}; // On the first bin boundary FRENSIE_CHECK_EQUAL( evaluate( 0.0*MeV, -1.0*cgs::centimeter ), 0.0); FRENSIE_CHECK_EQUAL( evaluate( 0.0*MeV, 0.0*cgs::centimeter ), 0.0 ); FRENSIE_CHECK_EQUAL( evaluate( 0.0*MeV, 5.0*cgs::centimeter ), 0.5 ); FRENSIE_CHECK_EQUAL( evaluate( 0.0*MeV, 10.0*cgs::centimeter ), 1.0 ); FRENSIE_CHECK_EQUAL( evaluate( 0.0*MeV, 11.0*cgs::centimeter ), 1.0 ); // In the first bin ua_min_func = [](XIndepType x){return 1.25*cgs::centimeter;}; ua_max_func = [](XIndepType x){return 8.75*cgs::centimeter;}; FRENSIE_CHECK_EQUAL( evaluate( 0.5*MeV, 1.0*cgs::centimeter ), 0.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( evaluate( 0.5*MeV, 1.25*cgs::centimeter ), 0.0, 1e-15 ); FRENSIE_CHECK_FLOATING_EQUALITY( evaluate( 0.5*MeV, 5.0*cgs::centimeter ), 4.6153846153846156e-01, 1e-6 ); FRENSIE_CHECK_FLOATING_EQUALITY( evaluate( 0.5*MeV, 8.75*cgs::centimeter ), 1.0, 1e-15 ); FRENSIE_CHECK_EQUAL( evaluate( 0.5*MeV, 9.0*cgs::centimeter ), 1.0 ); // On the second bin boundary ++ua_lower_bin; ++ua_upper_bin; ua_min_func = [](XIndepType x){return 2.5*cgs::centimeter;}; ua_max_func = [](XIndepType x){return 7.5*cgs::centimeter;}; FRENSIE_CHECK_EQUAL( evaluate( 1.0*MeV, 2.0*cgs::centimeter ), 0.0 ); FRENSIE_CHECK_EQUAL( evaluate( 1.0*MeV, 2.5*cgs::centimeter ), 0.0 ); FRENSIE_CHECK_EQUAL( evaluate( 1.0*MeV, 5.0*cgs::centimeter ), 4.23076923076923128e-01 ); FRENSIE_CHECK_EQUAL( evaluate( 1.0*MeV, 7.5*cgs::centimeter ), 1.0 ); FRENSIE_CHECK_EQUAL( evaluate( 1.0*MeV, 8.0*cgs::centimeter ), 1.0 ); // In the second bin ua_min_func = [](XIndepType x){return 1.25*cgs::centimeter;}; ua_max_func = [](XIndepType x){return 8.75*cgs::centimeter;}; FRENSIE_CHECK_EQUAL( evaluate( 1.5*MeV, 1.0*cgs::centimeter ), 0.0 ); FRENSIE_CHECK_FLOATING_EQUALITY( evaluate( 1.5*MeV, 1.25*cgs::centimeter ), 0.0, 1e-15 ); FRENSIE_CHECK_FLOATING_EQUALITY( evaluate( 1.5*MeV, 5.0*cgs::centimeter ), 4.6153846153846156e-01, 1e-6 ); FRENSIE_CHECK_FLOATING_EQUALITY( evaluate( 1.5*MeV, 8.75*cgs::centimeter ), 1.0, 1e-15 ); FRENSIE_CHECK_EQUAL( evaluate( 1.5*MeV, 9.0*cgs::centimeter ), 1.0 ); // On the upper bin boundary ua_min_func = [](XIndepType x){return 0.0*cgs::centimeter;}; ua_max_func = [](XIndepType x){return 10.0*cgs::centimeter;}; FRENSIE_CHECK_EQUAL( evaluate( 2.0*MeV, -1.0*cgs::centimeter ), 0.0 ); FRENSIE_CHECK_EQUAL( evaluate( 2.0*MeV, 0.0*cgs::centimeter ), 0.0 ); FRENSIE_CHECK_EQUAL( evaluate( 2.0*MeV, 5.0*cgs::centimeter ), 0.5 ); FRENSIE_CHECK_EQUAL( evaluate( 2.0*MeV, 10.0*cgs::centimeter ), 1.0 ); FRENSIE_CHECK_EQUAL( evaluate( 2.0*MeV, 11.0*cgs::centimeter ), 1.0 ); } //---------------------------------------------------------------------------// // Check that a secondary conditional PDF can be sampled FRENSIE_UNIT_TEST( UnitBase, sample ) { // On the first bin std::vector<double> fake_stream( 6 ); fake_stream[0] = 0.0; fake_stream[1] = 0.0; fake_stream[2] = 0.0; fake_stream[3] = 0.5; fake_stream[4] = 0.0; fake_stream[5] = 1.0-1e-15; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); lower_bin = distribution->begin(); upper_bin = lower_bin; ++upper_bin; double x_value = 0.0; min_func = [](double x){return 0.0;}; max_func = [](double x){return 10.0;}; double sample = Utility::UnitBase<Utility::LinLinLin>::sample<double,double>( functor, min_func, max_func, x_value, lower_bin, upper_bin ); FRENSIE_CHECK_EQUAL( sample, 0.0 ); sample = Utility::UnitBase<Utility::LinLinLin>::sample<double,double>( functor, min_func, max_func, x_value, lower_bin, upper_bin ); FRENSIE_CHECK_EQUAL( sample, 5.0 ); sample = Utility::UnitBase<Utility::LinLinLin>::sample<double,double>( functor, min_func, max_func, x_value, lower_bin, upper_bin ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-14 ); // In the first bin fake_stream.resize( 12 ); fake_stream[0] = 0.5; // use lower bin boundary fake_stream[1] = 0.0; fake_stream[2] = 0.5; // use lower bin boundary fake_stream[3] = 0.5; fake_stream[4] = 0.5; // use lower bin boundary fake_stream[5] = 1.0-1e-15; fake_stream[6] = 0.49; // use upper bin boundary fake_stream[7] = 0.0; fake_stream[8] = 0.49; // use upper bin boundary fake_stream[9] = 4.23076923076923128e-01; fake_stream[10] = 0.49; // use upper bin boundary fake_stream[11] = 1.0-1e-15; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); x_value = 0.5; min_func = [](double x){return 1.25;}; max_func = [](double x){return 8.75;}; // Samples from lower boundary of first bin sample = Utility::UnitBase<Utility::LinLinLin>::sample<double,double>( functor, min_func, max_func, x_value, lower_bin, upper_bin ); FRENSIE_CHECK_EQUAL( sample, 1.25 ); sample = Utility::UnitBase<Utility::LinLinLin>::sample<double,double>( functor, min_func, max_func, x_value, lower_bin, upper_bin ); FRENSIE_CHECK_EQUAL( sample, 5.0 ); sample = Utility::UnitBase<Utility::LinLinLin>::sample<double,double>( functor, min_func, max_func, x_value, lower_bin, upper_bin ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75, 1e-14 ); // Samples from the upper boundary of the first bin sample = Utility::UnitBase<Utility::LinLinLin>::sample<double,double>( functor, min_func, max_func, x_value, lower_bin, upper_bin ); FRENSIE_CHECK_EQUAL( sample, 1.25 ); sample = Utility::UnitBase<Utility::LinLinLin>::sample<double,double>( functor, min_func, max_func, x_value, lower_bin, upper_bin ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0, 1e-15 ); sample = Utility::UnitBase<Utility::LinLinLin>::sample<double,double>( functor, min_func, max_func, x_value, lower_bin, upper_bin ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75, 1e-14 ); // On the second bin fake_stream.resize( 6 ); fake_stream[0] = 0.0; fake_stream[1] = 0.0; fake_stream[2] = 0.0; fake_stream[3] = 4.23076923076923128e-01; fake_stream[4] = 0.0; fake_stream[5] = 1.0-1e-15; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); x_value = 1.0; min_func = [](double x){return 2.5;}; max_func = [](double x){return 7.5;}; sample = Utility::UnitBase<Utility::LinLinLin>::sample<double,double>( functor, min_func, max_func, x_value, lower_bin, upper_bin ); FRENSIE_CHECK_EQUAL( sample, 2.5 ); sample = Utility::UnitBase<Utility::LinLinLin>::sample<double,double>( functor, min_func, max_func, x_value, lower_bin, upper_bin ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0, 1e-15 ); sample = Utility::UnitBase<Utility::LinLinLin>::sample<double,double>( functor, min_func, max_func, x_value, lower_bin, upper_bin ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 7.5, 1e-15 ); // In the second bin ++lower_bin; ++upper_bin; fake_stream.resize( 12 ); fake_stream[0] = 0.5; // use lower bin boundary fake_stream[1] = 0.0; fake_stream[2] = 0.5; // use lower bin boundary fake_stream[3] = 4.23076923076923128e-01; fake_stream[4] = 0.5; // use lower bin boundary fake_stream[5] = 1.0-1e-15; fake_stream[6] = 0.49; // use upper bin boundary fake_stream[7] = 0.0; fake_stream[8] = 0.49; // use upper bin boundary fake_stream[9] = 0.5; fake_stream[10] = 0.49; // use upper bin boundary fake_stream[11] = 1.0-1e-15; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); x_value = 1.5; min_func = [](double x){return 1.25;}; max_func = [](double x){return 8.75;}; // Samples from lower boundary of second bin sample = Utility::UnitBase<Utility::LinLinLin>::sample<double,double>( functor, min_func, max_func, x_value, lower_bin, upper_bin ); FRENSIE_CHECK_EQUAL( sample, 1.25 ); sample = Utility::UnitBase<Utility::LinLinLin>::sample<double,double>( functor, min_func, max_func, x_value, lower_bin, upper_bin ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0, 1e-15 ); sample = Utility::UnitBase<Utility::LinLinLin>::sample<double,double>( functor, min_func, max_func, x_value, lower_bin, upper_bin ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75, 1e-14 ); // Samples from upper boundary of second bin sample = Utility::UnitBase<Utility::LinLinLin>::sample<double,double>( functor, min_func, max_func, x_value, lower_bin, upper_bin ); FRENSIE_CHECK_EQUAL( sample, 1.25 ); sample = Utility::UnitBase<Utility::LinLinLin>::sample<double,double>( functor, min_func, max_func, x_value, lower_bin, upper_bin ); FRENSIE_CHECK_EQUAL( sample, 5.0 ); sample = Utility::UnitBase<Utility::LinLinLin>::sample<double,double>( functor, min_func, max_func, x_value, lower_bin, upper_bin ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75, 1e-14 ); // On the upper bin boundary fake_stream.resize( 6 ); fake_stream[0] = 0.0; fake_stream[1] = 0.0; fake_stream[2] = 0.0; fake_stream[3] = 0.5; fake_stream[4] = 0.0; fake_stream[5] = 1.0-1e-15; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); x_value = 2.0; min_func = [](double x){return 0.0;}; max_func = [](double x){return 10.0;}; sample = Utility::UnitBase<Utility::LinLinLin>::sample<double,double>( functor, min_func, max_func, x_value, lower_bin, upper_bin ); FRENSIE_CHECK_EQUAL( sample, 0.0 ); sample = Utility::UnitBase<Utility::LinLinLin>::sample<double,double>( functor, min_func, max_func, x_value, lower_bin, upper_bin ); FRENSIE_CHECK_EQUAL( sample, 5.0 ); sample = Utility::UnitBase<Utility::LinLinLin>::sample<double,double>( functor, min_func, max_func, x_value, lower_bin, upper_bin ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-14 ); Utility::RandomNumberGenerator::unsetFakeStream(); } //---------------------------------------------------------------------------// // Check that a unit-aware secondary conditional PDF can be sampled FRENSIE_UNIT_TEST( UnitAwareUnitBase, sample ) { // On the first bin std::vector<double> fake_stream( 6 ); fake_stream[0] = 0.0; fake_stream[1] = 0.0; fake_stream[2] = 0.0; fake_stream[3] = 0.5; fake_stream[4] = 0.0; fake_stream[5] = 1.0-1e-15; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); ua_lower_bin = unit_aware_distribution->begin(); ua_upper_bin = ua_lower_bin; ++ua_upper_bin; quantity<MegaElectronVolt> x_value = 0.0*MeV; ua_min_func = [](quantity<MegaElectronVolt> x){return 0.0*cgs::centimeter;}; ua_max_func = [](quantity<MegaElectronVolt> x){return 10.0*cgs::centimeter;}; quantity<cgs::length> sample = Utility::UnitBase<Utility::LinLinLin>::sample<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, x_value, ua_lower_bin, ua_upper_bin ); FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter ); sample = Utility::UnitBase<Utility::LinLinLin>::sample<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, x_value, ua_lower_bin, ua_upper_bin ); FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter ); sample = Utility::UnitBase<Utility::LinLinLin>::sample<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, x_value, ua_lower_bin, ua_upper_bin ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-14 ); // In the first bin fake_stream.resize( 12 ); fake_stream[0] = 0.5; // use lower bin boundary fake_stream[1] = 0.0; fake_stream[2] = 0.5; // use lower bin boundary fake_stream[3] = 0.5; fake_stream[4] = 0.5; // use lower bin boundary fake_stream[5] = 1.0-1e-15; fake_stream[6] = 0.49; // use upper bin boundary fake_stream[7] = 0.0; fake_stream[8] = 0.49; // use upper bin boundary fake_stream[9] = 4.23076923076923128e-01; fake_stream[10] = 0.49; // use upper bin boundary fake_stream[11] = 1.0-1e-15; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); x_value = 0.5*MeV; ua_min_func = [](quantity<MegaElectronVolt> x){return 1.25*cgs::centimeter;}; ua_max_func = [](quantity<MegaElectronVolt> x){return 8.75*cgs::centimeter;}; // Samples from lower boundary of first bin sample = Utility::UnitBase<Utility::LinLinLin>::sample<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, x_value, ua_lower_bin, ua_upper_bin ); FRENSIE_CHECK_EQUAL( sample, 1.25*cgs::centimeter ); sample = Utility::UnitBase<Utility::LinLinLin>::sample<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, x_value, ua_lower_bin, ua_upper_bin ); FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter ); sample = Utility::UnitBase<Utility::LinLinLin>::sample<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, x_value, ua_lower_bin, ua_upper_bin ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75*cgs::centimeter, 1e-14 ); // Samples from the upper boundary of the first bin sample = Utility::UnitBase<Utility::LinLinLin>::sample<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, x_value, ua_lower_bin, ua_upper_bin ); FRENSIE_CHECK_EQUAL( sample, 1.25*cgs::centimeter ); sample = Utility::UnitBase<Utility::LinLinLin>::sample<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, x_value, ua_lower_bin, ua_upper_bin ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0*cgs::centimeter, 1e-15 ); sample = Utility::UnitBase<Utility::LinLinLin>::sample<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, x_value, ua_lower_bin, ua_upper_bin ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75*cgs::centimeter, 1e-14 ); // On the second bin fake_stream.resize( 6 ); fake_stream[0] = 0.0; fake_stream[1] = 0.0; fake_stream[2] = 0.0; fake_stream[3] = 4.23076923076923128e-01; fake_stream[4] = 0.0; fake_stream[5] = 1.0-1e-15; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); x_value = 1.0*MeV; ua_min_func = [](quantity<MegaElectronVolt> x){return 2.5*cgs::centimeter;}; ua_max_func = [](quantity<MegaElectronVolt> x){return 7.5*cgs::centimeter;}; sample = Utility::UnitBase<Utility::LinLinLin>::sample<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, x_value, ua_lower_bin, ua_upper_bin ); FRENSIE_CHECK_EQUAL( sample, 2.5*cgs::centimeter ); sample = Utility::UnitBase<Utility::LinLinLin>::sample<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, x_value, ua_lower_bin, ua_upper_bin ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0*cgs::centimeter, 1e-15 ); sample = Utility::UnitBase<Utility::LinLinLin>::sample<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, x_value, ua_lower_bin, ua_upper_bin ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 7.5*cgs::centimeter, 1e-15 ); // In the second bin ++ua_lower_bin; ++ua_upper_bin; fake_stream.resize( 12 ); fake_stream[0] = 0.5; // use lower bin boundary fake_stream[1] = 0.0; fake_stream[2] = 0.5; // use lower bin boundary fake_stream[3] = 4.23076923076923128e-01; fake_stream[4] = 0.5; // use lower bin boundary fake_stream[5] = 1.0-1e-15; fake_stream[6] = 0.49; // use upper bin boundary fake_stream[7] = 0.0; fake_stream[8] = 0.49; // use upper bin boundary fake_stream[9] = 0.5; fake_stream[10] = 0.49; // use upper bin boundary fake_stream[11] = 1.0-1e-15; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); x_value = 1.5*MeV; ua_min_func = [](quantity<MegaElectronVolt> x){return 1.25*cgs::centimeter;}; ua_max_func = [](quantity<MegaElectronVolt> x){return 8.75*cgs::centimeter;}; // Samples from lower boundary of second bin sample = Utility::UnitBase<Utility::LinLinLin>::sample<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, x_value, ua_lower_bin, ua_upper_bin ); FRENSIE_CHECK_EQUAL( sample, 1.25*cgs::centimeter ); sample = Utility::UnitBase<Utility::LinLinLin>::sample<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, x_value, ua_lower_bin, ua_upper_bin ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0*cgs::centimeter, 1e-15 ); sample = Utility::UnitBase<Utility::LinLinLin>::sample<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, x_value, ua_lower_bin, ua_upper_bin ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75*cgs::centimeter, 1e-14 ); // Samples from upper boundary of second bin sample = Utility::UnitBase<Utility::LinLinLin>::sample<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, x_value, ua_lower_bin, ua_upper_bin ); FRENSIE_CHECK_EQUAL( sample, 1.25*cgs::centimeter ); sample = Utility::UnitBase<Utility::LinLinLin>::sample<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, x_value, ua_lower_bin, ua_upper_bin ); FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter ); sample = Utility::UnitBase<Utility::LinLinLin>::sample<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, x_value, ua_lower_bin, ua_upper_bin ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75*cgs::centimeter, 1e-14 ); // On the upper bin boundary fake_stream.resize( 6 ); fake_stream[0] = 0.0; fake_stream[1] = 0.0; fake_stream[2] = 0.0; fake_stream[3] = 0.5;\ fake_stream[4] = 0.0; fake_stream[5] = 1.0-1e-15; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); x_value = 2.0*MeV; ua_min_func = [](quantity<MegaElectronVolt> x){return 0.0*cgs::centimeter;}; ua_max_func = [](quantity<MegaElectronVolt> x){return 10.0*cgs::centimeter;}; sample = Utility::UnitBase<Utility::LinLinLin>::sample<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, x_value, ua_lower_bin, ua_upper_bin ); FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter ); sample = Utility::UnitBase<Utility::LinLinLin>::sample<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, x_value, ua_lower_bin, ua_upper_bin ); FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter ); sample = Utility::UnitBase<Utility::LinLinLin>::sample<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, x_value, ua_lower_bin, ua_upper_bin ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-14 ); Utility::RandomNumberGenerator::unsetFakeStream(); } //---------------------------------------------------------------------------// // Check that a secondary conditional PDF can be sampled FRENSIE_UNIT_TEST( UnitBase, sampleDetailed ) { // On the first bin std::vector<double> fake_stream( 6 ); fake_stream[0] = 0.0; fake_stream[1] = 0.0; fake_stream[2] = 0.0; fake_stream[3] = 0.5; fake_stream[4] = 0.0; fake_stream[5] = 1.0-1e-15; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); double raw_sample; unsigned bin_index; start_bin = distribution->begin(); lower_bin = start_bin; upper_bin = lower_bin; ++upper_bin; min_func = [](double x){return 0.0;}; max_func = [](double x){return 10.0;}; double sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<double,double>( functor, min_func, max_func, 0.0, lower_bin, upper_bin, sampled_bin, raw_sample ); bin_index = std::distance( start_bin, sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 0u ); FRENSIE_CHECK_EQUAL( sample, 0.0 ); FRENSIE_CHECK_EQUAL( raw_sample, 0.0 ); sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<double,double>( functor, min_func, max_func, 0.0, lower_bin, upper_bin, sampled_bin, raw_sample ); bin_index = std::distance( start_bin, sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 0u ); FRENSIE_CHECK_EQUAL( sample, 5.0 ); FRENSIE_CHECK_EQUAL( raw_sample, 5.0 ); sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<double,double>( functor, min_func, max_func, 0.0, lower_bin, upper_bin, sampled_bin, raw_sample ); bin_index = std::distance( start_bin, sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 0u ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-14 ); FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 10.0, 1e-14 ); // In the first bin fake_stream.resize( 12 ); fake_stream[0] = 0.5; // use lower bin boundary fake_stream[1] = 0.0; fake_stream[2] = 0.5; // use lower bin boundary fake_stream[3] = 0.5; fake_stream[4] = 0.5; // use lower bin boundary fake_stream[5] = 1.0-1e-15; fake_stream[6] = 0.49; // use upper bin boundary fake_stream[7] = 0.0; fake_stream[8] = 0.49; // use upper bin boundary fake_stream[9] = 4.23076923076923128e-01; fake_stream[10] = 0.49; // use upper bin boundary fake_stream[11] = 1.0-1e-15; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); min_func = [](double x){return 1.25;}; max_func = [](double x){return 8.75;}; // Samples from lower boundary of first bin sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<double,double>( functor, min_func, max_func, 0.5, lower_bin, upper_bin, sampled_bin, raw_sample ); bin_index = std::distance( start_bin, sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 0u ); FRENSIE_CHECK_EQUAL( sample, 1.25 ); FRENSIE_CHECK_EQUAL( raw_sample, 0.0 ); sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<double,double>( functor, min_func, max_func, 0.5, lower_bin, upper_bin, sampled_bin, raw_sample ); bin_index = std::distance( start_bin, sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 0u ); FRENSIE_CHECK_EQUAL( sample, 5.0 ); FRENSIE_CHECK_EQUAL( raw_sample, 5.0 ); sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<double,double>( functor, min_func, max_func, 0.5, lower_bin, upper_bin, sampled_bin, raw_sample ); bin_index = std::distance( start_bin, sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 0u ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75, 1e-14 ); FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 10.0, 1e-14 ); // Samples from the upper boundary of the first bin sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<double,double>( functor, min_func, max_func, 0.5, lower_bin, upper_bin, sampled_bin, raw_sample ); bin_index = std::distance( start_bin, sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 1u ); FRENSIE_CHECK_EQUAL( sample, 1.25 ); FRENSIE_CHECK_EQUAL( raw_sample, 2.5 ); sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<double,double>( functor, min_func, max_func, 0.5, lower_bin, upper_bin, sampled_bin, raw_sample ); bin_index = std::distance( start_bin, sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 1u ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0, 1e-15 ); FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 5.0, 1e-15 ); sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<double,double>( functor, min_func, max_func, 0.5, lower_bin, upper_bin, sampled_bin, raw_sample ); bin_index = std::distance( start_bin, sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 1u ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75, 1e-14 ); FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 7.5, 1e-14 ); // On the second bin fake_stream.resize( 6 ); fake_stream[0] = 0.0; fake_stream[1] = 0.0; fake_stream[2] = 0.0; fake_stream[3] = 4.23076923076923128e-01; fake_stream[4] = 0.0; fake_stream[5] = 1.0-1e-15; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); min_func = [](double x){return 2.5;}; max_func = [](double x){return 7.5;}; sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<double,double>( functor, min_func, max_func, 1.0, lower_bin, upper_bin, sampled_bin, raw_sample ); bin_index = std::distance( start_bin, sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 1u ); FRENSIE_CHECK_EQUAL( sample, 2.5 ); FRENSIE_CHECK_EQUAL( raw_sample, 2.5 ); sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<double,double>( functor, min_func, max_func, 1.0, lower_bin, upper_bin, sampled_bin, raw_sample ); bin_index = std::distance( start_bin, sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 1u ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0, 1e-15 ); FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 5.0, 1e-15 ); sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<double,double>( functor, min_func, max_func, 1.0, lower_bin, upper_bin, sampled_bin, raw_sample ); bin_index = std::distance( start_bin, sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 1u ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 7.5, 1e-15 ); FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 7.5, 1e-15 ); // In the second bin ++lower_bin; ++upper_bin; fake_stream.resize( 12 ); fake_stream[0] = 0.5; // use lower bin boundary fake_stream[1] = 0.0; fake_stream[2] = 0.5; // use lower bin boundary fake_stream[3] = 4.23076923076923128e-01; fake_stream[4] = 0.5; // use lower bin boundary fake_stream[5] = 1.0-1e-15; fake_stream[6] = 0.49; // use upper bin boundary fake_stream[7] = 0.0; fake_stream[8] = 0.49; // use upper bin boundary fake_stream[9] = 0.5; fake_stream[10] = 0.49; // use upper bin boundary fake_stream[11] = 1.0-1e-15; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); min_func = [](double x){return 1.25;}; max_func = [](double x){return 8.75;}; // Samples from lower boundary of second bin sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<double,double>( functor, min_func, max_func, 1.5, lower_bin, upper_bin, sampled_bin, raw_sample ); bin_index = std::distance( start_bin, sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 1u ); FRENSIE_CHECK_EQUAL( sample, 1.25 ); FRENSIE_CHECK_EQUAL( raw_sample, 2.5 ); sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<double,double>( functor, min_func, max_func, 1.5, lower_bin, upper_bin, sampled_bin, raw_sample ); bin_index = std::distance( start_bin, sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 1u ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0, 1e-15 ); FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 5.0, 1e-15 ); sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<double,double>( functor, min_func, max_func, 1.5, lower_bin, upper_bin, sampled_bin, raw_sample ); bin_index = std::distance( start_bin, sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 1u ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75, 1e-14 ); FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 7.5, 1e-14 ); // Samples from upper boundary of second bin sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<double,double>( functor, min_func, max_func, 1.5, lower_bin, upper_bin, sampled_bin, raw_sample ); bin_index = std::distance( start_bin, sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 2u ); FRENSIE_CHECK_EQUAL( sample, 1.25 ); FRENSIE_CHECK_EQUAL( raw_sample, 0.0 ); sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<double,double>( functor, min_func, max_func, 1.5, lower_bin, upper_bin, sampled_bin, raw_sample ); bin_index = std::distance( start_bin, sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 2u ); FRENSIE_CHECK_EQUAL( sample, 5.0 ); FRENSIE_CHECK_EQUAL( raw_sample, 5.0 ); sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<double,double>( functor, min_func, max_func, 1.5, lower_bin, upper_bin, sampled_bin, raw_sample ); bin_index = std::distance( start_bin, sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 2u ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75, 1e-14 ); FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 10.0, 1e-14 ); // On the upper bin boundary fake_stream.resize( 6 ); fake_stream[0] = 0.0; fake_stream[1] = 0.0; fake_stream[2] = 0.0; fake_stream[3] = 0.5; fake_stream[4] = 0.0; fake_stream[5] = 1.0-1e-15; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); min_func = [](double x){return 0.0;}; max_func = [](double x){return 10.0;}; sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<double,double>( functor, min_func, max_func, 2.0, lower_bin, upper_bin, sampled_bin, raw_sample ); bin_index = std::distance( start_bin, sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 2u ); FRENSIE_CHECK_EQUAL( sample, 0.0 ); FRENSIE_CHECK_EQUAL( raw_sample, 0.0 ); sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<double,double>( functor, min_func, max_func, 2.0, lower_bin, upper_bin, sampled_bin, raw_sample ); bin_index = std::distance( start_bin, sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 2u ); FRENSIE_CHECK_EQUAL( sample, 5.0 ); FRENSIE_CHECK_EQUAL( raw_sample, 5.0 ); sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<double,double>( functor, min_func, max_func, 2.0, lower_bin, upper_bin, sampled_bin, raw_sample ); bin_index = std::distance( start_bin, sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 2u ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0, 1e-14 ); FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 10.0, 1e-14 ); Utility::RandomNumberGenerator::unsetFakeStream(); } //---------------------------------------------------------------------------// // Check that a unit-aware secondary conditional PDF can be sampled FRENSIE_UNIT_TEST( UnitAwareUnitBase, sampleDetailed ) { // On the first bin std::vector<double> fake_stream( 6 ); fake_stream[0] = 0.0; fake_stream[1] = 0.0; fake_stream[2] = 0.0; fake_stream[3] = 0.5; fake_stream[4] = 0.0; fake_stream[5] = 1.0-1e-15; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); unsigned bin_index; quantity<cgs::length> raw_sample; ua_start_bin = unit_aware_distribution->begin(); ua_lower_bin = ua_start_bin; ua_upper_bin = ua_lower_bin; ++ua_upper_bin; ua_min_func = [](quantity<MegaElectronVolt> x){return 0.0*cgs::centimeter;}; ua_max_func = [](quantity<MegaElectronVolt> x){return 10.0*cgs::centimeter;}; quantity<cgs::length> sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, 0.0*MeV, ua_lower_bin, ua_upper_bin, ua_sampled_bin, raw_sample ); bin_index = std::distance( ua_start_bin, ua_sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 0u ); FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter ); FRENSIE_CHECK_EQUAL( raw_sample, 0.0*cgs::centimeter ); sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, 0.0*MeV, ua_lower_bin, ua_upper_bin, ua_sampled_bin, raw_sample ); bin_index = std::distance( ua_start_bin, ua_sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 0u ); FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter ); FRENSIE_CHECK_EQUAL( raw_sample, 5.0*cgs::centimeter ); sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, 0.0*MeV, ua_lower_bin, ua_upper_bin, ua_sampled_bin, raw_sample ); bin_index = std::distance( ua_start_bin, ua_sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 0u ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-14 ); FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 10.0*cgs::centimeter, 1e-14 ); // In the first bin fake_stream.resize( 12 ); fake_stream[0] = 0.5; // use lower bin boundary fake_stream[1] = 0.0; fake_stream[2] = 0.5; // use lower bin boundary fake_stream[3] = 0.5; fake_stream[4] = 0.5; // use lower bin boundary fake_stream[5] = 1.0-1e-15; fake_stream[6] = 0.49; // use upper bin boundary fake_stream[7] = 0.0; fake_stream[8] = 0.49; // use upper bin boundary fake_stream[9] = 4.23076923076923128e-01; fake_stream[10] = 0.49; // use upper bin boundary fake_stream[11] = 1.0-1e-15; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); ua_min_func = [](quantity<MegaElectronVolt> x){return 1.25*cgs::centimeter;}; ua_max_func = [](quantity<MegaElectronVolt> x){return 8.75*cgs::centimeter;}; // Samples from lower boundary of first bin sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, 0.5*MeV, ua_lower_bin, ua_upper_bin, ua_sampled_bin, raw_sample ); bin_index = std::distance( ua_start_bin, ua_sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 0u ); FRENSIE_CHECK_EQUAL( sample, 1.25*cgs::centimeter ); FRENSIE_CHECK_EQUAL( raw_sample, 0.0*cgs::centimeter ); sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, 0.5*MeV, ua_lower_bin, ua_upper_bin, ua_sampled_bin, raw_sample ); bin_index = std::distance( ua_start_bin, ua_sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 0u ); FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter ); FRENSIE_CHECK_EQUAL( raw_sample, 5.0*cgs::centimeter ); sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, 0.5*MeV, ua_lower_bin, ua_upper_bin, ua_sampled_bin, raw_sample ); bin_index = std::distance( ua_start_bin, ua_sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 0u ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75*cgs::centimeter, 1e-14 ); FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 10.0*cgs::centimeter, 1e-14 ); // Samples from the upper boundary of the first bin sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, 0.5*MeV, ua_lower_bin, ua_upper_bin, ua_sampled_bin, raw_sample ); bin_index = std::distance( ua_start_bin, ua_sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 1u ); FRENSIE_CHECK_EQUAL( sample, 1.25*cgs::centimeter ); FRENSIE_CHECK_EQUAL( raw_sample, 2.5*cgs::centimeter ); sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, 0.5*MeV, ua_lower_bin, ua_upper_bin, ua_sampled_bin, raw_sample ); bin_index = std::distance( ua_start_bin, ua_sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 1u ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0*cgs::centimeter, 1e-15 ); FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 5.0*cgs::centimeter, 1e-15 ); sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, 0.5*MeV, ua_lower_bin, ua_upper_bin, ua_sampled_bin, raw_sample ); bin_index = std::distance( ua_start_bin, ua_sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 1u ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75*cgs::centimeter, 1e-14 ); FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 7.5*cgs::centimeter, 1e-14 ); // On the second bin fake_stream.resize( 6 ); fake_stream[0] = 0.0; fake_stream[1] = 0.0; fake_stream[2] = 0.0; fake_stream[3] = 4.23076923076923128e-01; fake_stream[4] = 0.0; fake_stream[5] = 1.0-1e-15; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); ua_min_func = [](quantity<MegaElectronVolt> x){return 2.5*cgs::centimeter;}; ua_max_func = [](quantity<MegaElectronVolt> x){return 7.5*cgs::centimeter;}; sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, 1.0*MeV, ua_lower_bin, ua_upper_bin, ua_sampled_bin, raw_sample ); bin_index = std::distance( ua_start_bin, ua_sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 1u ); FRENSIE_CHECK_EQUAL( sample, 2.5*cgs::centimeter ); FRENSIE_CHECK_EQUAL( raw_sample, 2.5*cgs::centimeter ); sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, 1.0*MeV, ua_lower_bin, ua_upper_bin, ua_sampled_bin, raw_sample ); bin_index = std::distance( ua_start_bin, ua_sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 1u ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0*cgs::centimeter, 1e-15 ); FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 5.0*cgs::centimeter, 1e-15 ); sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, 1.0*MeV, ua_lower_bin, ua_upper_bin, ua_sampled_bin, raw_sample ); bin_index = std::distance( ua_start_bin, ua_sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 1u ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 7.5*cgs::centimeter, 1e-15 ); FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 7.5*cgs::centimeter, 1e-15 ); // In the second bin ++ua_lower_bin; ++ua_upper_bin; fake_stream.resize( 12 ); fake_stream[0] = 0.5; // use lower bin boundary fake_stream[1] = 0.0; fake_stream[2] = 0.5; // use lower bin boundary fake_stream[3] = 4.23076923076923128e-01; fake_stream[4] = 0.5; // use lower bin boundary fake_stream[5] = 1.0-1e-15; fake_stream[6] = 0.49; // use upper bin boundary fake_stream[7] = 0.0; fake_stream[8] = 0.49; // use upper bin boundary fake_stream[9] = 0.5; fake_stream[10] = 0.49; // use upper bin boundary fake_stream[11] = 1.0-1e-15; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); ua_min_func = [](quantity<MegaElectronVolt> x){return 1.25*cgs::centimeter;}; ua_max_func = [](quantity<MegaElectronVolt> x){return 8.75*cgs::centimeter;}; // Samples from lower boundary of second bin sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, 1.5*MeV, ua_lower_bin, ua_upper_bin, ua_sampled_bin, raw_sample ); bin_index = std::distance( ua_start_bin, ua_sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 1u ); FRENSIE_CHECK_EQUAL( sample, 1.25*cgs::centimeter ); FRENSIE_CHECK_EQUAL( raw_sample, 2.5*cgs::centimeter ); sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, 1.5*MeV, ua_lower_bin, ua_upper_bin, ua_sampled_bin, raw_sample ); bin_index = std::distance( ua_start_bin, ua_sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 1u ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 5.0*cgs::centimeter, 1e-15 ); FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 5.0*cgs::centimeter, 1e-15 ); sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, 1.5*MeV, ua_lower_bin, ua_upper_bin, ua_sampled_bin, raw_sample ); bin_index = std::distance( ua_start_bin, ua_sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 1u ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75*cgs::centimeter, 1e-14 ); FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 7.5*cgs::centimeter, 1e-14 ); // Samples from upper boundary of second bin sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, 1.5*MeV, ua_lower_bin, ua_upper_bin, ua_sampled_bin, raw_sample ); bin_index = std::distance( ua_start_bin, ua_sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 2u ); FRENSIE_CHECK_EQUAL( sample, 1.25*cgs::centimeter ); FRENSIE_CHECK_EQUAL( raw_sample, 0.0*cgs::centimeter ); sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, 1.5*MeV, ua_lower_bin, ua_upper_bin, ua_sampled_bin, raw_sample ); bin_index = std::distance( ua_start_bin, ua_sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 2u ); FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter ); FRENSIE_CHECK_EQUAL( raw_sample, 5.0*cgs::centimeter ); sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, 1.5*MeV, ua_lower_bin, ua_upper_bin, ua_sampled_bin, raw_sample ); bin_index = std::distance( ua_start_bin, ua_sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 2u ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 8.75*cgs::centimeter, 1e-14 ); FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 10.0*cgs::centimeter, 1e-14 ); // On the upper bin boundary fake_stream.resize( 6 ); fake_stream[0] = 0.0; fake_stream[1] = 0.0; fake_stream[2] = 0.0; fake_stream[3] = 0.5; fake_stream[4] = 0.0; fake_stream[5] = 1.0-1e-15; Utility::RandomNumberGenerator::setFakeStream( fake_stream ); ua_min_func = [](quantity<MegaElectronVolt> x){return 0.0*cgs::centimeter;}; ua_max_func = [](quantity<MegaElectronVolt> x){return 10.0*cgs::centimeter;}; sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, 2.0*MeV, ua_lower_bin, ua_upper_bin, ua_sampled_bin, raw_sample ); bin_index = std::distance( ua_start_bin, ua_sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 2u ); FRENSIE_CHECK_EQUAL( sample, 0.0*cgs::centimeter ); FRENSIE_CHECK_EQUAL( raw_sample, 0.0*cgs::centimeter ); sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, 2.0*MeV, ua_lower_bin, ua_upper_bin, ua_sampled_bin, raw_sample ); bin_index = std::distance( ua_start_bin, ua_sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 2u ); FRENSIE_CHECK_EQUAL( sample, 5.0*cgs::centimeter ); FRENSIE_CHECK_EQUAL( raw_sample, 5.0*cgs::centimeter ); sample = Utility::UnitBase<Utility::LinLinLin>::sampleDetailed<XIndepType,YIndepType>( ua_functor, ua_min_func, ua_max_func, 2.0*MeV, ua_lower_bin, ua_upper_bin, ua_sampled_bin, raw_sample ); bin_index = std::distance( ua_start_bin, ua_sampled_bin ); FRENSIE_CHECK_EQUAL( bin_index, 2u ); FRENSIE_CHECK_FLOATING_EQUALITY( sample, 10.0*cgs::centimeter, 1e-14 ); FRENSIE_CHECK_FLOATING_EQUALITY( raw_sample, 10.0*cgs::centimeter, 1e-14 ); Utility::RandomNumberGenerator::unsetFakeStream(); } //---------------------------------------------------------------------------// // Custom setup //---------------------------------------------------------------------------// FRENSIE_CUSTOM_UNIT_TEST_SETUP_BEGIN(); FRENSIE_CUSTOM_UNIT_TEST_INIT() { // Create the two-dimensional distribution { DistributionType distribution_data( 3 ); // Create the secondary distribution in the first bin Utility::get<0>( distribution_data[0] ) = 0.0; Utility::get<1>( distribution_data[0] ) = std::make_shared<Utility::UniformDistribution>( 0.0, 10.0, 1.0 ); // Create the secondary distribution in the second bin std::vector<double> bin_boundaries( 3 ), values( 3 ); bin_boundaries[0] = 2.5; values[0] = 0.1; bin_boundaries[1] = 5.0; values[1] = 1.0; bin_boundaries[2] = 7.5; values[2] = 0.5; Utility::get<0>( distribution_data[1] ) = 1.0; Utility::get<1>( distribution_data[1] ) = std::make_shared<Utility::TabularDistribution<Utility::LinLin> >( bin_boundaries, values ); // Create the secondary distribution beyond the second bin Utility::get<0>( distribution_data[2] ) = 2.0; Utility::get<1>( distribution_data[2] ) = std::make_shared<Utility::UniformDistribution>( 0.0, 10.0, 0.1 ); distribution.reset( new DistributionType( distribution_data ) ); // Create the sampling functor functor = std::bind<double>( &Utility::TabularUnivariateDistribution::sample, std::placeholders::_1 ); threshold_functor =std::bind<double>( &Utility::TabularUnivariateDistribution::sampleWithRandomNumber, std::placeholders::_1, std::placeholders::_2 ); } // Create the unit-aware two-dimensional distribution { UnitAwareDistributionType distribution_data( 3 ); // Create the secondary distribution in the first bin Utility::get<0>( distribution_data[0] ) = 0.0*MeV; Utility::get<1>( distribution_data[0] ) = std::make_shared<Utility::UnitAwareUniformDistribution<cgs::length,Barn> >( 0.0*cgs::centimeter, 10.0*cgs::centimeter, 1.0*barn ); // Create the secondary distribution in the second bin std::vector<quantity<cgs::length> > bin_boundaries( 3 ); std::vector<quantity<Barn> > values( 3 ); bin_boundaries[0] = 2.5*cgs::centimeter; values[0] = 0.1*barn; bin_boundaries[1] = 5.0*cgs::centimeter; values[1] = 1.0*barn; bin_boundaries[2] = 7.5*cgs::centimeter; values[2] = 0.5*barn; Utility::get<0>( distribution_data[1] ) = 1.0*MeV; Utility::get<1>( distribution_data[1] ) = std::make_shared<Utility::UnitAwareTabularDistribution<Utility::LinLin,cgs::length,Barn> >( bin_boundaries, values ); // Create the secondary distribution beyond the second bin Utility::get<0>( distribution_data[2] ) = 2.0*MeV; Utility::get<1>( distribution_data[2] ) = std::make_shared<Utility::UnitAwareUniformDistribution<cgs::length,Barn> >( 0.0*cgs::centimeter, 10.0*cgs::centimeter, 0.1*barn ); unit_aware_distribution.reset( new UnitAwareDistributionType( distribution_data ) ); // Create the sampling functor ua_functor = std::bind<YIndepType>( &Utility::UnitAwareTabularUnivariateDistribution<cgs::length,Barn>::sample, std::placeholders::_1 ); ua_threshold_functor = std::bind<YIndepType>( &Utility::UnitAwareTabularUnivariateDistribution<cgs::length,Barn>::sampleWithRandomNumber, std::placeholders::_1, std::placeholders::_2 ); } // Initialize the random number generator Utility::RandomNumberGenerator::createStreams(); } FRENSIE_CUSTOM_UNIT_TEST_SETUP_END(); //---------------------------------------------------------------------------// // end tstUnitBaseTwoDGridPolicy.cpp //---------------------------------------------------------------------------//
43.421016
228
0.687047
[ "vector" ]
e55905a019ca7fc7c190ba5a402340f3407e76ff
3,700
hpp
C++
include/veriblock/entities/vbktx.hpp
Dmytro-Kyparenko/alt-integration-cpp
df18abdd4bfeec757c2df47efcaf4020d78880bb
[ "MIT" ]
null
null
null
include/veriblock/entities/vbktx.hpp
Dmytro-Kyparenko/alt-integration-cpp
df18abdd4bfeec757c2df47efcaf4020d78880bb
[ "MIT" ]
null
null
null
include/veriblock/entities/vbktx.hpp
Dmytro-Kyparenko/alt-integration-cpp
df18abdd4bfeec757c2df47efcaf4020d78880bb
[ "MIT" ]
null
null
null
// Copyright (c) 2019-2020 Xenios SEZC // https://www.veriblock.org // Distributed under the MIT software license, see the accompanying // file LICENSE or http://www.opensource.org/licenses/mit-license.php. #ifndef ALT_INTEGRATION_INCLUDE_VERIBLOCK_ENTITIES_VBKTX_HPP_ #define ALT_INTEGRATION_INCLUDE_VERIBLOCK_ENTITIES_VBKTX_HPP_ #include <cstdint> #include <vector> #include "veriblock/consts.hpp" #include "veriblock/entities/address.hpp" #include "veriblock/entities/coin.hpp" #include "veriblock/entities/output.hpp" #include "veriblock/entities/publication_data.hpp" #include "veriblock/hashutil.hpp" #include "veriblock/serde.hpp" #include "veriblock/slice.hpp" #include "veriblock/uint.hpp" namespace altintegration { /** * @struct VbkTx * * Veriblock transaction, which endorses ALT block in VBK blockchain. * * @ingroup entities */ struct VbkTx { using hash_t = uint256; NetworkBytePair networkOrType{}; Address sourceAddress{}; Coin sourceAmount{}; std::vector<Output> outputs{}; int64_t signatureIndex{}; PublicationData publicationData{}; std::vector<uint8_t> signature{}; std::vector<uint8_t> publicKey{}; /** * Read basic data from the stream, signature, publicKey and convert it to * VbkTx * @param stream data stream to read from * @param _signature bytes * @param _publicKey bytes * @return VbkTx */ static VbkTx fromRaw(ReadStream& stream, Slice<const uint8_t> _signature, Slice<const uint8_t> _publicKey); /** * Read VBK data from the stream and convert it to VbkTx * @param stream data stream to read from * @return VbkTx */ static VbkTx fromVbkEncoding(ReadStream& stream); /** * Convert VbkTx to data stream using VbkTx basic byte format without * signature and publicKey data * @param stream data stream to write into */ void toRaw(WriteStream& stream) const; /** * Convert VbkTx to data stream using VbkTx VBK byte format * @param stream data stream to write into */ void toVbkEncoding(WriteStream& stream) const; /** * Calculate the hash of the vbk transaction * @return hash vbk transaction hash */ uint256 getHash() const; }; template <typename JsonValue> JsonValue ToJSON(const VbkTx& tx) { JsonValue obj = json::makeEmptyObject<JsonValue>(); if (tx.networkOrType.hasNetworkByte) { json::putIntKV(obj, "networkByte", tx.networkOrType.networkByte); } else { json::putNullKV(obj, "networkByte"); } json::putStringKV(obj, "hash", tx.getHash().toHex()); json::putIntKV(obj, "type", tx.networkOrType.typeId); json::putStringKV(obj, "sourceAddress", tx.sourceAddress.toString()); json::putIntKV(obj, "sourceAmount", tx.sourceAmount.units); json::putArrayKV(obj, "outputs", tx.outputs); json::putIntKV(obj, "signatureIndex", tx.signatureIndex); json::putKV(obj, "publicationData", ToJSON<JsonValue>(tx.publicationData)); json::putStringKV(obj, "signature", HexStr(tx.signature)); json::putStringKV(obj, "publicKey", HexStr(tx.publicKey)); return obj; } bool DeserializeRaw(ReadStream& stream, Slice<const uint8_t> signature, Slice<const uint8_t> publicKey, VbkTx& out, ValidationState& state); bool DeserializeRaw(Slice<const uint8_t> data, Slice<const uint8_t> signature, Slice<const uint8_t> publicKey, VbkTx& out, ValidationState& state); bool Deserialize(ReadStream& stream, VbkTx& out, ValidationState& state); } // namespace altintegration #endif // ALT_INTEGRATION_INCLUDE_VERIBLOCK_ENTITIES_VBKTX_HPP_
31.092437
77
0.697297
[ "vector" ]
e561f3f845f45a55129527606deecd96e6f3fc4d
1,308
cpp
C++
src/methods/kcm.cpp
danny305/ChargeFW2
c68fd06b9af244e5d8ed9172de17748e587bf46e
[ "MIT" ]
7
2020-05-19T15:14:15.000Z
2022-03-03T06:38:09.000Z
src/methods/kcm.cpp
danny305/ChargeFW2
c68fd06b9af244e5d8ed9172de17748e587bf46e
[ "MIT" ]
10
2021-03-04T21:38:49.000Z
2022-02-11T07:11:19.000Z
src/methods/kcm.cpp
danny305/ChargeFW2
c68fd06b9af244e5d8ed9172de17748e587bf46e
[ "MIT" ]
5
2021-03-05T00:42:41.000Z
2021-07-01T05:47:39.000Z
// // Created by krab1k on 31/10/18. // #include <vector> #include <cmath> #include <Eigen/LU> #include "kcm.h" #include "../structures/molecule.h" #include "../parameters.h" CHARGEFW2_METHOD(KCM) std::vector<double> KCM::calculate_charges(const Molecule &molecule) const { size_t n = molecule.atoms().size(); size_t m = molecule.bonds().size(); Eigen::MatrixXd W = Eigen::MatrixXd::Zero(m, m); Eigen::MatrixXd B = Eigen::MatrixXd::Zero(m, n); Eigen::VectorXd chi0 = Eigen::VectorXd::Zero(n); /* Compute * q = (B.T @ W @ B + I)^-1 @ chi0 - chi0 */ for (size_t i = 0; i < n; i++) { chi0(i) = parameters_->atom()->parameter(atom::electronegativity)(molecule.atoms()[i]); } for (size_t i = 0; i < m; i++) { auto &bond = molecule.bonds()[i]; auto &first = bond.first(); auto &second = bond.second(); W(i, i) = 1 / (parameters_->atom()->parameter(atom::hardness)(first) + parameters_->atom()->parameter(atom::hardness)(second)); B(i, first.index()) = 1; B(i, second.index()) = -1; } Eigen::VectorXd q = (B.transpose() * W * B + Eigen::MatrixXd::Identity(n, n)).partialPivLu().solve(chi0) - chi0; return std::vector<double>(q.data(), q.data() + q.size()); }
27.25
116
0.568807
[ "vector" ]
e562f4b15469403396290dac50d3fb5b7c27437a
6,427
cc
C++
third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_descriptor.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_descriptor.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_descriptor.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_descriptor.h" #include <utility> #include "third_party/blink/renderer/bindings/core/v8/script_promise.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" #include "third_party/blink/renderer/core/dom/dom_exception.h" #include "third_party/blink/renderer/modules/bluetooth/bluetooth_error.h" #include "third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_service.h" #include "third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_utils.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/heap/garbage_collected.h" #include "third_party/blink/renderer/platform/wtf/functional.h" namespace blink { BluetoothRemoteGATTDescriptor::BluetoothRemoteGATTDescriptor( mojom::blink::WebBluetoothRemoteGATTDescriptorPtr descriptor, BluetoothRemoteGATTCharacteristic* characteristic) : descriptor_(std::move(descriptor)), characteristic_(characteristic) {} void BluetoothRemoteGATTDescriptor::ReadValueCallback( ScriptPromiseResolver* resolver, mojom::blink::WebBluetoothResult result, const absl::optional<Vector<uint8_t>>& value) { if (!resolver->GetExecutionContext() || resolver->GetExecutionContext()->IsContextDestroyed()) return; // If the device is disconnected, reject. if (!GetGatt()->RemoveFromActiveAlgorithms(resolver)) { resolver->Reject( BluetoothError::CreateNotConnectedException(BluetoothOperation::kGATT)); return; } if (result == mojom::blink::WebBluetoothResult::SUCCESS) { DCHECK(value); DOMDataView* dom_data_view = BluetoothRemoteGATTUtils::ConvertWTFVectorToDataView(value.value()); value_ = dom_data_view; resolver->Resolve(dom_data_view); } else { resolver->Reject(BluetoothError::CreateDOMException(result)); } } ScriptPromise BluetoothRemoteGATTDescriptor::readValue( ScriptState* script_state, ExceptionState& exception_state) { if (!GetGatt()->connected()) { exception_state.ThrowDOMException( DOMExceptionCode::kNetworkError, BluetoothError::CreateNotConnectedExceptionMessage( BluetoothOperation::kGATT)); return ScriptPromise(); } if (!GetGatt()->device()->IsValidDescriptor(descriptor_->instance_id)) { exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError, CreateInvalidDescriptorErrorMessage()); return ScriptPromise(); } auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); ScriptPromise promise = resolver->Promise(); GetGatt()->AddToActiveAlgorithms(resolver); GetService()->RemoteDescriptorReadValue( descriptor_->instance_id, WTF::Bind(&BluetoothRemoteGATTDescriptor::ReadValueCallback, WrapPersistent(this), WrapPersistent(resolver))); return promise; } void BluetoothRemoteGATTDescriptor::WriteValueCallback( ScriptPromiseResolver* resolver, const Vector<uint8_t>& value, mojom::blink::WebBluetoothResult result) { if (!resolver->GetExecutionContext() || resolver->GetExecutionContext()->IsContextDestroyed()) return; // If the resolver is not in the set of ActiveAlgorithms then the frame // disconnected so we reject. if (!GetGatt()->RemoveFromActiveAlgorithms(resolver)) { resolver->Reject( BluetoothError::CreateNotConnectedException(BluetoothOperation::kGATT)); return; } if (result == mojom::blink::WebBluetoothResult::SUCCESS) { value_ = BluetoothRemoteGATTUtils::ConvertWTFVectorToDataView(value); resolver->Resolve(); } else { resolver->Reject(BluetoothError::CreateDOMException(result)); } } ScriptPromise BluetoothRemoteGATTDescriptor::writeValue( ScriptState* script_state, const DOMArrayPiece& value, ExceptionState& exception_state) { if (!GetGatt()->connected()) { exception_state.ThrowDOMException( DOMExceptionCode::kNetworkError, BluetoothError::CreateNotConnectedExceptionMessage( BluetoothOperation::kGATT)); return ScriptPromise(); } if (!GetGatt()->device()->IsValidDescriptor(descriptor_->instance_id)) { exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError, CreateInvalidDescriptorErrorMessage()); return ScriptPromise(); } if (value.IsDetached()) { exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError, "Value buffer has been detached."); return ScriptPromise(); } // Partial implementation of writeValue algorithm: // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattdescriptor-writevalue // If bytes is more than 512 bytes long (the maximum length of an attribute // value, per Long Attribute Values) return a promise rejected with an // InvalidModificationError and abort. if (value.ByteLength() > 512) { exception_state.ThrowDOMException( DOMExceptionCode::kInvalidModificationError, "Value can't exceed 512 bytes."); return ScriptPromise(); } // Let valueVector be a copy of the bytes held by value. Vector<uint8_t> value_vector; value_vector.Append(value.Bytes(), static_cast<wtf_size_t>(value.ByteLength())); auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); ScriptPromise promise = resolver->Promise(); GetGatt()->AddToActiveAlgorithms(resolver); GetService()->RemoteDescriptorWriteValue( descriptor_->instance_id, value_vector, WTF::Bind(&BluetoothRemoteGATTDescriptor::WriteValueCallback, WrapPersistent(this), WrapPersistent(resolver), value_vector)); return promise; } String BluetoothRemoteGATTDescriptor::CreateInvalidDescriptorErrorMessage() { return "Descriptor with UUID " + uuid() + " is no longer valid. Remember to retrieve the Descriptor again " "after reconnecting."; } void BluetoothRemoteGATTDescriptor::Trace(Visitor* visitor) const { visitor->Trace(characteristic_); visitor->Trace(value_); ScriptWrappable::Trace(visitor); } } // namespace blink
37.805882
97
0.740314
[ "vector" ]
e567fc2a12ab157415276fe3f0759da06b6c77d1
21,274
cpp
C++
UI/Dialogs/MFCUtilityFunctions.cpp
stephenegriffin/mfcmapi
bffbff6da9a8c292891568159c8088aac9b2052c
[ "MIT" ]
655
2016-10-13T20:18:52.000Z
2022-03-28T21:25:14.000Z
UI/Dialogs/MFCUtilityFunctions.cpp
stephenegriffin/mfcmapi
bffbff6da9a8c292891568159c8088aac9b2052c
[ "MIT" ]
285
2016-10-18T19:03:31.000Z
2022-03-10T11:02:33.000Z
UI/Dialogs/MFCUtilityFunctions.cpp
stephenegriffin/mfcmapi
bffbff6da9a8c292891568159c8088aac9b2052c
[ "MIT" ]
129
2016-10-14T14:27:24.000Z
2022-03-30T12:34:01.000Z
// Common functions for MFCMAPI #include <StdAfx.h> #include <UI/Dialogs/MFCUtilityFunctions.h> #include <core/mapi/mapiStoreFunctions.h> #include <core/mapi/columnTags.h> #include <UI/Dialogs/BaseDialog.h> #include <core/mapi/cache/mapiObjects.h> #include <UI/Dialogs/Editors/Editor.h> #include <core/smartview/SmartView.h> #include <core/interpret/guid.h> #include <UI/Dialogs/HierarchyTable/MsgStoreDlg.h> #include <UI/Dialogs/ContentsTable/FolderDlg.h> #include <UI/Dialogs/ContentsTable/RecipientsDlg.h> #include <UI/Dialogs/ContentsTable/AttachmentsDlg.h> #include <UI/Dialogs/propList/SingleMessageDialog.h> #include <UI/Dialogs/propList/SingleRecipientDialog.h> #include <UI/Dialogs/ContentsTable/ABDlg.h> #include <UI/Dialogs/ContentsTable/RulesDlg.h> #include <UI/Dialogs/ContentsTable/AclDlg.h> #include <UI/Dialogs/ContentsTable/MailboxTableDlg.h> #include <UI/Dialogs/ContentsTable/PublicFolderTableDlg.h> #include <core/utility/registry.h> #include <core/mapi/mapiOutput.h> #include <core/utility/strings.h> #include <core/utility/output.h> #include <core/mapi/mapiFunctions.h> namespace dialog { _Check_return_ HRESULT DisplayObject(_In_ LPMAPIPROP lpUnk, ULONG ulObjType, objectType tType, _In_ CBaseDialog* lpHostDlg) { if (!lpHostDlg || !lpUnk) return MAPI_E_INVALID_PARAMETER; auto lpMapiObjects = lpHostDlg->GetMapiObjects(); // do not release if (!lpMapiObjects) return MAPI_E_INVALID_PARAMETER; const auto lpParentWnd = ui::GetParentWnd(); // do not release if (!lpParentWnd) return MAPI_E_INVALID_PARAMETER; // If we weren't passed an object type, go get one - careful! Some objects lie! if (!ulObjType) { ulObjType = mapi::GetMAPIObjectType(lpUnk); } auto szFlags = smartview::InterpretNumberAsStringProp(ulObjType, PR_OBJECT_TYPE); output::DebugPrint( output::dbgLevel::Generic, L"DisplayObject asked to display %p, with objectType of 0x%08X and MAPI type of 0x%08X = %ws\n", lpUnk, tType, ulObjType, szFlags.c_str()); // call the dialog switch (ulObjType) { // #define MAPI_STORE ((ULONG) 0x00000001) /* Message Store */ case MAPI_STORE: { lpHostDlg->OnUpdateSingleMAPIPropListCtrl(lpUnk, nullptr); auto lpTempMDB = mapi::safe_cast<LPMDB>(lpUnk); auto lpMDB = lpMapiObjects->GetMDB(); // do not release if (lpMDB) lpMDB->AddRef(); // hold on to this so that... lpMapiObjects->SetMDB(lpTempMDB); new CMsgStoreDlg( lpMapiObjects, lpUnk, nullptr, objectType::storeDeletedItems == tType ? tableDisplayFlags::dfDeleted : tableDisplayFlags::dfNormal); // restore the old MDB lpMapiObjects->SetMDB(lpMDB); // ...we can put it back if (lpMDB) lpMDB->Release(); if (lpTempMDB) lpTempMDB->Release(); break; } // #define MAPI_FOLDER ((ULONG) 0x00000003) /* Folder */ case MAPI_FOLDER: { // There are two ways to display a folder...either the contents table or the hierarchy table. if (tType == objectType::hierarchy) { const auto lpMDB = lpMapiObjects->GetMDB(); // do not release if (lpMDB) { new CMsgStoreDlg(lpMapiObjects, lpMDB, lpUnk, tableDisplayFlags::dfNormal); } else { // Since lpMDB was NULL, let's get a good MDB const auto lpMAPISession = lpMapiObjects->GetSession(); // do not release if (lpMAPISession) { auto lpNewMDB = mapi::store::OpenStoreFromMAPIProp(lpMAPISession, lpUnk); if (lpNewMDB) { lpMapiObjects->SetMDB(lpNewMDB); new CMsgStoreDlg(lpMapiObjects, lpNewMDB, lpUnk, tableDisplayFlags::dfNormal); // restore the old MDB lpMapiObjects->SetMDB(nullptr); lpNewMDB->Release(); } } } } else if (tType == objectType::contents || tType == objectType::assocContents) { new CFolderDlg( lpMapiObjects, lpUnk, tType == objectType::assocContents ? tableDisplayFlags::dfAssoc : tableDisplayFlags::dfNormal); } } break; // #define MAPI_ABCONT ((ULONG) 0x00000004) /* Address Book Container */ case MAPI_ABCONT: new CAbDlg(lpMapiObjects, lpUnk); break; // #define MAPI_MESSAGE ((ULONG) 0x00000005) /* Message */ case MAPI_MESSAGE: new SingleMessageDialog(lpMapiObjects, lpUnk); break; // #define MAPI_MAILUSER ((ULONG) 0x00000006) /* Individual Recipient */ case MAPI_MAILUSER: new SingleRecipientDialog(lpMapiObjects, lpUnk); break; // #define MAPI_DISTLIST ((ULONG) 0x00000008) /* Distribution List Recipient */ case MAPI_DISTLIST: // A DistList is really an Address book anyways new SingleRecipientDialog(lpMapiObjects, lpUnk); new CAbDlg(lpMapiObjects, lpUnk); break; // The following types don't have special viewers - just dump their props in the property pane // #define MAPI_ADDRBOOK ((ULONG) 0x00000002) /* Address Book */ // #define MAPI_ATTACH ((ULONG) 0x00000007) /* Attachment */ // #define MAPI_PROFSECT ((ULONG) 0x00000009) /* Profile Section */ // #define MAPI_STATUS ((ULONG) 0x0000000A) /* Status Object */ // #define MAPI_SESSION ((ULONG) 0x0000000B) /* Session */ // #define MAPI_FORMINFO ((ULONG) 0x0000000C) /* Form Information */ default: lpHostDlg->OnUpdateSingleMAPIPropListCtrl(lpUnk, nullptr); szFlags = smartview::InterpretNumberAsStringProp(ulObjType, PR_OBJECT_TYPE); output::DebugPrint( output::dbgLevel::Generic, L"DisplayObject: Object type: 0x%08X = %ws not implemented\r\n" // STRING_OK L"This is not an error. It just means no specialized viewer has been implemented for this object " L"type.", // STRING_OK ulObjType, szFlags.c_str()); break; } return S_OK; } _Check_return_ HRESULT DisplayTable(_In_ LPMAPITABLE lpTable, objectType tType, _In_ CBaseDialog* lpHostDlg) { if (!lpHostDlg) return MAPI_E_INVALID_PARAMETER; const auto lpMapiObjects = lpHostDlg->GetMapiObjects(); // do not release if (!lpMapiObjects) return MAPI_E_INVALID_PARAMETER; output::DebugPrint(output::dbgLevel::Generic, L"DisplayTable asked to display %p\n", lpTable); switch (tType) { case objectType::status: { if (!lpTable) return MAPI_E_INVALID_PARAMETER; new CContentsTableDlg( lpMapiObjects, IDS_STATUSTABLE, createDialogType::CALL_CREATE_DIALOG, nullptr, lpTable, &columns::sptSTATUSCols.tags, columns::STATUSColumns, NULL, MENU_CONTEXT_STATUS_TABLE); break; } case objectType::receive: { if (!lpTable) return MAPI_E_INVALID_PARAMETER; new CContentsTableDlg( lpMapiObjects, IDS_RECEIVEFOLDERTABLE, createDialogType::CALL_CREATE_DIALOG, nullptr, lpTable, &columns::sptRECEIVECols.tags, columns::RECEIVEColumns, NULL, MENU_CONTEXT_RECIEVE_FOLDER_TABLE); break; } case objectType::hierarchy: { if (!lpTable) return MAPI_E_INVALID_PARAMETER; new CContentsTableDlg( lpMapiObjects, IDS_HIERARCHYTABLE, createDialogType::CALL_CREATE_DIALOG, nullptr, lpTable, &columns::sptHIERARCHYCols.tags, columns::HIERARCHYColumns, NULL, MENU_CONTEXT_HIER_TABLE); break; } default: case objectType::otDefault: { if (!lpTable) return MAPI_E_INVALID_PARAMETER; if (tType != objectType::otDefault) error::ErrDialog(__FILE__, __LINE__, IDS_EDDISPLAYTABLE, tType); new CContentsTableDlg( lpMapiObjects, IDS_CONTENTSTABLE, createDialogType::CALL_CREATE_DIALOG, nullptr, lpTable, &columns::sptDEFCols.tags, columns::DEFColumns, NULL, MENU_CONTEXT_DEFAULT_TABLE); break; } } return S_OK; } _Check_return_ HRESULT DisplayTable(_In_ LPMAPIPROP lpMAPIProp, ULONG ulPropTag, objectType tType, _In_ CBaseDialog* lpHostDlg) { LPMAPITABLE lpTable = nullptr; if (!lpHostDlg || !lpMAPIProp) return MAPI_E_INVALID_PARAMETER; if (PT_OBJECT != PROP_TYPE(ulPropTag)) return MAPI_E_INVALID_TYPE; auto unicodeFlag = registry::preferUnicodeProps ? MAPI_UNICODE : fMapiUnicode; auto hRes = WC_MAPI(lpMAPIProp->OpenProperty( ulPropTag, &IID_IMAPITable, unicodeFlag, 0, reinterpret_cast<LPUNKNOWN*>(&lpTable))); if (hRes == MAPI_E_INTERFACE_NOT_SUPPORTED) { hRes = S_OK; switch (PROP_ID(ulPropTag)) { case PROP_ID(PR_MESSAGE_ATTACHMENTS): { auto lpMessage = mapi::safe_cast<LPMESSAGE>(lpMAPIProp); if (lpMessage) { lpMessage->GetAttachmentTable(unicodeFlag, &lpTable); lpMessage->Release(); } break; } case PROP_ID(PR_MESSAGE_RECIPIENTS): { auto lpMessage = mapi::safe_cast<LPMESSAGE>(lpMAPIProp); if (lpMessage) { lpMessage->GetRecipientTable(unicodeFlag, &lpTable); lpMessage->Release(); } break; } } } if (lpTable) { switch (PROP_ID(ulPropTag)) { case PROP_ID(PR_MESSAGE_ATTACHMENTS): new CAttachmentsDlg(lpHostDlg->GetMapiObjects(), lpTable, lpMAPIProp); break; case PROP_ID(PR_MESSAGE_RECIPIENTS): new CRecipientsDlg(lpHostDlg->GetMapiObjects(), lpTable, lpMAPIProp); break; default: hRes = EC_H(DisplayTable(lpTable, tType, lpHostDlg)); break; } lpTable->Release(); } return hRes; } _Check_return_ HRESULT DisplayExchangeTable(_In_ LPMAPIPROP lpMAPIProp, ULONG ulPropTag, objectType tType, _In_ CBaseDialog* lpHostDlg) { LPEXCHANGEMODIFYTABLE lpExchTbl = nullptr; LPMAPITABLE lpMAPITable = nullptr; if (!lpMAPIProp || !lpHostDlg) return MAPI_E_INVALID_PARAMETER; const auto lpMapiObjects = lpHostDlg->GetMapiObjects(); // do not release if (!lpMapiObjects) return MAPI_E_INVALID_PARAMETER; // Open the table in an IExchangeModifyTable interface auto hRes = EC_MAPI(lpMAPIProp->OpenProperty( ulPropTag, const_cast<LPGUID>(&IID_IExchangeModifyTable), 0, MAPI_DEFERRED_ERRORS, reinterpret_cast<LPUNKNOWN*>(&lpExchTbl))); if (lpExchTbl) { switch (tType) { case objectType::rules: new CRulesDlg(lpMapiObjects, lpExchTbl); break; case objectType::ACL: { editor::CEditor MyData( lpHostDlg, IDS_ACLTABLE, IDS_ACLTABLEPROMPT, CEDITOR_BUTTON_OK | CEDITOR_BUTTON_CANCEL); MyData.AddPane(viewpane::CheckPane::Create(0, IDS_FBRIGHTSVISIBLE, false, false)); if (MyData.DisplayDialog()) { new CAclDlg(lpMapiObjects, lpExchTbl, MyData.GetCheck(0)); } } break; default: // Open a MAPI table on the Exchange table property. This table can be // read to determine what the Exchange table looks like. hRes = EC_MAPI(lpExchTbl->GetTable(0, &lpMAPITable)); if (lpMAPITable) { hRes = EC_H(DisplayTable(lpMAPITable, tType, lpHostDlg)); lpMAPITable->Release(); } break; } lpExchTbl->Release(); } return hRes; } _Check_return_ bool bShouldCancel(_In_opt_ CWnd* cWnd, HRESULT hResPrev) { auto bGotError = false; if (S_OK != hResPrev) { if (MAPI_E_USER_CANCEL != hResPrev && MAPI_E_CANCEL != hResPrev) { bGotError = true; } editor::CEditor Cancel(cWnd, ID_PRODUCTNAME, IDS_CANCELPROMPT, CEDITOR_BUTTON_OK | CEDITOR_BUTTON_CANCEL); if (bGotError) { const auto szPrevErr = strings::formatmessage(IDS_PREVIOUSCALL, error::ErrorNameFromErrorCode(hResPrev).c_str(), hResPrev); Cancel.AddPane(viewpane::TextPane::CreateSingleLinePane(0, IDS_ERROR, szPrevErr, true)); } if (Cancel.DisplayDialog()) { output::DebugPrint(output::dbgLevel::Generic, L"bShouldCancel: User asked to cancel\n"); return true; } } return false; } void DisplayMailboxTable(_In_ std::shared_ptr<cache::CMapiObjects> lpMapiObjects) { if (!lpMapiObjects) return; LPMDB lpPrivateMDB = nullptr; auto lpMDB = lpMapiObjects->GetMDB(); // do not release const auto lpMAPISession = lpMapiObjects->GetSession(); // do not release // try the 'current' MDB first if (!mapi::store::StoreSupportsManageStore(lpMDB)) { // if that MDB doesn't support manage store, try to get one that does lpPrivateMDB = mapi::store::OpenMessageStoreGUID(lpMAPISession, pbExchangeProviderPrimaryUserGuid); lpMDB = lpPrivateMDB; } if (lpMDB && mapi::store::StoreSupportsManageStore(lpMDB)) { LPMAPITABLE lpMailboxTable = nullptr; const auto szServerName = mapi::store::GetServerName(lpMAPISession); editor::CEditor MyData( nullptr, IDS_DISPLAYMAILBOXTABLE, IDS_SERVERNAMEPROMPT, CEDITOR_BUTTON_OK | CEDITOR_BUTTON_CANCEL); MyData.AddPane(viewpane::TextPane::CreateSingleLinePane(0, IDS_SERVERNAME, szServerName, false)); MyData.AddPane(viewpane::TextPane::CreateSingleLinePane(1, IDS_OFFSET, false)); MyData.SetHex(1, 0); MyData.AddPane(viewpane::TextPane::CreateSingleLinePane(2, IDS_MAILBOXGUID, false)); UINT uidDropDown[] = {IDS_GETMBXINTERFACE1, IDS_GETMBXINTERFACE3, IDS_GETMBXINTERFACE5}; MyData.AddPane( viewpane::DropDownPane::Create(3, IDS_GETMBXINTERFACE, _countof(uidDropDown), uidDropDown, true)); if (MyData.DisplayDialog()) { if (0 != MyData.GetHex(1) && 0 == MyData.GetDropDown(3)) { error::ErrDialog(__FILE__, __LINE__, IDS_EDOFFSETWITHWRONGINTERFACE); } else { auto szServerDN = mapi::store::BuildServerDN(MyData.GetStringW(0), L""); if (!szServerDN.empty()) { LPMDB lpOldMDB = nullptr; // if we got a new MDB, set it in lpMapiObjects if (lpPrivateMDB) { lpOldMDB = lpMapiObjects->GetMDB(); // do not release if (lpOldMDB) lpOldMDB->AddRef(); // hold on to this so that... // If we don't do this, we crash when destroying the Mailbox Table Window lpMapiObjects->SetMDB(lpMDB); } switch (MyData.GetDropDown(3)) { case 0: lpMailboxTable = mapi::store::GetMailboxTable1(lpMDB, szServerDN, fMapiUnicode); break; case 1: lpMailboxTable = mapi::store::GetMailboxTable3(lpMDB, szServerDN, MyData.GetHex(1), fMapiUnicode); break; case 2: { GUID MyGUID = {0}; auto bHaveGUID = false; auto pszGUID = MyData.GetStringW(2); if (!pszGUID.empty()) { bHaveGUID = true; MyGUID = guid::StringToGUID(pszGUID); if (MyGUID == GUID_NULL) { error::ErrDialog(__FILE__, __LINE__, IDS_EDINVALIDGUID); break; } } lpMailboxTable = mapi::store::GetMailboxTable5( lpMDB, szServerDN, MyData.GetHex(1), fMapiUnicode, bHaveGUID ? &MyGUID : nullptr); break; } } if (lpMailboxTable) { new CMailboxTableDlg(lpMapiObjects, MyData.GetStringW(0), lpMailboxTable); lpMailboxTable->Release(); } else { error::ErrDialog( __FILE__, __LINE__, IDS_EDGETMAILBOXTABLEFAILED, _T("GetMailboxTable"), _T("GetMailboxTable")); // STRING_OK } if (lpOldMDB) { lpMapiObjects->SetMDB(lpOldMDB); // ...we can put it back if (lpOldMDB) lpOldMDB->Release(); } } } } } if (lpPrivateMDB) lpPrivateMDB->Release(); } void DisplayPublicFolderTable(_In_ std::shared_ptr<cache::CMapiObjects> lpMapiObjects) { if (!lpMapiObjects) return; LPMDB lpPrivateMDB = nullptr; auto lpMDB = lpMapiObjects->GetMDB(); // do not release const auto lpMAPISession = lpMapiObjects->GetSession(); // do not release // try the 'current' MDB first if (!mapi::store::StoreSupportsManageStore(lpMDB)) { // if that MDB doesn't support manage store, try to get one that does lpPrivateMDB = mapi::store::OpenMessageStoreGUID(lpMAPISession, pbExchangeProviderPrimaryUserGuid); lpMDB = lpPrivateMDB; } if (lpMDB && mapi::store::StoreSupportsManageStore(lpMDB)) { LPMAPITABLE lpPFTable = nullptr; const auto szServerName = mapi::store::GetServerName(lpMAPISession); editor::CEditor MyData( nullptr, IDS_DISPLAYPFTABLE, IDS_DISPLAYPFTABLEPROMPT, CEDITOR_BUTTON_OK | CEDITOR_BUTTON_CANCEL); MyData.AddPane(viewpane::TextPane::CreateSingleLinePane(0, IDS_SERVERNAME, szServerName, false)); MyData.AddPane(viewpane::TextPane::CreateSingleLinePane(1, IDS_OFFSET, false)); MyData.SetHex(1, 0); MyData.AddPane(viewpane::TextPane::CreateSingleLinePane(2, IDS_FLAGS, false)); MyData.SetHex(2, MDB_IPM); MyData.AddPane(viewpane::TextPane::CreateSingleLinePane(3, IDS_PUBLICFOLDERGUID, false)); UINT uidDropDown[] = {IDS_GETPFINTERFACE1, IDS_GETPFINTERFACE4, IDS_GETPFINTERFACE5}; MyData.AddPane( viewpane::DropDownPane::Create(4, IDS_GETMBXINTERFACE, _countof(uidDropDown), uidDropDown, true)); if (MyData.DisplayDialog()) { if (0 != MyData.GetHex(1) && 0 == MyData.GetDropDown(4)) { error::ErrDialog(__FILE__, __LINE__, IDS_EDOFFSETWITHWRONGINTERFACE); } else { auto szServerDN = mapi::store::BuildServerDN(MyData.GetStringW(0), L""); if (!szServerDN.empty()) { LPMDB lpOldMDB = nullptr; // if we got a new MDB, set it in lpMapiObjects if (lpPrivateMDB) { lpOldMDB = lpMapiObjects->GetMDB(); // do not release if (lpOldMDB) lpOldMDB->AddRef(); // hold on to this so that... // If we don't do this, we crash when destroying the Mailbox Table Window lpMapiObjects->SetMDB(lpMDB); } switch (MyData.GetDropDown(4)) { case 0: lpPFTable = mapi::store::GetPublicFolderTable1(lpMDB, szServerDN, MyData.GetHex(2) | fMapiUnicode); break; case 1: lpPFTable = mapi::store::GetPublicFolderTable4( lpMDB, szServerDN, MyData.GetHex(1), MyData.GetHex(2) | fMapiUnicode); break; case 2: { GUID MyGUID = {0}; auto bHaveGUID = false; auto pszGUID = MyData.GetStringW(3); if (!pszGUID.empty()) { bHaveGUID = true; MyGUID = guid::StringToGUID(pszGUID); if (MyGUID == GUID_NULL) { error::ErrDialog(__FILE__, __LINE__, IDS_EDINVALIDGUID); break; } } lpPFTable = mapi::store::GetPublicFolderTable5( lpMDB, szServerDN, MyData.GetHex(1), MyData.GetHex(2) | fMapiUnicode, bHaveGUID ? &MyGUID : nullptr); break; } } if (lpPFTable) { new CPublicFolderTableDlg(lpMapiObjects, MyData.GetStringW(0), lpPFTable); lpPFTable->Release(); } else { error::ErrDialog( __FILE__, __LINE__, IDS_EDGETMAILBOXTABLEFAILED, _T("GetPublicFolderTable"), _T("GetPublicFolderTable")); // STRING_OK } if (lpOldMDB) { lpMapiObjects->SetMDB(lpOldMDB); // ...we can put it back if (lpOldMDB) lpOldMDB->Release(); } } } } } if (lpPrivateMDB) lpPrivateMDB->Release(); } _Check_return_ LPMAPIFORMINFO ResolveMessageClass(_In_ std::shared_ptr<cache::CMapiObjects> lpMapiObjects, _In_opt_ LPMAPIFOLDER lpMAPIFolder) { LPMAPIFORMMGR lpMAPIFormMgr = nullptr; if (!lpMapiObjects) return nullptr; const auto lpMAPISession = lpMapiObjects->GetSession(); // do not release if (!lpMAPISession) nullptr; LPMAPIFORMINFO lpMAPIFormInfo = nullptr; EC_MAPI_S(MAPIOpenFormMgr(lpMAPISession, &lpMAPIFormMgr)); if (lpMAPIFormMgr) { output::DebugPrint(output::dbgLevel::Forms, L"OnResolveMessageClass: resolving message class\n"); editor::CEditor MyData( nullptr, IDS_RESOLVECLASS, IDS_RESOLVECLASSPROMPT, CEDITOR_BUTTON_OK | CEDITOR_BUTTON_CANCEL); MyData.AddPane(viewpane::TextPane::CreateSingleLinePane(0, IDS_CLASS, false)); MyData.AddPane(viewpane::TextPane::CreateSingleLinePane(1, IDS_FLAGS, false)); if (MyData.DisplayDialog()) { auto szClass = MyData.GetStringW(0); const auto ulFlags = MyData.GetHex(1); if (!szClass.empty()) { output::DebugPrint( output::dbgLevel::Forms, L"OnResolveMessageClass: Calling ResolveMessageClass(\"%ws\",0x%08X)\n", szClass.c_str(), ulFlags); // STRING_OK // ResolveMessageClass requires an ANSI string EC_MAPI_S(lpMAPIFormMgr->ResolveMessageClass( strings::wstringTostring(szClass).c_str(), ulFlags, lpMAPIFolder, &lpMAPIFormInfo)); if (lpMAPIFormInfo) { output::outputFormInfo(output::dbgLevel::Forms, nullptr, lpMAPIFormInfo); } } } lpMAPIFormMgr->Release(); } return lpMAPIFormInfo; } _Check_return_ LPMAPIFORMINFO SelectForm( _In_ HWND hWnd, _In_ std::shared_ptr<cache::CMapiObjects> lpMapiObjects, _In_opt_ LPMAPIFOLDER lpMAPIFolder) { LPMAPIFORMMGR lpMAPIFormMgr = nullptr; LPMAPIFORMINFO lpMAPIFormInfo = nullptr; if (!lpMapiObjects) return nullptr; const auto lpMAPISession = lpMapiObjects->GetSession(); // do not release if (!lpMAPISession) return nullptr; EC_MAPI_S(MAPIOpenFormMgr(lpMAPISession, &lpMAPIFormMgr)); if (lpMAPIFormMgr) { // Apparently, SelectForm doesn't support unicode auto szTitle = strings::wstringTostring(strings::loadstring(IDS_SELECTFORMPROPS)); EC_H_CANCEL_S(lpMAPIFormMgr->SelectForm( reinterpret_cast<ULONG_PTR>(hWnd), 0, // fMapiUnicode, LPCTSTR(szTitle.c_str()), lpMAPIFolder, &lpMAPIFormInfo)); if (lpMAPIFormInfo) { output::outputFormInfo(output::dbgLevel::Forms, nullptr, lpMAPIFormInfo); } lpMAPIFormMgr->Release(); } return lpMAPIFormInfo; } } // namespace dialog
30.261735
113
0.690091
[ "object" ]
e5702f15f4ce374a90edaa54e473f79e6a9fa253
3,047
cpp
C++
sta-src/Astro-Core/sphericalTOcartesian.cpp
hoehnp/SpaceDesignTool
9abd34048274b2ce9dbbb685124177b02d6a34ca
[ "IJG" ]
6
2018-09-05T12:41:59.000Z
2021-07-01T05:34:23.000Z
sta-src/Astro-Core/sphericalTOcartesian.cpp
hoehnp/SpaceDesignTool
9abd34048274b2ce9dbbb685124177b02d6a34ca
[ "IJG" ]
2
2015-02-07T19:09:21.000Z
2015-08-14T03:15:42.000Z
sta-src/Astro-Core/sphericalTOcartesian.cpp
hoehnp/SpaceDesignTool
9abd34048274b2ce9dbbb685124177b02d6a34ca
[ "IJG" ]
2
2015-03-25T15:50:31.000Z
2017-12-06T12:16:47.000Z
/* This program is free software; you can redistribute it and/or modify it under the terms of the European Union Public Licence - EUPL v.1.1 as published by the European Commission. 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 European Union Public Licence - EUPL v.1.1 for more details. You should have received a copy of the European Union Public Licence - EUPL v.1.1 along with this program. Further information about the European Union Public Licence - EUPL v.1.1 can also be found on the world wide web at http://ec.europa.eu/idabc/eupl */ /* ------ Copyright (C) 2010 STA Steering Board (space.trajectory.analysis AT gmail.com) ---- */ // Author G. Ortega #include "sphericalTOcartesian.h" #include "Scenario/staschema.h" #include<float.h> #include<math.h> #include<stdio.h> void sphericalTOcartesian(double tau,double delta,double r,double V,double gamma,double chi, double& x,double& y,double& z,double& xd,double& yd,double& zd) { x = r * cos(delta) * cos(tau); y = r * cos(delta) * sin(tau); z = r * sin(delta); xd = V * ( sin(gamma)*cos(delta)*cos(tau) - cos(gamma)*cos(chi)*sin(delta)*cos(tau) - cos(gamma)*sin(chi)*sin(tau) ); yd = V * ( sin(gamma)*cos(delta)*sin(tau) - cos(gamma)*cos(chi)*sin(delta)*sin(tau) + cos(gamma)*sin(chi)*cos(tau) ); zd = V * ( cos(gamma)*cos(chi)*cos(delta) + sin(gamma)*sin(delta) ); // x = cos(theta)*x + sin(theta)*y; // y = -sin(theta)*x + cos(theta)*y; //------ Transform velocity to rotating frame by subtracting r x omega //double rxomega_x = -y * mu; //double rxomega_y = x * mu; //xd -= rxomega_x; //yd -= rxomega_y; } sta::StateVector sphericalTOcartesian(double spherCoord[6])//Added by Dominic { double delta = spherCoord[2]; double tau = spherCoord[1]; double r = spherCoord[0]; double gamma = spherCoord[4]; double chi = spherCoord[5]; double V = spherCoord[3]; sta::StateVector cartesian; cartesian.position.x() = r * cos(delta) * cos(tau); cartesian.position.y() = r * cos(delta) * sin(tau); cartesian.position.z() = r * sin(delta); cartesian.velocity.x() = V * ( sin(gamma)*cos(delta)*cos(tau) - cos(gamma)*cos(chi)*sin(delta)*cos(tau) - cos(gamma)*sin(chi)*sin(tau) ); cartesian.velocity.y() = V * ( sin(gamma)*cos(delta)*sin(tau) - cos(gamma)*cos(chi)*sin(delta)*sin(tau) + cos(gamma)*sin(chi)*cos(tau) ); cartesian.velocity.z() = V * ( cos(gamma)*cos(chi)*cos(delta) + sin(gamma)*sin(delta) ); // x = cos(theta)*x + sin(theta)*y; // y = -sin(theta)*x + cos(theta)*y; //------ Transform velocity to rotating frame by subtracting r x omega //double rxomega_x = -y * mu; //double rxomega_y = x * mu; //xd -= rxomega_x; //yd -= rxomega_y; return cartesian; }
38.56962
142
0.626518
[ "transform" ]
ec78c29e40223f56087493ed1b2220128f643161
1,162
cpp
C++
src/modules/multiblade/caen/DigitizerMappingTest.cpp
geishm-ansto/event-formation-unit
bab9f211913ee9e633eae627ec2c2ed96ae380b4
[ "BSD-2-Clause" ]
null
null
null
src/modules/multiblade/caen/DigitizerMappingTest.cpp
geishm-ansto/event-formation-unit
bab9f211913ee9e633eae627ec2c2ed96ae380b4
[ "BSD-2-Clause" ]
null
null
null
src/modules/multiblade/caen/DigitizerMappingTest.cpp
geishm-ansto/event-formation-unit
bab9f211913ee9e633eae627ec2c2ed96ae380b4
[ "BSD-2-Clause" ]
null
null
null
/** Copyright (C) 2016, 2017 European Spallation Source ERIC */ #include <multiblade/caen/DigitizerMapping.h> #include <test/TestBase.h> class DigitizerMappingTest : public TestBase {}; std::vector<struct Multiblade::DigitizerMapping::Digitiser> digits { {0, 137} , {1, 143}, {2, 142}, {3, 31}, {4, 33}, {5, 34} }; /** Test cases below */ TEST_F(DigitizerMappingTest, CassetteValid) { Multiblade::DigitizerMapping mbg(digits); ASSERT_EQ(0, mbg.cassette(137)); ASSERT_EQ(1, mbg.cassette(143)); ASSERT_EQ(2, mbg.cassette(142)); ASSERT_EQ(3, mbg.cassette(31)); ASSERT_EQ(4, mbg.cassette(33)); ASSERT_EQ(5, mbg.cassette(34)); } TEST_F(DigitizerMappingTest, CassetteInValid) { Multiblade::DigitizerMapping mbg(digits); ASSERT_EQ(-1, mbg.cassette(-1)); ASSERT_EQ(-1, mbg.cassette(0)); ASSERT_EQ(-1, mbg.cassette(30)); ASSERT_EQ(-1, mbg.cassette(32)); ASSERT_EQ(-1, mbg.cassette(35)); ASSERT_EQ(-1, mbg.cassette(136)); ASSERT_EQ(-1, mbg.cassette(138)); ASSERT_EQ(-1, mbg.cassette(141)); ASSERT_EQ(-1, mbg.cassette(144)); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
27.666667
68
0.69191
[ "vector" ]
ec79ca076caeddf231dd6b502d986ba78a2b871f
14,651
cpp
C++
src/prod/src/Common/FabricSerializer.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
1
2018-03-15T02:09:21.000Z
2018-03-15T02:09:21.000Z
src/prod/src/Common/FabricSerializer.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
null
null
null
src/prod/src/Common/FabricSerializer.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
null
null
null
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" #include "KtlSF.Common.h" namespace Common { ErrorCode FabricSerializer::Serialize(Serialization::IFabricSerializable const * serializable, std::vector<byte> & bytes) { return ErrorCode::FromNtStatus(FabricSerializer::InnerSerialize(serializable, bytes)); } ErrorCode FabricSerializer::Serialize(Serialization::IFabricSerializable const * serializable, Serialization::IFabricSerializableStreamUPtr & streamUPtr, ULONG maxGrowBy) { return ErrorCode::FromNtStatus(FabricSerializer::InnerSerialize(serializable, streamUPtr, maxGrowBy)); } ErrorCode FabricSerializer::Deserialize(Serialization::IFabricSerializable & serializable, std::vector<byte> & bytes) { return ErrorCode::FromNtStatus(InnerDeserialize(serializable, static_cast<ULONG>(bytes.size()), bytes.data())); } ErrorCode FabricSerializer::Deserialize(Serialization::IFabricSerializable & serializable, ULONG size, void * buffer) { return ErrorCode::FromNtStatus(InnerDeserialize(serializable, size, buffer)); } ErrorCode FabricSerializer::Deserialize(Serialization::IFabricSerializable & serializable, ULONG size, std::vector<Serialization::FabricIOBuffer> const & buffers) { return ErrorCode::FromNtStatus(InnerDeserialize(serializable, size, buffers)); } ErrorCode FabricSerializer::GetOperationBuffersFromSerializableStream(Serialization::IFabricSerializableStreamUPtr const & streamUPtr, std::vector<FABRIC_OPERATION_DATA_BUFFER> & buffers, ULONG & totalSize) { return ErrorCode::FromNtStatus(InnerGetOperationBuffersFromSerializableStream(streamUPtr, buffers, totalSize)); } NTSTATUS FabricSerializer::InnerGetOperationBuffersFromSerializableStream(Serialization::IFabricSerializableStreamUPtr const & streamUPtr, std::vector<FABRIC_OPERATION_DATA_BUFFER> & buffers, ULONG & totalSize) { Serialization::FabricIOBuffer buffer; bool isExtensionBuffer; NTSTATUS status = streamUPtr->GetNextBuffer(buffer, isExtensionBuffer); while (NT_SUCCESS(status)) { if (isExtensionBuffer) { Common::Assert::TestAssert("Extension buffers not supported yet in fabric user mode"); return K_STATUS_OTHER_SERIALIZATION_ERRORS; } FABRIC_OPERATION_DATA_BUFFER operationBuffer; operationBuffer.Buffer = static_cast<BYTE*>(buffer.buffer); operationBuffer.BufferSize = buffer.length; buffers.push_back(operationBuffer); totalSize += buffer.length; status = streamUPtr->GetNextBuffer(buffer, isExtensionBuffer); } if (status != (NTSTATUS)K_STATUS_NO_MORE_EXTENSION_BUFFERS) { Common::Assert::TestAssert("GetNextBuffer returned an error other than K_STATUS_NO_MORE_EXTENSION_BUFFERS: {0}", status); return status; } if(*(buffers[0].Buffer) != Serialization::FabricSerializationTypes::Object) { Common::Assert::TestAssert("Extension buffers not supported yet in fabric user mode"); return K_STATUS_OTHER_SERIALIZATION_ERRORS; } return STATUS_SUCCESS; } NTSTATUS FabricSerializer::InnerSerialize(Serialization::IFabricSerializable const * serializable, Serialization::IFabricSerializableStreamUPtr & streamUPtr, ULONG maxGrowBy) { if(serializable == nullptr) { Common::Assert::TestAssert("serializable can't be null"); return K_STATUS_NULL_REF_POINTER; } Serialization::IFabricStream * innerStream = nullptr; NTSTATUS status = Serialization::FabricStream::Create(&innerStream, maxGrowBy); if (NT_ERROR(status) || innerStream == nullptr) { Common::Assert::TestAssert("Insufficient resources constructing an inner stream"); return NT_ERROR(status)?status:K_STATUS_NULL_REF_POINTER; } Serialization::IFabricSerializableStream * stream = nullptr; status = Serialization::FabricSerializableStream::Create(&stream, Serialization::IFabricStreamUPtr(innerStream)); Serialization::IFabricSerializableStreamUPtr streamInternalUPtr(stream); if (NT_ERROR(status) || stream == nullptr) { Common::Assert::TestAssert("Insufficient resources constructing a stream"); return NT_ERROR(status)?status:K_STATUS_NULL_REF_POINTER; } status = streamInternalUPtr->WriteSerializable(const_cast<Serialization::IFabricSerializable*>(serializable)); if (NT_ERROR(status)) { Common::Assert::TestAssert("Writing object to stream failed: {0}", status); return status; } streamUPtr = Ktl::Move(streamInternalUPtr); return STATUS_SUCCESS; } ErrorCode FabricSerializer::Serialize(Serialization::IFabricSerializable const * serializable, KBuffer::SPtr & bytes) { NTSTATUS status = KBuffer::Create(0, bytes, GetSFDefaultPagedKAllocator()); if (NT_ERROR(status)) { return ErrorCode::FromNtStatus(status); } return ErrorCode::FromNtStatus(Serialize(serializable, *bytes)); } Serialization::IFabricSerializableStreamUPtr FabricSerializer::CreateSerializableStream() { Serialization::IFabricSerializableStream* stream = nullptr; NTSTATUS status = Serialization::FabricSerializableStream::Create(&stream); Serialization::IFabricSerializableStreamUPtr streamUPtr(stream); // todo, consider setting failure status on message instead of assert ASSERT_IF( (NT_ERROR(status) || stream == nullptr), "Failed to construct a stream: status = {0:x}", status); return streamUPtr; } NTSTATUS FabricSerializer::CreateKBufferFromStream(Serialization::IFabricSerializableStream const& stream, KBuffer::SPtr& buffer) { std::unique_ptr<Serialization::FabricIOBuffer> bufferListInHeap; Serialization::FabricIOBuffer bufferListOnStack[16]; Serialization::FabricIOBuffer* bufferList = bufferListOnStack; size_t count = sizeof(bufferListOnStack) / sizeof(Serialization::FabricIOBuffer); auto status = stream.GetAllBuffers(bufferList, count); if (!NT_SUCCESS(status)) { Invariant(status == K_STATUS_BUFFER_TOO_SMALL); bufferListInHeap = std::unique_ptr<Serialization::FabricIOBuffer>(new Serialization::FabricIOBuffer[count]); bufferList = bufferListInHeap.get(); status = stream.GetAllBuffers(bufferList, count); Invariant(NT_SUCCESS(status)); } status = KBuffer::Create(stream.Size(), buffer, Serialization::FabricSerializationCommon::GetPagedKtlAllocator()); if (!NT_SUCCESS(status)) return status; byte* pointer = (byte*)buffer->GetBuffer(); size_t size = 0; for (uint i = 0; i < count; ++i) { KMemCpySafe(pointer + size, buffer->QuerySize() - size, bufferList[i].buffer, bufferList[i].length); size += bufferList[i].length; } return status; } NTSTATUS FabricSerializer::Serialize(Serialization::IFabricSerializable const * serializable, KBuffer & bytes) { Serialization::IFabricSerializableStreamUPtr streamUPtr; NTSTATUS status = InnerSerialize(serializable, streamUPtr); if (NT_ERROR(status)) { return status; } status = bytes.SetSize(streamUPtr->Size()); if (NT_ERROR(status)) { return status; } byte* pointer = (byte*)bytes.GetBuffer(); ULONG size = 0; Serialization::FabricIOBuffer buffer; bool isExtensionBuffer; while (NT_SUCCESS(status = streamUPtr->GetNextBuffer(buffer, isExtensionBuffer))) { if (isExtensionBuffer) { Common::Assert::TestAssert("Extension buffers not supported yet in fabric user mode"); return K_STATUS_OTHER_SERIALIZATION_ERRORS; } KMemCpySafe(pointer + size, bytes.QuerySize() - size, buffer.buffer, buffer.length); size += buffer.length; } if (status != (NTSTATUS)K_STATUS_NO_MORE_EXTENSION_BUFFERS) { Common::Assert::TestAssert("GetNextBuffer returned an error other than K_STATUS_NO_MORE_EXTENSION_BUFFERS: {0}", status); return status; } byte* bytePtr = (byte*)bytes.GetBuffer(); if(bytePtr[0] != Serialization::FabricSerializationTypes::Object) { Common::Assert::TestAssert("Extension buffers not supported yet in fabric user mode"); return K_STATUS_OTHER_SERIALIZATION_ERRORS; } return STATUS_SUCCESS; } NTSTATUS FabricSerializer::InnerSerialize(Serialization::IFabricSerializable const * serializable, std::vector<byte> & bytes) { Serialization::IFabricSerializableStreamUPtr streamUPtr; NTSTATUS status = InnerSerialize(serializable, streamUPtr); if (NT_ERROR(status)) { return status; } bytes.resize(streamUPtr->Size()); byte * pointer = bytes.data(); ULONG size = 0; Serialization::FabricIOBuffer buffer; bool isExtensionBuffer; while (NT_SUCCESS(status = streamUPtr->GetNextBuffer(buffer, isExtensionBuffer))) { if (isExtensionBuffer) { Common::Assert::TestAssert("Extension buffers not supported yet in fabric user mode"); return K_STATUS_OTHER_SERIALIZATION_ERRORS; } KMemCpySafe(pointer + size, bytes.size() - size, buffer.buffer, buffer.length); size += buffer.length; } if (status != (NTSTATUS)K_STATUS_NO_MORE_EXTENSION_BUFFERS) { Common::Assert::TestAssert("GetNextBuffer returned an error other than K_STATUS_NO_MORE_EXTENSION_BUFFERS: {0}", status); return status; } if(bytes[0] != Serialization::FabricSerializationTypes::Object) { Common::Assert::TestAssert("Extension buffers not supported yet in fabric user mode"); return K_STATUS_OTHER_SERIALIZATION_ERRORS; } return STATUS_SUCCESS; } NTSTATUS FabricSerializer::InnerDeserialize(Serialization::IFabricSerializable & serializable, ULONG size, void * buffer) { Serialization::FabricIOBuffer ioBuffer; ioBuffer.buffer = static_cast<UCHAR*>(buffer); ioBuffer.length = size; std::vector<Serialization::FabricIOBuffer> ioBuffers; ioBuffers.push_back(ioBuffer); return InnerDeserialize(serializable, size, ioBuffers); } NTSTATUS FabricSerializer::InnerDeserialize(Serialization::IFabricSerializable & serializable, ULONG size, std::vector<Serialization::FabricIOBuffer> const & buffers) { KMemChannel::UPtr memoryStream = KMemChannel::UPtr(_new (WF_SERIALIZATION_TAG, GetSFDefaultNonPagedKAllocator()) KMemChannel(GetSFDefaultNonPagedKAllocator(), static_cast<ULONG>(size))); if (!memoryStream) { Common::Assert::TestAssert("Allocation of KMemChannel failed"); return K_STATUS_NULL_REF_POINTER; } NTSTATUS status = memoryStream->Status(); if (NT_ERROR(status)) { Common::Assert::TestAssert("KMemChannel constructor failed: {0}", status); return status; } // Tell the stream not to delete what it is looking at memoryStream->DetachOnDestruct(); status = memoryStream->StartCapture(); if (NT_ERROR(status)) { Common::Assert::TestAssert("StartCapture failed: {0}", status); return status; } for (Serialization::FabricIOBuffer const & buffer : buffers) { KMemRef memoryReference(buffer.length, buffer.buffer); memoryReference._Param = buffer.length; status = memoryStream->Capture(memoryReference); if (NT_ERROR(status)) { Common::Assert::TestAssert("Capture failed: {0}", status); return status; } } status = memoryStream->EndCapture(); if (NT_ERROR(status)) { Common::Assert::TestAssert("EndCapture failed: {0}", status); return status; } KArray<Serialization::FabricIOBuffer> receivingExtensionBuffers(GetSFDefaultNonPagedKAllocator()); status = receivingExtensionBuffers.Status(); if (NT_ERROR(status)) { Common::Assert::TestAssert("KArray constructor failed: {0}", status); return status; } Serialization::IFabricStream * receiveByteStream; status = Serialization::FabricStream::Create(&receiveByteStream, Ktl::Move(memoryStream), Ktl::Move(receivingExtensionBuffers)); Serialization::IFabricStreamUPtr receiveByteStreamUPtr(receiveByteStream); if (NT_ERROR(status) || receiveByteStream == nullptr) { Common::Assert::TestAssert("Allocation of IFabricStream failed"); return NT_ERROR(status)?status:K_STATUS_NULL_REF_POINTER; } Serialization::IFabricSerializableStream * readStream; status = Serialization::FabricSerializableStream::Create(&readStream, Ktl::Move(receiveByteStreamUPtr)); Serialization::IFabricSerializableStreamUPtr readStreamUPtr(readStream); if (NT_ERROR(status) || readStream == nullptr) { Common::Assert::TestAssert("Allocation of FabricSerializableStream failed: {0}", status); return NT_ERROR(status)?status:K_STATUS_NULL_REF_POINTER; } status = readStreamUPtr->ReadSerializable(&serializable); if (NT_ERROR(status)) { Common::Assert::TestAssert("Deserialization failed: {0}", status); } return status; } }
39.173797
214
0.647464
[ "object", "vector" ]
ec7c777a5fd747710a84cba8a945ffc3dbb5d9c1
56,715
cxx
C++
com/ole32/com/catalog/class.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
com/ole32/com/catalog/class.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
com/ole32/com/catalog/class.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/* class.cxx */ #include <ole2int.h> #include <appmgmt.h> #include <msi.h> #include <comdef.h> #include <string.h> #include <wow64reg.h> #include "globals.hxx" #include "services.hxx" #include "catalog.h" #include "partitions.h" #include "class.hxx" #include "catalog.hxx" #define SAFEALLOCA_ASSERT Win4Assert #include <alloca.h> #if DBG #include <debnot.h> #endif const WCHAR g_wszInprocServer32[] = L"InprocServer32"; const WCHAR g_wszInprocHandler32[] = L"InprocHandler32"; const WCHAR g_wszLocalServer32[] = L"LocalServer32"; const WCHAR g_wszServerExecutable[] = L"ServerExecutable"; const WCHAR g_wszLocalServer16[] = L"LocalServer"; const WCHAR g_wszInprocServer16[] = L"InprocServer"; const WCHAR g_wszRemoteServerName[] = L"RemoteServerName"; const WCHAR g_wszInprocHandler16[] = L"InprocHandler"; const WCHAR g_wszThreadingModel[] = L"ThreadingModel"; const WCHAR g_wszOle32Dll[] = L"OLE32.DLL"; const WCHAR g_wszApartment[] = L"Apartment"; const WCHAR g_wszBoth[] = L"Both"; const WCHAR g_wszFree[] = L"Free"; const WCHAR g_wszNeutral[] = L"Neutral"; const WCHAR g_wszProgId[] = L"Progid"; const WCHAR g_wszProcessId[] = L"AppID"; const WCHAR g_wszAppidTemplate[] = L"AppID\\{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"; const WCHAR g_wszLocalService[] = L"LocalService"; const WCHAR g_wszDllSurrogate[] = L"DllSurrogate"; const WCHAR g_wszDllSurrogateExecutable[] = L"DllSurrogateExecutable"; const WCHAR g_wszDebugSurrogate[] = L"DebugSurrogate"; const WCHAR g_wszDllHostSlashProcessId[] = L"DllHost.exe /Processid:"; const WCHAR g_wszDllHost[] = L"DllHost.exe"; const WCHAR g_wszEmbedding[] = L" -Embedding"; #define STRLEN_WCHAR(s) ((sizeof((s)) / sizeof((s)[0])) -1) #define STRLEN_OLE32DLL (STRLEN_WCHAR(g_wszOle32Dll)) #ifdef _WIN64 HRESULT GetFileTypeFromRegString (LPCWSTR pwszRegString, CoModuleType* pFileType) { // We need to get the file type of the binary in the inputstring. // However, there may be cmd line arguments at the end complicating matters. // // As a heuristic, we'll look for an initial quote. // If there's a quote, then we'll scan to the end of the quote // and cut off everything else off. // If there isn't a quote, we'll scan until we hit a space HRESULT hr; size_t stDiff, stStrLen = wcslen (pwszRegString) + 1; WCHAR* pwsEnd, * pwszFileName = (WCHAR*) _alloca (stStrLen * sizeof (WCHAR)); if (pwszRegString[0] == L'\"') { // Search for the end quote pwsEnd = wcsstr (pwszRegString + 1, L"\""); if (pwsEnd == NULL) { // Ill formed string; copy without the quote and hope it works wcscpy (pwszFileName, pwszRegString + 1); } else { // Copy everything inside the quotes, stripping the quotes // because Create Process doesn't like quotes // This covers cases like: "C:\Program Files\Directory\Exe.exe" or // "C:\Program Files\Directory\Exe.exe" /Surrogate stDiff = pwsEnd - pwszRegString - 1; wcsncpy (pwszFileName, pwszRegString + 1, stDiff); pwszFileName[stDiff] = L'\0'; } } else { // Search for a space pwsEnd = wcsstr (pwszRegString + 1, L" "); if (pwsEnd == NULL) { // Just copy the line // This covers cases like: C:\Progra~1\Directory\Exe.exe wcscpy (pwszFileName, pwszRegString); } else { // Copy to the space // This covers cases like: C:\Progra~1\Directory\Exe.exe /Surrogate stDiff = pwsEnd - pwszRegString; wcsncpy (pwszFileName, pwszRegString, stDiff); pwszFileName[stDiff] = L'\0'; } } // Now that we have the right kind of string, get the file type hr = CoGetModuleType (pwszFileName, pFileType); return hr; } #endif /* * class CComClassInfo */ CComClassInfo::CComClassInfo() { m_cRef = 0; #if DBG m_cRefCache = 0; #endif m_cLocks = 0; m_hKeyClassesRoot = NULL; m_fValues = VALUE_NONE; m_clsctx = 0; m_pwszProgid = NULL; m_pwszClassName = NULL; m_pwszInprocServer32 = NULL; m_pwszInprocHandler32 = NULL; m_pwszLocalServer = NULL; m_pwszInprocServer16 = NULL; m_pwszRemoteServerName = NULL; m_pwszInprocHandler16 = NULL; m_pwszSurrogateCommand = NULL; m_pwszServerExecutable = NULL; m_pUserToken = NULL; } HRESULT CComClassInfo::FinalConstruct( IUserToken *pUserToken, HKEY hKeyClassesRoot, const GUID *pClsid, WCHAR *pwszClsidString, HKEY hKey, REGSAM regType ) { HRESULT hr = S_OK; CatalogDebugOut((DEB_CLASSINFO, "CComClassInfo::FinalConstruct: this %p hkcr %p clsid %ws\n", this, hKeyClassesRoot, pwszClsidString)); wcsncpy(m_wszClsidString, pwszClsidString, sizeof(m_wszClsidString)/sizeof(*m_wszClsidString)); m_wszClsidString[sizeof(m_wszClsidString)/sizeof(*m_wszClsidString) - 1] = L'\0'; m_regType = regType; m_clsid = *pClsid; m_pUserToken = pUserToken; if (m_pUserToken != NULL) m_pUserToken->AddRef(); LONG lRet = RegOpenKeyEx(hKeyClassesRoot, NULL, 0, KEY_READ, &m_hKeyClassesRoot); if (lRet != ERROR_SUCCESS) hr = HRESULT_FROM_WIN32(lRet); CatalogDebugOut((DEB_CLASSINFO, "CComClassInfo::FinalConstruct: returning 0x%08x\n", hr)); return hr; } #define DELETE_CLASS_STRING(p) \ if (((p) != NULL) && ((p) != g_wszEmptyString)) \ { \ delete [] (p); \ } CComClassInfo::~CComClassInfo() { DELETE_CLASS_STRING(m_pwszProgid); DELETE_CLASS_STRING(m_pwszClassName); DELETE_CLASS_STRING(m_pwszInprocServer32); DELETE_CLASS_STRING(m_pwszInprocHandler32); DELETE_CLASS_STRING(m_pwszLocalServer); DELETE_CLASS_STRING(m_pwszInprocServer16); DELETE_CLASS_STRING(m_pwszRemoteServerName); DELETE_CLASS_STRING(m_pwszInprocHandler16); DELETE_CLASS_STRING(m_pwszSurrogateCommand); DELETE_CLASS_STRING(m_pwszServerExecutable); if ( m_pUserToken != NULL ) { m_pUserToken->Release(); } if (m_hKeyClassesRoot) { RegCloseKey(m_hKeyClassesRoot); m_hKeyClassesRoot = NULL; } } /* IUnknown methods */ STDMETHODIMP CComClassInfo::QueryInterface( REFIID riid, LPVOID FAR* ppvObj) { *ppvObj = NULL; if ( riid == IID_IComClassInfo ) { *ppvObj = (LPVOID) (IComClassInfo *) this; } else if ( riid == IID_IClassClassicInfo ) { *ppvObj = (LPVOID) (IClassClassicInfo *) this; } else if ( riid == IID_IClassClassicInfo2 ) { *ppvObj = (LPVOID) (IClassClassicInfo2 *) this; } #if DBG else if ( riid == IID_ICacheControl ) { *ppvObj = (LPVOID) (ICacheControl *) this; } #endif else if ( riid == IID_IUnknown ) { *ppvObj = (LPVOID) (IComClassInfo *) this; } if ( *ppvObj != NULL ) { ((LPUNKNOWN)*ppvObj)->AddRef(); return NOERROR; } return(E_NOINTERFACE); } STDMETHODIMP_(ULONG) CComClassInfo::AddRef(void) { long cRef; cRef = InterlockedIncrement(&m_cRef); return(cRef); } STDMETHODIMP_(ULONG) CComClassInfo::Release(void) { long cRef; cRef = InterlockedDecrement(&m_cRef); if ( cRef == 0 ) { #if DBG //Win4Assert((m_cRefCache == 0) && "attempt to release an un-owned ClassInfo object"); #endif delete this; } return(cRef); } /* IComClassInfo methods */ HRESULT STDMETHODCALLTYPE CComClassInfo::GetConfiguredClsid ( /* [out] */ GUID __RPC_FAR *__RPC_FAR *ppguidClsid ) { *ppguidClsid = &m_clsid; return(S_OK); } HRESULT STDMETHODCALLTYPE CComClassInfo::GetProgId ( /* [out] */ WCHAR __RPC_FAR *__RPC_FAR *pwszProgid ) { HKEY hKey; if ( (m_fValues & VALUE_PROGID) == 0 ) { g_CatalogLock.AcquireWriterLock(); if ( (m_fValues & VALUE_PROGID) == 0 ) { if ( ERROR_SUCCESS == RegOpenKeyExW(m_hKeyClassesRoot, m_wszClsidString, 0, KEY_READ | m_regType, &hKey) ) { GetRegistryStringValue(hKey, g_wszProgId, NULL, RQ_ALLOWQUOTEQUOTE, &m_pwszProgid); RegCloseKey(hKey); } m_fValues |= VALUE_PROGID; } g_CatalogLock.ReleaseWriterLock(); } *pwszProgid = m_pwszProgid; if ( m_pwszProgid != NULL && m_pwszProgid[0] != L'\0' ) { return(S_OK); } else { return(E_FAIL); } } HRESULT STDMETHODCALLTYPE CComClassInfo::GetClassName ( /* [out] */ WCHAR __RPC_FAR *__RPC_FAR *pwszClassName ) { HKEY hKey; if ( (m_fValues & VALUE_CLASSNAME) == 0 ) { g_CatalogLock.AcquireWriterLock(); if ( (m_fValues & VALUE_CLASSNAME) == 0 ) { if (ERROR_SUCCESS == RegOpenKeyExW(m_hKeyClassesRoot, m_wszClsidString, 0, KEY_READ | m_regType, &hKey)) { GetRegistryStringValue(hKey, NULL, NULL, RQ_ALLOWQUOTEQUOTE, &m_pwszClassName); RegCloseKey(hKey); } m_fValues |= VALUE_CLASSNAME; } g_CatalogLock.ReleaseWriterLock(); } *pwszClassName = m_pwszClassName; if ( (m_pwszClassName != NULL) && (*m_pwszClassName != L'\0') ) { return(S_OK); } else { return(E_FAIL); } } HRESULT STDMETHODCALLTYPE CComClassInfo::GetApplication ( /* [in] */ REFIID riid, /* [out] */ void __RPC_FAR *__RPC_FAR *ppv ) { return(E_FAIL); } #ifdef DARWIN_ENABLED HRESULT CComClassInfo::GetDarwinIdentifier(HKEY hKey, LPCWSTR wszInprocServerRegValue, LPWSTR *lpwszInprocServerKey) { // The Darwin identifiers are stored in a named value of the same name as the // server subkey. Thus a LocalServer32 named value could exist under the // LocalSever32 CLSID subkey, or an InprocServer32 named value could exist // under the InprocServer32 subkey. 16 bit servers are not supported. // // Additional details can be found in the ZAW spec on // \\popcorn\razzle1\src\spec\zawdes.doc. LPWSTR pwszDarwinId=NULL; // Read Darwin identifier if present HRESULT hr = GetRegistryStringValue(hKey, wszInprocServerRegValue, wszInprocServerRegValue, RQ_MULTISZ, &pwszDarwinId); if (SUCCEEDED(hr)) { // Found a Darwin descriptor // Call Darwin and use the returned path as IPS32 hr=GetPathFromDarwinDescriptor(pwszDarwinId, lpwszInprocServerKey); DELETE_CLASS_STRING(pwszDarwinId); if (SUCCEEDED(hr)) { // Darwin might give back a quoted string: unquote it if ((*lpwszInprocServerKey)[0] == L'"') { size_t cbValue = wcslen(*lpwszInprocServerKey); if ((cbValue >= 2) && ((*lpwszInprocServerKey)[cbValue - 1] == L'"')) { WCHAR *t = *lpwszInprocServerKey; WCHAR *s = t + 1; (*lpwszInprocServerKey)[cbValue - 1] = L'\0'; while (*t++ = *s++) { /* slide the string down */ } } } } } return hr; } #endif HRESULT STDMETHODCALLTYPE CComClassInfo::GetClassContext ( /* [in] */ CLSCTX clsctxFilter, /* [out] */ CLSCTX __RPC_FAR *pclsctx ) { HRESULT hr; LONG res; HKEY hKey = NULL; HKEY hKey2; WCHAR *pwsz; int clsctxNotValid; _GUID *pguidProcess; // If there's any chance we'll need hKey, get it now so we don't have to // open it once for the Darwin code and again down below. If another // thread beats us in, then we wind up not using hKey after all, but // that's okay - we optimize the normal case. if ( clsctxFilter & ~m_fValues ) { res = RegOpenKeyExW(m_hKeyClassesRoot, m_wszClsidString, 0, KEY_READ | m_regType, &hKey); if (res != ERROR_SUCCESS) { return HRESULT_FROM_WIN32(res); } } #ifdef DARWIN_ENABLED WCHAR *pwszDarwinLocalServer = NULL; WCHAR *pwszDarwinInprocServer32 = NULL; // See if we *might* need to get class info from Darwin. We don't want to // serialize threads through possibly lengthy Darwin code, so we accept the // fact that multiple threads could pass through here for the same class. // We take care to avoid updating any member variables in this unprotected // section. clsctxNotValid = clsctxFilter & ~m_fValues & (CLSCTX_INPROC_SERVER|CLSCTX_LOCAL_SERVER); if ( clsctxNotValid & CLSCTX_INPROC_SERVER ) { hr = GetDarwinIdentifier(hKey, g_wszInprocServer32, &pwszDarwinInprocServer32); //Win4Assert( SUCCEEDED(hr) || pwszDarwinInprocServer32 == NULL); } if ( clsctxNotValid & CLSCTX_LOCAL_SERVER ) { // The Darwin identifiers are stored in a named value of the same name as the // server subkey. Thus a LocalServer32 named value could exist under the // LocalSever32 CLSID subkey, or an InprocServer32 named value could exist // under the InprocServer32 subkey. 16 bit servers are not supported. // // Additional details can be found in the ZAW spec on // \\popcorn\razzle1\src\spec\zawdes.doc. LPWSTR pwszDarwinId = NULL; // Read Darwin identifier if present hr = GetRegistryStringValue(hKey, g_wszLocalServer32, g_wszLocalServer32, RQ_MULTISZ, &pwszDarwinId); if ( SUCCEEDED(hr) ) { // Found a Darwin descriptor // We purposefully resolve Darwin ids in the client as well so that // we can see the install UI. This is not possible from rpcss since // it is not in Winsta0. // Get the path from Darwin: this can cause files to be copied, registry keys to // be written or pretty much anything else... hr = GetPathFromDarwinDescriptor(pwszDarwinId, &pwszDarwinLocalServer); //Win4Assert( SUCCEEDED(hr) || pwszDarwinLocalServer == NULL); DELETE_CLASS_STRING(pwszDarwinId); } } #endif // Second pass through after loading all Darwin info... if ( clsctxFilter & ~m_fValues ) { g_CatalogLock.AcquireWriterLock(); clsctxNotValid = clsctxFilter & ~m_fValues & ~CLSCTX_REMOTE_SERVER; if ( clsctxNotValid & CLSCTX_INPROC_SERVER ) { #ifdef DARWIN_ENABLED if (pwszDarwinInprocServer32) { m_clsctx |= CLSCTX_INPROC_SERVER; m_pwszInprocServer32 = pwszDarwinInprocServer32; pwszDarwinInprocServer32 = NULL; goto foundInprocServer; } #endif hr = GetRegistryStringValue(hKey, g_wszInprocServer32, NULL, 0, &m_pwszInprocServer32); if ( SUCCEEDED(hr) ) { if ( m_pwszInprocServer32 && *m_pwszInprocServer32 ) { m_clsctx |= CLSCTX_INPROC_SERVER; } else { DELETE_CLASS_STRING(m_pwszInprocServer32); m_pwszInprocServer32=NULL; } } foundInprocServer: m_fValues |= VALUE_INPROC_SERVER; } if ( clsctxNotValid & CLSCTX_INPROC_HANDLER ) { hr = GetRegistryStringValue(hKey, g_wszInprocHandler32, NULL, 0, &m_pwszInprocHandler32); if ( SUCCEEDED(hr) ) { if ( m_pwszInprocHandler32 && *m_pwszInprocHandler32 ) { m_clsctx |= CLSCTX_INPROC_HANDLER; } else { DELETE_CLASS_STRING(m_pwszInprocHandler32); m_pwszInprocHandler32=NULL; } } m_fValues |= VALUE_INPROC_HANDLER; } if ( clsctxNotValid & CLSCTX_LOCAL_SERVER ) { #ifdef DARWIN_ENABLED if (pwszDarwinLocalServer) { m_clsctx |= CLSCTX_LOCAL_SERVER; m_pwszLocalServer = pwszDarwinLocalServer; pwszDarwinLocalServer = NULL; m_fValues |= VALUE_LOCALSERVERIS32; goto foundLocalServer; } #endif hr = GetRegistryStringValue(hKey, g_wszLocalServer32, NULL, 0, &m_pwszLocalServer); if ( SUCCEEDED(hr) ) { Win4Assert(m_pwszLocalServer != NULL); #ifdef _WIN64 BOOL fValid = TRUE; // Because all the AppID settings are not reflected, we need to // make sure we're dealing with the correct side of the registry. // // In RPCSS, the bitness of the executable in the LocalServer32 // key must match our bitness. In practice, we only check if we // are not the 32bit registry. (If there turn out to be more registries // later, we will need to change this.... hahaha) if (g_bInSCM && (m_regType != KEY_WOW64_32KEY)) { CoModuleType processType; RPC_STATUS status; // Best effort impersonate before hitting the disk, because rpcss // credentials may not have access to the file status = RpcImpersonateClient (NULL); if (SUCCEEDED (GetFileTypeFromRegString (m_pwszLocalServer, &processType))) { // If this is the processType that gets the other // side of the registry, then *I* am not qualified // to answer *ANY* configuration questions about this class. // Go bother someone else. if (processType == CO_MODULE_32BIT) { CatalogDebugOut((DEB_CLASSINFO, "CComClassInfo appears valid, but is for the wrong process type.\n")); delete [] m_pwszLocalServer; m_pwszLocalServer = NULL; fValid = FALSE; } } else { // If GetProcessType failed then I say the LocalServer32 // key is invalid. delete [] m_pwszLocalServer; m_pwszLocalServer = NULL; fValid = FALSE; } if (status == RPC_S_OK) { RpcRevertToSelf(); } } if (fValid) #endif { m_clsctx |= CLSCTX_LOCAL_SERVER; m_fValues |= VALUE_LOCALSERVERIS32; goto foundLocalServer; } } hr = GetRegistryStringValue(hKey, g_wszLocalServer16, NULL, 0, &m_pwszLocalServer); if ( SUCCEEDED(hr) ) { m_clsctx |= CLSCTX_LOCAL_SERVER; goto foundLocalServer; } hr = GetProcessId(&pguidProcess); if ( hr == S_OK ) { WCHAR wszAppidString[45]; wcscpy(wszAppidString, g_wszAppidTemplate); GUIDToString(pguidProcess, wszAppidString + 7); res = RegOpenKeyExW (m_hKeyClassesRoot, wszAppidString, 0, KEY_READ | m_regType, &hKey2); if ( ERROR_SUCCESS == res ) { const DWORD cchValue = 10; WCHAR wszValue [cchValue + 1]; DWORD cbValue = 0; res = RegQueryValueExW(hKey2, g_wszDllSurrogate, NULL, NULL, NULL, &cbValue); if (ERROR_SUCCESS == res && cbValue > 1) { WCHAR* pwszSurrogate = (WCHAR*) _alloca (cbValue + sizeof (WCHAR)); res = RegQueryValueExW(hKey2, g_wszDllSurrogate, NULL, NULL, (BYTE *) pwszSurrogate, &cbValue); if (ERROR_SUCCESS == res) { BOOL bAcceptable = TRUE; // We found a surrogate // // We need to be careful, though - if we're in the 64 bit registry // and the surrogate is a custom surrogate and it's 32 bit, // we shouldn't add local server to our acceptable contexts because // this way we'll fall through to a 32 bit classinfo that will do the right thing #ifdef _WIN64 if (g_bInSCM && m_regType != KEY_WOW64_32KEY && pwszSurrogate[0] != L'\0') { CoModuleType processType; RPC_STATUS status; status = RpcImpersonateClient (NULL); hr = GetFileTypeFromRegString (pwszSurrogate, &processType); if (FAILED (hr) || processType != CO_MODULE_64BIT) { bAcceptable = FALSE; } if (status == RPC_S_OK) { RpcRevertToSelf(); } } #endif if (bAcceptable) { RegCloseKey(hKey2); m_clsctx |= CLSCTX_LOCAL_SERVER; goto foundLocalServer; } } } cbValue = (DWORD) (cchValue * sizeof(WCHAR)); res = RegQueryValueExW(hKey2, g_wszLocalService, NULL, NULL, (BYTE *) wszValue, &cbValue); if ((cbValue > 3) && ((ERROR_SUCCESS == res) || (ERROR_MORE_DATA == res))) { RegCloseKey(hKey2); m_clsctx |= CLSCTX_LOCAL_SERVER; goto foundLocalServer; } RegCloseKey(hKey2); } } foundLocalServer: m_fValues |= VALUE_LOCAL_SERVER; } if ( clsctxNotValid & CLSCTX_INPROC_SERVER16 ) { hr = GetRegistryStringValue(hKey, g_wszInprocServer16, NULL, 0, &m_pwszInprocServer16); if ( SUCCEEDED(hr) ) { m_clsctx |= CLSCTX_INPROC_SERVER16; } m_fValues |= VALUE_INPROC_SERVER16; } if ( clsctxNotValid & CLSCTX_INPROC_HANDLER16 ) { hr = GetRegistryStringValue(hKey, g_wszInprocHandler16, NULL, 0, &m_pwszInprocHandler16); if ( SUCCEEDED(hr) ) { m_clsctx |= CLSCTX_INPROC_HANDLER16; } m_fValues |= VALUE_INPROC_HANDLER16; } g_CatalogLock.ReleaseWriterLock(); } if (hKey) { RegCloseKey(hKey); } *pclsctx = (CLSCTX) (((int) clsctxFilter) & (m_clsctx | CLSCTX_REMOTE_SERVER | CLSCTX_INPROC_HANDLER | CLSCTX_INPROC_HANDLER16 | CLSCTX_NO_FAILURE_LOG)); #ifdef DARWIN_ENABLED // Normally, these are assigned to member variables, but if we had multiple // threads racing through the unprotected Darwin calls, we might need to // free memory that was allocated by the "losing" thread(s). DELETE_CLASS_STRING(pwszDarwinInprocServer32); DELETE_CLASS_STRING(pwszDarwinLocalServer); #endif return(S_OK); } HRESULT STDMETHODCALLTYPE CComClassInfo::GetCustomActivatorCount ( /* [in] */ ACTIVATION_STAGE activationStage, /* [out] */ unsigned long __RPC_FAR *pulCount ) { *pulCount = 0; return(S_OK); } HRESULT STDMETHODCALLTYPE CComClassInfo::GetCustomActivatorClsids ( /* [in] */ ACTIVATION_STAGE activationStage, /* [out] */ GUID __RPC_FAR *__RPC_FAR *prgguidClsid ) { *prgguidClsid = NULL; return(E_NOTIMPL); } HRESULT STDMETHODCALLTYPE CComClassInfo::GetCustomActivators ( /* [in] */ ACTIVATION_STAGE activationStage, /* [out] */ ISystemActivator __RPC_FAR *__RPC_FAR *__RPC_FAR *prgpActivator ) { *prgpActivator = NULL; return(S_FALSE); } HRESULT STDMETHODCALLTYPE CComClassInfo::GetTypeInfo ( /* [in] */ REFIID riid, /* [out] */ void __RPC_FAR *__RPC_FAR *ppv ) { *ppv = NULL; return(E_NOTIMPL); } HRESULT STDMETHODCALLTYPE CComClassInfo::IsComPlusConfiguredClass ( /* [out] */ BOOL __RPC_FAR *pfComPlusConfiguredClass ) { *pfComPlusConfiguredClass = FALSE; return(S_OK); } /* IClassClassicInfo methods */ HRESULT STDMETHODCALLTYPE CComClassInfo::GetThreadingModel ( /* [out] */ ThreadingModel __RPC_FAR *pthreadmodel ) { HRESULT hr; HKEY hKey; CLSCTX clsctx; if ( (m_fValues & VALUE_THREADINGMODEL) == 0 ) { g_CatalogLock.AcquireWriterLock(); if ( (m_fValues & VALUE_THREADINGMODEL) == 0 ) { m_threadingmodel = SingleThreaded; /* default */ if ( (m_fValues & VALUE_INPROC_SERVER) == 0 ) { GetClassContext(CLSCTX_INPROC_SERVER, &clsctx); } if ( m_pwszInprocServer32 != NULL ) { /* OLE32.DLL is always BOTH */ /* check for "ole32.dll" or anypath+"\ole32.dll" */ const size_t cch = wcslen(m_pwszInprocServer32); if ( ((cch == STRLEN_OLE32DLL) || ((cch > STRLEN_OLE32DLL) && (m_pwszInprocServer32[cch - STRLEN_OLE32DLL - 1] == L'\\'))) && ( _wcsicmp(m_pwszInprocServer32 + cch - STRLEN_OLE32DLL, g_wszOle32Dll) == 0) ) { m_threadingmodel = BothThreaded; } else { if ( ERROR_SUCCESS == RegOpenKeyExW(m_hKeyClassesRoot, m_wszClsidString, 0, KEY_READ | m_regType, &hKey) ) { WCHAR wszValue[25]; hr = ReadRegistryStringValue(hKey, g_wszInprocServer32, g_wszThreadingModel, FALSE, wszValue, sizeof(wszValue)/sizeof(WCHAR)); if ( SUCCEEDED(hr) ) { if ( _wcsicmp(wszValue, g_wszApartment) == 0 ) { m_threadingmodel = ApartmentThreaded; } else if ( _wcsicmp(wszValue, g_wszBoth) == 0 ) { m_threadingmodel = BothThreaded; } else if ( _wcsicmp(wszValue, g_wszFree) == 0 ) { m_threadingmodel = FreeThreaded; } else if ( _wcsicmp(wszValue, g_wszNeutral) == 0 ) { m_threadingmodel = NeutralThreaded; } else if ( *wszValue == L'\0' ) { // Treat this as if the value wasn't specified at all } else if ( _wcsicmp(wszValue, L"Single") == 0 ) { // NT #339216 - Some vendors thought ThreadingModel=Single // was valid. Treat this as if the value wasn't specified at all } else { m_threadingmodel = -1; /* unrecognized */ } } RegCloseKey(hKey); } } } m_fValues |= VALUE_THREADINGMODEL; } g_CatalogLock.ReleaseWriterLock(); } if ( m_threadingmodel != -1 ) { *pthreadmodel = (ThreadingModel) m_threadingmodel; return(S_OK); } else { return(REGDB_E_INVALIDVALUE); } } HRESULT STDMETHODCALLTYPE CComClassInfo::GetModulePath ( /* [in] */ CLSCTX clsctx, /* [out] */ WCHAR __RPC_FAR *__RPC_FAR *pwszDllName ) { int clsctxAvailable; WCHAR *pwsz; *pwszDllName = NULL; /* make sure exactly one context is requested */ if ( (clsctx & (clsctx - 1)) != 0 ) { return(E_FAIL); } GetClassContext(clsctx, (CLSCTX *) &clsctxAvailable); if ( clsctx & clsctxAvailable ) { switch ( clsctx ) { case CLSCTX_INPROC_SERVER: pwsz = m_pwszInprocServer32; break; case CLSCTX_INPROC_HANDLER: pwsz = m_pwszInprocHandler32; break; case CLSCTX_LOCAL_SERVER: pwsz = m_pwszLocalServer; break; case CLSCTX_INPROC_SERVER16: pwsz = m_pwszInprocServer16; break; case CLSCTX_REMOTE_SERVER: GetRemoteServerName(&pwsz); break; case CLSCTX_INPROC_HANDLER16: pwsz = m_pwszInprocHandler16; break; default: Win4Assert (!"Unexpected class context"); return E_UNEXPECTED; } if ( pwsz != NULL ) { *pwszDllName = pwsz; return(S_OK); } } return(E_FAIL); } HRESULT STDMETHODCALLTYPE CComClassInfo::GetImplementedClsid ( /* [out] */ GUID __RPC_FAR *__RPC_FAR *ppguidClsid ) { *ppguidClsid = &m_clsid; return(S_OK); } HRESULT STDMETHODCALLTYPE CComClassInfo::GetProcess ( /* [in] */ REFIID riid, /* [out] */ void __RPC_FAR *__RPC_FAR *ppv ) { *ppv = NULL; _GUID *pProcessId; HRESULT hr = GetProcessId(&pProcessId); if ( hr == S_OK ) { DWORD flags = 0; // Make sure that if we're a 32bit ClassInfo we take the // 32bit ProcessInfo if (m_regType == KEY_WOW64_32KEY) flags = CAT_REG32_ONLY; hr = CComCatalog::GetProcessInfoInternal(flags, m_pUserToken, m_guidProcessId, riid, ppv); } else { hr = E_FAIL; } return(hr); } HRESULT STDMETHODCALLTYPE CComClassInfo::GetRemoteServerName ( /* [out] */ WCHAR __RPC_FAR *__RPC_FAR *pwszServerName ) { HRESULT hr; if ( (m_fValues & VALUE_REMOTE_SERVER) == 0 ) { g_CatalogLock.AcquireWriterLock(); if ( (m_fValues & VALUE_REMOTE_SERVER) == 0 ) { _GUID *pguidProcess; hr = GetProcessId(&pguidProcess); if ( hr == S_OK ) { WCHAR wszAppidString[45]; wcscpy(wszAppidString, g_wszAppidTemplate); GUIDToString(pguidProcess, wszAppidString + 7); HKEY hKey; if (ERROR_SUCCESS == RegOpenKeyExW(m_hKeyClassesRoot, wszAppidString, 0, KEY_READ | m_regType, &hKey)) { hr = GetRegistryStringValue(hKey, NULL, g_wszRemoteServerName, (RQ_MULTISZ | RQ_ALLOWQUOTEQUOTE), &m_pwszRemoteServerName); if ( SUCCEEDED(hr) ) { m_clsctx |= CLSCTX_REMOTE_SERVER; } RegCloseKey(hKey); } } m_fValues |= VALUE_REMOTE_SERVER; } g_CatalogLock.ReleaseWriterLock(); } *pwszServerName = m_pwszRemoteServerName; if ( m_pwszRemoteServerName != NULL ) { return(S_OK); } else { return(E_FAIL); } } HRESULT STDMETHODCALLTYPE CComClassInfo::GetLocalServerType ( /* [out] */ LocalServerType __RPC_FAR *pType ) { CLSCTX clsctx; GetClassContext(CLSCTX_LOCAL_SERVER, &clsctx); if ( m_pwszLocalServer == NULL ) { return(E_FAIL); } else if ( m_fValues & VALUE_LOCALSERVERIS32 ) { *pType = LocalServerType32; } else { *pType = LocalServerType16; } return(S_OK); } HRESULT STDMETHODCALLTYPE CComClassInfo::GetSurrogateCommandLine ( /* [out] */ WCHAR __RPC_FAR *__RPC_FAR *pwszSurrogateCommandLine ) { HRESULT hr; IComProcessInfo *pProcess; size_t cch; _GUID *pguidProcess; if ( (m_fValues & VALUE_SURROGATE_COMMAND) == 0 ) { g_CatalogLock.AcquireWriterLock(); if ( (m_fValues & VALUE_SURROGATE_COMMAND) == 0 ) { hr = GetProcessId(&pguidProcess); if ( hr == S_OK ) { WCHAR wszAppidString[45]; wcscpy(wszAppidString, g_wszAppidTemplate); GUIDToString(pguidProcess, wszAppidString + 7); HKEY hKey; DWORD res = RegOpenKeyExW (m_hKeyClassesRoot, wszAppidString, 0, KEY_READ | m_regType, &hKey); if (res != ERROR_SUCCESS) hr = MAKE_SCODE( SEVERITY_ERROR, FACILITY_WIN32, res ); else { hr = GetRegistryStringValue(hKey, NULL, g_wszDebugSurrogate, 0, &m_pwszSurrogateCommand); RegCloseKey(hKey); } if ( SUCCEEDED(hr) ) { m_fValues |= VALUE_SURROGATE_IS_DBG; goto gotCommandLine; } } hr = GetProcess(IID_IComProcessInfo, (void **) &pProcess); if ( hr == S_OK ) { ProcessType eProcessType; hr = pProcess->GetProcessType(&eProcessType); if ( hr == S_OK ) { if ( eProcessType == ProcessTypeComPlus ) { WCHAR wszSystemDirectory[MAX_PATH] = L""; if (m_regType == KEY_WOW64_32KEY) { // Point over to the 32bit dllhost instead of the 64bit one. cch = GetSystemWow64Directory(wszSystemDirectory, STRLEN_WCHAR(wszSystemDirectory)); } else { cch = GetSystemDirectory(wszSystemDirectory, STRLEN_WCHAR(wszSystemDirectory)); } if (cch > 0) { if ( wszSystemDirectory[cch - 1] != L'\\' ) { wszSystemDirectory[cch] = L'\\'; cch++; wszSystemDirectory[cch] = L'\0'; } m_pwszSurrogateCommand = new WCHAR[ cch + STRLEN_WCHAR(g_wszDllHostSlashProcessId) + STRLEN_CURLY_GUID + 1]; if ( m_pwszSurrogateCommand != NULL ) { wcscpy(m_pwszSurrogateCommand, wszSystemDirectory); wcscpy(m_pwszSurrogateCommand + cch, g_wszDllHostSlashProcessId); cch += STRLEN_WCHAR(g_wszDllHostSlashProcessId); GUIDToCurlyString(&m_guidProcessId, m_pwszSurrogateCommand + cch); cch += STRLEN_CURLY_GUID; m_pwszSurrogateCommand[cch] = L'\0'; } } } else if ( eProcessType == ProcessTypeLegacySurrogate ) { WCHAR *pwszSurrogatePath; hr = pProcess->GetSurrogatePath(&pwszSurrogatePath); if ( hr == S_OK ) { cch = wcslen(pwszSurrogatePath); m_pwszSurrogateCommand = new WCHAR[ cch + 1 + STRLEN_CURLY_GUID + STRLEN_WCHAR(g_wszEmbedding) + 1]; if ( m_pwszSurrogateCommand != NULL ) { wcscpy(m_pwszSurrogateCommand, pwszSurrogatePath); m_pwszSurrogateCommand[cch] = L' '; cch += 1; GUIDToCurlyString(&m_clsid, m_pwszSurrogateCommand + cch); cch += STRLEN_CURLY_GUID; wcscpy(m_pwszSurrogateCommand + cch, g_wszEmbedding); } } } } pProcess->Release(); } gotCommandLine: m_fValues |= VALUE_SURROGATE_COMMAND; } g_CatalogLock.ReleaseWriterLock(); } if ( m_pwszSurrogateCommand != NULL ) { *pwszSurrogateCommandLine = m_pwszSurrogateCommand; return(S_OK); } else { return(E_OUTOFMEMORY); } } HRESULT STDMETHODCALLTYPE CComClassInfo::MustRunInClientContext ( /* [out] */ BOOL __RPC_FAR *pbMustRunInClientContext ) { *pbMustRunInClientContext = FALSE; return(S_OK); } HRESULT STDMETHODCALLTYPE CComClassInfo::GetVersionNumber ( /* [out] */ DWORD __RPC_FAR *pdwVersionMS, /* [out] */ DWORD __RPC_FAR *pdwVersionLS ) { return(E_NOTIMPL); } HRESULT STDMETHODCALLTYPE CComClassInfo::Lock(void) { return(S_OK); } HRESULT STDMETHODCALLTYPE CComClassInfo::Unlock(void) { return(S_OK); } /* IClassClassicInfo2 methods */ HRESULT STDMETHODCALLTYPE CComClassInfo::GetServerExecutable ( /* [out] */ WCHAR **pwszServerExecutable ) { IComProcessInfo *pProcess = NULL; HRESULT hr = S_OK; *pwszServerExecutable = NULL; if (!(m_fValues & VALUE_SERVER_EXECUTABLE)) { // If we can't to CLSCTX_LOCAL_SERVER, then this whole thing // is pointless anyway. CLSCTX clsctx; hr = GetClassContext(CLSCTX_LOCAL_SERVER, &clsctx); if (clsctx & CLSCTX_LOCAL_SERVER) { if (m_pwszLocalServer != NULL) { // We've got a LocalServer32. HKEY hkeyBase = NULL; DWORD res = RegOpenKeyExW(m_hKeyClassesRoot, m_wszClsidString, 0, KEY_READ | m_regType, &hkeyBase); if (res == ERROR_SUCCESS) { hr = GetRegistryStringValue(hkeyBase, g_wszLocalServer32, g_wszServerExecutable, 0, &m_pwszServerExecutable); RegCloseKey(hkeyBase); } else { hr = HRESULT_FROM_WIN32(res); } } else { hr = GetProcess(IID_IComProcessInfo, (void **) &pProcess); if ( hr == S_OK ) { ProcessType eProcessType; hr = pProcess->GetProcessType(&eProcessType); if (SUCCEEDED(hr)) { if ((eProcessType == ProcessTypeComPlus) || (eProcessType == ProcessTypeLegacySurrogate)) { // Attempt to fault in surrogate command line, so we can check // to see if we're using the debug surrogate value. If so, then // we don't want to have a ServerExecutable. // LPWSTR wszDummy = NULL; hr = GetSurrogateCommandLine(&wszDummy); if (FAILED(hr)) goto gotServerExe; if (m_fValues & VALUE_SURROGATE_IS_DBG) { // Don't read the registry-- you asked for the debug surrogate // key. hr = S_OK; goto gotServerExe; } } if (eProcessType == ProcessTypeComPlus) { // No registry reading for us-- you're a dllhost! WCHAR wszSystemDirectory[MAX_PATH+1] = L""; SIZE_T cch; if (m_regType == KEY_WOW64_32KEY) { // Point over to the 32bit dllhost instead of the 64bit one. cch = GetSystemWow64Directory(wszSystemDirectory, STRLEN_WCHAR(wszSystemDirectory)); } else { cch = GetSystemDirectory(wszSystemDirectory, STRLEN_WCHAR(wszSystemDirectory)); } if (cch > 0) { if ( wszSystemDirectory[cch - 1] != L'\\' ) { wszSystemDirectory[cch] = L'\\'; cch++; wszSystemDirectory[cch] = L'\0'; } m_pwszServerExecutable = new WCHAR[cch + STRLEN_WCHAR(g_wszDllHost) + 1]; if (m_pwszServerExecutable) { wcscpy(m_pwszServerExecutable, wszSystemDirectory); wcscpy(m_pwszServerExecutable+cch, g_wszDllHost); } else { hr = E_OUTOFMEMORY; } } else { hr = HRESULT_FROM_WIN32(GetLastError()); } } else if (eProcessType == ProcessTypeLegacySurrogate) { HKEY hkeyBase = NULL; GUID *pguidProcess; hr = GetProcessId(&pguidProcess); if (hr == S_OK) { WCHAR wszAppidString[45]; wcscpy(wszAppidString, g_wszAppidTemplate); GUIDToString(pguidProcess, wszAppidString + 7); DWORD res = RegOpenKeyExW (m_hKeyClassesRoot, wszAppidString, 0, KEY_READ | m_regType, &hkeyBase); if (res == ERROR_SUCCESS) { hr = GetRegistryStringValue(hkeyBase, NULL, g_wszDllSurrogateExecutable, 0, &m_pwszServerExecutable); RegCloseKey(hkeyBase); } else { hr = HRESULT_FROM_WIN32(res); } } } else { // Not any of these things, so there's no ServerExecutable // to get. hr = S_OK; } } } } } gotServerExe: if (hr != E_OUTOFMEMORY) { // Well, at least we tried. m_fValues |= VALUE_SERVER_EXECUTABLE; hr = S_OK; } } if (pProcess) { pProcess->Release(); } *pwszServerExecutable = m_pwszServerExecutable; return hr; } #if DBG /* ICacheControl methods */ STDMETHODIMP_(ULONG) CComClassInfo::CacheAddRef(void) { long cRef; cRef = InterlockedIncrement(&m_cRefCache); return(cRef); } STDMETHODIMP_(ULONG) CComClassInfo::CacheRelease(void) { long cRef; cRef = InterlockedDecrement(&m_cRefCache); return(cRef); } #endif /* private methods */ HRESULT STDMETHODCALLTYPE CComClassInfo::GetProcessId ( /* [out] */ GUID __RPC_FAR *__RPC_FAR *ppguidProcessId ) { HRESULT hr; HKEY hKey; if ( (m_fValues & VALUE_PROCESSID) == 0 ) { g_CatalogLock.AcquireWriterLock(); if ( (m_fValues & VALUE_PROCESSID) == 0 ) { if ( ERROR_SUCCESS == RegOpenKeyExW(m_hKeyClassesRoot, m_wszClsidString, 0, KEY_READ | m_regType, &hKey) ) { WCHAR wszValue[50]; hr = ReadRegistryStringValue(hKey, NULL, g_wszProcessId, FALSE, wszValue, sizeof(wszValue)/sizeof(WCHAR)); if ( SUCCEEDED(hr) ) { if ( CurlyStringToGUID(wszValue, &m_guidProcessId) == TRUE ) { m_fValues |= VALUE_PROCESSID_VALID; } } RegCloseKey(hKey); } m_fValues |= VALUE_PROCESSID; } g_CatalogLock.ReleaseWriterLock(); } if ( m_fValues & VALUE_PROCESSID_VALID ) { *ppguidProcessId = &m_guidProcessId; return(S_OK); } else { *ppguidProcessId = NULL; return(E_FAIL); } } #ifdef DARWIN_ENABLED //------------------------------------------------------------------------- // // CComClassInfo::GetPathFromDarwinDescriptor // // Looks for Darwin identifiers for a CLSID in the registry, and calls // MSI apis to process the identifiers into real paths. // // This method can cause Darwin applications to be installed for the calling // user. It should always be called before trying to load full CLSID settings. // // //------------------------------------------------------------------------- HRESULT CComClassInfo::GetPathFromDarwinDescriptor(LPWSTR pszDarwinId, LPWSTR* ppszPath) { INSTALLUILEVEL OldUILevel = INSTALLUILEVEL_NONE; WCHAR wszPath[MAX_PATH]; WCHAR * pwszPath; DWORD PathLength; int MsiStatus; HRESULT hr; *ppszPath = 0; hr = S_OK; pwszPath = wszPath; PathLength = sizeof(wszPath) / sizeof(WCHAR); if ( g_bInSCM ) { // Though we attempt to force all install actions to be done in the client, // there may still be instances when Darwin will want to put up install // UI when called from SCM. So we explicitly set the UI level to none // to prevent any possible UI calls from hanging this thread. // Note: we delay-load link to msi!MsiSetInternalUI, but the api cannot // return an error directly, given the way it is prototyped. The dload // error stub sets GLE to indicate a problem occurred. SetLastError(ERROR_SUCCESS); OldUILevel = MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); if (ERROR_PROC_NOT_FOUND == GetLastError()) return CO_E_MSI_ERROR; // // Impersonate so that Darwin can figure out the proper // HKU Software\Classes subkey. // if (RpcImpersonateClient( 0 ) != RPC_S_OK) { // Reset the UI level before we leave... MsiSetInternalUI(OldUILevel, NULL); return CO_E_MSI_ERROR; } } for ( ;; ) { // // On input, PathLength is number of wchars in pwszPath. On output // it is the length of the (needed) returned path in wchars, not including // the null. // MsiStatus = CommandLineFromMsiDescriptor( pszDarwinId, pwszPath, &PathLength ); PathLength++; if ( ERROR_MORE_DATA == MsiStatus ) { pwszPath = (WCHAR *) new WCHAR[PathLength]; if ( ! pwszPath ) { hr = E_OUTOFMEMORY; break; } continue; } if ( MsiStatus != ERROR_SUCCESS ) hr = CO_E_MSI_ERROR; break; } if ( g_bInSCM ) { RevertToSelf(); MsiSetInternalUI(OldUILevel, NULL); } if ( S_OK == hr ) { *ppszPath = new WCHAR[PathLength]; if ( *ppszPath ) wcscpy( *ppszPath, pwszPath ); } if ( pwszPath != wszPath ) delete [] pwszPath; if ( hr != S_OK ) return(hr); if ( ! *ppszPath ) return(E_OUTOFMEMORY); return hr; } #endif // DARWIN_ENABLED //+------------------------------------------------------------------- // // Function: CoGetModuleType (this api is currently unpublished!) // // Synopsis: API to retrieve the type of a given module (mainly, 32 vs 64 bit) // // Algorithm: Memory map the file and deduce its type from its headers // // History: 12-Feb-2002 mfeingol Created // //+------------------------------------------------------------------- STDAPI CoGetModuleType (LPCWSTR pwszModule, CoModuleType* pModType ) { HRESULT hr = S_OK; HANDLE hFile = INVALID_HANDLE_VALUE; HANDLE hFileMapping = NULL; WCHAR* pwszFullPath = NULL; LPVOID pBase = NULL; // Verify args // (CreateFile can't handle a path with quotes) if (pwszModule == NULL || pModType == NULL || pwszModule[0] == L'\"') return E_INVALIDARG; *pModType = CO_MODULE_UNKNOWN; // Memmap the requested file hFile = CreateFileW ( pwszModule, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL ); if (hFile == INVALID_HANDLE_VALUE && GetLastError() == ERROR_FILE_NOT_FOUND) { WCHAR* pszTmpFileName; SafeAllocaAllocate (pwszFullPath, (MAX_PATH + 1) * sizeof (WCHAR)); if (!pwszFullPath) { hr = E_OUTOFMEMORY; goto Cleanup; } DWORD dwRetVal = SearchPathW ( NULL, pwszModule, NULL, MAX_PATH, pwszFullPath, &pszTmpFileName ); if (dwRetVal == 0 || dwRetVal > MAX_PATH) { hr = HRESULT_FROM_WIN32 (GetLastError()); goto Cleanup; } hFile = CreateFileW ( pwszFullPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL ); } if (hFile == INVALID_HANDLE_VALUE) { hr = HRESULT_FROM_WIN32 (GetLastError()); goto Cleanup; } hFileMapping = CreateFileMapping ( hFile, NULL, PAGE_READONLY, 0, 0, NULL ); if (hFileMapping == NULL) { hr = HRESULT_FROM_WIN32 (GetLastError()); goto Cleanup; } pBase = MapViewOfFile (hFileMapping, FILE_MAP_READ, 0, 0, 0); if (pBase == NULL) { hr = HRESULT_FROM_WIN32 (GetLastError()); goto Cleanup; } // Get image header PIMAGE_NT_HEADERS pImage = RtlImageNtHeader (pBase); if (pImage == NULL) { hr = HRESULT_FROM_WIN32 (GetLastError()); goto Cleanup; } // Determine type switch (pImage->FileHeader.Machine) { case IMAGE_FILE_MACHINE_I386: *pModType = CO_MODULE_32BIT; break; case IMAGE_FILE_MACHINE_IA64: case IMAGE_FILE_MACHINE_AMD64: *pModType = CO_MODULE_64BIT; break; default: // Couldn't determine type hr = E_INVALIDARG; break; } Cleanup: if (pBase != NULL) UnmapViewOfFile (pBase); if (hFileMapping != NULL) CloseHandle (hFileMapping); if (hFile != INVALID_HANDLE_VALUE && hFile != NULL) CloseHandle (hFile); SafeAllocaFree (pwszFullPath); return hr; }
31.09375
144
0.486203
[ "object" ]
ec7f5a740629b46c379a5588cf49e7889ac3576a
2,909
cpp
C++
SurfaceReconstruction/SurfaceReconstruction/Refinement/FSSFParameters.cpp
pavelsevecek/TSR
ca411dedf178e5830f0536e361136f1e16751bc8
[ "BSD-3-Clause" ]
102
2017-10-17T10:10:59.000Z
2022-01-19T02:10:29.000Z
SurfaceReconstruction/SurfaceReconstruction/Refinement/FSSFParameters.cpp
pavelsevecek/TSR
ca411dedf178e5830f0536e361136f1e16751bc8
[ "BSD-3-Clause" ]
2
2019-12-21T11:59:15.000Z
2020-09-08T11:38:36.000Z
SurfaceReconstruction/SurfaceReconstruction/Refinement/FSSFParameters.cpp
pavelsevecek/TSR
ca411dedf178e5830f0536e361136f1e16751bc8
[ "BSD-3-Clause" ]
27
2017-10-18T09:37:34.000Z
2022-03-22T01:30:51.000Z
/* * Copyright (C) 2018 by Author: Aroudj, Samir * TU Darmstadt - Graphics, Capture and Massively Parallel Computing * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD 3-Clause license. See the License.txt file for details. */ #include <iostream> #include <string> #include "Math/MathHelper.h" #include "Platform/FailureHandling/Exception.h" #include "Platform/Utilities/ParametersManager.h" #include "SurfaceReconstruction/Refinement/FSSFParameters.h" using namespace FailureHandling; using namespace Math; using namespace std; using namespace SurfaceReconstruction; using namespace Utilities; FSSFParameters::FSSFParameters() { const ParametersManager &m = ParametersManager::getSingleton(); // intersection fixing search length maximum & step size bool ok = true; ok &= m.get(mEdgeMergeRelativeThreshold, "FSSF::edgeMergeRelativeThreshold"); // detection of spiky geometry ok &= m.get(mSpikyGeometryAngleThreshold, "FSSF::spikyGeometryAngleThreshold"); ok &= m.get(mSpikyGeometryRelativeScaleThreshold, "FSSF::spikyGeometryRelativeScaleThreshold"); // subdivision ok &= m.get(mSubdivisionRelativeErrorThreshold, "FSSF::subdivisionRelativeErrorThreshold"); ok &= m.get(mSubdivisionRelativeScaleMinimum, "FSSF::subdivisionRelativeScaleMinimum"); // sample support / mismatch confidence ok &= m.get(mProjectionConfidenceDistanceBandwidth, "FSSF::ProjectionConfidence::distanceBandwidth"); ok &= m.get(mProjectionConfidenceMaxAngleDifference, "FSSF::ProjectionConfidence::maxDegreesDifference"); // weak surface support threshold ok &= m.get(mSupportWeakThreshold, "FSSF::supportWeakThreshold"); // when to revert vertex position changes? ok &= m.get(mSurfaceErrorRelativeThreshold, "FSSF::surfaceErrorRelativeThreshold"); // smoothing ok &= m.get(mSmoothingUmbrellaLambdaHigh, "FSSF::Smoothing::umbrellaLambdaWeaklySupported"); ok &= m.get(mSmoothingUmbrellaLambdaLow, "FSSF::Smoothing::umbrellaLambdaWellSupported"); ok &= m.get(mSmoothingInitialIterCount, "FSSF::Smoothing::initialIterCount"); ok &= m.get(mSmoothingTaubinIterCount, "FSSF::Smoothing::taubinIterCount"); // rays per cone ok &= m.get(mRaysPerLinkedPair[0], "FSSF::raysPerLinkedPairDim0"); ok &= m.get(mRaysPerLinkedPair[1], "FSSF::raysPerLinkedPairDim1"); ok &= m.get(mOrientSamplingPattern, "FSSF::orientSamplingPattern"); // outlier removal stuff ok &= m.get(mOutlierIsleMinKeepingSize, "FSSF::outlierIsleMinKeepingSize"); // convert degrees to angles mSpikyGeometryAngleThreshold = convertDegreesToRadians(mSpikyGeometryAngleThreshold); mProjectionConfidenceMaxAngleDifference = convertDegreesToRadians(mProjectionConfidenceMaxAngleDifference); // check that all parameters were ok properly if (ok) return; string message = "FSSF: Could not load all required parameters."; cerr << message << endl; throw Exception(message); }
38.786667
108
0.785837
[ "geometry" ]
ec8497f1a34e95ef8389c4c12712af402bd3d3d4
2,275
cpp
C++
external/vulkancts/modules/vulkan/dynamic_state/vktDynamicStateBufferObjectUtil.cpp
TinkerBoard-Android/external_deqp
fbf76f4e30a964813b9cdfa0dd36dadc25220939
[ "Apache-2.0" ]
null
null
null
external/vulkancts/modules/vulkan/dynamic_state/vktDynamicStateBufferObjectUtil.cpp
TinkerBoard-Android/external_deqp
fbf76f4e30a964813b9cdfa0dd36dadc25220939
[ "Apache-2.0" ]
null
null
null
external/vulkancts/modules/vulkan/dynamic_state/vktDynamicStateBufferObjectUtil.cpp
TinkerBoard-Android/external_deqp
fbf76f4e30a964813b9cdfa0dd36dadc25220939
[ "Apache-2.0" ]
3
2017-01-21T00:56:25.000Z
2020-10-31T12:00:02.000Z
/*------------------------------------------------------------------------ * Vulkan Conformance Tests * ------------------------ * * Copyright (c) 2015 The Khronos Group Inc. * Copyright (c) 2015 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief Buffer Object Util *//*--------------------------------------------------------------------*/ #include "vktDynamicStateBufferObjectUtil.hpp" #include "vkQueryUtil.hpp" namespace vkt { namespace DynamicState { Buffer::Buffer (const vk::DeviceInterface& vk, vk::VkDevice device, vk::Move<vk::VkBuffer> object_) : m_allocation (DE_NULL) , m_object (object_) , m_vk (vk) , m_device (device) { } void Buffer::bindMemory (de::MovePtr<vk::Allocation> allocation) { DE_ASSERT(allocation); VK_CHECK(m_vk.bindBufferMemory(m_device, *m_object, allocation->getMemory(), allocation->getOffset())); DE_ASSERT(!m_allocation); m_allocation = allocation; } de::SharedPtr<Buffer> Buffer::createAndAlloc (const vk::DeviceInterface& vk, vk::VkDevice device, const vk::VkBufferCreateInfo &createInfo, vk::Allocator &allocator, vk::MemoryRequirement memoryRequirement) { de::SharedPtr<Buffer> ret = create(vk, device, createInfo); vk::VkMemoryRequirements bufferRequirements = vk::getBufferMemoryRequirements(vk, device, ret->object()); ret->bindMemory(allocator.allocate(bufferRequirements, memoryRequirement)); return ret; } de::SharedPtr<Buffer> Buffer::create (const vk::DeviceInterface& vk, vk::VkDevice device, const vk::VkBufferCreateInfo& createInfo) { return de::SharedPtr<Buffer>(new Buffer(vk, device, vk::createBuffer(vk, device, &createInfo))); } } // DynamicState } // vkt
31.164384
106
0.662418
[ "object" ]
ec8a3ce832140412fe5b49e3642868c49a8c1637
33,779
cc
C++
extensions/gst_video_element/gadget_videosink.cc
suzhe/google-gadgets-for-linux
b58baabd8458c8515c9902b8176151a08d240983
[ "Apache-2.0" ]
175
2015-01-01T12:40:33.000Z
2019-05-24T22:33:59.000Z
extensions/gst_video_element/gadget_videosink.cc
suzhe/google-gadgets-for-linux
b58baabd8458c8515c9902b8176151a08d240983
[ "Apache-2.0" ]
11
2015-01-19T16:30:56.000Z
2018-04-25T01:06:52.000Z
extensions/gst_video_element/gadget_videosink.cc
suzhe/google-gadgets-for-linux
b58baabd8458c8515c9902b8176151a08d240983
[ "Apache-2.0" ]
97
2015-01-19T15:35:29.000Z
2019-05-15T05:48:02.000Z
/* Copyright 2008 Google Inc. 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 "gadget_videosink.h" #include <pthread.h> namespace ggadget { namespace gst { class GadgetVideoSink::ImageBuffer { public: enum BufferRecycleFlag { BUFFER_NOT_RECYCLED, BUFFER_TO_BE_RECYCLED, BUFFER_RECYCLED }; static GType ImageBufferGetType() { static GType image_buffer_type; if (G_UNLIKELY(image_buffer_type == 0)) { static const GTypeInfo image_buffer_info = { sizeof(GstBufferClass), NULL, NULL, ImageBufferClassInit, NULL, NULL, sizeof(ImageBuffer), 0, 0, NULL }; image_buffer_type = g_type_register_static(GST_TYPE_BUFFER, "ImageBuffer", &image_buffer_info, static_cast<GTypeFlags>(0)); } return image_buffer_type; } #define IS_IMAGE_BUFFER(obj) \ (G_TYPE_CHECK_INSTANCE_TYPE((obj), ImageBuffer::ImageBufferGetType())) #define IMAGE_BUFFER(obj) \ (G_TYPE_CHECK_INSTANCE_CAST((obj), ImageBuffer::ImageBufferGetType(), \ ImageBuffer)) static void ImageBufferClassInit(gpointer g_class, gpointer class_data) { GGL_UNUSED(class_data); GstMiniObjectClass *mini_object_class = GST_MINI_OBJECT_CLASS(g_class); mini_object_class->finalize = (GstMiniObjectFinalizeFunction)Finalize; } static void Finalize(ImageBuffer *image) { g_return_if_fail(image != NULL); if (!image->videosink_) { GST_WARNING_OBJECT(image->videosink_, "no sink found"); return; } // For those that are already recycled or to be recycled, just return. if (image->recycle_flag_ != BUFFER_NOT_RECYCLED) return; if (image->width_ != GST_VIDEO_SINK_WIDTH(image->videosink_) || image->height_ != GST_VIDEO_SINK_HEIGHT(image->videosink_)) { // The data buffer is allocated by us, we free it ourselves. g_free(GST_BUFFER_DATA(image)); } else { // Append to buffer pool. gst_buffer_ref(GST_BUFFER_CAST(image)); image->recycle_flag_ = BUFFER_RECYCLED; image->videosink_->buffer_pool_ = g_slist_prepend(image->videosink_->buffer_pool_, image); } } static ImageBuffer *CreateInstance(GadgetVideoSink *videosink, GstCaps *caps) { ImageBuffer *image = IMAGE_BUFFER(gst_mini_object_new(ImageBufferGetType())); if (!image) return NULL; GstStructure *structure = gst_caps_get_structure(caps, 0); if (!gst_structure_get_int (structure, "width", &image->width_) || !gst_structure_get_int (structure, "height", &image->height_)) { GST_WARNING("failed getting geometry from caps %" GST_PTR_FORMAT, caps); return NULL; } // We use 32-bpp. image->bytes_per_line_ = 4 * image->width_; image->size_ = image->bytes_per_line_ * image->height_; GST_BUFFER_DATA(image) = (guchar *)g_malloc(image->size_); if (!GST_BUFFER_DATA(image)) { gst_buffer_unref(GST_BUFFER_CAST(image)); return NULL; } GST_BUFFER_SIZE(image) = static_cast<guint>(image->size_); image->recycle_flag_ = BUFFER_NOT_RECYCLED; // Keep a ref to our sink. image->videosink_ = videosink; gst_object_ref(videosink); return image; } static void FreeInstance(ImageBuffer *image) { if (image == NULL) return; // Make sure it is not recycled. image->width_ = -1; image->height_ = -1; if (image->videosink_) { gst_object_unref(image->videosink_); image->videosink_ = NULL; } g_free(GST_BUFFER_DATA(image)); gst_buffer_unref(GST_BUFFER_CAST(image)); } void SetRecycleFlag(BufferRecycleFlag flag) { recycle_flag_ = flag; } BufferRecycleFlag GetRecycleFlag() { return recycle_flag_; } // Must be the first non-static property. GstBuffer buffer_; GadgetVideoSink *videosink_; // Image's real size, width, and height. size_t size_; int width_, height_; // We need the following information to show an image. int x_, y_; int w_, h_; int bytes_per_line_; // Stride // The state of the buffer. BufferRecycleFlag recycle_flag_; private: // Cannot new/delete image buffer object explicitly. // Use @CreateInstance and @FreeInstance instead. ImageBuffer(); ~ImageBuffer(); }; // ImageQueue is a cycle buffer which manages ImageBuffers provided // by the host. class GadgetVideoSink::ImageQueue { public: static const int kMaxLength = 4; ImageQueue() : p_(0), c_(0) { pthread_mutex_init(&mutex_, NULL); for (int i = 0; i < kMaxLength; i++) images_[i] = NULL; } ~ImageQueue() { // Maybe consumer is holding the lock. pthread_mutex_lock(&mutex_); pthread_mutex_destroy(&mutex_); for (int i = 0; i < kMaxLength; i++) { if (images_[i]) ImageBuffer::FreeInstance(images_[i]); } } // Only provided to producer. It can help avoid passing in duplicated image // buffer pointer. Since consumer never changes the image queue, it's ok with // no using lock here for the sole producer. bool DupImage(ImageBuffer *image) { for (int i = 0; i < kMaxLength; i++) { if (image && images_[i] == image) return true; } return false; } // Store @a image to the queue, return one that won't be used and can // be recycled or destroyed by the host. ImageBuffer *ProduceOneImage(ImageBuffer *image) { ASSERT(image); // If the mutex is being destroyed, lock may fail. if (pthread_mutex_lock(&mutex_) != 0) return NULL; // If it's full, don't produce new images, just discard it. if ((p_ + 1) % kMaxLength == c_) { pthread_mutex_unlock(&mutex_); return image; } ImageBuffer *to_be_recycled = images_[p_]; images_[p_] = image; p_ = (p_ + 1) % kMaxLength; pthread_mutex_unlock(&mutex_); return to_be_recycled; } ImageBuffer *ConsumeOneImage() { // If the mutex is being destroyed, lock may fail. if (pthread_mutex_lock(&mutex_) != 0) return NULL; // Check if it's null. if (p_ == c_) { pthread_mutex_unlock(&mutex_); return NULL; } ImageBuffer *cur = images_[c_]; c_ = (c_ + 1) % kMaxLength; pthread_mutex_unlock(&mutex_); return cur; } private: int p_; int c_; ImageBuffer *images_[kMaxLength]; pthread_mutex_t mutex_; }; bool GadgetVideoSink::registered_ = false; GstVideoSinkClass *GadgetVideoSink::parent_class_ = NULL; GstStaticPadTemplate GadgetVideoSink::gadget_videosink_template_factory_ = GST_STATIC_PAD_TEMPLATE(const_cast<gchar*>("sink"), GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS("video/x-raw-rgb, " "framerate = (fraction) [ 0, MAX ]," "width = (int) [ 1, MAX ], " "height = (int) [ 1, MAX ]")); const GstElementDetails GadgetVideoSink::gst_videosink_details_ = GST_ELEMENT_DETAILS(const_cast<gchar*>("Video sink"), const_cast<gchar*>("Sink/Video"), const_cast<gchar*>("A standard X based videosink"), const_cast<gchar*>("Yuxiang Luo<luoyx@google.com>")); #define IS_GADGET_VIDEOSINK(obj) \ (G_TYPE_CHECK_INSTANCE_TYPE((obj), GadgetVideoSinkGetType())) #define GADGET_VIDEOSINK(obj) \ (G_TYPE_CHECK_INSTANCE_CAST((obj), GadgetVideoSinkGetType(), \ GadgetVideoSink)) bool GadgetVideoSink::Register() { if (registered_) return true; // gst_plugin_register_static() is available after gstreamter 0.10.16. #if GST_VERSION_MAJOR > 0 || GST_VERSION_MINOR > 10 || \ (GST_VERSION_MINOR == 10 && GST_VERSION_MICRO >= 16) if (!gst_plugin_register_static(GST_VERSION_MAJOR, GST_VERSION_MINOR, "gadget_videosink_plugin", const_cast<gchar *>(""), GadgetVideoSink::InitPlugin, "1.0", "unknown", "", "", "")) return false; #else // Hacked GST_PLUGIN_DEFINE_STATIC. GST_PLUGIN_DEFINE_STATIC uses gcc // specific "__attribute__((constructor))" which is not portable and reliable. static GstPluginDesc plugin_desc = { GST_VERSION_MAJOR, GST_VERSION_MINOR, "gadget_videosink_plugin", "", GadgetVideoSink::InitPlugin, "1.0", "unknown", "", "", "", GST_PADDING_INIT }; _gst_plugin_register_static(&plugin_desc); #endif // registered_ is set in InitPlugin(). return registered_; } gboolean GadgetVideoSink::InitPlugin(GstPlugin *plugin) { registered_ = gst_element_register(plugin, kGadgetVideoSinkElementName, GST_RANK_SECONDARY, GadgetVideoSinkGetType()); return registered_; } GType GadgetVideoSink::GadgetVideoSinkGetType(void) { static GType videosink_type = 0; if (!videosink_type) { static const GTypeInfo videosink_info = { sizeof(GadgetVideoSinkClass), BaseInit, NULL, (GClassInitFunc)ClassInit, NULL, NULL, sizeof(GadgetVideoSink), 0, (GInstanceInitFunc)Init, (GTypeValueTable*)NULL }; videosink_type = g_type_register_static(GST_TYPE_VIDEO_SINK, "GadgetVideoSink", &videosink_info, static_cast<GTypeFlags>(0)); g_type_class_ref(ImageBuffer::ImageBufferGetType()); } return videosink_type; } void GadgetVideoSink::Init(GadgetVideoSink *videosink) { videosink->caps_ = NULL; videosink->bus_ = NULL; videosink->image_ = NULL; videosink->image_queue_ = NULL; videosink->buffer_pool_ = NULL; videosink->fps_n_ = 0; videosink->fps_d_ = 1; videosink->par_ = NULL; videosink->keep_aspect_ = FALSE; } void GadgetVideoSink::BaseInit(gpointer g_class) { GstElementClass *element_class = GST_ELEMENT_CLASS(g_class); gst_element_class_set_details(element_class, &gst_videosink_details_); gst_element_class_add_pad_template( element_class, gst_static_pad_template_get(&gadget_videosink_template_factory_)); } void GadgetVideoSink::ClassInit(GadgetVideoSinkClass *klass) { GObjectClass *gobject_class; GstElementClass *gstelement_class; GstBaseSinkClass *gstbasesink_class; gobject_class = reinterpret_cast<GObjectClass*>(klass); gstelement_class = reinterpret_cast<GstElementClass*>(klass); gstbasesink_class = reinterpret_cast<GstBaseSinkClass*>(klass); parent_class_ = static_cast<GstVideoSinkClass*>(g_type_class_peek_parent(klass)); gobject_class->finalize = Finalize; gobject_class->set_property = SetProperty; gobject_class->get_property = GetProperty; g_object_class_install_property( gobject_class, PROP_FORCE_ASPECT_RATIO, g_param_spec_boolean("force-aspect-ratio", "Force aspect ratio", "When enabled, reverse caps negotiation (scaling)" "will respect original aspect ratio", FALSE, static_cast<GParamFlags>(G_PARAM_READWRITE))); g_object_class_install_property( gobject_class, PROP_PIXEL_ASPECT_RATIO, g_param_spec_string("pixel-aspect-ratio", "Pixel Aspect Ratio", "The pixel aspect ratio of the device", "1/1", static_cast<GParamFlags>(G_PARAM_READWRITE))); g_object_class_install_property( gobject_class, PROP_GEOMETRY_WIDTH, g_param_spec_int("geometry-width", "Geometry Width", "Geometry Width", 0, G_MAXINT, 0, static_cast<GParamFlags>(G_PARAM_WRITABLE))); g_object_class_install_property( gobject_class, PROP_GEOMETRY_HEIGHT, g_param_spec_int("geometry-height", "Geometry Height", "Geometry height", 0, G_MAXINT, 0, static_cast<GParamFlags>(G_PARAM_WRITABLE))); g_object_class_install_property( gobject_class, PROP_RECEIVE_IMAGE_HANDLER, g_param_spec_pointer("receive-image-handler", "Receive Image Handler", "The handler is the only way to receive images" "from the sink", static_cast<GParamFlags>(G_PARAM_READABLE))); gstelement_class->change_state = ChangeState; gstelement_class->set_bus = SetBus; gstbasesink_class->get_caps = GST_DEBUG_FUNCPTR(GetCaps); gstbasesink_class->set_caps = GST_DEBUG_FUNCPTR(SetCaps); gstbasesink_class->buffer_alloc = GST_DEBUG_FUNCPTR(BufferAlloc); gstbasesink_class->get_times = GST_DEBUG_FUNCPTR(GetTimes); gstbasesink_class->event = GST_DEBUG_FUNCPTR(Event); gstbasesink_class->preroll = GST_DEBUG_FUNCPTR(ShowFrame); gstbasesink_class->render = GST_DEBUG_FUNCPTR(ShowFrame); } void GadgetVideoSink::Finalize(GObject * object) { g_return_if_fail(object != NULL); // We cannot delete the object directly, as gstreamer doesn't expect us // to free the object pointer. GadgetVideoSink *videosink = GADGET_VIDEOSINK(object); videosink->Reset(); G_OBJECT_CLASS(parent_class_)->finalize(object); } GstCaps *GadgetVideoSink::GetCaps(GstBaseSink *bsink) { GadgetVideoSink *videosink= GADGET_VIDEOSINK(bsink); if (videosink->caps_) { return gst_caps_ref(videosink->caps_); } // get a template copy and add the pixel aspect ratio. size_t i; GstCaps *caps; caps = gst_caps_copy( gst_pad_get_pad_template_caps(GST_BASE_SINK(videosink)->sinkpad)); for (i = 0; i < gst_caps_get_size(caps); ++i) { GstStructure *structure = gst_caps_get_structure(caps, static_cast<guint>(i)); if (videosink->par_) { int nom, den; nom = gst_value_get_fraction_numerator(videosink->par_); den = gst_value_get_fraction_denominator(videosink->par_); gst_structure_set(structure, "pixel-aspect-ratio", GST_TYPE_FRACTION, nom, den, NULL); } else { gst_structure_set(structure, "pixel-aspect-ratio", GST_TYPE_FRACTION, 1, 1, NULL); } } return caps; } gboolean GadgetVideoSink::SetCaps(GstBaseSink *bsink, GstCaps *caps) { // We intersect caps with our template to make sure they are correct. GadgetVideoSink *videosink = GADGET_VIDEOSINK(bsink); GstCaps *intersection = gst_caps_intersect(videosink->caps_, caps); GST_DEBUG_OBJECT(videosink, "intersection returned %" GST_PTR_FORMAT, intersection); if (gst_caps_is_empty(intersection)) { gst_caps_unref(intersection); return FALSE; } gst_caps_unref(intersection); gboolean ret = TRUE; GstStructure *structure; gint new_width, new_height; const GValue *fps; structure = gst_caps_get_structure(caps, 0); ret &= gst_structure_get_int(structure, "width", &new_width); ret &= gst_structure_get_int(structure, "height", &new_height); fps = gst_structure_get_value(structure, "framerate"); ret &= (fps != NULL); if (!ret) { return FALSE; } // If the caps contain pixel-aspect-ratio, they have to match ours, otherwise // linking should fail. const GValue *par = gst_structure_get_value(structure, "pixel-aspect-ratio"); if (par) { if (videosink->par_) { if (gst_value_compare(par, videosink->par_) != GST_VALUE_EQUAL) { goto wrong_aspect; } } else { // Try the default. int nom, den; nom = gst_value_get_fraction_numerator(par); den = gst_value_get_fraction_denominator(par); if (nom != 1 || den != 1) { goto wrong_aspect; } } } GST_VIDEO_SINK_WIDTH(videosink) = new_width; GST_VIDEO_SINK_HEIGHT(videosink) = new_height; videosink->fps_n_ = gst_value_get_fraction_numerator(fps); videosink->fps_d_ = gst_value_get_fraction_denominator(fps); if (GST_VIDEO_SINK_WIDTH(videosink) <= 0 || GST_VIDEO_SINK_HEIGHT(videosink) <= 0) { return FALSE; } return TRUE; // ERRORS wrong_aspect: { GST_INFO_OBJECT(videosink, "pixel aspect ratio does not match"); return FALSE; } } GstStateChangeReturn GadgetVideoSink::ChangeState(GstElement *element, GstStateChange transition) { GadgetVideoSink *videosink = GADGET_VIDEOSINK(element); GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS; switch (transition) { case GST_STATE_CHANGE_NULL_TO_READY: videosink->InitCaps(); break; case GST_STATE_CHANGE_READY_TO_PAUSED: videosink->image_ = new Image; videosink->image_queue_ = new ImageQueue; case GST_STATE_CHANGE_PAUSED_TO_PLAYING: break; default: break; } ret = GST_ELEMENT_CLASS(parent_class_)->change_state(element, transition); switch (transition) { case GST_STATE_CHANGE_PLAYING_TO_PAUSED: break; case GST_STATE_CHANGE_PAUSED_TO_READY: videosink->fps_n_ = 0; videosink->fps_d_ = 1; GST_VIDEO_SINK_WIDTH(videosink) = 0; GST_VIDEO_SINK_HEIGHT(videosink) = 0; delete videosink->image_; delete videosink->image_queue_; videosink->image_ = NULL; videosink->image_queue_ = NULL; break; case GST_STATE_CHANGE_READY_TO_NULL: videosink->Reset(); break; default: break; } return ret; } void GadgetVideoSink::SetBus(GstElement *element, GstBus *bus) { GadgetVideoSink *videosink = GADGET_VIDEOSINK(element); videosink->bus_ = bus; } void GadgetVideoSink::GetTimes(GstBaseSink * bsink, GstBuffer * buf, GstClockTime * start, GstClockTime * end) { GadgetVideoSink *videosink = GADGET_VIDEOSINK(bsink); if (GST_BUFFER_TIMESTAMP_IS_VALID(buf)) { *start = GST_BUFFER_TIMESTAMP(buf); if (GST_BUFFER_DURATION_IS_VALID(buf)) { *end = *start + GST_BUFFER_DURATION(buf); } else { if (videosink->fps_n_ > 0) { *end = *start + gst_util_uint64_scale_int(GST_SECOND, videosink->fps_d_, videosink->fps_n_); } } } } // Buffer management // // The buffer_alloc function must either return a buffer with given size and // caps or create a buffer with different caps attached to the buffer. This // last option is called reverse negotiation, ie, where the sink suggests a // different format from the upstream peer. // // We try to do reverse negotiation when our geometry changes and we like a // resized buffer. GstFlowReturn GadgetVideoSink::BufferAlloc(GstBaseSink * bsink, guint64 offset, guint size, GstCaps * caps, GstBuffer ** buf) { ImageBuffer *image = NULL; GstStructure *structure = NULL; GstFlowReturn ret = GST_FLOW_OK; gint width = 0, height = 0; GadgetVideoSink *videosink = GADGET_VIDEOSINK(bsink); GST_LOG_OBJECT(videosink, "a buffer of %d bytes was requested with caps %" GST_PTR_FORMAT " and offset %" G_GUINT64_FORMAT, size, caps, offset); // assume we're going to alloc what was requested, keep track of wheter // we need to unref or not. When we suggest a new format upstream we will // create a new caps that we need to unref. GstCaps *alloc_caps = caps; bool alloc_unref = false; // get struct to see what is requested. structure = gst_caps_get_structure(caps, 0); if (gst_structure_get_int(structure, "width", &width) && gst_structure_get_int(structure, "height", &height)) { GstVideoRectangle dst, src, result; src.w = width; src.h = height; // What is our geometry. dst.w = videosink->geometry_width_; dst.h = videosink->geometry_height_; if (videosink->keep_aspect_) { GST_LOG_OBJECT(videosink, "enforcing aspect ratio in reverse caps negotiation"); src.x = src.y = dst.x = dst.y = 0; gst_video_sink_center_rect(src, dst, &result, TRUE); } else { GST_LOG_OBJECT(videosink, "trying to resize to window geometry " "ignoring aspect ratio"); result.x = result.y = 0; result.w = dst.w; result.h = dst.h; } // We would like another geometry. if (width != result.w || height != result.h) { int nom, den; GstCaps *desired_caps; GstStructure *desired_struct; // Make a copy of the incomming caps to create the new suggestion. // We can't use make_writable because we might then destroy the original // caps which we still need when the peer does not accept the suggestion. desired_caps = gst_caps_copy(caps); desired_struct = gst_caps_get_structure(desired_caps, 0); gst_structure_set (desired_struct, "width", G_TYPE_INT, result.w, NULL); gst_structure_set (desired_struct, "height", G_TYPE_INT, result.h, NULL); // PAR property overrides the default one. if (videosink->par_) { nom = gst_value_get_fraction_numerator(videosink->par_); den = gst_value_get_fraction_denominator(videosink->par_); gst_structure_set(desired_struct, "pixel-aspect-ratio", GST_TYPE_FRACTION, nom, den, NULL); } else { gst_structure_set(desired_struct, "pixel-aspect-ratio", GST_TYPE_FRACTION, 1, 1, NULL); } // see if peer accepts our new suggestion, if there is no peer, this // function returns true. if (gst_pad_peer_accept_caps(GST_VIDEO_SINK_PAD (videosink), desired_caps)) { gint bpp; bpp = size / height / width; // we will not alloc a buffer of the new suggested caps. Make sure // we also unref this new caps after we set it on the buffer. alloc_caps = desired_caps; alloc_unref = true; width = result.w; height = result.h; size = bpp * width * height; GST_DEBUG ("peed pad accepts our desired caps %" GST_PTR_FORMAT " buffer size is now %d bytes", desired_caps, size); } else { GST_DEBUG("peer pad does not accept our desired caps %" GST_PTR_FORMAT, desired_caps); // we alloc a buffer with the original incomming caps. width = GST_VIDEO_SINK_WIDTH(videosink); height = GST_VIDEO_SINK_HEIGHT(videosink); } } } // Check whether we can reuse any buffer from our buffer pool. while (videosink->buffer_pool_) { image = static_cast<ImageBuffer*>(videosink->buffer_pool_->data); if (image) { // Removing from the pool. videosink->buffer_pool_ = g_slist_delete_link(videosink->buffer_pool_, videosink->buffer_pool_); // If the image is invalid for our need, destroy. if ((image->width_ != width) || (image->height_ != height)) { ImageBuffer::FreeInstance(image); image = NULL; } else { // We found a suitable image. Reset the recycle flag. ASSERT(image->GetRecycleFlag() == ImageBuffer::BUFFER_RECYCLED); image->SetRecycleFlag(ImageBuffer::BUFFER_NOT_RECYCLED); break; } } else { break; } } // We haven't found anything, creating a new one. if (!image) { image = ImageBuffer::CreateInstance(videosink, alloc_caps); } // Now we should have an image, set appropriate caps on it. g_return_val_if_fail(image != NULL, GST_FLOW_ERROR); gst_buffer_set_caps(GST_BUFFER_CAST(image), alloc_caps); // Could be our new reffed suggestion or the original unreffed caps. if (alloc_unref) gst_caps_unref(alloc_caps); *buf = GST_BUFFER_CAST(image); return ret; } gboolean GadgetVideoSink::Event(GstBaseSink *sink, GstEvent *event) { // FIXME: // The default event handler would post an EOS message after it receives // the EOS event. But it seems not for our gadget video sink. So we post // the EOS message manually here. if (GST_EVENT_TYPE(event) == GST_EVENT_EOS) { GadgetVideoSink *videosink = GADGET_VIDEOSINK(sink); GstMessage *eos = gst_message_new_eos(reinterpret_cast<GstObject*>(sink)); if (eos) gst_bus_post(videosink->bus_, eos); } return TRUE; } GstFlowReturn GadgetVideoSink::ShowFrame(GstBaseSink *bsink, GstBuffer *buf) { g_return_val_if_fail(buf != NULL, GST_FLOW_ERROR); GadgetVideoSink *videosink = GADGET_VIDEOSINK(bsink); if (IS_IMAGE_BUFFER(buf)) { GST_LOG_OBJECT(videosink, "buffer from our pool, writing directly"); videosink->PutImage(IMAGE_BUFFER(buf)); } else { // Else we have to copy the data into our image buffer. GST_LOG_OBJECT(videosink, "normal buffer, copying from it"); GST_DEBUG_OBJECT(videosink, "creating our image"); ImageBuffer *image_buf = ImageBuffer::CreateInstance(videosink, GST_BUFFER_CAPS(buf)); if (!image_buf) goto no_image; if (image_buf->size_ < GST_BUFFER_SIZE(buf)) { ImageBuffer::FreeInstance(image_buf); goto no_image; } memcpy(GST_BUFFER_DATA(image_buf), GST_BUFFER_DATA(buf), MIN(GST_BUFFER_SIZE(buf), image_buf->size_)); videosink->PutImage(image_buf); ImageBuffer::Finalize(image_buf); gst_buffer_unref(GST_BUFFER_CAST(image_buf)); } return GST_FLOW_OK; no_image: // No image available. GST_DEBUG("could not create image"); return GST_FLOW_ERROR; } void GadgetVideoSink::SetProperty(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { g_return_if_fail(IS_GADGET_VIDEOSINK(object)); GadgetVideoSink *videosink = GADGET_VIDEOSINK(object); switch (prop_id) { case PROP_FORCE_ASPECT_RATIO: videosink->keep_aspect_ = g_value_get_boolean(value); break; case PROP_PIXEL_ASPECT_RATIO: { GValue *tmp; tmp = g_new0(GValue, 1); g_value_init(tmp, GST_TYPE_FRACTION); if (!g_value_transform(value, tmp)) { GST_WARNING_OBJECT(videosink, "Could not transform string to aspect ratio"); g_free(tmp); } else { GST_DEBUG_OBJECT(videosink, "set PAR to %d/%d", gst_value_get_fraction_numerator(tmp), gst_value_get_fraction_denominator(tmp)); g_free(videosink->par_); videosink->par_ = tmp; } } break; case PROP_GEOMETRY_WIDTH: videosink->geometry_width_ = g_value_get_int(value); break; case PROP_GEOMETRY_HEIGHT: videosink->geometry_height_ = g_value_get_int(value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } void GadgetVideoSink::GetProperty(GObject * object, guint prop_id, GValue * value, GParamSpec * pspec) { g_return_if_fail(IS_GADGET_VIDEOSINK (object)); GadgetVideoSink *videosink = GADGET_VIDEOSINK(object); switch (prop_id) { case PROP_FORCE_ASPECT_RATIO: g_value_set_boolean(value, videosink->keep_aspect_); break; case PROP_PIXEL_ASPECT_RATIO: if (videosink->par_) g_value_transform(videosink->par_, value); break; case PROP_RECEIVE_IMAGE_HANDLER: g_value_set_pointer(value, (void*)ReceiveImageHandler); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } // This function initializes caps for the only supported format. void GadgetVideoSink::InitCaps() { ASSERT(!caps_); caps_ = gst_caps_new_simple("video/x-raw-rgb", "bpp", G_TYPE_INT, 32, "depth", G_TYPE_INT, 24, "endianness", G_TYPE_INT, G_BIG_ENDIAN, "red_mask", G_TYPE_INT, 0xff00, "green_mask", G_TYPE_INT, 0xff0000, "blue_mask", G_TYPE_INT,0xff000000, "width", GST_TYPE_INT_RANGE, 1, G_MAXINT, "height", GST_TYPE_INT_RANGE, 1, G_MAXINT, "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, G_MAXINT, 1, NULL); // Update par with the default one if not set yet. if (!par_) { par_ = g_new0(GValue, 1); g_value_init(par_, GST_TYPE_FRACTION); gst_value_set_fraction(par_, 1, 1); // 1:1 } int nom, den; nom = gst_value_get_fraction_numerator(par_); den = gst_value_get_fraction_denominator(par_); gst_caps_set_simple(caps_, const_cast<gchar*>("pixel-aspect-ratio"), GST_TYPE_FRACTION, 1, 1, NULL); } // This function converts the image format if necessary, puts the image into // the image queue, sends message to notify that a new image frame is coming, // and recycles any reusable image buffer. gboolean GadgetVideoSink::PutImage(ImageBuffer *image) { if (!image) return TRUE; // The upstream may pass in the same image buffer twice. For example, before // upstream finalizes an image buffer, a seeking operation occurs, and under // some condition, the upstream may reuse the image buffer instead of // finalizing and freeing it. Since we may store image buffers in // image queue or buffer pool during putting images, the image passed in // this time may already be stored in image queue or buffer pool during // the last call of this function. So, first check whether the buffer is // duplicated, and simply discuss it and return if it's. if (g_slist_find(buffer_pool_, image) || image_queue_->DupImage(image)) { return TRUE; } GstVideoRectangle dst, src, result; src.w = image->width_; src.h = image->height_; dst.w = geometry_width_; dst.h = geometry_height_; src.x = src.y = dst.x = dst.y = 0; gst_video_sink_center_rect(src, dst, &result, FALSE); image->x_ = result.x; image->y_ = result.y; image->w_ = result.w; image->h_ = result.h; // Increase refcount and set TO_BE_RECYCLED flag so that image buffer won't // be finalized/freed by upstream. gst_buffer_ref(GST_BUFFER_CAST(image)); image->SetRecycleFlag(ImageBuffer::BUFFER_TO_BE_RECYCLED); // Put it to the buffer queue. ImageBuffer *to_be_recycled = image_queue_->ProduceOneImage(image); // Send a message to notify that a new frame is coming. if (bus_) { GstStructure *structure = gst_structure_new("New Image", kGadgetVideoSinkMessageName, G_TYPE_INT, NEW_IMAGE, NULL); GstMessage *message = gst_message_new_element(reinterpret_cast<GstObject*>(this), structure); if (message) gst_bus_post(bus_, message); } if (to_be_recycled) { if (to_be_recycled->width_ != GST_VIDEO_SINK_WIDTH(this) || to_be_recycled->height_ != GST_VIDEO_SINK_HEIGHT(this)) { ImageBuffer::FreeInstance(to_be_recycled); } else { to_be_recycled->SetRecycleFlag(ImageBuffer::BUFFER_RECYCLED); buffer_pool_ = g_slist_prepend(buffer_pool_, to_be_recycled); } } return TRUE; } void GadgetVideoSink::BufferPoolClear() { while (buffer_pool_) { ImageBuffer *image = static_cast<ImageBuffer*>(buffer_pool_->data); buffer_pool_ = g_slist_delete_link(buffer_pool_, buffer_pool_); ImageBuffer::FreeInstance(image); } } void GadgetVideoSink::Reset() { if (caps_) { gst_caps_unref(caps_); caps_ = NULL; } if (image_) { delete image_; image_ = NULL; } if (image_queue_) { delete image_queue_; image_queue_ = NULL; } BufferPoolClear(); if(par_) { g_free(par_); par_ = NULL; } } GadgetVideoSink::Image * GadgetVideoSink::ReceiveImageHandler(GstElement *element) { ASSERT(element); GadgetVideoSink *videosink = GADGET_VIDEOSINK(element); if (videosink->image_queue_) { ImageBuffer *image_internal = videosink->image_queue_->ConsumeOneImage(); if (image_internal != NULL) { ASSERT(videosink->image_); videosink->image_->data = reinterpret_cast<char*>(GST_BUFFER_DATA(image_internal)); videosink->image_->x = image_internal->x_; videosink->image_->y = image_internal->y_; videosink->image_->w = image_internal->w_; videosink->image_->h = image_internal->h_; videosink->image_->stride = image_internal->bytes_per_line_; return videosink->image_; } } return NULL; } } // namespace gst } // namespace ggadget
33.181729
93
0.645135
[ "geometry", "render", "object", "transform" ]
ec8b4e4121f747a72fc0f6ea88c8c69724fa58c7
1,213
cpp
C++
CodeForces/5B/12021308_AC_124ms_2648kB.cpp
BakaErii/ACM_Collection
d368b15c7f1c84472424d5e61e5ebc667f589025
[ "WTFPL" ]
null
null
null
CodeForces/5B/12021308_AC_124ms_2648kB.cpp
BakaErii/ACM_Collection
d368b15c7f1c84472424d5e61e5ebc667f589025
[ "WTFPL" ]
null
null
null
CodeForces/5B/12021308_AC_124ms_2648kB.cpp
BakaErii/ACM_Collection
d368b15c7f1c84472424d5e61e5ebc667f589025
[ "WTFPL" ]
null
null
null
/** * @authors Moe_Sakiya sakiya@tun.moe * @date 2017-12-19 19:40:23 * */ #include <iostream> #include <string> #include <algorithm> #include <set> #include <map> #include <vector> #include <stack> #include <queue> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> using namespace std; struct text { string str; int len; } s[1050]; int main(void) { int i, j, line = 0, column = 0, offset; bool al = false; while (getline(cin, s[line].str)) { s[line].len = (int)s[line].str.length(); column = max(s[line].len, column); line++; } //输出 for (i = 0; i < column + 2; i++) putchar('*'); putchar('\n'); for (i = 0; i < line; i++) { putchar('*'); if ((column - s[i].len) % 2 == 0) offset = (column - s[i].len) / 2; else { offset = (column - s[i].len) / 2; if (al) { offset++; al = false; } else { al = true; } } for (j = 0; j < column; j++) if (j == offset) { cout << s[i].str; j += s[i].len; if(j!=column) putchar(' '); } else putchar(' '); // if (al == true) // putchar(' '); putchar('*'); putchar('\n'); } for (i = 0; i < column + 2; i++) putchar('*'); putchar('\n'); return 0; }
16.847222
42
0.518549
[ "vector" ]
ec8bfb0e7a7aa9e43c508c1c077e16bba5e6465d
1,958
cpp
C++
Hackerrank/balanced-forest.cpp
aleya0/Hacktoberfest
11738b7f6ad03dc8714e550513eb684d917cb47e
[ "MIT" ]
null
null
null
Hackerrank/balanced-forest.cpp
aleya0/Hacktoberfest
11738b7f6ad03dc8714e550513eb684d917cb47e
[ "MIT" ]
null
null
null
Hackerrank/balanced-forest.cpp
aleya0/Hacktoberfest
11738b7f6ad03dc8714e550513eb684d917cb47e
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; map <long long, int> Map1, Map2; long long ctot; vector <int> ve[110000]; long long sum[1100000],ans; int n,q,c[110000]; void test(long long x) { long long y = ctot - 2 * x; if (y > 0 && y <= x) ans = min(ans, x - y); } void dfs1(int x, int f) { sum[x] = c[x]; for (int i = 0; i < (int) ve[x].size(); i++) if (ve[x][i] != f) { dfs1(ve[x][i], x); sum[x] += sum[ve[x][i]]; } Map1[sum[x]] += 1; } void dfs2(int x, int f) { if (Map2[2 * sum[x]]) test(sum[x]); if (Map2[ctot - sum[x]]) test(sum[x]); if ((ctot - sum[x]) % 2 == 0 && Map2[ctot - (ctot - sum[x]) / 2]) test((ctot - sum[x]) / 2); Map2[sum[x]] += 1; if (Map1[sum[x]] > Map2[sum[x]]) test(sum[x]); if (ctot - 2 * sum[x] >= sum[x] && Map1[ctot - 2 * sum[x]] > Map2[ctot - 2 * sum[x]]) test(sum[x]); if ((ctot - sum[x]) % 2 == 0 && (ctot - sum[x]) / 2 >= sum[x] && Map1[(ctot - sum[x]) / 2] > Map2[(ctot - sum[x]) / 2]) test((ctot - sum[x]) / 2); if (sum[x] * 2 == ctot) ans = min(ans, sum[x]); for (int i = 0; i < (int) ve[x].size(); i++) if (ve[x][i] != f) { dfs2(ve[x][i], x); } Map2[sum[x]] -= 1; } int main() { scanf("%d", &q); while (q--) { Map1.clear(); Map2.clear(); ans = 1e18; scanf("%d", &n); ctot = 0; for (int i = 1; i <= n; i++) { scanf("%d", &c[i]); ctot += c[i]; } for (int i = 1; i <= n; i++) ve[i].clear(); for (int i = 1; i < n; i++) { int x, y; scanf("%d%d", &x, &y); ve[x].push_back(y); ve[y].push_back(x); } dfs1(1, 0); dfs2(1, 0); if (ans == 1e18) printf("-1\n"); else printf("%lld\n", ans); } }
22.505747
123
0.38713
[ "vector" ]
ec9179d9649e303302ab91212e5355721dbf555b
1,029
cpp
C++
contest/1512/b/b.cpp
GoatGirl98/cf
4077ca8e0fe29dc2bbb7b60166989857cc062e17
[ "MIT" ]
null
null
null
contest/1512/b/b.cpp
GoatGirl98/cf
4077ca8e0fe29dc2bbb7b60166989857cc062e17
[ "MIT" ]
null
null
null
contest/1512/b/b.cpp
GoatGirl98/cf
4077ca8e0fe29dc2bbb7b60166989857cc062e17
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define watch(x) std::cout << (#x) << " is " << (x) << std::endl using LL = long long; int main() { //freopen("in", "r", stdin); std::cin.tie(nullptr)->sync_with_stdio(false); int cas = 1; std::cin >> cas; while (cas--) { int n; std::cin >> n; std::vector<std::string> s(n); for (auto &x : s) std::cin >> x; std::vector<std::pair<int, int>> a; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) if (s[i][j] == '*') { a.emplace_back(i, j); } } if (a[0].first != a[1].first && a[0].second != a[1].second) { s[a[0].first][a[1].second] = s[a[1].first][a[0].second] = '*'; } else if (a[0].first == a[1].first) { if (a[0].first == 0) { s[1][a[0].second] = s[1][a[1].second] = '*'; } else { s[0][a[0].second] = s[0][a[1].second] = '*'; } } else { if (a[0].second == 0) { s[a[0].first][1] = s[a[1].first][1] = '*'; } else { s[a[0].first][0] = s[a[1].first][0] = '*'; } } for (auto &x : s) std::cout << x << '\n'; } return 0; }
26.384615
65
0.45967
[ "vector" ]
ec9478e411ef36a1b16fe7129c3a19c5bd4939ce
6,924
cpp
C++
Runtime/Graphics/Shaders/CSpaceWarpFilter.cpp
Jcw87/urde
fb9ea9092ad00facfe957ece282a86c194e9cbda
[ "MIT" ]
267
2016-03-10T21:59:16.000Z
2021-03-28T18:21:03.000Z
Runtime/Graphics/Shaders/CSpaceWarpFilter.cpp
cobalt2727/metaforce
3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a
[ "MIT" ]
129
2016-03-12T10:17:32.000Z
2021-04-05T20:45:19.000Z
Runtime/Graphics/Shaders/CSpaceWarpFilter.cpp
cobalt2727/metaforce
3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a
[ "MIT" ]
31
2016-03-20T00:20:11.000Z
2021-03-10T21:14:11.000Z
#include "Runtime/Graphics/Shaders/CSpaceWarpFilter.hpp" #include "Runtime/Graphics/CBooRenderer.hpp" #include "Runtime/Graphics/CGraphics.hpp" #include <hecl/Pipeline.hpp> #define WARP_RAMP_RES 32 namespace metaforce { static boo::ObjToken<boo::IShaderPipeline> s_Pipeline; void CSpaceWarpFilter::Initialize() { s_Pipeline = hecl::conv->convert(Shader_CSpaceWarpFilter{}); } void CSpaceWarpFilter::Shutdown() { s_Pipeline.reset(); } void CSpaceWarpFilter::GenerateWarpRampTex(boo::IGraphicsDataFactory::Context& ctx) { std::array<std::array<std::array<u8, 4>, WARP_RAMP_RES + 1>, WARP_RAMP_RES + 1> data{}; const float halfRes = WARP_RAMP_RES / 2.f; for (int y = 0; y < WARP_RAMP_RES + 1; ++y) { for (int x = 0; x < WARP_RAMP_RES + 1; ++x) { zeus::CVector2f vec((x - halfRes) / halfRes, (y - halfRes) / halfRes); const float mag = vec.magnitude(); if (mag < 1.f && vec.canBeNormalized()) { vec.normalize(); vec *= zeus::CVector2f(std::sqrt(mag)); } data[y][x][3] = zeus::clamp(0, int((((vec.x() / 2.f + 0.5f) - x / float(WARP_RAMP_RES)) + 0.5f) * 255), 255); data[y][x][2] = zeus::clamp(0, int((((vec.y() / 2.f + 0.5f) - y / float(WARP_RAMP_RES)) + 0.5f) * 255), 255); data[y][x][0] = data[y][x][1] = data[y][x][2]; } } m_warpTex = ctx.newStaticTexture(WARP_RAMP_RES + 1, WARP_RAMP_RES + 1, 1, boo::TextureFormat::RGBA8, boo::TextureClampMode::Repeat, data.data(), (WARP_RAMP_RES + 1) * (WARP_RAMP_RES + 1) * 4) .get(); } CSpaceWarpFilter::CSpaceWarpFilter() { CGraphics::CommitResources([&](boo::IGraphicsDataFactory::Context& ctx) { GenerateWarpRampTex(ctx); struct Vert { zeus::CVector2f m_pos; zeus::CVector2f m_uv; }; const std::array<Vert, 4> verts{{ {{-1.f, -1.f}, {0.f, 0.f}}, {{-1.f, 1.f}, {0.f, 1.f}}, {{1.f, -1.f}, {1.f, 0.f}}, {{1.f, 1.f}, {1.f, 1.f}}, }}; m_vbo = ctx.newStaticBuffer(boo::BufferUse::Vertex, verts.data(), 32, verts.size()); m_uniBuf = ctx.newDynamicBuffer(boo::BufferUse::Uniform, sizeof(Uniform), 1); const std::array<boo::ObjToken<boo::IGraphicsBuffer>, 1> bufs{m_uniBuf.get()}; constexpr std::array<boo::PipelineStage, 1> stages{boo::PipelineStage::Vertex}; const std::array<boo::ObjToken<boo::ITexture>, 2> texs{ CGraphics::g_SpareTexture.get(), m_warpTex.get(), }; m_dataBind = ctx.newShaderDataBinding(s_Pipeline, m_vbo.get(), nullptr, nullptr, bufs.size(), bufs.data(), stages.data(), nullptr, nullptr, texs.size(), texs.data(), nullptr, nullptr); return true; } BooTrace); } void CSpaceWarpFilter::draw(const zeus::CVector3f& pt) { SCOPED_GRAPHICS_DEBUG_GROUP("CSpaceWarpFilter::draw", zeus::skMagenta); /* Indirect coords are full-texture sampling when warp is completely in viewport */ m_uniform.m_indXf[1][1] = 1.f; m_uniform.m_indXf[0][0] = 1.f; m_uniform.m_indXf[2][0] = 0.f; m_uniform.m_indXf[2][1] = 0.f; /* Warp effect is fixed at 192x192 rectangle in original (1/2.5 viewport height) */ float aspect = CGraphics::g_CroppedViewport.xc_width / float(CGraphics::g_CroppedViewport.x10_height); m_uniform.m_matrix[1][1] = 1.f / 2.5f; m_uniform.m_matrix[0][0] = m_uniform.m_matrix[1][1] / aspect; SClipScreenRect clipRect = {}; clipRect.x4_left = ((pt[0] - m_uniform.m_matrix[0][0]) / 2.f + 0.5f) * CGraphics::g_CroppedViewport.xc_width; if (clipRect.x4_left >= CGraphics::g_CroppedViewport.xc_width) return; clipRect.x8_top = ((pt[1] - m_uniform.m_matrix[1][1]) / 2.f + 0.5f) * CGraphics::g_CroppedViewport.x10_height; if (clipRect.x8_top >= CGraphics::g_CroppedViewport.x10_height) return; clipRect.xc_width = CGraphics::g_CroppedViewport.xc_width * m_uniform.m_matrix[0][0]; if (clipRect.x4_left + clipRect.xc_width <= 0) return; clipRect.x10_height = CGraphics::g_CroppedViewport.x10_height * m_uniform.m_matrix[1][1]; if (clipRect.x8_top + clipRect.x10_height <= 0) return; float oldW = clipRect.xc_width; if (clipRect.x4_left < 0) { clipRect.xc_width += clipRect.x4_left; m_uniform.m_indXf[0][0] = clipRect.xc_width / oldW; m_uniform.m_indXf[2][0] = -clipRect.x4_left / oldW; clipRect.x4_left = 0; } float oldH = clipRect.x10_height; if (clipRect.x8_top < 0) { clipRect.x10_height += clipRect.x8_top; m_uniform.m_indXf[1][1] = clipRect.x10_height / oldH; m_uniform.m_indXf[2][1] = -clipRect.x8_top / oldH; clipRect.x8_top = 0; } float tmp = clipRect.x4_left + clipRect.xc_width; if (tmp >= CGraphics::g_CroppedViewport.xc_width) { clipRect.xc_width = CGraphics::g_CroppedViewport.xc_width - clipRect.x4_left; m_uniform.m_indXf[0][0] = clipRect.xc_width / oldW; } tmp = clipRect.x8_top + clipRect.x10_height; if (tmp >= CGraphics::g_CroppedViewport.x10_height) { clipRect.x10_height = CGraphics::g_CroppedViewport.x10_height - clipRect.x8_top; m_uniform.m_indXf[1][1] = clipRect.x10_height / oldH; } /* Transform UV coordinates of rectangle within viewport and sampled scene texels (clamped to viewport bounds) */ zeus::CVector2f vp{float(CGraphics::g_CroppedViewport.xc_width), float(CGraphics::g_CroppedViewport.x10_height)}; m_uniform.m_matrix[0][0] = clipRect.xc_width / vp.x(); m_uniform.m_matrix[1][1] = clipRect.x10_height / vp.y(); m_uniform.m_matrix[3][0] = pt.x() + (1.f / vp.x()); m_uniform.m_matrix[3][1] = pt.y() + (1.f / vp.y()); if (CGraphics::g_BooPlatform == boo::IGraphicsDataFactory::Platform::OpenGL) { m_uniform.m_matrix[3][2] = pt.z() * 2.f - 1.f; } else if (CGraphics::g_BooPlatform == boo::IGraphicsDataFactory::Platform::Vulkan) { m_uniform.m_matrix[1][1] *= -1.f; m_uniform.m_matrix[3][1] *= -1.f; m_uniform.m_matrix[3][2] = pt.z(); } else { m_uniform.m_matrix[3][2] = pt.z(); } if (clipRect.x4_left) { clipRect.x4_left -= 1; clipRect.xc_width += 1; } if (clipRect.x8_top) { clipRect.x8_top -= 1; clipRect.x10_height += 1; } if (clipRect.x4_left + clipRect.xc_width < CGraphics::g_CroppedViewport.xc_width) clipRect.xc_width += 1; if (clipRect.x8_top + clipRect.x10_height < CGraphics::g_CroppedViewport.x10_height) clipRect.x10_height += 1; clipRect.x4_left += CGraphics::g_CroppedViewport.x4_left; clipRect.x8_top += CGraphics::g_CroppedViewport.x8_top; clipRect.x8_top = g_Viewport.xc_height - clipRect.x10_height - clipRect.x8_top; CGraphics::ResolveSpareTexture(clipRect); m_uniform.m_strength.x() = m_uniform.m_matrix[0][0] * m_strength * 0.5f * (clipRect.x10_height / float(clipRect.xc_width)); m_uniform.m_strength.y() = m_uniform.m_matrix[1][1] * m_strength * 0.5f; m_uniBuf->load(&m_uniform, sizeof(m_uniform)); CGraphics::SetShaderDataBinding(m_dataBind); CGraphics::DrawArray(0, 4); } } // namespace metaforce
40.729412
119
0.666233
[ "transform" ]
ec9bb81cabcbf33601296eedaf08bfb4ccb5ffc3
2,191
hpp
C++
Code/include/OE/UI/Element.hpp
mlomb/OrbitEngine
41f053626f05782e81c2e48f5c87b04972f9be2c
[ "Apache-2.0" ]
21
2018-06-26T16:37:36.000Z
2022-01-11T01:19:42.000Z
Code/include/OE/UI/Element.hpp
mlomb/OrbitEngine
41f053626f05782e81c2e48f5c87b04972f9be2c
[ "Apache-2.0" ]
null
null
null
Code/include/OE/UI/Element.hpp
mlomb/OrbitEngine
41f053626f05782e81c2e48f5c87b04972f9be2c
[ "Apache-2.0" ]
3
2019-10-01T14:10:50.000Z
2021-11-19T20:30:18.000Z
#ifndef UI_ELEMENT_HPP #define UI_ELEMENT_HPP #include <vector> #include "OE/UI/Style/StyleEnums.hpp" #include "OE/Math/Rect.hpp" // forward def to avoid include class YGNode; namespace OrbitEngine { namespace UI { class Painter; class StyleSheet; class StyleComputed; class EventBase; class Surface; class EventsController; enum class MeasureMode { UNDEFINED, EXACTLY, AT_MOST }; /// The base of all UI controls class Element { public: Element(); virtual ~Element(); void addElement(Element* child, int index = -1); void removeElement(Element* child); void setID(const std::string& id); void addClass(const std::string& klass); void addStyleSheet(StyleSheet* stylesheet); void setStyleProperty(const StyleProperty& property); void setPseudoStates(const StylePseudoStates states); void removePseudoStates(const StylePseudoStates states); Element* getParent() const; const std::vector<Element*>& getChildrens() const; const std::vector<StyleSheet*>& getStyleSheets() const; Math::Rectf getBoundingRect() const; Math::Rectf getContentRect() const; bool isVisible() const; int getDepth() const; Surface* getSurface() const; EventsController* getEventsController() const; std::string getQualifiedName() const; virtual void paintContent(Painter* painter); virtual Math::Vec2f measureContent(float width, MeasureMode widthMode, float height, MeasureMode heightMode); virtual void executeDefault(EventBase* evt); protected: StyleComputed* m_ComputedStyle; void setTag(const std::string& tag); void enableMeasurement(); void setAsTextType(); private: friend class Surface; friend class StyleTreeUpdater; friend class LayoutTreeUpdater; friend class PaintTreeUpdater; void updateHierarchy(); Element* m_Parent; std::vector<Element*> m_Childrens; int m_Depth; friend class StyleSelectorMatcher; StyleIdentifier m_ID, m_Tag; std::vector<StyleIdentifier> m_Classes; StylePseudoStates m_PseudoStates; std::vector<StyleSheet*> m_StyleSheets; StyleRule m_InlineRules; YGNode* m_YogaNode; Math::Rectf m_LayoutRect; Math::Rectf m_BoundingRect; Surface* m_Surface; }; } } #endif
23.55914
111
0.752624
[ "vector" ]