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
fc020396547899e56c0c115c6ecb12fa1b0bc66a
2,196
cpp
C++
Source/src/UI/WindowInspector.cpp
Erick9Thor/Engine3D
32d78f79723fb7c319f79d5e26cdc26481d5cb35
[ "MIT" ]
1
2021-11-17T19:20:07.000Z
2021-11-17T19:20:07.000Z
Source/src/UI/WindowInspector.cpp
Erick9Thor/Engine3D
32d78f79723fb7c319f79d5e26cdc26481d5cb35
[ "MIT" ]
null
null
null
Source/src/UI/WindowInspector.cpp
Erick9Thor/Engine3D
32d78f79723fb7c319f79d5e26cdc26481d5cb35
[ "MIT" ]
null
null
null
#include "WindowInspector.h" #include "../Application.h" #include "../GameObject.h" #include "../Modules/ModuleEditor.h" #include "imgui.h" #include <IconsFontAwesome5.h> WindowInspector::WindowInspector() : Window("Inspector", true) {} WindowInspector::~WindowInspector() { } void WindowInspector::Update() { ImGui::SetNextWindowDockID(App->editor->dock_right_id, ImGuiCond_FirstUseEver); if (ImGui::Begin((std::string(ICON_FA_EYE " ") + name).c_str(), &active)) { DrawGameObject(App->editor->GetSelectedGO()); } ImGui::End(); } void WindowInspector::DrawGameObject(GameObject* game_object) { if (game_object != nullptr) { char go_name[50]; strcpy_s(go_name, 50, game_object->name.c_str()); ImGuiInputTextFlags name_input_flags = ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_EnterReturnsTrue; if (ImGui::InputText("###", go_name, 50, name_input_flags)) game_object->name = go_name; ImGui::SameLine(); ImGui::Checkbox("Active", &game_object->active); std::vector<Component*> go_components = game_object->GetComponents(); for (vector<Component*>::iterator it = go_components.begin(); it != go_components.end(); ++it) (*it)->DrawGui(); ImGui::Separator(); const float x = (ImGui::GetContentRegionAvail().x - ImGui::CalcTextSize((std::string(ICON_FA_PLUS " ") + "Add component").c_str()).x - ImGui::GetStyle().FramePadding.x * 2) * 0.5f; ImGui::SetCursorPosX(x); if (ImGui::Button((std::string(ICON_FA_PLUS " ") + "Add component").c_str())) { ImGui::OpenPopup("AddComponentPopup"); } if (ImGui::BeginPopup("AddComponentPopup")) { if (ImGui::MenuItem("Camera")) { game_object->CreateComponent(Component::Type::CAMERA); ImGui::CloseCurrentPopup(); } if (ImGui::MenuItem("Point Light")) { game_object->CreateComponent(Component::Type::POINTLIGHT); ImGui::CloseCurrentPopup(); } if (ImGui::MenuItem("Spot Light")) { game_object->CreateComponent(Component::Type::SPOTLIGHT); ImGui::CloseCurrentPopup(); } if (ImGui::MenuItem("Dir Light")) { game_object->CreateComponent(Component::Type::DIRLIGHT); ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } } }
27.45
182
0.689435
[ "vector" ]
fc0a5cc749a83f15df8cc512c79935acf1279252
817
hpp
C++
src/Include/Util/FinalAction.hpp
0KABE/Owl
e9d5981e5d41f6d327ef84cb0c3a66f41d68b91b
[ "MIT" ]
2
2021-09-11T07:35:06.000Z
2022-03-05T09:52:00.000Z
src/Include/Util/FinalAction.hpp
0KABE/Owl
e9d5981e5d41f6d327ef84cb0c3a66f41d68b91b
[ "MIT" ]
null
null
null
src/Include/Util/FinalAction.hpp
0KABE/Owl
e9d5981e5d41f6d327ef84cb0c3a66f41d68b91b
[ "MIT" ]
null
null
null
#pragma once #include <functional> #include <algorithm> #include <utility> namespace Owl { class FinalAction { public: using Action = std::function<void()>; FinalAction() = default; explicit FinalAction(Action action) : mActions({std::move(action)}) {} explicit FinalAction(std::vector<Action> actions) : mActions(std::move(actions)) {} ~FinalAction() { if (enable) std::for_each(mActions.begin(), mActions.end(), [=](const Action &action) { action(); }); } void Disable() { enable = false; } FinalAction &operator+=(Action action) { mActions.push_back(std::move(action)); return *this; } private: bool enable = true; std::vector<Action> mActions; }; }
24.029412
105
0.567931
[ "vector" ]
fc0c498399941b75975989fd1db6eae4bf9b3aea
496
cc
C++
洛谷/普及-/P1100.cc
OFShare/Algorithm-challenger
43336871a5e48f8804d6e737c813d9d4c0dc2731
[ "MIT" ]
67
2019-07-14T05:38:41.000Z
2021-12-23T11:52:51.000Z
洛谷/普及-/P1100.cc
OFShare/Algorithm-challenger
43336871a5e48f8804d6e737c813d9d4c0dc2731
[ "MIT" ]
null
null
null
洛谷/普及-/P1100.cc
OFShare/Algorithm-challenger
43336871a5e48f8804d6e737c813d9d4c0dc2731
[ "MIT" ]
12
2020-01-16T10:48:01.000Z
2021-06-11T16:49:04.000Z
#include <iostream> #include <algorithm> #include <string> #include <bitset> #include <vector> using std::cin; using std::cout; using std::endl; using std::string; using std::vector; using std::sort; using std::bitset; int main(void) { unsigned long long n = 0; cin >> n; bitset<32> binary(n),rev(0); for (int i = 0; i < 16; i++) { rev[16+i] = binary[i]; } for (int i = 0; i < 16; i++) { rev[i] = binary[i + 16]; } cout << rev.to_ullong() << endl; return 0; }
14.588235
34
0.580645
[ "vector" ]
fc14d8de2aaf563555d9a08ed09f9f887f44f20e
39,908
cpp
C++
src/chess_engine_search.cpp
MetalPhaeton/sayuri
27a65bc2c2a9be49d394fbc9abbe50ad91dfa718
[ "MIT" ]
7
2015-09-15T23:56:35.000Z
2022-01-21T03:06:22.000Z
src/chess_engine_search.cpp
MetalPhaeton/sayuri
27a65bc2c2a9be49d394fbc9abbe50ad91dfa718
[ "MIT" ]
5
2016-04-09T21:37:04.000Z
2018-06-12T07:12:34.000Z
src/chess_engine_search.cpp
MetalPhaeton/sayuri
27a65bc2c2a9be49d394fbc9abbe50ad91dfa718
[ "MIT" ]
2
2018-08-11T21:30:16.000Z
2021-08-03T15:43:27.000Z
/* The MIT License (MIT) * * Copyright (c) 2013-2018 Hironori Ishibashi * * 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. */ /** * @file chess_engine_search.cpp * @author Hironori Ishibashi * @brief チェスエンジンの本体の実装。 (探索関数) */ #include "chess_engine.h" #include <iostream> #include <vector> #include <algorithm> #include <memory> #include <thread> #include <mutex> #include <memory> #include <cstddef> #include <functional> #include <queue> #include <system_error> #include "common.h" #include "transposition_table.h" #include "move_maker.h" #include "pv_line.h" #include "evaluator.h" #include "uci_shell.h" #include "position_record.h" #include "job.h" #include "helper_queue.h" #include "params.h" #include "cache.h" /** Sayuri 名前空間。 */ namespace Sayuri { // クイース探索。 int ChessEngine::Quiesce(u32 level, int alpha, int beta, int material) { // ジョブの準備。 Job& job = job_table_[level]; job.Init(maker_table_[level]); // キャッシュ。 Cache& cache = shared_st_ptr_->cache_; // 探索中止。 if (JudgeToStop(job)) return ReturnProcess(alpha, level); // ノード数を加算。 ++(shared_st_ptr_->searched_nodes_); // 最大探索数。 Util::UpdateMax(shared_st_ptr_->searched_level_, level); // 勝負に十分な駒がなければ0点。 if (!HasSufficientMaterial()) { return ReturnProcess(SCORE_DRAW, level); } // サイド。 Side side = basic_st_.to_move_; Side enemy_side = Util::GetOppositeSide(side); // stand_pad。 int stand_pad = evaluator_.Evaluate(material); // アルファ値、ベータ値を調べる。 if (stand_pad >= beta) { return ReturnProcess(stand_pad, level); } Util::UpdateMax(alpha, stand_pad); // 探索できる限界を超えているか。 // 超えていればこれ以上探索しない。 if (level >= MAX_PLYS) { return ReturnProcess(alpha, level); } // 候補手を作る。 // 駒を取る手だけ。 MoveMaker& maker = maker_table_[level]; if (IsAttacked(basic_st_.king_[side], enemy_side)) { maker.GenMoves<GenMoveType::ALL>(0, 0, 0, 0); } else { maker.GenMoves<GenMoveType::CAPTURE>(0, 0, 0, 0); } // 探索する。 // --- Futility Pruning --- // int margin = cache.futility_pruning_margin_[0]; for (Move move = maker.PickMove(); move; move = maker.PickMove()) { if (JudgeToStop(job)) break; // 次の自分のマテリアル。 int next_material = GetNextMaterial(material, move); MakeMove(move); // 合法手かどうか調べる。 if (IsAttacked(basic_st_.king_[side], enemy_side)) { UnmakeMove(move); continue; } // Futility Pruning。 if ((-next_material + margin) <= alpha) { UnmakeMove(move); continue; } // 次の手を探索。 int score = -Quiesce(level + 1, -beta, -alpha, next_material); UnmakeMove(move); // アルファ値、ベータ値を調べる。 Util::UpdateMax(alpha, score); if (alpha >= beta) { break; } } return ReturnProcess(alpha, level); } // 通常の探索。 int ChessEngine::Search(NodeType node_type, Hash pos_hash, int depth, u32 level, int alpha, int beta, int material) { // ジョブの準備。 Job& job = job_table_[level]; job.Init(maker_table_[level]); // キャッシュ。 Cache& cache = shared_st_ptr_->cache_; // 探索中止。 if (JudgeToStop(job)) return ReturnProcess(alpha, level); // ノード数を加算。 ++(shared_st_ptr_->searched_nodes_); // 最大探索数。 Util::UpdateMax(shared_st_ptr_->searched_level_, level); // サイドとチェックされているか。 Side side = basic_st_.to_move_; Side enemy_side = Util::GetOppositeSide(side); bool is_checked = IsAttacked(basic_st_.king_[side], enemy_side); // PVLineをリセット。 pv_line_table_[level].ResetLine(); // 勝負に十分な駒がなければ0点。 if (!HasSufficientMaterial()) { return ReturnProcess(SCORE_DRAW, level); } // --- 繰り返しチェック (繰り返しなら0点。) --- // basic_st_.position_memo_[level] = pos_hash; if (cache.enable_repetition_check_) { if (level <= 4) { // お互いの2手目。 int index = (shared_st_ptr_->position_history_.size() - 5) + level; if ((index >= 0) && (shared_st_ptr_->position_history_[index].pos_hash() == pos_hash)) { return ReturnProcess(SCORE_DRAW, level); } } else { // お互いの3手目以降。 if (basic_st_.position_memo_[level - 4] == pos_hash) { return ReturnProcess(SCORE_DRAW, level); } } } // --- トランスポジションテーブル --- // Move prev_best = 0; if (cache.enable_ttable_) { table_ptr_->Lock(); // ロック。 // 前回の繰り返しの最善手を含めたエントリーを得る。 const TTEntry& tt_entry = table_ptr_->GetEntry(pos_hash); if (tt_entry) { ScoreType score_type = tt_entry.score_type(); // 前回の最善手を得る。 if (score_type != ScoreType::ALPHA) { prev_best = tt_entry.best_move(); } // 探索省略のための探索済み局面をチェック。 // (注 1) 局面の繰り返し対策などのため、 // 自分の初手と相手の初手の場合(level < 2の場合)は探索省略しない。 // (注 2) チェックメイトを見つけていた時 // (SCORE_WIN以上、SCORE_LOSE以下)は、 // 「チェックメイト遠回り問題」を避けるため、探索省略しない。。 int score = tt_entry.score(); if ((level >= 2) && (tt_entry.depth() >= depth) && (score < SCORE_WIN) && (score > SCORE_LOSE)) { if (tt_entry.score_type() == ScoreType::EXACT) { // エントリーが正確な値。 pv_line_table_[level].score(score); table_ptr_->Unlock(); // ロック解除。 return ReturnProcess(score, level); } else if (tt_entry.score_type() == ScoreType::ALPHA) { // エントリーがアルファ値。 if (score <= alpha) { // アルファ値以下が確定。 pv_line_table_[level].score(score); table_ptr_->Unlock(); // ロック解除。 return ReturnProcess(score, level); } // ベータ値を下げられる。 if (score < beta) beta = score + 1; } else { if (score >= beta) { // ベータ値以上が確定。 pv_line_table_[level].score(score); table_ptr_->Unlock(); // ロック解除。 return ReturnProcess(score, level); } // アルファ値を上げられる。 if (score > alpha) alpha = score - 1; } } } table_ptr_->Unlock(); // ロック解除。 } // 深さが0ならクイース。 (無効なら評価値を返す。) // 限界探索数を超えていてもクイース。 if ((depth <= 0) || (level >= MAX_PLYS)) { if (cache.enable_quiesce_search_) { // クイース探索ノードに移行するため、ノード数を減らしておく。 --(shared_st_ptr_->searched_nodes_); return ReturnProcess(Quiesce(level, alpha, beta, material), level); } else { return ReturnProcess(evaluator_.Evaluate(material), level); } } // --- Internal Iterative Deepening --- // if (cache.enable_iid_ && (node_type == NodeType::PV)) { // 前回の繰り返しの最善手があればIIDしない。 if (prev_best) { shared_st_ptr_->iid_stack_[level] = prev_best; } else { if (!is_checked && (depth >= cache.iid_limit_depth_)) { // Internal Iterative Deepening。 Search(NodeType::PV, pos_hash, cache.iid_search_depth_, level, alpha, beta, material); shared_st_ptr_->iid_stack_[level] = pv_line_table_[level][0]; } } } // --- Null Move Reduction --- // int null_reduction = 0; if (cache.enable_nmr_ && (node_type == NodeType::NON_PV)) { if (!(is_null_searching_ || is_checked) && (depth >= cache.nmr_limit_depth_)) { // Null Move Reduction。 Move null_move = 0; is_null_searching_ = true; MakeNullMove(null_move); // Null Move Search。 int score = -(Search(NodeType::NON_PV, pos_hash, depth - cache.nmr_search_reduction_ - 1, level + 1, -(beta), -(beta - 1), -material)); UnmakeNullMove(null_move); is_null_searching_ = false; if (score >= beta) { null_reduction = cache.nmr_reduction_; depth = depth - null_reduction; if (depth <= 0) { if (cache.enable_quiesce_search_) { // クイース探索ノードに移行するため、ノード数を減らしておく。 --(shared_st_ptr_->searched_nodes_); return ReturnProcess (Quiesce(level, alpha, beta, material), level); } else { return ReturnProcess(evaluator_.Evaluate(material), level); } } } } } // 手を作る。 maker_table_[level].GenMoves<GenMoveType::ALL>(prev_best, shared_st_ptr_->iid_stack_[level], shared_st_ptr_->killer_stack_[level][0], shared_st_ptr_->killer_stack_[level][1]); ScoreType score_type = ScoreType::ALPHA; // --- ProbCut --- // if (cache.enable_probcut_ && (node_type == NodeType::NON_PV)) { if (!(is_null_searching_ || is_checked) && (depth >= cache.probcut_limit_depth_)) { // 手を作る。 MoveMaker& maker = maker_table_[level]; maker.RegenMoves(); // 浅読みパラメータ。 int prob_beta = beta + cache.probcut_margin_; int prob_depth = depth - cache.probcut_search_reduction_; // 探索。 for (Move move = maker.PickMove(); move; move = maker.PickMove()) { if (JudgeToStop(job)) return ReturnProcess(alpha, level); // 次のノードへの準備。 Hash next_hash = GetNextHash(pos_hash, move); int next_material = GetNextMaterial(material, move); MakeMove(move); // 合法手じゃなければ次の手へ。 if (IsAttacked(basic_st_.king_[side], enemy_side)) { UnmakeMove(move); continue; } int score = -Search(NodeType::NON_PV, next_hash, prob_depth - 1, level + 1, -prob_beta, -(prob_beta - 1), next_material); UnmakeMove(move); if (JudgeToStop(job)) return ReturnProcess(alpha, level); // ベータカット。 if (score >= prob_beta) { // PVライン。 pv_line_table_[level].SetMove(move); pv_line_table_[level].Insert(pv_line_table_[level + 1]); // 取らない手。 if (!(move & MASK[CAPTURED_PIECE])) { // 手の情報を得る。 Square from = Get<FROM>(move); Square to = Get<TO>(move); // キラームーブ。 if (cache.enable_killer_) { shared_st_ptr_->killer_stack_[level][0] = move; shared_st_ptr_->killer_stack_[level + 2][1] = move; } // ヒストリー。 if (cache.enable_history_) { shared_st_ptr_->history_[side][from][to] += Util::DepthToHistory(depth); Util::UpdateMax (shared_st_ptr_->history_[side][from][to], shared_st_ptr_->history_max_); } } // トランスポジションテーブルに登録。 if (!null_reduction) { table_ptr_->Add(pos_hash, depth, beta, ScoreType::BETA, move); } return ReturnProcess(beta, level); } } } } // --- Check Extension --- // if (is_checked && cache.enable_check_extension_) { depth += 1; } // 準備。 int num_all_moves = maker_table_[level].RegenMoves(); int move_number = 0; int margin = cache.futility_pruning_margin_[depth]; // 仕事の生成。 job.Lock(); job.Init(maker_table_[level]); job.node_type_ = node_type; job.pos_hash_ = pos_hash; job.depth_ = depth; job.alpha_ = alpha; job.beta_ = beta; job.pv_line_ptr_ = &pv_line_table_[level]; job.is_null_searching_ = is_null_searching_; job.null_reduction_ = null_reduction; job.score_type_ = score_type; job.material_ = material; job.is_checked_ = is_checked; job.num_all_moves_ = num_all_moves; job.has_legal_move_ = false; job.Unlock(); // パラメータ準備。 int history_pruning_move_number = cache.history_pruning_invalid_moves_[num_all_moves]; u64 history_pruning_threshold = (shared_st_ptr_->history_max_ * cache.history_pruning_threshold_) >> 8; // Late Move Reduction。 int lmr_move_number = cache.lmr_invalid_moves_[num_all_moves]; for (Move move = job.PickMove(); move; move = job.PickMove()) { // 探索終了ならループを抜ける。 if (JudgeToStop(job)) break; // 別スレッドに助けを求める。(YBWC) if ((job.depth_ >= cache.ybwc_limit_depth_) && (move_number > cache.ybwc_invalid_moves_)) { shared_st_ptr_->helper_queue_ptr_->Help(job); } // 次のハッシュ。 Hash next_hash = GetNextHash(job.pos_hash_, move); // 次の自分のマテリアル。 int next_material = GetNextMaterial(job.material_, move); MakeMove(move); // 合法手じゃなければ次の手へ。 if (IsAttacked(basic_st_.king_[side], enemy_side)) { UnmakeMove(move); continue; } // 合法手があったのでフラグを立てる。 job.has_legal_move_ = true; move_number = job.Count(); // -- Futility Pruning --- // if ((-next_material + margin) <= job.alpha_) { UnmakeMove(move); continue; } // 手の情報を得る。 Square from = Get<FROM>(move); Square to = Get<TO>(move); // 探索。 int temp_alpha = job.alpha_; int temp_beta = job.beta_; int score = temp_alpha; // --- Late Move Reduction --- // if (cache.enable_lmr_) { if (!(is_checked || null_reduction) && (depth >= cache.lmr_limit_depth_) && (move_number > lmr_move_number) && !((move & (MASK[CAPTURED_PIECE] | MASK[PROMOTION])) || EqualMove(move, shared_st_ptr_->killer_stack_[level][0]) || EqualMove(move, shared_st_ptr_->killer_stack_[level][1]))) { score = -Search(NodeType::NON_PV, next_hash, depth - cache.lmr_search_reduction_ - 1, level + 1, -(temp_alpha + 1), -temp_alpha, next_material); } else { ++score; } } else { ++score; } // Late Move Reduction失敗。 // PVノードの探索とNON_PVノードの探索に分ける。 if (score > temp_alpha) { if (node_type == NodeType::PV) { // PV。 // --- PVSearch --- // if (move_number <= 1) { // フルウィンドウで探索。 score = -Search(node_type, next_hash, depth - 1, level + 1, -temp_beta, -temp_alpha, next_material); } else { // PV発見後のPVノード。 // ゼロウィンドウ探索。 score = -Search(NodeType::NON_PV, next_hash, depth - 1, level + 1, -(temp_alpha + 1), -temp_alpha, next_material); if ((score > temp_alpha) && (score < temp_beta)) { // Fail Lowならず。 // Fail-Softなので、Beta値以上も探索しない。 // フルウィンドウで再探索。 score = -Search(NodeType::PV, next_hash, depth - 1, level + 1, -temp_beta, -temp_alpha, next_material); } } } else { // NON_PV。 // --- History Pruning --- // int new_depth = depth; if (cache.enable_history_pruning_) { if (!(is_checked || null_reduction) && (depth >= cache.history_pruning_limit_depth_) && (move_number > history_pruning_move_number) && (shared_st_ptr_->history_[side][from][to] < history_pruning_threshold) && !((move & (MASK[CAPTURED_PIECE] | MASK[PROMOTION])) || EqualMove(move, shared_st_ptr_->killer_stack_[level][0]) || EqualMove(move, shared_st_ptr_->killer_stack_[level][1]))) { new_depth -= cache.history_pruning_reduction_; } } // 探索。 NON_PVノードなので、ゼロウィンドウになる。 score = -Search(node_type, next_hash, new_depth - 1, level + 1, -temp_beta, -temp_alpha, next_material); } } UnmakeMove(move); // 探索終了ならループを抜ける。 if (JudgeToStop(job)) break; job.Lock(); // ロック。 // アルファ値を更新。 if (score > job.alpha_) { // 評価値のタイプをセット。 job.score_type_ = ScoreType::EXACT; // PVライン。 job.pv_line_ptr_->SetMove(move); job.pv_line_ptr_->Insert(pv_line_table_[level + 1]); job.pv_line_ptr_->score(score); job.alpha_ = score; } // ベータ値を調べる。 if (job.alpha_ >= job.beta_) { // 評価値の種類をセット。 job.score_type_ = ScoreType::BETA; // ベータカット。 job.NotifyBetaCut(*this); job.Unlock(); // ロック解除。 break; } job.Unlock(); // ロック解除。 } // スレッドを合流。 if (job.depth_ >= cache.ybwc_limit_depth_) { job.WaitForHelpers(); } // このノードでゲーム終了だった場合。 if (!(job.has_legal_move_)) { if (is_checked) { // チェックメイト。 pv_line_table_[level].score(SCORE_LOSE); pv_line_table_[level].mate_in(level); return ReturnProcess(SCORE_LOSE, level); } else { // ステールメイト。 pv_line_table_[level].score(SCORE_DRAW); return ReturnProcess(SCORE_DRAW, level); } } // --- 後処理 --- // { Move best_move = pv_line_table_[level][0]; pv_line_table_[level].score(job.alpha_); // キラームーブ、ヒストリーを記録。 if (job.score_type_ != ScoreType::ALPHA) { if (!(best_move & (MASK[CAPTURED_PIECE] | MASK[PROMOTION]))) { // キラームーブ。 if (cache.enable_killer_) { shared_st_ptr_->killer_stack_[level][0] = best_move; shared_st_ptr_->killer_stack_[level + 2][1] = best_move; } // ヒストリー。 if (cache.enable_history_) { Square from = Get<FROM>(best_move); Square to = Get<TO>(best_move); shared_st_ptr_->history_[side][from][to] += Util::DepthToHistory(job.depth_); Util::UpdateMax(shared_st_ptr_->history_max_, shared_st_ptr_->history_[side][from][to]); } } } // トランスポジションテーブルに登録。 // Null Move探索中の局面は登録しない。 // Null Move Reductionされていた場合、容量節約のため登録しない。 if (cache.enable_ttable_) { if (!(is_null_searching_ || null_reduction)) { table_ptr_->Add(pos_hash, depth, job.alpha_, job.score_type_, best_move); } } } return ReturnProcess(job.alpha_, level); } // 探索のルート。 PVLine ChessEngine::SearchRoot(const std::vector<Move>& moves_to_search, UCIShell& shell) { constexpr int level = 0; // --- 初期化 --- // // ジョブ。 Job& job = job_table_[level]; job.Init(maker_table_[level]); // カット通知。 notice_cut_level_ = MAX_PLYS + 1; // キャッシュ。 table_ptr_ = shared_st_ptr_->table_ptr_; shared_st_ptr_->CacheParams(); Cache& cache = shared_st_ptr_->cache_; shared_st_ptr_->searched_nodes_ = 0; shared_st_ptr_->searched_level_ = 0; shared_st_ptr_->is_time_over_ = false; FOR_SIDES(side) { FOR_SQUARES(from) { FOR_SQUARES(to) { shared_st_ptr_->history_[side][from][to] = 0; } } } for (u32 i = 0; i < (MAX_PLYS + 1); ++i) { basic_st_.position_memo_[i] = 0; shared_st_ptr_->iid_stack_[i] = 0; shared_st_ptr_->killer_stack_[i][0] = 0; shared_st_ptr_->killer_stack_[i][1] = 0; shared_st_ptr_->killer_stack_[i + 2][0] = 0; shared_st_ptr_->killer_stack_[i + 2][1] = 0; maker_table_[i].ResetStack(); pv_line_table_[i].ResetLine(); } shared_st_ptr_->history_max_ = 1; shared_st_ptr_->stop_now_ = false; shared_st_ptr_->i_depth_ = 1; is_null_searching_ = false; // PVLineに最初の候補手を入れておく。 MoveMaker temp_maker(*this); temp_maker.GenMoves<GenMoveType::ALL>(0, 0, 0, 0); pv_line_table_[level].SetMove(temp_maker.PickMove()); // スレッドの準備。 shared_st_ptr_->helper_queue_ptr_.reset(new HelperQueue()); std::vector<std::unique_ptr<ChessEngine>> child_vec(0); for (unsigned int i = 0; i < thread_vec_.size(); ++i) { child_vec.push_back (std::unique_ptr<ChessEngine>(new ChessEngine(*this))); ChessEngine* child_ptr = child_vec.back().get(); child_ptr->shared_st_ptr_ = shared_st_ptr_; thread_vec_[i] = std::thread([child_ptr, &shell]() { child_ptr->ThreadYBWC(shell); }); } // 定期処理開始。 std::thread time_thread([this, &shell]() { this->shared_st_ptr_->ThreadPeriodicProcess(shell); }); // --- Iterative Deepening --- // Move prev_best = 0; Hash pos_hash = basic_st_.position_memo_[level] = GetCurrentHash(); int material = GetMaterial(basic_st_.to_move_); int alpha = -MAX_VALUE; int beta = MAX_VALUE; Side side = basic_st_.to_move_; Side enemy_side = Util::GetOppositeSide(side); bool is_checked = IsAttacked(basic_st_.king_[side], enemy_side); bool found_mate = false; for (shared_st_ptr_->i_depth_ = 1; shared_st_ptr_->i_depth_ <= MAX_PLYS; ++(shared_st_ptr_->i_depth_)) { // 探索終了。 if (JudgeToStop(job)) { --(shared_st_ptr_->i_depth_); break; } int depth = shared_st_ptr_->i_depth_; // ノードを加算。 ++(shared_st_ptr_->searched_nodes_); // 探索したレベルをリセット。 shared_st_ptr_->searched_level_ = 0; // 勝負に十分な駒がなければ探索しない。 if (!HasSufficientMaterial()) { pv_line_table_[level].score(SCORE_DRAW); Chrono::milliseconds time = Chrono::duration_cast<Chrono::milliseconds> (SysClock::now() - shared_st_ptr_->start_time_); shell.PrintPVInfo(depth, 0, pv_line_table_[level].score(), time, shared_st_ptr_->searched_nodes_, table_ptr_->GetUsedPermill(), pv_line_table_[level]); continue; } // メイトをすでに見つけていたら探索しない。 if (found_mate) { Chrono::milliseconds time = Chrono::duration_cast<Chrono::milliseconds> (SysClock::now() - shared_st_ptr_->start_time_); shell.PrintPVInfo(depth, 0, pv_line_table_[level].score(), time, shared_st_ptr_->searched_nodes_, table_ptr_->GetUsedPermill(), pv_line_table_[level]); continue; } // --- Aspiration Windows --- // int delta = cache.aspiration_windows_delta_; // 探索窓の設定。 if (cache.enable_aspiration_windows_ && (depth >= cache.aspiration_windows_limit_depth_)) { beta = alpha + delta; alpha -= delta; } else { alpha = -MAX_VALUE; beta = MAX_VALUE; } // 標準出力に深さ情報を送る。 shell.PrintDepthInfo(depth); // --- Check Extension --- // if (is_checked && cache.enable_check_extension_) { depth += 1; } // 仕事を作る。 int num_all_moves = maker_table_[level].GenMoves<GenMoveType::ALL>(prev_best, shared_st_ptr_->iid_stack_[level], shared_st_ptr_->killer_stack_[level][0], shared_st_ptr_->killer_stack_[level][1]); job.Lock(); job.Init(maker_table_[level]); job.node_type_ = NodeType::PV; job.pos_hash_ = pos_hash; job.depth_ = depth; job.alpha_ = alpha; job.beta_ = beta; job.delta_ = delta; job.pv_line_ptr_ = &pv_line_table_[level]; job.is_null_searching_ = is_null_searching_; job.null_reduction_ = 0; job.score_type_ = ScoreType::EXACT; job.material_ = material; job.is_checked_ = is_checked; job.num_all_moves_ = num_all_moves; job.has_legal_move_ = false; job.moves_to_search_ptr_ = &moves_to_search; job.Unlock(); // ヘルプして待つ。 shared_st_ptr_->helper_queue_ptr_->HelpRoot(job); job.WaitForHelpers(); // 最善手を記録する。 prev_best = pv_line_table_[level][0]; // アルファ、ベータ、デルタを更新。 alpha = job.alpha_; beta = job.beta_; delta = job.delta_; // 最善手が取らない手の場合、ヒストリー、キラームーブをセット。 if (!(prev_best & MASK[CAPTURED_PIECE])) { // キラームーブ。 if (cache.enable_killer_) { shared_st_ptr_->killer_stack_[level][0] = prev_best; shared_st_ptr_->killer_stack_[level + 2][1] = prev_best; } // ヒストリー。 if (cache.enable_history_) { // 手の情報を得る。 Square from = Get<FROM>(prev_best); Square to = Get<TO>(prev_best); shared_st_ptr_->history_[side][from][to] += Util::DepthToHistory(job.depth_); Util::UpdateMax(shared_st_ptr_->history_[side][from][to], shared_st_ptr_->history_max_); } } // 最善手をトランスポジションテーブルに登録。 if (cache.enable_ttable_) { table_ptr_->Add(job.pos_hash_, job.depth_, job.alpha_, ScoreType::EXACT, prev_best); } // メイトを見つけたらフラグを立てる。 // 直接ループを抜けない理由は、depth等の終了条件対策。 if (pv_line_table_[level].mate_in() >= 0) { found_mate = true; } } // スレッドをジョイン。 shared_st_ptr_->helper_queue_ptr_->ReleaseHelpers(); for (auto& thread : thread_vec_) { try { thread.join(); } catch (std::system_error err) { // 無視。 } } // 探索終了したけど、まだ思考を止めてはいけない場合、関数を終了しない。 while (!JudgeToStop(job)) { std::this_thread::sleep_for(Chrono::milliseconds(1)); } // 定期処理スレッドを待つ。 try { time_thread.join(); } catch (std::system_error err) { // 無視。 } // 最後に情報を送る。 shell.PrintFinalInfo(shared_st_ptr_->i_depth_, Chrono::duration_cast<Chrono::milliseconds> (SysClock::now() - (shared_st_ptr_->start_time_)), shared_st_ptr_->searched_nodes_, table_ptr_->GetUsedPermill(), pv_line_table_[level].score(), pv_line_table_[level]); return pv_line_table_[level]; } // YBWC探索用スレッド。 void ChessEngine::ThreadYBWC(UCIShell& shell) { // 準備。 notice_cut_level_ = MAX_PLYS + 1; table_ptr_ = shared_st_ptr_->table_ptr_; is_null_searching_ = false; // 仕事ループ。 while (true) { // 準備。 Job* job_ptr = nullptr; notice_cut_level_ = MAX_PLYS + 1; // 仕事を拾う。 job_ptr = shared_st_ptr_->helper_queue_ptr_->GetJob(this); if (job_ptr) { if (job_ptr->level_ <= 0) { // ルートノード。 SearchRootParallel(*job_ptr, shell); } else { // ルートではないノード。 SearchParallel(job_ptr->node_type_, *job_ptr); } job_ptr->ReleaseHelper(*this); } else { break; } } } // 並列探索。 void ChessEngine::SearchParallel(NodeType node_type, Job& job) { // キャッシュ。 Cache& cache = shared_st_ptr_->cache_; // 仕事ループ。 Side side = basic_st_.to_move_; Side enemy_side = Util::GetOppositeSide(side); int move_number = 0; int margin = cache.futility_pruning_margin_[job.depth_]; // パラメータ準備。 int history_pruning_move_number = cache.history_pruning_invalid_moves_[job.num_all_moves_]; u64 history_pruning_threshold = (shared_st_ptr_->history_max_ * cache.history_pruning_threshold_) >> 8; // Late Move Reduction。 int lmr_move_number = cache.lmr_invalid_moves_[job.num_all_moves_]; for (Move move = job.PickMove(); move; move = job.PickMove()) { // 探索終了ならループを抜ける。 if (JudgeToStop(job)) break; // 次のハッシュ。 Hash next_hash = GetNextHash(job.pos_hash_, move); // 次の局面のマテリアルを得る。 int next_material = GetNextMaterial(job.material_, move); MakeMove(move); // 合法手じゃなければ次の手へ。 if (IsAttacked(basic_st_.king_[side], enemy_side)) { UnmakeMove(move); continue; } move_number = job.Count(); // 合法手が見つかったのでフラグを立てる。 job.has_legal_move_ = true; // --- Futility Pruning --- // if ((-next_material + margin) <= job.alpha_) { UnmakeMove(move); continue; } // 手の情報を得る。 Square from = Get<FROM>(move); Square to = Get<TO>(move); // 探索。 int temp_alpha = job.alpha_; int temp_beta = job.beta_; int score = temp_alpha; // --- Late Move Reduction --- // if (cache.enable_lmr_) { if (!(job.is_checked_ || job.null_reduction_) && (job.depth_ >= cache.lmr_limit_depth_) && (move_number > lmr_move_number) && !((move & (MASK[CAPTURED_PIECE] | MASK[PROMOTION])) || EqualMove(move, shared_st_ptr_->killer_stack_[job.level_][0]) || EqualMove(move, shared_st_ptr_->killer_stack_[job.level_][1]))) { score = -Search(NodeType::NON_PV, next_hash, job.depth_ - cache.lmr_search_reduction_ - 1, job.level_ + 1, -(temp_alpha + 1), -temp_alpha, next_material); } else { ++score; } } else { ++score; } // Late Move Reduction失敗時。 // PVノードの探索とNON_PVノードの探索に分ける。 if (score > temp_alpha) { if (node_type == NodeType::PV) { // PV。 // --- PVSearch --- // if (move_number <= 1) { // フルウィンドウで探索。 score = -Search(node_type, next_hash, job.depth_ - 1, job.level_ + 1, -temp_beta, -temp_alpha, next_material); } else { // PV発見後のPVノード。 // ゼロウィンドウ探索。 score = -Search(NodeType::NON_PV, next_hash, job.depth_ - 1, job.level_ + 1, -(temp_alpha + 1), -temp_alpha, next_material); if ((score > temp_alpha) && (score < temp_beta)) { // Fail Lowならず。 // Fail-Softなので、Beta値以上も探索しない。 // フルウィンドウで再探索。 score = -Search(NodeType::PV, next_hash, job.depth_ - 1, job.level_ + 1, -temp_beta, -temp_alpha, next_material); } } } else { // NON_PV。 // --- History Pruning --- // int new_depth = job.depth_; if (cache.enable_history_pruning_) { if (!(job.is_checked_ || job.null_reduction_) && (job.depth_ >= cache.history_pruning_limit_depth_) && (move_number > history_pruning_move_number) && (shared_st_ptr_->history_[side][from][to] < history_pruning_threshold) && !((move & (MASK[CAPTURED_PIECE] | MASK[PROMOTION])) || EqualMove(move, shared_st_ptr_->killer_stack_[job.level_][0]) || EqualMove (move, shared_st_ptr_->killer_stack_[job.level_][1]))) { new_depth -= cache.history_pruning_reduction_; } } // 探索。 NON_PVノードなので、ゼロウィンドウになる。 score = -Search(node_type, next_hash, new_depth - 1, job.level_ + 1, -temp_beta, -temp_alpha, next_material); } } UnmakeMove(move); // 探索終了ならループを抜ける。 if (JudgeToStop(job)) break; job.Lock(); // ロック。 // アルファ値を更新。 if (score > job.alpha_) { // 評価値のタイプをセット。 job.score_type_ = ScoreType::EXACT; // PVラインをセット。 job.pv_line_ptr_->SetMove(move); job.pv_line_ptr_->Insert(pv_line_table_[job.level_ + 1]); job.pv_line_ptr_->score(score); job.alpha_ = score; } // ベータ値を調べる。 if (job.alpha_ >= job.beta_) { // 評価値の種類をセット。 job.score_type_ = ScoreType::BETA; // ベータカット。 job.NotifyBetaCut(*this); job.Unlock(); // ロック解除。 break; } job.Unlock(); // ロック解除。 } } // ルートノードで呼び出される、別スレッド用探索関数。 void ChessEngine::SearchRootParallel(Job& job, UCIShell& shell) { // キャッシュ。 Cache& cache = shared_st_ptr_->cache_; // 仕事ループ。 Side side = basic_st_.to_move_; Side enemy_side = Util::GetOppositeSide(side); int move_number = 0; // パラメータを準備。 int lmr_move_number = cache.lmr_invalid_moves_[job.num_all_moves_]; for (Move move = job.PickMove(); move; move = job.PickMove()) { if (JudgeToStop(job)) break; // 探索すべき手が指定されていれば、今の手がその手かどうか調べる。 if (!(job.moves_to_search_ptr_->empty())) { bool hit = false; for (auto move_2 : *(job.moves_to_search_ptr_)) { if (EqualMove(move_2, move)) { // 探索すべき手だった。 hit = true; break; } } if (!hit) { // 探索すべき手ではなかった。 // 次の手へ。 continue; } } // 次のハッシュ。 Hash next_hash = GetNextHash(job.pos_hash_, move); // 次の局面のマテリアル。 int next_material = GetNextMaterial(job.material_, move); MakeMove(move); // 合法手じゃなければ次の手へ。 if (IsAttacked(basic_st_.king_[side], enemy_side)) { UnmakeMove(move); continue; } move_number = job.Count(); // 現在探索している手の情報を表示。 job.Lock(); // ロック。 shell.PrintCurrentMoveInfo(move, move_number); job.Unlock(); // ロック解除。 // --- PVSearch --- // int temp_alpha = job.alpha_; int temp_beta = job.beta_; int score = temp_alpha; if (move_number <= 1) { while (true) { // 探索終了。 if (JudgeToStop(job)) break; // フルでPVを探索。 score = -Search(NodeType::PV, next_hash, job.depth_ - 1, job.level_ + 1, -temp_beta, -temp_alpha, next_material); // アルファ値、ベータ値を調べる。 job.Lock(); // ロック。 if (score >= temp_beta) { // 探索失敗。 // ベータ値を広げる。 job.delta_ *= 2; temp_beta = score + job.delta_; if (job.beta_ >= temp_beta) { temp_beta = job.beta_; } else { job.beta_ = temp_beta; } if ((pv_line_table_[job.level_ + 1].mate_in() >= 0) && ((pv_line_table_[job.level_ + 1].mate_in() % 2) == 1)) { // メイトっぽかった場合。 job.beta_ = MAX_VALUE; temp_beta = MAX_VALUE; } job.Unlock(); // ロック解除。 continue; } else if (score <= temp_alpha) { // 探索失敗。 // アルファ値を広げる。 job.delta_ *= 2; temp_alpha = score - job.delta_; if (job.alpha_ <= temp_alpha) { temp_alpha = job.alpha_; } else { job.alpha_ = temp_alpha; } if ((pv_line_table_[job.level_ + 1].mate_in() >= 0) && ((pv_line_table_[job.level_ + 1].mate_in() % 2) == 0)) { // メイトされていたかもしれない場合。 job.alpha_ = -MAX_VALUE; temp_alpha = -MAX_VALUE; } job.Unlock(); // ロック解除。 continue; } else { job.Unlock(); // ロック解除。 break; } job.Unlock(); // ロック解除。 } } else { // --- Late Move Reduction --- // if (cache.enable_lmr_) { if (!(job.is_checked_) && (job.depth_ >= cache.lmr_limit_depth_) && (move_number > lmr_move_number) && !(move & (MASK[CAPTURED_PIECE] | MASK[PROMOTION]))) { // ゼロウィンドウ探索。 score = -Search(NodeType::NON_PV, next_hash, job.depth_ - cache.lmr_search_reduction_ - 1, job.level_ + 1, -(temp_alpha + 1), -temp_alpha, next_material); } else { ++score; } } else { ++score; } // 普通の探索。 if (score > temp_alpha) { // ゼロウィンドウ探索。 score = -Search(NodeType::NON_PV, next_hash, job.depth_ - 1, job.level_ + 1, -(temp_alpha + 1), -temp_alpha, next_material); if (score > temp_alpha) { while (true) { // 探索終了。 if (JudgeToStop(job)) break; // フルウィンドウで再探索。 score = -Search(NodeType::PV, next_hash, job.depth_ - 1, job.level_ + 1, -temp_beta, -temp_alpha, next_material); // ベータ値を調べる。 job.Lock(); // ロック。 // if (score >= temp_beta) { if (score >= job.beta_) { // 探索失敗。 // ベータ値を広げる。 job.delta_ *= 2; temp_beta = score + job.delta_; if (job.beta_ >= temp_beta) { temp_beta = job.beta_; } else { job.beta_ = temp_beta; } if ((pv_line_table_[job.level_ + 1].mate_in() >= 0) && ((pv_line_table_[job.level_ + 1].mate_in() % 2) == 1)) { // メイトっぽかった場合。 job.beta_ = MAX_VALUE; temp_beta = MAX_VALUE; } job.Unlock(); // ロック解除。 continue; } else { job.Unlock(); // ロック解除。 break; } job.Unlock(); // ロック解除。 } } } } UnmakeMove(move); // ストップがかかっていたらループを抜ける。 if (JudgeToStop(job)) break; // 最善手を見つけた。 job.Lock(); // ロック。 if (score > job.alpha_) { // PVラインにセット。 job.pv_line_ptr_->SetMove(move); job.pv_line_ptr_->Insert(pv_line_table_[job.level_ + 1]); job.pv_line_ptr_->score(score); // 標準出力にPV情報を表示。 Chrono::milliseconds time = Chrono::duration_cast<Chrono::milliseconds> (SysClock::now() - shared_st_ptr_->start_time_); shell.PrintPVInfo(job.depth_, shared_st_ptr_->searched_level_, score, time, shared_st_ptr_->searched_nodes_, table_ptr_->GetUsedPermill(), *(job.pv_line_ptr_)); job.alpha_ = score; } job.Unlock(); // ロック解除。 } } // SEEで候補手を評価する。 u32 ChessEngine::SEE(Move move) const { Cache& cache = shared_st_ptr_->cache_; // SEEが無効かどうか。 if (!(cache.enable_see_)) return 1; return Get<MOVE_TYPE>(move) == EN_PASSANT ? cache.material_[PAWN] : cache.material_[basic_st_.piece_board_[Get<TO>(move)]]; } // 探索のストップ条件を設定する。 void ChessEngine::SetStopper(u32 max_depth, u64 max_nodes, const Chrono::milliseconds& thinking_time, bool infinite_thinking) { shared_st_ptr_->max_depth_ = Util::GetMin(max_depth, MAX_PLYS); shared_st_ptr_->max_nodes_ = Util::GetMin(max_nodes, MAX_NODES); shared_st_ptr_->start_time_ = SysClock::now(); // 時間を10ミリ秒(100分の1秒)余裕を見る。 shared_st_ptr_->end_time_ = shared_st_ptr_->start_time_ + thinking_time - Chrono::milliseconds(10); shared_st_ptr_->infinite_thinking_ = infinite_thinking; } // 無限に思考するかどうかのフラグをセットする。 void ChessEngine::EnableInfiniteThinking(bool enable) { shared_st_ptr_->infinite_thinking_ = enable; } // 現在のノードの探索を中止すべきかどうか判断する。 bool ChessEngine::JudgeToStop(Job& job) { // キャッシュ。 Cache& cache = shared_st_ptr_->cache_; // 今すぐ終了すべきかどうか。 if (shared_st_ptr_->stop_now_) { return true; } // ベータカット通知で終了すべきかどうか。 if (notice_cut_level_ <= job.level_) { if ((job.client_ptr_ == this) && (job.level_ != notice_cut_level_)) { // 自分のヘルパーに「もう意味ないよ」と通知する。 job.NotifyBetaCut(*this); } return true; } // --- 思考ストップ条件から判断 --- // // ストップするべきではない。 if ((shared_st_ptr_->i_depth_ <= 1) || shared_st_ptr_->infinite_thinking_) { return false; } // ストップするべき。 if ((shared_st_ptr_->is_time_over_) || (shared_st_ptr_->searched_nodes_ >= cache.max_nodes_) || (shared_st_ptr_->i_depth_ > cache.max_depth_)) { shared_st_ptr_->stop_now_ = true; return true; } return false; } } // namespace Sayuri
29.215227
79
0.569385
[ "vector" ]
fc16f9cf742ce7090c53811bdf4f9a674dd96385
2,335
hh
C++
src/plugin/compute/cuda/include/kernelobject.hh
bugengine/BugEngine
1b3831d494ee06b0bd74a8227c939dd774b91226
[ "BSD-3-Clause" ]
4
2015-05-13T16:28:36.000Z
2017-05-24T15:34:14.000Z
src/plugin/compute/cuda/include/kernelobject.hh
bugengine/BugEngine
1b3831d494ee06b0bd74a8227c939dd774b91226
[ "BSD-3-Clause" ]
null
null
null
src/plugin/compute/cuda/include/kernelobject.hh
bugengine/BugEngine
1b3831d494ee06b0bd74a8227c939dd774b91226
[ "BSD-3-Clause" ]
1
2017-03-21T08:28:07.000Z
2017-03-21T08:28:07.000Z
/* BugEngine <bugengine.devel@gmail.com> see LICENSE for detail */ #ifndef BE_COMPUTE_CUDA_KERNELOBJECT_HH_ #define BE_COMPUTE_CUDA_KERNELOBJECT_HH_ /**************************************************************************************************/ #include <bugengine/plugin.compute.cuda/stdafx.h> #include <bugengine/plugin/dynobject.hh> #include <bugengine/scheduler/task/task.hh> namespace BugEngine { namespace KernelScheduler { namespace Cuda { class KernelObject; class Scheduler; struct CudaKernelTask { weak< KernelObject > object; weak< Task::ITask > sourceTask; minitl::array< weak< const IMemoryBuffer > > params; struct Range { u32 index; u32 total; Range(u32 total) : index(total), total(total) { } Range(u32 index, u32 total) : index(index), total(total) { be_assert(index != total, "index should not be equal to total"); } bool atomic() const { return index != total; } u32 partCount(u32 workerCount) const { be_forceuse(workerCount); return total; } Range part(u32 i, u32 t) const { return Range(i, t); } }; CudaKernelTask(weak< KernelObject > object); Range prepare(); void operator()(const Range& range) const; }; class KernelObject : public minitl::refcountable { friend class Scheduler; private: typedef void(KernelMain)(const u32, const u32, const minitl::array< weak< const IMemoryBuffer > >& params); private: class Callback; private: Plugin::DynamicObject m_kernel; KernelMain* m_entryPoint; scoped< Task::Task< CudaKernelTask > > m_task; scoped< Task::ITask::ICallback > m_callback; Task::ITask::CallbackConnection m_callbackConnection; public: KernelObject(const inamespace& name); ~KernelObject(); void run(const u32 index, const u32 total, const minitl::array< weak< const IMemoryBuffer > >& params); }; }}} // namespace BugEngine::KernelScheduler::Cuda /**************************************************************************************************/ #endif
28.13253
100
0.552463
[ "object" ]
fc1ed1c42ed3be36e6aba3db42dfba2444413e57
1,356
cpp
C++
test/IniParserTest.cpp
hzx/mutant2
5029d4ef59dca55819a98975b47554110913d62e
[ "MIT" ]
1
2016-08-03T13:15:05.000Z
2016-08-03T13:15:05.000Z
test/IniParserTest.cpp
hzx/mutant2
5029d4ef59dca55819a98975b47554110913d62e
[ "MIT" ]
null
null
null
test/IniParserTest.cpp
hzx/mutant2
5029d4ef59dca55819a98975b47554110913d62e
[ "MIT" ]
null
null
null
#include <gmock/gmock.h> #include <string> #include <vector> #include "mutant/IniParser.h" #include "mutant/error.h" class IniParserTest: public ::testing::Test { public: Config config; IniParser parser; }; TEST_F(IniParserTest, parse) { std::string content = R"( [core] user.email = test@example.com path = /usr/local/lib/mutant/libs:$HOME/projects/mutant-libs foo = "Some path with spaces here" [watch] bar = 12.3 )"; int error = parser.parse(config, content); ASSERT_EQ(ERROR_OK, error); ASSERT_EQ(2, config.groups.size()); auto it = config.groups.find("core"); ASSERT_TRUE(it != config.groups.end()); ConfigGroup& core = it->second; ASSERT_EQ(3, core.settings.size()); auto emailIt = core.settings.find("user.email"); ASSERT_TRUE(emailIt != core.settings.end()); ASSERT_EQ("test@example.com", emailIt->second); auto pathIt = core.settings.find("path"); ASSERT_TRUE(pathIt != core.settings.end()); ASSERT_EQ("/usr/local/lib/mutant/libs:$HOME/projects/mutant-libs", pathIt->second); auto fooIt = core.settings.find("foo"); ASSERT_TRUE(fooIt != core.settings.end()); ASSERT_EQ("Some path with spaces here", fooIt->second); auto watchIt = config.groups.find("watch"); ASSERT_TRUE(watchIt != config.groups.end()); ConfigGroup& watch = watchIt->second; ASSERT_EQ(1, watch.settings.size()); }
23.789474
85
0.693953
[ "vector" ]
fc221ef8c5fc2cb3bd7817ee8a253e5d17408dad
11,278
hpp
C++
3rdparty/GPSTk/ext/lib/Geomatics/DiscCorr.hpp
mfkiwl/ICE
e660d031bb1bcea664db1de4946fd8781be5b627
[ "MIT" ]
50
2019-10-12T01:22:20.000Z
2022-02-15T23:28:26.000Z
3rdparty/GPSTk/ext/lib/Geomatics/DiscCorr.hpp
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
2f1ff054b7c5059da80bb3b2f80c05861a02cc36
[ "MIT" ]
null
null
null
3rdparty/GPSTk/ext/lib/Geomatics/DiscCorr.hpp
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
2f1ff054b7c5059da80bb3b2f80c05861a02cc36
[ "MIT" ]
14
2019-11-05T01:50:29.000Z
2021-08-06T06:23:44.000Z
//============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 3.0 of the License, or // any later version. // // The GPSTk is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with GPSTk; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= /// @file DiscCorr.hpp /// GPS phase discontinuity correction. Given a SatPass object /// containing dual-frequency pseudorange and phase for an entire satellite pass, /// and a configuration object (as defined herein), detect discontinuities in /// the phase and, if possible, estimate their size. /// Output is in the form of Rinex editing commands (see class RinexEditor). #ifndef GPSTK_DISCONTINUITY_CORRECTOR_INCLUDE #define GPSTK_DISCONTINUITY_CORRECTOR_INCLUDE #include "Epoch.hpp" #include "RinexSatID.hpp" #include "RinexObsHeader.hpp" #include "SatPass.hpp" #include "Exception.hpp" #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <map> namespace gpstk { /** @addtogroup rinexutils */ //@{ /// class GDCconfiguration encapsulates the configuration for input to the /// GPSTK Discontinuity Corrector. class GDCconfiguration { public: /// constructor; this sets a full default set of parameters. GDCconfiguration(void) { initialize(); } // destructor ~GDCconfiguration(void) { CFG.clear(); CFGdescription.clear(); } /// Set a parameter in the configuration; the input string 'cmd' /// is of the form '[--DC]<id><s><value>' where the separator s is /// one of (:=,) and leading '-','--', or '--DC' are optional. void setParameter(std::string cmd) throw(gpstk::Exception); /// Set a parameter in the configuration using the label and the value, /// for booleans use (T,F)=(non-zero,zero). void setParameter(std::string label, double value) throw(gpstk::Exception); /// Get the parameter in the configuration corresponding to label double getParameter(std::string label) throw() { if(CFG.find(label) == CFG.end()) return 0.0; // TD throw? return CFG[label]; } /// Get the description of a parameter std::string getDescription(std::string label) throw() { if(CFGdescription.find(label) == CFGdescription.end()) return std::string("Invalid label"); return CFGdescription[label]; } /// Tell GDCconfiguration to which stream to send debugging output. void setDebugStream(std::ostream& os) { p_oflog = &os; } /// Print help page, including descriptions and current values of all /// the parameters, to the ostream. If 'advanced' is true, also print /// advanced parameters. void DisplayParameterUsage(std::ostream& os, bool advanced=false) throw(gpstk::Exception); /// Return version string std::string Version() throw() { return GDCVersion; } protected: /// map containing configuration labels and their values std::map <std::string,double> CFG; /// map containing configuration labels and their descriptions std::map <std::string,std::string> CFGdescription; /// Stream on which to write debug output. std::ostream *p_oflog; void initialize(void); static const std::string GDCVersion; }; // end class GDCconfiguration /// class GDCreturn encapsulates the information in the 'message' returned by /// the GPSTK Discontinuity Corrector. Create it using the string created by /// a call to DiscontinuityCorrector(SP,config,EditCmds,retMsg), then use it to /// access specific information about the results of the GDC. class GDCreturn { public: /// constructor; this parses the string explicit GDCreturn(std::string msg) { passN = -1; nGFslips = nWLslips = 0; nGFslipGross = nWLslipGross = 0; nGFslipSmall = nWLslipSmall = 0; WLsig = GFsig = 0.0; sat = ""; GLOn = -99; std::string::size_type pos; std::string word,line; std::vector<std::string> lines,words; if(msg.empty()) return; // split into lines while(1) { pos = msg.find_first_not_of("\n"); if(pos > 0) msg.erase(0,pos); if(msg.empty()) break; pos = msg.find_first_of("\n"); if(pos > 0) { word = msg.substr(0,pos); msg.erase(0,pos); } else { word = msg; msg.clear(); } lines.push_back(word); } ptsdeleted = ptsgood = 0; for(int i=0; i<lines.size(); i++) { line = lines[i]; if(line.empty()) continue; // split line into words words.clear(); while(1) { pos = line.find_first_not_of(" \t\n"); if(pos != 0 && pos != std::string::npos) line.erase(0,pos); if(line.empty()) break; pos = line.find_first_of(" \t\n"); if(pos == std::string::npos) word = line; else word = line.substr(0,pos); if(!word.empty()) { words.push_back(word); line.erase(0,word.length()+1); } } //std::cout << "Line " << i << ":"; //for(int j=0; j<words.size(); j++) std::cout << " /" << words[j] << "/"; //std::cout << std::endl; line = lines[i]; //std::cout << line << std::endl; if(line.find("WL sigma in cycles",0) != std::string::npos) passN = strtol(words[1].c_str(),0,10); else if(line.find("insufficient data",0) != std::string::npos) passN = strtol(words[1].c_str(),0,10); else if(line.find("list of Segments",0) != std::string::npos) passN = strtol(words[1].c_str(),0,10); if(line.find("bias(wl)",0) != std::string::npos) { sat = words[2]; word = words[5]; pos = word.find_first_of("/"); if(pos > 0) word = words[5].substr(0,pos); ptsgood += strtol(word.c_str(),0,10); } if(line.find("WL slip gross",0) != std::string::npos) nWLslipGross = strtol(words[3].c_str(),0,10); if(line.find("WL slip small",0) != std::string::npos) nWLslipSmall = strtol(words[3].c_str(),0,10); if(line.find("GF slip gross",0) != std::string::npos) nGFslipGross = strtol(words[3].c_str(),0,10); if(line.find("GF slip small",0) != std::string::npos) nGFslipSmall = strtol(words[3].c_str(),0,10); if(line.find("sigma GF variation",0) != std::string::npos) GFsig = strtod(words[3].c_str(),0); if(line.find("WL sigma in cycles",0) != std::string::npos) WLsig = strtod(words[3].c_str(),0); if(line.find("points deleted",0) != std::string::npos) ptsdeleted += strtol(words[3].c_str(),0,10); if(line.find("GLONASS frequency channel",0) != std::string::npos) GLOn = strtod(words[3].c_str(),0); } nWLslips = nWLslipGross + nWLslipSmall; nGFslips = nGFslipGross + nGFslipSmall; } // end constructor/parser int passN,GLOn; int nGFslips,nWLslips,nGFslipGross,nGFslipSmall,nWLslipGross,nWLslipSmall; int ptsdeleted,ptsgood; double WLsig,GFsig; std::string sat; }; // end class GDCreturn /// GPSTK Discontinuity Corrector. Find, and fix if possible, discontinuities /// in the GPS or GLONASS carrier phase data, given dual-frequency pseudorange and /// phase data for an entire satellite pass. /// Input is the SatPass object holding the data, and a GDCconfiguration object /// giving the parameter values for the corrector. /// Output is in the form of a list of strings - editing commands - that can be /// parsed and applied using the GPSTK Rinex Editor (see Prgm EditRinex and the /// RinexEditor class). Also, the L1 and L2 arrays in the input SatPass are /// corrected. The routine will mark bad points in the input data using /// the SatPass flag. /// Glonass satellites require a frequency channel integer; the caller may pass /// this in, or let the GDC compute it from the data - if it fails it returns -6. /// /// @param SP SatPass object containing the input data. /// @param config GDCconfiguration object. /// @param EditCmds vector<string> (output) containing RinexEditor commands. /// @param retMsg string summary of results: see 'GDC' in output, class GDCreturn /// if retMsg is not empty on call, replace 'GDC' with retMsg. /// @param GLOn GLONASS frequency channel (-7<=n<7), -99 means UNKNOWN /// @return 0 for success, otherwise return an Error code; /// /// codes are defined as follows. /// const int GLOfail = -6 failed to find the Glonass frequency channel /// const int BadInput = -5 input data does not have the required obs types /// const int NoData = -4 insufficient input data, or all data is bad /// const int FatalProblem = -3 DT is not set, or memory problem /// const int Singularity = -1 polynomial fit fails /// const int ReturnOK = 0 normal return int DiscontinuityCorrector(SatPass& SP, GDCconfiguration& config, std::vector<std::string>& EditCmds, std::string& retMsg, int GLOn=-99) throw(Exception); //@} } // end namespace gpstk //------------------------------------------------------------------------------------ #endif
41.160584
86
0.580156
[ "object", "vector" ]
fc22bedf626d0d072c9d41b0dc4736afec6b6cf4
1,231
cpp
C++
universal-problems/79.cpp
Galaxies99/leetcode
8099cf93fa1c61032449e67032eac1ea66bcc8fc
[ "MIT" ]
1
2020-07-19T15:37:01.000Z
2020-07-19T15:37:01.000Z
universal-problems/79.cpp
Galaxies99/leetcode
8099cf93fa1c61032449e67032eac1ea66bcc8fc
[ "MIT" ]
null
null
null
universal-problems/79.cpp
Galaxies99/leetcode
8099cf93fa1c61032449e67032eac1ea66bcc8fc
[ "MIT" ]
null
null
null
const int dx[] = {0, 0, 1, -1}; const int dy[] = {1, -1, 0, 0}; class Solution { public: int n, m; bool ok; void dfs(int x, int y, vector<vector<char>>& board, vector<vector<bool>> &vis, string word, int step) { if(ok) return; if (board[x][y] != word[step]) return ; if (step == word.size() - 1) { ok = 1; return ; } vis[x][y] = 1; for (int i = 0; i < 4; ++ i) { int xx = x + dx[i], yy = y + dy[i]; if(xx < 0 || yy < 0 || xx >= n || yy >= m) continue ; if(vis[xx][yy]) continue; dfs(xx, yy, board, vis, word, step + 1); } vis[x][y] = 0; } bool exist(vector<vector<char>>& board, string word) { vector<vector<bool>> vis; n = board.size(); m = board[0].size(); vis.resize(n); for (int i = 0; i < n; ++ i) { vis[i].resize(m); for (int j = 0; j < m; ++ j) vis[i][j] = 0; } ok = 0; for (int i = 0; i < n; ++ i) for (int j = 0; j < m; ++ j) { dfs(i, j, board, vis, word, 0); if (ok) return true; } return false; } };
30.02439
107
0.393989
[ "vector" ]
fc27f6e02872db4c946afbecdd5f0c64e20c037d
1,580
cpp
C++
src/nodes/pcss_directional_light_depth_node.cpp
hdachev/Nimble
922144ebdf1d3ee8c3df44feab4454ff9b0d8375
[ "MIT" ]
null
null
null
src/nodes/pcss_directional_light_depth_node.cpp
hdachev/Nimble
922144ebdf1d3ee8c3df44feab4454ff9b0d8375
[ "MIT" ]
null
null
null
src/nodes/pcss_directional_light_depth_node.cpp
hdachev/Nimble
922144ebdf1d3ee8c3df44feab4454ff9b0d8375
[ "MIT" ]
1
2021-05-10T02:07:12.000Z
2021-05-10T02:07:12.000Z
#include "pcss_directional_light_depth_node.h" #include "../render_graph.h" #include "../renderer.h" namespace nimble { DEFINE_RENDER_NODE_FACTORY(PCSSDirectionalLightDepthNode) // ----------------------------------------------------------------------------------------------------------------------------------- PCSSDirectionalLightDepthNode::PCSSDirectionalLightDepthNode(RenderGraph* graph) : PCFDirectionalLightDepthNode(graph) { } // ----------------------------------------------------------------------------------------------------------------------------------- PCSSDirectionalLightDepthNode::~PCSSDirectionalLightDepthNode() { } // ----------------------------------------------------------------------------------------------------------------------------------- std::string PCSSDirectionalLightDepthNode::shadow_test_source_path() { return "shader/shadows/directional_light/sampling/pcss_directional_light.glsl"; } // ----------------------------------------------------------------------------------------------------------------------------------- std::string PCSSDirectionalLightDepthNode::name() { return "PCSS Directional Light Depth Node"; } // ----------------------------------------------------------------------------------------------------------------------------------- std::vector<std::string> PCSSDirectionalLightDepthNode::shadow_test_source_defines() { return { }; } // ----------------------------------------------------------------------------------------------------------------------------------- } // namespace nimble
35.909091
134
0.388608
[ "vector" ]
fc287d06bcf7da7902e8616de90139661e4a3035
4,526
cpp
C++
cgal-plane-detection/src/planefit.cpp
phygitalism/cgal-plane-detector
c34a5887d62501f14e51a07e69cc72ba960311fa
[ "MIT" ]
7
2020-11-04T02:23:07.000Z
2022-02-14T02:54:39.000Z
cgal-plane-detection/src/planefit.cpp
phygitalism/cgal-plane-detector
c34a5887d62501f14e51a07e69cc72ba960311fa
[ "MIT" ]
null
null
null
cgal-plane-detection/src/planefit.cpp
phygitalism/cgal-plane-detector
c34a5887d62501f14e51a07e69cc72ba960311fa
[ "MIT" ]
1
2021-12-14T04:58:01.000Z
2021-12-14T04:58:01.000Z
#include "planefit.h" #include "polygons_helper.h" util::Polygon_mesh util::build_planes(const Polygon_mesh & mesh, const Regions & regions, std::vector<Rectangle> & rectangles, double min_area) { using size_type = Polygon_mesh::size_type; using Halfedge_index = Polygon_mesh::Halfedge_index; using vertex_descriptor = Polygon_mesh::Vertex_index; using face_descriptor = Polygon_mesh::Face_index; Polygon_mesh new_mesh; rectangles.clear(); for (const auto & region : regions) { std::vector<Point_3> points; for (const auto & index : region) { const Halfedge_index hf = mesh.halfedge(Face_index(index)); for (const auto & vertex : mesh.vertices_around_face(hf)) { if (vertex.is_valid()) { points.push_back(mesh.point(vertex)); } } } Plane_3 plane; Point_3 centroid; double quality = CGAL::linear_least_squares_fitting_3(points.cbegin(), points.cend(), plane, centroid, CGAL::Dimension_tag<0>()); if (CGAL::is_zero(quality)) { std::cout << "Bad quality of fitting plane is " << quality << std::endl; } Kernel::Iso_cuboid_3 bbox = CGAL::bounding_box(points.cbegin(), points.cend()); points.clear(); constexpr double eps{ 1E-2 }; if (bbox.is_degenerate()) { auto mid_point{ CGAL::midpoint(bbox.min(), bbox.max()) }; double x_size{ bbox.xmax() - bbox.xmin() }, y_size{ bbox.ymax() - bbox.ymin() }, z_size{ bbox.zmax() - bbox.zmin() }; // Too small size of bbox. Intersections with point my be invalid if (boost::math::epsilon_difference(CGAL::to_double(bbox.xmax()), CGAL::to_double(bbox.xmin())) < eps) { x_size = 2 * eps; } if (boost::math::epsilon_difference(CGAL::to_double(bbox.ymax()), CGAL::to_double(bbox.ymin())) < eps) { y_size = 2 * eps; } if (boost::math::epsilon_difference(CGAL::to_double(bbox.zmin()), CGAL::to_double(bbox.zmax())) < eps) { z_size = 2 * eps; } const Vector_3 shift_vector{ x_size / 2, y_size / 2, z_size / 2 }; bbox = Kernel::Iso_cuboid_3{ mid_point - shift_vector, mid_point + shift_vector }; } auto interesct_points{ plane_aabb_intersection_points(plane, bbox) }; if (interesct_points.size() >= 3) { if (interesct_points.size() != 4) { interesct_points = polygon_to_rectangle_on_plane(interesct_points, plane); } double length_dir1 = CGAL::sqrt((interesct_points.at(1) - interesct_points.at(0)).squared_length()); double length_dir2 = CGAL::sqrt((interesct_points.at(3) - interesct_points.at(0)).squared_length()); if (length_dir1 * length_dir2 >= min_area) { auto p_min{ interesct_points.at(0) }, p_max{ interesct_points.at(2) }; auto rectangle_center{ CGAL::midpoint(p_min, p_max) }; Vector_3 shifting{ centroid - rectangle_center }; Rectangle rect; std::vector<vertex_descriptor> vertex_descriptors; for (size_t i = 0, j = 0; i < interesct_points.size(); i++, j += 3) { interesct_points.at(i) = interesct_points.at(i) + shifting; rect[j] = CGAL::to_double(interesct_points.at(i).x()); rect[j + 1] = CGAL::to_double(interesct_points.at(i).y()); rect[j + 2] = CGAL::to_double(interesct_points.at(i).z()); vertex_descriptors.push_back(new_mesh.add_vertex(interesct_points.at(i))); } rectangles.push_back(rect); face_descriptor f1 = new_mesh.add_face(vertex_descriptors); if (f1 == Polygon_mesh::null_face()) { std::cerr << u8"The face could not be added because of an orientation error." << std::endl; } } } else if (interesct_points.size() > 0 && interesct_points.size() < 3) { std::cerr << u8"Number of intersections between plane and bbox is incorrect. Number of intersections:" << interesct_points.size() << std::endl; } } return new_mesh; }
36.208
155
0.56076
[ "mesh", "vector" ]
fc2be2e82f1ac65ee5e2dc58cd39c6d6d3cf10a3
6,980
cpp
C++
AGL/DefaultShaders.cpp
wolfprint3d/AlphaGL
d47ed65b529bfb13775de0599499951c8feabbf1
[ "MIT" ]
2
2018-12-19T11:40:16.000Z
2018-12-19T14:15:12.000Z
AGL/DefaultShaders.cpp
wolfprint3d/AlphaGL
d47ed65b529bfb13775de0599499951c8feabbf1
[ "MIT" ]
null
null
null
AGL/DefaultShaders.cpp
wolfprint3d/AlphaGL
d47ed65b529bfb13775de0599499951c8feabbf1
[ "MIT" ]
2
2018-10-18T11:49:04.000Z
2019-12-02T22:35:05.000Z
#include "DefaultShaders.h" namespace AGL { //////////////////////////////////////////////////////////////////////////// ShaderPair GetEngineShaderSource(EngineShader engineShader) { // LAZY init all the shaders //////////////////////////////////////////////////////////////////////////////// static strview VS_PassthroughUVColor = R"END( // Basic passthrough 2D/3D vertex shader with UV coordinates and color uniform highp mat4 transform; // transformation matrix attribute highp vec3 position; // in vertex position (px,py,px) attribute highp vec2 coord; // in vertex texture coordinates attribute highp vec4 color; // rgba color varying highp vec2 vCoord; // out vertex texture coord for frag varying highp vec4 vColor; void main(void) { gl_Position = transform * vec4(position, 1.0); vCoord = coord; vColor = color; } )END"; //////////////////////////////////////////////////////////////////////////////// static strview PS_PassthroughColor = R"END( // Basic passthrough color-only shader uniform highp vec4 diffuseColor; void main(void) { highp vec4 texel = diffuseColor; if (texel.a < 0.025) discard; gl_FragColor = texel; } )END"; static strview PS_VertexColor = R"END( // A simple vertex-color shader uniform highp vec4 diffuseColor; varying highp vec4 vColor; // vertex color void main(void) { highp vec4 texel = vColor * diffuseColor; if (texel.a < 0.025) discard; gl_FragColor = texel; } )END"; //////////////////////////////////////////////////////////////////////////////// static strview PS_TextureWithColor = R"END( // Basic texture + color shader // diffuseColor is used to multiply main color from diffuseTexture uniform highp sampler2D diffuseTex; // diffuse texture uniform highp vec4 diffuseColor; // output color multiplier varying highp vec2 vCoord; // vertex texture coords void main(void) { highp vec4 texel = texture2D(diffuseTex, vCoord) * diffuseColor; if (texel.a < 0.025) discard; gl_FragColor = texel; } )END"; static strview PS_AlphaTextureWithColor = R"END( // Basic texture + color shader // diffuseColor is used to multiply main color from diffuseTexture uniform highp sampler2D diffuseTex; // diffuse texture uniform highp vec4 diffuseColor; // output color multiplier varying highp vec2 vCoord; // vertex texture coords void main(void) { // we assume diffuseTex is monochrome; -- reuse alpha from R channel highp float mainAlpha = texture2D(diffuseTex, vCoord).r; highp vec4 texel = mainAlpha * diffuseColor; if (texel.a < 0.025) discard; gl_FragColor = texel; } )END"; //////////////////////////////////////////////////////////////////////////////// static strview PS_OutlineText = R"END( // Basic UI Text shader // diffuseColor is used to multiply main color from diffuseTexture uniform highp sampler2D diffuseTex; // font atlas texture uniform highp vec4 diffuseColor; // font color uniform highp vec4 outlineColor; // font outline color varying highp vec2 vCoord; // vertex texture coords void main(void) { // assume diffuseTex R is main color and G is outline highp vec2 tex = texture2D(diffuseTex, vCoord).rg; // color consists of the (diffuse color * main alpha) + (background color * outline alpha) highp vec3 color = (diffuseColor.rgb * tex.r) + (outlineColor.rgb * tex.g); // make the main alpha more pronounced, makes small text sharper tex.r = clamp(tex.r * 1.5, 0.0, 1.0); // alpha is the sum of main alpha and outline alpha // main alpha is main font color alpha // outline alpha is the stroke or shadow alpha highp float mainAlpha = tex.r * diffuseColor.a; highp float outlineAlpha = tex.g * outlineColor.a * diffuseColor.a; gl_FragColor = vec4(color, mainAlpha + outlineAlpha); } )END"; static strview PS_Rect = R"END( // Advanced distance-field shader for drawing rounded rects with border uniform highp vec4 diffuseColor; // output color multiplier uniform highp vec4 outlineColor; // border color // custom shader data: // x: cornerRadius // y: borderWidth // z: absSize.x // w: absSize.y uniform highp vec4 shaderData; varying highp vec2 vCoord; // vertex texture coords highp float aa_step(highp float t1, highp float t2, highp float f) { //return step(t2, f); return smoothstep(t1, t2, f); } void main(void) { highp vec4 color = diffuseColor; if (color.a < 0.025) discard; gl_FragColor = color; } )END"; //////////////////////////////////////////////////////////////////////////////// static ShaderPair sources[] = { { strview{}, strview{} }, // ES_None { PS_PassthroughColor, VS_PassthroughUVColor }, // ES_Color { PS_PassthroughColor, VS_PassthroughUVColor }, // ES_DebugLines { PS_PassthroughColor, VS_PassthroughUVColor }, // ES_OutlineText { PS_Rect, VS_PassthroughUVColor }, // ES_Rect { PS_TextureWithColor, VS_PassthroughUVColor }, // ES_Simple { PS_AlphaTextureWithColor, VS_PassthroughUVColor }, // ES_Text { PS_VertexColor, VS_PassthroughUVColor }, // ES_VertexColor { PS_PassthroughColor, VS_PassthroughUVColor }, // ES_Color3d { PS_TextureWithColor, VS_PassthroughUVColor }, // ES_Simple3D }; static_assert(sizeof(sources) == ES_Max*sizeof(ShaderPair), "Shader source array must match enum EngineShader layout"); if (ES_None < engineShader && engineShader < ES_Max) return sources[engineShader]; return ShaderPair{}; } ShaderPair GetEngineShaderSource(strview name) { EngineShader shader = ES_None; if (name == "color") shader = ES_Color; else if (name == "debuglines") shader = ES_DebugLines; else if (name == "outlinetext") shader = ES_OutlineText; else if (name == "rect") shader = ES_Rect; else if (name == "simple") shader = ES_Simple; else if (name == "text") shader = ES_Text; else if (name == "vertexcolor") shader = ES_VertexColor; else if (name == "color3d") shader = ES_Color3d; else if (name == "simple3d") shader = ES_Simple3d; return GetEngineShaderSource(shader); } //////////////////////////////////////////////////////////////////////////// }
35.075377
98
0.571633
[ "transform", "3d" ]
fc42f65571679dbf8a0252daba0e843e9f53dcc6
427
cpp
C++
solutions/467.unique-substrings-in-wraparound-string.298676947.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
78
2020-10-22T11:31:53.000Z
2022-02-22T13:27:49.000Z
solutions/467.unique-substrings-in-wraparound-string.298676947.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
null
null
null
solutions/467.unique-substrings-in-wraparound-string.298676947.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
26
2020-10-23T15:10:44.000Z
2021-11-07T16:13:50.000Z
class Solution { public: int findSubstringInWraproundString(string p) { vector<int> alp(26, 0); int n = p.length(); int len = 0, res = 0; for (int i = 0; i < n; i++) { char cur = p[i] - 'a'; if (i > 0 && p[i - 1] != (cur + 26 - 1) % 26 + 'a') len = 0; len++; if (len > alp[cur]) { res += len - alp[cur]; alp[cur] = len; } } return res; } };
17.791667
57
0.423888
[ "vector" ]
fc4b69e2b4d8178f5c0bd9f6611557bfefd180bd
1,567
cpp
C++
cpp_unlimited_numbers_library/digit.cpp
Vanderkast/unlimited_numbers_cpp_library
02de59e819ec5b2ea7c2588cf513ff4a6710b7c5
[ "Apache-2.0" ]
null
null
null
cpp_unlimited_numbers_library/digit.cpp
Vanderkast/unlimited_numbers_cpp_library
02de59e819ec5b2ea7c2588cf513ff4a6710b7c5
[ "Apache-2.0" ]
null
null
null
cpp_unlimited_numbers_library/digit.cpp
Vanderkast/unlimited_numbers_cpp_library
02de59e819ec5b2ea7c2588cf513ff4a6710b7c5
[ "Apache-2.0" ]
null
null
null
#include "digit.h" Digit::Digit() { this->binary.resize(1, false); } void absAndTrim(int& number) { number = abs(number) % 10; } void fillBinary(std::vector<bool>& vector, int number) { while (number > 1) { vector.push_back((bool)(number % 2)); number /= 2; } vector.push_back((bool)number); } Digit::Digit(int number) { absAndTrim(number); fillBinary(this->binary, number); } int intFromChar(char& number) { return number - '0'; } Digit::Digit(char charDigit){ fillBinary(this->binary, intFromChar(charDigit)); } Digit::Digit(std::vector<bool> vector){ this->binary = vector; } Digit::Digit(Digit* number) { for (std::vector<bool>::iterator iterator = number->binary.begin(); iterator != number->binary.end(); iterator++) { this->binary.push_back(*iterator); } } Digit setBinaryAndReturnOverflow(std::vector<bool>& binary, int number) { binary = Digit(number % 10).vector(); return Digit(number / 10); } Digit Digit::plus(Digit& number) { int sum = this->asInt() + number.asInt(); return setBinaryAndReturnOverflow(this->binary, sum); } Digit Digit::minus(Digit& number) { int difference = this->asInt() - number.asInt(); return setBinaryAndReturnOverflow(this->binary, difference); } int Digit::asInt() { int i = 1, result = 0; for (std::vector<bool>::iterator iterator = this->binary.begin(); iterator != this->binary.end(); iterator++) { if (*iterator) result += i; i <<= 1; } return result; } char Digit::asChar() { return (char)(asInt() + (int)'0'); } std::vector<bool> Digit::vector(){ return this->binary; }
21.175676
116
0.668156
[ "vector" ]
fc4bc08cf2615e1e0622a46c170a52e56f05e6b8
3,846
cpp
C++
tests/prepared_statement_tests/replace_range.cpp
tstrutz/sqlite_orm
1ee0a8653fe57ed4d4f69b5a65839b1861c41d32
[ "BSD-3-Clause" ]
1,566
2016-12-20T15:31:04.000Z
2022-03-31T18:17:34.000Z
tests/prepared_statement_tests/replace_range.cpp
tstrutz/sqlite_orm
1ee0a8653fe57ed4d4f69b5a65839b1861c41d32
[ "BSD-3-Clause" ]
620
2017-01-06T13:53:35.000Z
2022-03-31T12:05:50.000Z
tests/prepared_statement_tests/replace_range.cpp
tstrutz/sqlite_orm
1ee0a8653fe57ed4d4f69b5a65839b1861c41d32
[ "BSD-3-Clause" ]
274
2017-01-07T05:34:24.000Z
2022-03-27T18:22:47.000Z
#include <sqlite_orm/sqlite_orm.h> #include <catch2/catch.hpp> #include "prepared_common.h" using namespace sqlite_orm; TEST_CASE("Prepared replace range") { using namespace PreparedStatementTests; using Catch::Matchers::UnorderedEquals; const int defaultVisitTime = 50; auto filename = "prepared.sqlite"; remove(filename); auto storage = make_storage(filename, make_index("user_id_index", &User::id), make_table("users", make_column("id", &User::id, primary_key(), autoincrement()), make_column("name", &User::name)), make_table("visits", make_column("id", &Visit::id, primary_key(), autoincrement()), make_column("user_id", &Visit::userId), make_column("time", &Visit::time, default_value(defaultVisitTime)), foreign_key(&Visit::userId).references(&User::id)), make_table("users_and_visits", make_column("user_id", &UserAndVisit::userId), make_column("visit_id", &UserAndVisit::visitId), make_column("description", &UserAndVisit::description), primary_key(&UserAndVisit::userId, &UserAndVisit::visitId))); storage.sync_schema(); storage.replace(User{1, "Team BS"}); storage.replace(User{2, "Shy'm"}); storage.replace(User{3, "Maître Gims"}); storage.replace(UserAndVisit{2, 1, "Glad you came"}); storage.replace(UserAndVisit{3, 1, "Shine on"}); std::vector<User> users; std::vector<User> expected; SECTION("empty") { expected.push_back(User{1, "Team BS"}); expected.push_back(User{2, "Shy'm"}); expected.push_back(User{3, "Maître Gims"}); try { auto statement = storage.prepare(replace_range(users.begin(), users.end())); REQUIRE(false); } catch(const std::system_error &e) { //.. } } SECTION("one existing") { User user{1, "Raye"}; expected.push_back(user); expected.push_back(User{2, "Shy'm"}); expected.push_back(User{3, "Maître Gims"}); users.push_back(user); auto statement = storage.prepare(replace_range(users.begin(), users.end())); REQUIRE(get<0>(statement) == users.begin()); REQUIRE(get<1>(statement) == users.end()); storage.execute(statement); } SECTION("one existing and one new") { User user{2, "Raye"}; User user2{4, "Bebe Rexha"}; expected.push_back(User{1, "Team BS"}); expected.push_back(user); expected.push_back(User{3, "Maître Gims"}); expected.push_back(user2); users.push_back(user); users.push_back(user2); auto statement = storage.prepare(replace_range(users.begin(), users.end())); REQUIRE(get<0>(statement) == users.begin()); REQUIRE(get<1>(statement) == users.end()); storage.execute(statement); } SECTION("All existing") { users.push_back(User{1, "Selena Gomez"}); users.push_back(User{2, "Polina"}); users.push_back(User{3, "Polina"}); expected = users; auto statement = storage.prepare(replace_range(users.begin(), users.end())); REQUIRE(get<0>(statement) == users.begin()); REQUIRE(get<1>(statement) == users.end()); storage.execute(statement); } auto rows = storage.get_all<User>(); REQUIRE_THAT(rows, UnorderedEquals(expected)); }
42.263736
110
0.545762
[ "vector" ]
fc5214e54d8ea2634c3819b2e533c386e5ef695f
17,855
cc
C++
beast_output.cc
migetwi25/oi90jj
f895deb1f19ae89f12634fd06d36b6e8601be279
[ "BSD-2-Clause" ]
23
2016-05-31T15:43:11.000Z
2021-12-09T23:55:15.000Z
beast_output.cc
migetwi25/oi90jj
f895deb1f19ae89f12634fd06d36b6e8601be279
[ "BSD-2-Clause" ]
5
2016-10-10T11:46:14.000Z
2021-11-17T09:40:23.000Z
beast_output.cc
migetwi25/oi90jj
f895deb1f19ae89f12634fd06d36b6e8601be279
[ "BSD-2-Clause" ]
9
2017-01-10T00:54:43.000Z
2021-04-12T17:13:10.000Z
// Copyright (c) 2015-2016, FlightAware LLC. // Copyright (c) 2015, Oliver Jowett <oliver@mutability.co.uk> // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <iomanip> #include <iostream> #include <boost/asio.hpp> #include <boost/asio/ip/v6_only.hpp> #include <boost/asio/steady_timer.hpp> #include "beast_output.h" #include "modes_message.h" namespace asio = boost::asio; using boost::asio::ip::tcp; namespace beast { enum class SocketOutput::ParserState { FIND_1A, READ_1, READ_OPTION }; SocketOutput::SocketOutput(asio::io_service &service_, tcp::socket &&socket_, const Settings &settings_) : service(service_), socket(std::move(socket_)), peer(socket.remote_endpoint()), state(ParserState::FIND_1A), settings(settings_), flush_pending(false) {} void SocketOutput::start() { read_commands(); } void SocketOutput::read_commands() { auto self(shared_from_this()); auto buf = std::make_shared<std::vector<std::uint8_t>>(512); socket.async_read_some(asio::buffer(*buf), [this, self, buf](const boost::system::error_code &ec, std::size_t len) { if (ec) { handle_error(ec); } else { buf->resize(len); process_commands(*buf); read_commands(); } }); } void SocketOutput::process_commands(std::vector<std::uint8_t> data) { bool got_a_command = false; for (auto p = data.begin(); p != data.end(); ++p) { switch (state) { case ParserState::FIND_1A: if (*p == 0x1A) state = ParserState::READ_1; break; case ParserState::READ_1: if (*p == 0x31) state = ParserState::READ_OPTION; else state = ParserState::FIND_1A; break; case ParserState::READ_OPTION: process_option_command(*p); got_a_command = true; state = ParserState::FIND_1A; break; } } if (got_a_command) { // just do this once at the end, not on every command std::cerr << peer << ": settings changed to " << settings << std::endl; if (settings_notifier) settings_notifier(settings); } } void SocketOutput::process_option_command(uint8_t option) { char ch = (char)option; switch (ch) { case 'c': case 'C': settings.binary_format = (ch == 'C'); break; case 'd': case 'D': settings.filter_11_17_18 = (ch == 'D'); break; case 'e': case 'E': settings.avrmlat = (ch == 'E'); break; case 'f': case 'F': settings.crc_disable = (ch == 'F'); break; case 'g': case 'G': if (settings.radarcape) settings.gps_timestamps = (ch == 'G'); else settings.filter_0_4_5 = (ch == 'G'); break; case 'h': case 'H': settings.rts_handshake = (ch == 'H'); break; case 'i': case 'I': settings.fec_disable = (ch == 'I'); break; case 'j': case 'J': settings.modeac_enable = (ch == 'J'); break; case 'v': case 'V': settings.verbatim = (ch == 'V'); break; default: // unrecognized return; } } void SocketOutput::write(const modes::Message &message) { if (!socket.is_open()) return; // we are shut down if (message.type() == modes::MessageType::STATUS) { // local connection settings override the upstream data Settings upstream = Settings(message.data()[0]); Settings used = settings | upstream; auto copy = message.data(); copy[0] = used.to_status_byte(); if (settings.gps_timestamps.on() && !upstream.gps_timestamps.on()) { // we are translating 12MHz to "GPS", set the emulation flag copy[2] |= 0x80; // set UTC-bugfix-and-more-bits flag copy[2] |= 0x20; // set emulated-timestamp flag } write_message(message.type(), message.timestamp_type(), message.timestamp(), message.signal(), copy); } else { // apply FEC if requested bool needs_fec = (!settings.verbatim && !settings.fec_disable && message.crc_correctable()); write_message(message.type(), message.timestamp_type(), message.timestamp(), message.signal(), needs_fec ? message.corrected_data() : message.data()); } } void SocketOutput::write_message(modes::MessageType type, modes::TimestampType timestamp_type, std::uint64_t timestamp, std::uint8_t signal, const helpers::bytebuf &data) { if (timestamp_type == modes::TimestampType::TWELVEMEG && !settings.radarcape.off() && settings.gps_timestamps.on()) { // GPS timestamps were explicitly requested // scale 12MHz to pseudo-GPS std::uint64_t ns = timestamp * 1000ULL / 12ULL; std::uint64_t seconds = (ns / 1000000000ULL) % 86400; std::uint64_t nanos = ns % 1000000000ULL; timestamp = (seconds << 30) | nanos; } else if (timestamp_type == modes::TimestampType::GPS && (settings.radarcape.off() || settings.gps_timestamps.off())) { // beast output or 12MHz timestamps were explicitly requested // scale GPS to 12MHz std::uint64_t seconds = timestamp >> 30; std::uint64_t nanos = timestamp & 0x3FFFFFFF; std::uint64_t ns = seconds * 1000000000ULL + nanos; timestamp = ns * 12ULL / 1000ULL; } // if gps_timestamps is DONTCARE, we just use whatever is provided if (settings.binary_format) { write_binary(type, timestamp, signal, data); } else if (settings.avrmlat) { if (type != modes::MessageType::STATUS && type != modes::MessageType::POSITION) write_avrmlat(timestamp, data); } else { if (type != modes::MessageType::STATUS && type != modes::MessageType::POSITION) write_avr(data); } } void SocketOutput::prepare_write() { if (!outbuf) { outbuf = std::make_shared<helpers::bytebuf>(); outbuf->reserve(read_buffer_size); } } void SocketOutput::complete_write() { if (!flush_pending && !outbuf->empty()) { flush_pending = true; service.post(std::bind(&SocketOutput::flush_outbuf, shared_from_this())); } } void SocketOutput::flush_outbuf() { if (!outbuf || outbuf->empty()) return; std::shared_ptr<helpers::bytebuf> writebuf; writebuf.swap(outbuf); auto self(shared_from_this()); async_write(socket, boost::asio::buffer(*writebuf), [this, self, writebuf](const boost::system::error_code &ec, size_t len) { // NB: we only reset the pending flag here, // because async_write is a composed operation // that might take a while to complete, and // if we do another write before it completes // then it might interleave data. flush_pending = false; if (!outbuf) { writebuf->clear(); outbuf = writebuf; } if (ec) handle_error(ec); }); } static inline void push_back_beast(helpers::bytebuf &v, std::uint8_t b) { if (b == 0x1A) v.push_back(0x1A); v.push_back(b); } void SocketOutput::write_binary(modes::MessageType type, std::uint64_t timestamp, std::uint8_t signal, const helpers::bytebuf &data) { prepare_write(); outbuf->push_back(0x1A); outbuf->push_back(messagetype_to_byte(type)); if (type != modes::MessageType::POSITION) { push_back_beast(*outbuf, (timestamp >> 40) & 0xFF); push_back_beast(*outbuf, (timestamp >> 32) & 0xFF); push_back_beast(*outbuf, (timestamp >> 24) & 0xFF); push_back_beast(*outbuf, (timestamp >> 16) & 0xFF); push_back_beast(*outbuf, (timestamp >> 8) & 0xFF); push_back_beast(*outbuf, timestamp & 0xFF); push_back_beast(*outbuf, signal); } for (auto b : data) push_back_beast(*outbuf, b); complete_write(); } // we could use ostrstream here, I guess, but this is simpler static inline void push_back_hex(helpers::bytebuf &v, std::uint8_t b) { static const char *hexdigits = "0123456789ABCDEF"; v.push_back((std::uint8_t)hexdigits[(b >> 4) & 0x0F]); v.push_back((std::uint8_t)hexdigits[b & 0x0F]); } void SocketOutput::write_avr(const helpers::bytebuf &data) { prepare_write(); outbuf->push_back((std::uint8_t)'*'); for (auto b : data) push_back_hex(*outbuf, b); outbuf->push_back((std::uint8_t)';'); outbuf->push_back((std::uint8_t)'\n'); complete_write(); } void SocketOutput::write_avrmlat(std::uint64_t timestamp, const helpers::bytebuf &data) { prepare_write(); outbuf->push_back((std::uint8_t)'@'); push_back_hex(*outbuf, (timestamp >> 40) & 0xFF); push_back_hex(*outbuf, (timestamp >> 32) & 0xFF); push_back_hex(*outbuf, (timestamp >> 24) & 0xFF); push_back_hex(*outbuf, (timestamp >> 16) & 0xFF); push_back_hex(*outbuf, (timestamp >> 8) & 0xFF); push_back_hex(*outbuf, timestamp & 0xFF); for (auto b : data) push_back_hex(*outbuf, b); outbuf->push_back((std::uint8_t)';'); outbuf->push_back((std::uint8_t)'\n'); complete_write(); } void SocketOutput::handle_error(const boost::system::error_code &ec) { if (ec == boost::asio::error::eof) { std::cerr << peer << ": connection closed" << std::endl; } else if (ec != boost::asio::error::operation_aborted) { std::cerr << peer << ": connection error: " << ec.message() << std::endl; } close(); } void SocketOutput::close() { socket.close(); if (close_notifier) close_notifier(); } ////////////// SocketListener::SocketListener(asio::io_service &service_, const tcp::endpoint &endpoint_, modes::FilterDistributor &distributor_, const Settings &initial_settings_) : service(service_), acceptor(service_), endpoint(endpoint_), socket(service_), distributor(distributor_), initial_settings(initial_settings_) {} void SocketListener::start() { acceptor.open(endpoint.protocol()); acceptor.set_option(asio::socket_base::reuse_address(true)); acceptor.set_option(tcp::acceptor::reuse_address(true)); // We are v6 aware and bind separately to v4 and v6 addresses if (endpoint.protocol() == tcp::v6()) acceptor.set_option(asio::ip::v6_only(true)); acceptor.bind(endpoint); acceptor.listen(); accept_connection(); } void SocketListener::close() { acceptor.cancel(); socket.close(); } void SocketListener::accept_connection() { auto self(shared_from_this()); acceptor.async_accept(socket, peer, [this, self](const boost::system::error_code &ec) { if (!ec) { std::cerr << endpoint << ": accepted a connection from " << peer << " with settings " << initial_settings << std::endl; SocketOutput::pointer new_output = SocketOutput::create(service, std::move(socket), initial_settings); modes::FilterDistributor::handle h = distributor.add_client(std::bind(&SocketOutput::write, new_output, std::placeholders::_1), initial_settings.to_filter()); new_output->set_settings_notifier([this, self, h](const Settings &newsettings) { distributor.update_client_filter(h, newsettings.to_filter()); }); new_output->set_close_notifier([this, self, h] { distributor.remove_client(h); }); new_output->start(); } else { if (ec == boost::system::errc::operation_canceled) return; std::cerr << endpoint << ": accept error: " << ec.message() << std::endl; } accept_connection(); }); } ////////////// SocketConnector::SocketConnector(asio::io_service &service_, const std::string &host_, const std::string &port_or_service_, modes::FilterDistributor &distributor_, const Settings &initial_settings_) : service(service_), resolver(service_), socket(service_), reconnect_timer(service_), host(host_), port_or_service(port_or_service_), distributor(distributor_), initial_settings(initial_settings_), running(false) {} void SocketConnector::start() { running = true; resolve_and_connect(); } void SocketConnector::close() { running = false; resolver.cancel(); reconnect_timer.cancel(); socket.close(); } void SocketConnector::resolve_and_connect(const boost::system::error_code &ec) { if (!running) { return; } if (ec) { assert(ec == boost::asio::error::operation_aborted); return; } auto self(shared_from_this()); tcp::resolver::query query(host, port_or_service); resolver.async_resolve(query, [this, self](const boost::system::error_code &ec, tcp::resolver::iterator it) { if (!ec) { next_endpoint = it; try_next_endpoint(); } else if (ec == boost::asio::error::operation_aborted) { return; } else { std::cerr << host << ":" << port_or_service << ": could not resolve address: " << ec.message() << std::endl; schedule_reconnect(); return; } }); } void SocketConnector::try_next_endpoint() { if (!running) { return; } if (next_endpoint == tcp::resolver::iterator()) { // No more addresses to try schedule_reconnect(); return; } tcp::endpoint endpoint = *next_endpoint++; auto self(shared_from_this()); socket.async_connect(endpoint, [this, self, endpoint](const boost::system::error_code &ec) { if (!ec) { connection_established(endpoint); } else if (ec == boost::asio::error::operation_aborted) { return; } else { std::cerr << host << ":" << port_or_service << ": connection to " << endpoint << " failed: " << ec.message() << std::endl; socket.close(); try_next_endpoint(); } }); } void SocketConnector::schedule_reconnect() { if (running) { std::cerr << host << ":" << port_or_service << ": reconnecting in " << std::chrono::duration_cast<std::chrono::seconds>(reconnect_interval).count() << " seconds" << std::endl; auto self(shared_from_this()); reconnect_timer.expires_from_now(reconnect_interval); reconnect_timer.async_wait(std::bind(&SocketConnector::resolve_and_connect, self, std::placeholders::_1)); } } void SocketConnector::connection_established(const tcp::endpoint &endpoint) { auto self(shared_from_this()); std::cerr << host << ":" << port_or_service << ": connected to " << endpoint << " with settings " << initial_settings << std::endl; SocketOutput::pointer new_output = SocketOutput::create(service, std::move(socket), initial_settings); modes::FilterDistributor::handle h = distributor.add_client(std::bind(&SocketOutput::write, new_output, std::placeholders::_1), initial_settings.to_filter()); new_output->set_settings_notifier([this, self, h](const Settings &newsettings) { distributor.update_client_filter(h, newsettings.to_filter()); }); new_output->set_close_notifier([this, self, h] { distributor.remove_client(h); schedule_reconnect(); }); new_output->start(); } }; // namespace beast
38.397849
418
0.585382
[ "vector" ]
fc5579b13362d8f609bf392740398479f042485f
12,948
cc
C++
cpp_src/gtests/tests/unit/clientsstats_test.cc
andyoknen/reindexer
ff1b2bcc0a80c4692361c9c184243d74a920ead7
[ "Apache-2.0" ]
null
null
null
cpp_src/gtests/tests/unit/clientsstats_test.cc
andyoknen/reindexer
ff1b2bcc0a80c4692361c9c184243d74a920ead7
[ "Apache-2.0" ]
null
null
null
cpp_src/gtests/tests/unit/clientsstats_test.cc
andyoknen/reindexer
ff1b2bcc0a80c4692361c9c184243d74a920ead7
[ "Apache-2.0" ]
null
null
null
#include "clientsstats_api.h" #include "gason/gason.h" #include "reindexer_version.h" #include "tools/semversion.h" #include "tools/stringstools.h" TEST_F(ClientsStatsApi, ClientsStatsConcurrent) { RunServerInThread(true); RunClient(4, 1); RunNSelectThread(10); RunNReconnectThread(10); std::this_thread::sleep_for(std::chrono::seconds(5)); StopThreads(); } TEST_F(ClientsStatsApi, ClientsStatsData) { RunServerInThread(true); reindexer::client::ReindexerConfig config; config.ConnPoolSize = 1; config.WorkerThreads = 1; const int kconnectionCount = 10; std::vector<std::unique_ptr<reindexer::client::Reindexer>> NClients; for (int i = 0; i < kconnectionCount; i++) { std::unique_ptr<reindexer::client::Reindexer> clientPtr(new reindexer::client::Reindexer(config)); reindexer::client::ConnectOpts opts; opts.CreateDBIfMissing(); auto err = clientPtr->Connect(GetConnectionString(), opts); ASSERT_TRUE(err.ok()) << err.what(); reindexer::client::QueryResults result; err = clientPtr->Select(reindexer::Query("#namespaces"), result); ASSERT_TRUE(err.ok()) << err.what(); NClients.push_back(std::move(clientPtr)); } reindexer::client::QueryResults result; auto err = NClients[0]->Select(reindexer::Query("#clientsstats"), result); ASSERT_TRUE(err.ok()) << err.what(); ASSERT_EQ(result.Count(), kconnectionCount); } TEST_F(ClientsStatsApi, ClientsStatsOff) { RunServerInThread(false); reindexer::client::ReindexerConfig config; config.ConnPoolSize = 1; config.WorkerThreads = 1; reindexer::client::Reindexer reindexer(config); reindexer::client::ConnectOpts opts; opts.CreateDBIfMissing(); auto err = reindexer.Connect(GetConnectionString(), opts); ASSERT_TRUE(err.ok()) << err.what(); reindexer::client::QueryResults resultNs; err = reindexer.Select(reindexer::Query("#namespaces"), resultNs); reindexer::client::QueryResults resultCs; err = reindexer.Select(reindexer::Query("#clientsstats"), resultCs); ASSERT_TRUE(err.ok()) << err.what(); ASSERT_EQ(resultCs.Count(), 0); } TEST_F(ClientsStatsApi, ClientsStatsValues) { RunServerInThread(true); reindexer::client::ReindexerConfig config; config.ConnPoolSize = 1; config.WorkerThreads = 1; config.AppName = kAppName; reindexer::client::Reindexer reindexer(config); reindexer::client::ConnectOpts opts; opts.CreateDBIfMissing(); auto err = reindexer.Connect(GetConnectionString(), opts); ASSERT_TRUE(err.ok()) << err.what(); std::string nsName("ns1"); err = reindexer.OpenNamespace(nsName); ASSERT_TRUE(err.ok()) << err.what(); auto tx1 = reindexer.NewTransaction(nsName); ASSERT_FALSE(tx1.IsFree()); auto tx2 = reindexer.NewTransaction(nsName); ASSERT_FALSE(tx2.IsFree()); TestObserver observer; reindexer::UpdatesFilters filters; filters.AddFilter(nsName, reindexer::UpdatesFilters::Filter()); err = reindexer.SubscribeUpdates(&observer, filters, SubscriptionOpts().IncrementSubscription()); ASSERT_TRUE(err.ok()) << err.what(); auto beginTs = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count(); std::this_thread::sleep_for(std::chrono::milliseconds(2000)); // Timeout to update send/recv rate reindexer::client::QueryResults resultNs; err = reindexer.Select(reindexer::Query("#namespaces"), resultNs); SetProfilingFlag(true, "profiling.activitystats", &reindexer); reindexer::client::QueryResults resultCs; const std::string selectClientsStats = "SELECT * FROM #clientsstats"; err = reindexer.Select(selectClientsStats, resultCs); ASSERT_TRUE(err.ok()) << err.what(); ASSERT_EQ(resultCs.Count(), 1); auto it = resultCs.begin(); reindexer::WrSerializer wrser; err = it.GetJSON(wrser, false); ASSERT_TRUE(err.ok()) << err.what(); auto endTs = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count(); gason::JsonParser parser; gason::JsonNode clientsStats = parser.Parse(wrser.Slice()); std::string curActivity = clientsStats["current_activity"].As<std::string>(); EXPECT_TRUE(curActivity == selectClientsStats) << "curActivity = [" << curActivity << "]"; std::string curIP = clientsStats["ip"].As<std::string>(); std::vector<std::string> addrParts; reindexer::split(curIP, ":", false, addrParts); EXPECT_EQ(addrParts.size(), 2); EXPECT_EQ(addrParts[0], kipaddress) << curIP; int port = std::atoi(addrParts[1].c_str()); EXPECT_TRUE(port > 0) << curIP; EXPECT_NE(port, kPortI) << curIP; int64_t sentBytes = clientsStats["sent_bytes"].As<int64_t>(); EXPECT_TRUE(sentBytes > 0) << "sentBytes = [" << sentBytes << "]"; int64_t recvBytes = clientsStats["recv_bytes"].As<int64_t>(); EXPECT_TRUE(recvBytes > 0) << "recvBytes = [" << recvBytes << "]"; std::string userName = clientsStats["user_name"].As<std::string>(); EXPECT_TRUE(userName == kUserName) << "userName =[" << userName << "]"; std::string dbName = clientsStats["db_name"].As<std::string>(); EXPECT_TRUE(dbName == kdbName) << "dbName =[" << dbName << "]"; std::string appName = clientsStats["app_name"].As<std::string>(); EXPECT_TRUE(appName == kAppName) << "appName =[" << appName << "]"; std::string userRights = clientsStats["user_rights"].As<std::string>(); EXPECT_TRUE(userRights == "owner") << "userRights =[" << userRights << "]"; std::string clientVersion = clientsStats["client_version"].As<std::string>(); EXPECT_TRUE(clientVersion == reindexer::SemVersion(REINDEX_VERSION).StrippedString()) << "clientVersion =[" << clientVersion << "]"; uint32_t txCount = clientsStats["tx_count"].As<uint32_t>(); EXPECT_TRUE(txCount == 2) << "tx_count =[" << txCount << "]"; int64_t sendBufBytes = clientsStats["send_buf_bytes"].As<int64_t>(-1); EXPECT_TRUE(sendBufBytes == 0) << "sendBufBytes = [" << sendBufBytes << "]"; int64_t pendedUpdates = clientsStats["pended_updates"].As<int64_t>(-1); EXPECT_TRUE(pendedUpdates == 0) << "pendedUpdates = [" << pendedUpdates << "]"; int64_t sendRate = clientsStats["send_rate"].As<int64_t>(); EXPECT_TRUE(sendRate > 0) << "sendRate = [" << sendRate << "]"; int64_t recvRate = clientsStats["recv_rate"].As<int64_t>(); EXPECT_TRUE(recvRate > 0) << "recvRate = [" << recvRate << "]"; int64_t lastSendTs = clientsStats["last_send_ts"].As<int64_t>(); EXPECT_TRUE(lastSendTs > beginTs) << "lastSendTs = [" << lastSendTs << "], beginTs = [" << beginTs << "]"; EXPECT_TRUE(lastSendTs <= endTs) << "lastSendTs = [" << lastSendTs << "], endTs = [" << endTs << "]"; int64_t lastRecvTs = clientsStats["last_recv_ts"].As<int64_t>(); EXPECT_TRUE(lastRecvTs > beginTs) << "lastRecvTs = [" << lastRecvTs << "], beginTs = [" << beginTs << "]"; EXPECT_TRUE(lastRecvTs <= endTs) << "lastRecvTs = [" << lastRecvTs << "], endTs = [" << endTs << "]"; bool isSubscribed = clientsStats["is_subscribed"].As<bool>(false); EXPECT_EQ(isSubscribed, true); reindexer::UpdatesFilters resultFilters; resultFilters.FromJSON(clientsStats["updates_filter"]); EXPECT_EQ(resultFilters, filters); err = reindexer.CommitTransaction(tx1); ASSERT_TRUE(err.ok()) << err.what(); err = reindexer.CommitTransaction(tx2); ASSERT_TRUE(err.ok()) << err.what(); } TEST_F(ClientsStatsApi, UpdatesFilters) { RunServerInThread(true); reindexer::client::ReindexerConfig config; config.ConnPoolSize = 1; config.WorkerThreads = 1; reindexer::client::Reindexer reindexer(config); reindexer::client::ConnectOpts opts; opts.CreateDBIfMissing(); auto err = reindexer.Connect(GetConnectionString(), opts); ASSERT_TRUE(err.ok()) << err.what(); std::string ns1Name("ns1"); err = reindexer.OpenNamespace(ns1Name); ASSERT_TRUE(err.ok()) << err.what(); std::string ns2Name("ns2"); err = reindexer.OpenNamespace(ns2Name); ASSERT_TRUE(err.ok()) << err.what(); std::string ns3Name("ns3"); err = reindexer.OpenNamespace(ns3Name); ASSERT_TRUE(err.ok()) << err.what(); { reindexer::client::QueryResults resultCs; err = reindexer.Select(reindexer::Query("#clientsstats"), resultCs); ASSERT_TRUE(err.ok()) << err.what(); ASSERT_EQ(resultCs.Count(), 1); auto it = resultCs.begin(); reindexer::WrSerializer wrser; err = it.GetJSON(wrser, false); ASSERT_TRUE(err.ok()) << err.what(); gason::JsonParser parser; gason::JsonNode clientsStats = parser.Parse(wrser.Slice()); bool isSubscribed = clientsStats["is_subscribed"].As<bool>(true); EXPECT_EQ(isSubscribed, false); reindexer::UpdatesFilters resultFilters; resultFilters.FromJSON(clientsStats["updates_filter"]); EXPECT_EQ(resultFilters, reindexer::UpdatesFilters()); } TestObserver observer; reindexer::UpdatesFilters filters1; filters1.AddFilter(ns1Name, reindexer::UpdatesFilters::Filter()); filters1.AddFilter(ns2Name, reindexer::UpdatesFilters::Filter()); err = reindexer.SubscribeUpdates(&observer, filters1, SubscriptionOpts().IncrementSubscription()); ASSERT_TRUE(err.ok()) << err.what(); { reindexer::client::QueryResults resultCs; err = reindexer.Select(reindexer::Query("#clientsstats"), resultCs); ASSERT_TRUE(err.ok()) << err.what(); ASSERT_EQ(resultCs.Count(), 1); auto it = resultCs.begin(); reindexer::WrSerializer wrser; err = it.GetJSON(wrser, false); ASSERT_TRUE(err.ok()) << err.what(); gason::JsonParser parser; gason::JsonNode clientsStats = parser.Parse(wrser.Slice()); bool isSubscribed = clientsStats["is_subscribed"].As<bool>(false); EXPECT_EQ(isSubscribed, true); reindexer::UpdatesFilters resultFilters; resultFilters.FromJSON(clientsStats["updates_filter"]); EXPECT_EQ(resultFilters, filters1); } reindexer::UpdatesFilters filters2; filters1.AddFilter(ns3Name, reindexer::UpdatesFilters::Filter()); filters2.AddFilter(ns3Name, reindexer::UpdatesFilters::Filter()); err = reindexer.SubscribeUpdates(&observer, filters2, SubscriptionOpts().IncrementSubscription()); ASSERT_TRUE(err.ok()) << err.what(); { reindexer::client::QueryResults resultCs; err = reindexer.Select(reindexer::Query("#clientsstats"), resultCs); ASSERT_TRUE(err.ok()) << err.what(); ASSERT_EQ(resultCs.Count(), 1); auto it = resultCs.begin(); reindexer::WrSerializer wrser; err = it.GetJSON(wrser, false); ASSERT_TRUE(err.ok()) << err.what(); gason::JsonParser parser; gason::JsonNode clientsStats = parser.Parse(wrser.Slice()); bool isSubscribed = clientsStats["is_subscribed"].As<bool>(false); EXPECT_EQ(isSubscribed, true); reindexer::UpdatesFilters resultFilters; resultFilters.FromJSON(clientsStats["updates_filter"]); EXPECT_EQ(resultFilters, filters1); } err = reindexer.UnsubscribeUpdates(&observer); ASSERT_TRUE(err.ok()) << err.what(); { reindexer::client::QueryResults resultCs; err = reindexer.Select(reindexer::Query("#clientsstats"), resultCs); ASSERT_TRUE(err.ok()) << err.what(); ASSERT_EQ(resultCs.Count(), 1); auto it = resultCs.begin(); reindexer::WrSerializer wrser; err = it.GetJSON(wrser, false); ASSERT_TRUE(err.ok()) << err.what(); gason::JsonParser parser; gason::JsonNode clientsStats = parser.Parse(wrser.Slice()); bool isSubscribed = clientsStats["is_subscribed"].As<bool>(true); EXPECT_EQ(isSubscribed, false); reindexer::UpdatesFilters resultFilters; resultFilters.FromJSON(clientsStats["updates_filter"]); EXPECT_EQ(resultFilters, reindexer::UpdatesFilters()); } } TEST_F(ClientsStatsApi, TxCountLimitation) { const size_t kMaxTxCount = 1024; RunServerInThread(true); reindexer::client::ReindexerConfig config; config.ConnPoolSize = 1; config.WorkerThreads = 1; reindexer::client::Reindexer reindexer(config); reindexer::client::ConnectOpts opts; opts.CreateDBIfMissing(); auto err = reindexer.Connect(GetConnectionString(), opts); ASSERT_TRUE(err.ok()) << err.what(); std::string nsName("ns1"); err = reindexer.OpenNamespace(nsName); ASSERT_TRUE(err.ok()) << err.what(); std::vector<reindexer::client::Transaction> txs; txs.reserve(kMaxTxCount); for (size_t i = 0; i < 2 * kMaxTxCount; ++i) { auto tx = reindexer.NewTransaction(nsName); if (tx.Status().ok()) { ASSERT_FALSE(tx.IsFree()); txs.emplace_back(std::move(tx)); } } ASSERT_EQ(txs.size(), kMaxTxCount); ASSERT_EQ(StatsTxCount(reindexer), kMaxTxCount); for (size_t i = 0; i < kMaxTxCount / 2; ++i) { if (i % 2) { err = reindexer.CommitTransaction(txs[i]); } else { err = reindexer.RollBackTransaction(txs[i]); } ASSERT_TRUE(err.ok()) << err.what() << "; i = " << i; } for (size_t i = 0; i < kMaxTxCount / 4; ++i) { auto tx = reindexer.NewTransaction(nsName); ASSERT_FALSE(tx.IsFree()); ASSERT_TRUE(tx.Status().ok()); txs[i] = std::move(tx); } ASSERT_EQ(StatsTxCount(reindexer), kMaxTxCount / 2 + kMaxTxCount / 4); for (size_t i = 0; i < txs.size(); ++i) { if (!txs[i].IsFree() && txs[i].Status().ok()) { if (i % 2) { err = reindexer.CommitTransaction(txs[i]); } else { err = reindexer.RollBackTransaction(txs[i]); } ASSERT_TRUE(err.ok()) << err.what() << "; i = " << i; } } ASSERT_EQ(StatsTxCount(reindexer), 0); }
40.589342
133
0.711616
[ "vector" ]
fc561d13bbdb71ccfe6168e68f1076e6b5092a6d
1,616
cpp
C++
SOLVER/src/models3D/geometric/Ellipticity.cpp
nicklinyi/AxiSEM-3D
cd11299605cd6b92eb867d4109d2e6a8f15e6b4d
[ "MIT" ]
8
2020-06-05T01:13:20.000Z
2022-02-24T05:11:50.000Z
SOLVER/src/models3D/geometric/Ellipticity.cpp
nicklinyi/AxiSEM-3D
cd11299605cd6b92eb867d4109d2e6a8f15e6b4d
[ "MIT" ]
24
2020-10-21T19:03:38.000Z
2021-11-17T21:32:02.000Z
SOLVER/src/models3D/geometric/Ellipticity.cpp
nicklinyi/AxiSEM-3D
cd11299605cd6b92eb867d4109d2e6a8f15e6b4d
[ "MIT" ]
5
2020-06-21T11:54:22.000Z
2021-06-23T01:02:39.000Z
// // Ellipticity.cpp // AxiSEM3D // // Created by Kuangdai Leng on 5/29/20. // Copyright © 2020 Kuangdai Leng. All rights reserved. // // ellipticity #include "Ellipticity.hpp" #include "sg_tools.hpp" // get undulation on points bool Ellipticity::getUndulation(const eigen::DMatX3 &spz, eigen::DColX &undulation) const { if (geodesy::isCartesian() || geodesy::getOuterFlattening() < numerical::dEpsilon) { return false; } // theta, phi, r const eigen::DMatX3 &llr = coordsFromMeshToModel(spz, false, false, false, false, false, false, mModelName); const eigen::DMatX3 &tpr = geodesy::llr2tpr(llr, false); // flattening typedef Eigen::Array<double, Eigen::Dynamic, 1> DColX_Array; const DColX_Array &r = tpr.col(2); const DColX_Array &t = tpr.col(0); const DColX_Array &f = geodesy::computeFlattening(r); // a and b const DColX_Array &b = (1. - f).pow(2. / 3.) * r; const DColX_Array &a = b / (1. - f); const DColX_Array &tmp = (a * t.cos()).square() + (b * t.sin()).square(); undulation = a * b / tmp.sqrt().max(numerical::dEpsilon) - r; return true; } // verbose std::string Ellipticity::verbose() const { std::stringstream ss; ss << bstring::boxSubTitle(0, mModelName + " ", '~'); ss << bstring::boxEquals(2, 21, "class name", "Ellipticity"); ss << bstring::boxEquals(2, 21, "model scope", "global"); ss << bstring::boxEquals(2, 21, "flattening on surface", geodesy::getOuterFlattening()); return ss.str(); }
32.979592
77
0.600248
[ "model" ]
fc596cbb8a610b30c2a98b87a1a45675c42b72ec
601
cpp
C++
src/apps/PathFinderApp.cpp
Person-93/aima-cpp
08d062dcb971edeaddb9a10083cf6da5a1b869f7
[ "MIT" ]
null
null
null
src/apps/PathFinderApp.cpp
Person-93/aima-cpp
08d062dcb971edeaddb9a10083cf6da5a1b869f7
[ "MIT" ]
null
null
null
src/apps/PathFinderApp.cpp
Person-93/aima-cpp
08d062dcb971edeaddb9a10083cf6da5a1b869f7
[ "MIT" ]
null
null
null
#include "PathFinderApp.hpp" #include "util/parseTitle.hpp" using namespace aima::core; using namespace aima::path_finder; using aima::apps::PathFinderApp; PathFinderApp::PathFinderApp( aima::gui::ImGuiWrapper& imGuiWrapper ) : App{ imGuiWrapper }, gui{ util::parseTitle<PathFinderApp>(), &stayOpen_ }, env{ std::make_shared<PathFinderEnvironment>() }, agentPicker{ *env, &stayOpen_ } { viewer().setEnvironment( env ); } void aima::apps::PathFinderApp::renderImpl() { agentPicker.done() ? gui.render( imGuiWrapper()) : agentPicker.render( imGuiWrapper()); }
31.631579
91
0.697171
[ "render" ]
fc60b69dc747d10bd6817072eccaf879d3b10731
11,355
hpp
C++
src/GeneticAlgorithm.hpp
CLRN/GALGO-2.0
b1af23ac5ce7aba074b9a994921b8a9165704aa8
[ "MIT" ]
null
null
null
src/GeneticAlgorithm.hpp
CLRN/GALGO-2.0
b1af23ac5ce7aba074b9a994921b8a9165704aa8
[ "MIT" ]
null
null
null
src/GeneticAlgorithm.hpp
CLRN/GALGO-2.0
b1af23ac5ce7aba074b9a994921b8a9165704aa8
[ "MIT" ]
null
null
null
//================================================================================================= // Copyright (C) 2017 Olivier Mallet - All Rights Reserved //================================================================================================= #ifndef GENETICALGORITHM_HPP #define GENETICALGORITHM_HPP namespace galgo { //================================================================================================= template<typename T> class GeneticAlgorithm { static_assert(std::is_same<float, T>::value || std::is_same<double, T>::value, "variable type can only be float or double, please amend."); template<typename K> friend class Population; template<typename K> friend class Chromosome; template<typename K> using Func = std::vector<K> (*)(const std::vector<K>&); private: Population<T> pop; // population of chromosomes std::vector<PAR < T>> param; // parameter(s) std::vector<T> lowerBound; // parameter(s) lower bound std::vector<T> upperBound; // parameter(s) upper bound std::vector<T> initialSet; // initial set of parameter(s) std::vector<int> idx; // indexes for chromosome breakdown public: // objective function pointer Func<T> Objective; // selection method initialized to roulette wheel selection void (* Selection)(Population<T>&) = RWS; // cross-over method initialized to 1-point cross-over void (* CrossOver)(const Population<T>&, CHR <T>&, CHR <T>&) = P1XO; // mutation method initialized to single-point mutation void (* Mutation)(CHR <T>&) = SPM; // adaptation to constraint(s) method void (* Adaptation)(Population<T>&) = nullptr; // constraint(s) std::vector<T> (* Constraint)(const std::vector<T>&) = nullptr; T covrate = .50; // cross-over rate T mutrate = .05; // mutation rate T SP = 1.5; // selective pressure for RSP selection method T tolerance = 0.0; // terminal condition (inactive if equal to zero) int elitpop = 1; // elit population size int matsize; // mating pool size, set to popsize by default int tntsize = 10; // tournament size int genstep = 10; // generation step for outputting results int precision = 5; // precision for outputting results // constructor template<int...N> GeneticAlgorithm(Func<T> objective, int popsize, int nbgen, bool output, const Parameter<T, N>& ...args); template<typename Param> void addParam(Param param); // run genetic algorithm void run(); // return best chromosome const CHR <T>& result() const; private: int nbbit = 0; // total number of bits per chromosome int nbgen; // number of generations int nogen = 0; // numero of generation int nbparam = 0; // number of parameters to be estimated int popsize; // population size bool output; // control if results must be outputted // end of recursion for initializing parameter(s) data template<int I = 0, int...N> typename std::enable_if<I == sizeof...(N), void>::type init(const TUP<T, N...>&); // recursion for initializing parameter(s) data template<int I = 0, int...N> typename std::enable_if<I < sizeof...(N), void>::type init(const TUP<T, N...>&); // check inputs validity void check() const; // print results for each new generation void print() const; }; /*-------------------------------------------------------------------------------------------------*/ // constructor template<typename T> template<int...N> GeneticAlgorithm<T>::GeneticAlgorithm(Func<T> objective, int popsize, int nbgen, bool output, const Parameter<T, N>& ...args) { this->Objective = objective; this->nbgen = nbgen; // getting number of parameters in the pack this->popsize = popsize; this->matsize = popsize; this->output = output; // unpacking parameter pack in tuple TUP<T, N...> tp(args...); // initializing parameter(s) data this->init(tp); } /*-------------------------------------------------------------------------------------------------*/ // end of recursion for initializing parameter(s) data template<typename T> template<int I, int...N> inline typename std::enable_if<I == sizeof...(N), void>::type GeneticAlgorithm<T>::init(const TUP<T, N...>& tp) {} // recursion for initializing parameter(s) data template<typename T> template<int I, int...N> inline typename std::enable_if<I < sizeof...(N), void>::type GeneticAlgorithm<T>::init(const TUP<T, N...>& tp) { // getting Ith parameter in tuple auto par = std::get<I>(tp); addParam(par); // recursing init<I + 1>(tp); } template<typename T> template<typename Param> void GeneticAlgorithm<T>::addParam(Param par) { ++this->nbparam; this->nbbit += par.size(); // getting Ith parameter initial data const auto& data = par.getData(); // copying parameter data param.emplace_back(new decltype(par)(par)); lowerBound.push_back(data[0]); upperBound.push_back(data[1]); // if parameter has initial value if (data.size() > 2) { initialSet.push_back(data[2]); } // setting indexes for chromosome breakdown int I = idx.size(); if (I == 0) { idx.push_back(0); } else { idx.push_back(idx[I - 1] + par.size()); } } /*-------------------------------------------------------------------------------------------------*/ // check inputs validity template<typename T> void GeneticAlgorithm<T>::check() const { if (!initialSet.empty()) { for (int i = 0; i < nbparam; ++i) { if (initialSet[i] < lowerBound[i] || initialSet[i] > upperBound[i]) { throw std::invalid_argument( "Error: in class galgo::Parameter<T,N>, initial parameter value cannot be outside the parameter boundaries, please choose a value between its lower and upper bounds."); } } if (initialSet.size() != (unsigned) nbparam) { throw std::invalid_argument( "Error: in class galgo::GeneticAlgorithm<T>, initial set of parameters does not have the same dimension than the number of parameters, please adjust."); } } if (SP < 1.0 || SP > 2.0) { throw std::invalid_argument( "Error: in class galgo::GeneticAlgorithm<T>, selective pressure (SP) cannot be outside [1.0,2.0], please choose a real value within this interval."); } if (elitpop > popsize || elitpop < 0) { throw std::invalid_argument( "Error: in class galgo::GeneticAlgorithm<T>, elit population (elitpop) cannot outside [0,popsize], please choose an integral value within this interval."); } if (covrate < 0.0 || covrate > 1.0) { throw std::invalid_argument( "Error: in class galgo::GeneticAlgorithm<T>, cross-over rate (covrate) cannot outside [0.0,1.0], please choose a real value within this interval."); } if (genstep <= 0) { throw std::invalid_argument( "Error: in class galgo::GeneticAlgorithm<T>, generation step (genstep) cannot be <= 0, please choose an integral value > 0."); } } /*-------------------------------------------------------------------------------------------------*/ // run genetic algorithm template<typename T> void GeneticAlgorithm<T>::run() { // checking inputs validity this->check(); // setting adaptation method to default if needed if (Constraint != nullptr && Adaptation == nullptr) { Adaptation = DAC; } // initializing population pop = Population<T>(*this); if (output) { std::cout << "\n Running Genetic Algorithm...\n"; std::cout << " ----------------------------\n"; } // creating population pop.creation(); // initializing best result and previous best result T bestResult = pop(0)->getTotal(); T prevBestResult = bestResult; // outputting results if (output) print(); // starting population evolution for (nogen = 1; nogen <= nbgen; ++nogen) { // evolving population pop.evolution(); // getting best current result bestResult = pop(0)->getTotal(); // outputting results if (output) print(); // checking convergence if (tolerance != 0.0) { if (fabs(bestResult - prevBestResult) < fabs(tolerance)) { break; } prevBestResult = bestResult; } } // outputting contraint value if (Constraint != nullptr) { // getting best parameter(s) constraint value(s) std::vector<T> cst = pop(0)->getConstraint(); if (output) { std::cout << "\n Constraint(s)\n"; std::cout << " -------------\n"; for (unsigned i = 0; i < cst.size(); ++i) { std::cout << " C"; if (nbparam > 1) { std::cout << std::to_string(i + 1); } std::cout << "(x) = " << std::setw(6) << std::fixed << std::setprecision(precision) << cst[i] << "\n"; } std::cout << "\n"; } } } /*-------------------------------------------------------------------------------------------------*/ // return best chromosome template<typename T> inline const CHR <T>& GeneticAlgorithm<T>::result() const { return pop(0); } /*-------------------------------------------------------------------------------------------------*/ // print results for each new generation template<typename T> void GeneticAlgorithm<T>::print() const { // getting best parameter(s) from best chromosome std::vector<T> bestParam = pop(0)->getParam(); std::vector<T> bestResult = pop(0)->getResult(); if (nogen % genstep == 0) { std::cout << " Generation = " << std::setw(std::to_string(nbgen).size()) << nogen << " |"; for (int i = 0; i < nbparam; ++i) { std::cout << " X"; if (nbparam > 1) { std::cout << std::to_string(i + 1); } std::cout << " = " << std::setw(9) << std::fixed << std::setprecision(precision) << bestParam[i] << " |"; } for (unsigned i = 0; i < bestResult.size(); ++i) { std::cout << " F"; if (bestResult.size() > 1) { std::cout << std::to_string(i + 1); } std::cout << "(x) = " << std::setw(12) << std::fixed << std::setprecision(precision) << bestResult[i]; if (i < bestResult.size() - 1) { std::cout << " |"; } else { std::cout << "\n"; } } } } //================================================================================================= } #endif
31.717877
192
0.510348
[ "vector" ]
fc6a8371f2d6026a09abf8945140e0d075ad4eac
2,013
cpp
C++
lynton/src/core/log.cpp
Light3039/lynton
e6610bcd2ebbf27d0a70cc82f7fa9a0bbd2d4f87
[ "MIT" ]
7
2021-01-04T15:16:48.000Z
2021-12-01T21:43:42.000Z
lynton/src/core/log.cpp
Light3039/lynton
e6610bcd2ebbf27d0a70cc82f7fa9a0bbd2d4f87
[ "MIT" ]
3
2021-08-12T21:28:54.000Z
2021-09-02T13:20:18.000Z
lynton/src/core/log.cpp
Light3039/lynton
e6610bcd2ebbf27d0a70cc82f7fa9a0bbd2d4f87
[ "MIT" ]
1
2021-07-26T10:41:56.000Z
2021-07-26T10:41:56.000Z
#include "log.h" #include "pch.h" namespace Lynton { std::shared_ptr<spdlog::logger> Log::s_lynton_logger; std::shared_ptr<spdlog::logger> Log::s_client_logger; std::shared_ptr<spdlog::logger> Log::s_error_logger; void Log::init() { try { // log to console and file std::vector<spdlog::sink_ptr> default_log_sinks; default_log_sinks.emplace_back(std::make_shared<spdlog::sinks::stdout_color_sink_mt>()); #ifndef __EMSCRIPTEN__ default_log_sinks.emplace_back(std::make_shared<spdlog::sinks::basic_file_sink_mt>("lynton.log", true)); #endif // log to std error stream std::vector<spdlog::sink_ptr> error_log_sinks; error_log_sinks.emplace_back(std::make_shared<spdlog::sinks::stderr_color_sink_mt>()); default_log_sinks[0]->set_pattern("%^[%T] %n: %v%$"); #ifndef __EMSCRIPTEN__ default_log_sinks[1]->set_pattern("[%T] [%l] %n: %v"); #endif error_log_sinks[0]->set_pattern("%^[%T] %n: %v%$"); s_lynton_logger = std::make_shared<spdlog::logger>("Lynton", begin(default_log_sinks), end(default_log_sinks)); s_client_logger = std::make_shared<spdlog::logger>("Client", begin(default_log_sinks), end(default_log_sinks)); s_error_logger = std::make_shared<spdlog::logger>("Error", begin(error_log_sinks), end(error_log_sinks)); spdlog::register_logger(s_lynton_logger); s_lynton_logger->set_level(spdlog::level::trace); s_lynton_logger->flush_on(spdlog::level::trace); spdlog::register_logger(s_client_logger); s_client_logger->set_level(spdlog::level::trace); s_client_logger->flush_on(spdlog::level::trace); spdlog::register_logger(s_error_logger); s_error_logger->set_level(spdlog::level::critical); s_error_logger->flush_on(spdlog::level::critical); } catch(const spdlog::spdlog_ex& ex) { std::cerr << "Log init failed: " << ex.what() << std::endl; std::exit(EXIT_FAILURE); } } } // namespace Lynton
40.26
119
0.682563
[ "vector" ]
fc6bb082b8295687e9a0c3eec063682ef4639227
17,487
cpp
C++
LDFV.cpp
constanton/bLDFV
7609f9d3c719cd1e707eb05fb8472449bd11f0cf
[ "Apache-2.0" ]
16
2015-04-11T12:44:36.000Z
2021-07-19T15:14:40.000Z
LDFV.cpp
constanton/bLDFV
7609f9d3c719cd1e707eb05fb8472449bd11f0cf
[ "Apache-2.0" ]
null
null
null
LDFV.cpp
constanton/bLDFV
7609f9d3c719cd1e707eb05fb8472449bd11f0cf
[ "Apache-2.0" ]
12
2015-04-14T12:12:15.000Z
2018-12-10T00:15:12.000Z
/* Copyright 2014 Konstantinos Antonakoglou 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 "LDFV.h" LDFV::LDFV(string config) { vector<Mat> imgs; loadconfigxml(config); int imgcount; string fullpath; char filenum[10]; //initialize GMM VlGMM** gmm = new VlGMM*[opts.numofblocksX*opts.numofblocksY]; for(int i=0; i<opts.numofblocksX*opts.numofblocksY;i++) { gmm[i] = vl_gmm_new (VL_TYPE_FLOAT, opts.dimensions, opts.numofclusters); } if(opts.LDFVfunction == 1){ //Find and export LDFV descriptors from the test image database Mat Sigmas[opts.numofblocksX*opts.numofblocksY]; Mat Means[opts.numofblocksX*opts.numofblocksY]; Mat Weights[opts.numofblocksX*opts.numofblocksY]; /* Initialize an array of [number of test images] pointers to an * array of [number of blocks] pointers to an * array of floats (the fisher vectors).*/ float*** fisherVects = new float**[opts.numoftestimgs]; for(int z=0; z<opts.numoftestimgs;z++){ fisherVects[z] = new float*[opts.numofblocksX*opts.numofblocksY]; for (int p=0; p< opts.numofblocksX*opts.numofblocksY;p++) /* One array of FVs is vl_malloc(sizeof(float)*2*DIMENSIONS*opts.numofclusters); */ fisherVects[z][p] = new float[2*opts.numofclusters*opts.dimensions]; } importGMMparams(Sigmas, Means, Weights); fullpath = opts.pathToTestImages; for(imgcount = 0; imgcount < opts.numoftestimgs; imgcount++) { //image is 3 characters wide plus the image format (NNN.bmp) sprintf(filenum,"%03d.bmp",imgcount); imgs.push_back(imread(fullpath+filenum)); if (!imgs[imgcount].data){ perror("Image data not loaded properly"); } } //Convert from (default) BGR to HSV for each image of the vector imgs vector<Mat>::const_iterator iter; vector<float> featVector; int numofdata = 3*(imgs[0].cols/opts.numofblocksX)*(imgs[0].rows/opts.numofblocksY); featVector.reserve(numofdata*opts.dimensions); for(iter = imgs.begin(); iter != imgs.end(); iter++){ cvtColor((*iter), (*iter), CV_BGR2HSV,CV_32FC3); getLDFVs((*iter), Sigmas, Means, Weights, fisherVects,iter - imgs.begin(), featVector); exportDescriptor(opts.pathToTestImages, fisherVects[iter - imgs.begin()], iter - imgs.begin() ); } //Memory deallocation for(int z=0; z<opts.numoftestimgs;z++){ for (int p=0; p< opts.numofblocksX*opts.numofblocksY;p++) delete [] fisherVects[z][p]; delete [] fisherVects[z]; } delete [] fisherVects; }else if(opts.LDFVfunction == 0){ /* Training...fill in the vector of training images * to compute GMM */ fullpath = opts.pathToTrainImages; for(imgcount = 0; imgcount < opts.numoftrainimgs; imgcount++) { //image is 3 characters wide plus the image format (NNN.bmp) sprintf(filenum,"%03d.bmp",imgcount); imgs.push_back(imread(fullpath+filenum)); cout << filenum << endl; if (!imgs[imgcount].data){ perror("Image data not loaded properly"); } } vector<Mat>::const_iterator iter; //Convert from (default) BGR to HSV for each image of the vector imgs for(iter = imgs.begin(); iter != imgs.end(); iter++){ cvtColor((*iter), (*iter), CV_BGR2HSV, CV_32FC3); } //Start training and extract GMM parameters training(imgs, gmm); for(int i=0; i< opts.numofblocksX*opts.numofblocksY;i++){ vl_gmm_delete(gmm[i]); } }else if(opts.LDFVfunction == 2){ Mat testDescriptors[opts.numoftestimgs+1]; Mat Sigmas[opts.numofblocksX*opts.numofblocksY]; Mat Means[opts.numofblocksX*opts.numofblocksY]; Mat Weights[opts.numofblocksX*opts.numofblocksY]; Mat queryImg = imread(opts.queryImg); vector<float> featVector; int numofdata = 3*(queryImg.cols/opts.numofblocksX)*(queryImg.rows/opts.numofblocksY); featVector.reserve(numofdata*opts.dimensions); /* Initialize an array of [number of test images] pointers to an * array of [number of blocks] pointers to an * array of floats (the fisher vectors).*/ float*** fisherVects = new float**[1]; for(int z=0; z<1;z++){ fisherVects[z] = new float*[opts.numofblocksX*opts.numofblocksY]; for (int p=0; p< opts.numofblocksX*opts.numofblocksY;p++) /* One array of FVs is vl_malloc(sizeof(float)*2*DIMENSIONS*opts.numofclusters); */ fisherVects[z][p] = new float[2*opts.numofclusters*opts.dimensions]; } //Import GMM parameters importGMMparams(Sigmas, Means, Weights); //Convert image to HSV cvtColor(queryImg, queryImg, CV_BGR2HSV,CV_32FC3); //Get feature vectors getLDFVs(queryImg, Sigmas, Means, Weights, fisherVects, 0, featVector); //Export the final image descriptor as fisher-999.xml exportDescriptor(opts.pathToTestImages,fisherVects[0], -1 ); //import Fisher Vectors of all test images in separate Mat arrays importFisherVectors(testDescriptors,0); int x = findMinDistancePic(testDescriptors); cout << "Matching picture is: " << endl; cout << x << endl; //Memory deallocation for (int p=0; p< opts.numofblocksX*opts.numofblocksY;p++) delete [] fisherVects[0][p]; delete [] fisherVects[0]; delete [] fisherVects; }else if(opts.LDFVfunction == 3){ Mat testDescriptors[opts.numoftestimgs+1]; Mat queryDescriptors[opts.numofqueryimgs+1]; //import Fisher Vectors of all test images in separate Mat arrays importFisherVectors(testDescriptors,0); //import Fisher Vectors of all Query images in separate Mat arrays importFisherVectors(queryDescriptors,1); exportDistancesCSV(testDescriptors,queryDescriptors); }else{ //xml configuration is wrong perror("'DBdescriptors-Training-ReId' option in config.xml must be either 0,1,2"); } }; void LDFV::getLDFVs(const Mat pic, const Mat* Sigmas, const Mat* Means, const Mat* Weights, float*** fisherVects, int imgcount, vector<float>& featVector) { //initialize loop counters int x,y,numofdata; /* initialize "layers" Mat and * STL vector of floats (used for feature vectors) */ Mat layers[3*opts.dimensions]; for(int i=0; i< 3 * (int) opts.dimensions; i++){ layers[i].create(pic.rows, pic.cols,CV_32FC1); } numofdata = 3*(pic.cols/opts.numofblocksX)*(pic.rows/opts.numofblocksY); /* split colors, compute derivatives, * place them all layers in "layers" array */ computeLayers(pic, layers); //horizontal scan block by block for (y=0; y < opts.numofblocksY; y++){ for(x=0; x< opts.numofblocksX; x++){ /* retrieve all feature vectors of this block and then * array the std::vector is using internally */ blockFeatVector(x,y,layers, featVector); vl_fisher_encode(fisherVects[imgcount][y*opts.numofblocksX+x], VL_TYPE_FLOAT,(float const*) Means[y*opts.numofblocksX+x].data, opts.dimensions, opts.numofclusters, (float const*) Sigmas[y*opts.numofblocksX+x].data, (float const*) Weights[y*opts.numofblocksX+x].data, &featVector[0],numofdata, VL_FISHER_FLAG_IMPROVED); featVector.resize(0); } } for(int i=0;i< 3 * (int) opts.dimensions; i++){ layers[i].release(); } } //Export final descriptor (concatenation of fisher vectors from each block) void LDFV::exportDescriptor(string path, float** fisherVectors, int imgcount){ int x,y,z; char filename[15]; if(imgcount != -1){ sprintf(filename,"fisher-%03d.xml",imgcount); }else{ sprintf(filename,"fisher-%03d.xml",opts.numoftestimgs); } string fullpath = path + filename; FILE * ofpFV = fopen(fullpath.c_str(), "w"); fprintf(ofpFV, "<?xml version=\"1.0\"?>\n<opencv_storage>\n<final_descriptor type_id=\"opencv-matrix\">\n<rows>1</rows>\n<cols>%d</cols>\n<dt>f</dt>\n<data>" ,2*(int) opts.numofclusters * (int) opts.dimensions*opts.numofblocksX*opts.numofblocksY); for (y=0; y< opts.numofblocksY; y++){ for(x=0; x< opts.numofblocksX; x++){ for(z = 0; z < 2*(int) opts.numofclusters* (int) opts.dimensions; z++) { fprintf(ofpFV, "%f ", (float)fisherVectors[y*opts.numofblocksX+x][z]); } } } fprintf(ofpFV, "</data>\n</final_descriptor>\n</opencv_storage>\n"); fclose(ofpFV); } void LDFV::training(const vector<Mat> trainPics, VlGMM** gmm) { //initialize loop counters int x,y; vl_size numofdata; /* initialize layers Mat and * STL vector of floats (used for feature vectors) */ Mat layers[3*opts.dimensions]; for(int i=0;i< 3 * (int) opts.dimensions; i++){ layers[i].create(trainPics[0].rows, trainPics[0].cols,CV_32FC1); } vector<float> featVector; //iterator of training images vector vector<Mat>::const_iterator iter; //horizontal scan block by block for (y=0; y< opts.numofblocksY; y++){ for(x=0; x< opts.numofblocksX; x++){ //of every picture (applies only to the training process for(iter = trainPics.begin(); iter != trainPics.end(); iter++){ /* split colors, compute derivatives, * place them all as layers in "layers" array*/ computeLayers((*iter), layers); /* retrieve all feature vectors of this block and then use the * array the std::vector is using internally */ blockFeatVector(x,y,layers, featVector); } //Get number of multidimensional data numofdata= featVector.size()/opts.dimensions; /* convert the std::vector to an array by pointing to the actual * array the std::vector is using internally */ computeGMM(x,y,&featVector[0], gmm, numofdata); featVector.clear(); } } exportGMMparams(gmm); } void LDFV::blockFeatVector(int x, int y,const Mat* layers, vector<float>& featVect ) { int blockx, blocky, layercount; /* get block width & height using one of the layers * not the original picture (Mat includes channels) */ int blockwidth = layers[0].cols / opts.numofblocksX; int blockheight = layers[0].rows / opts.numofblocksY; //horizontal scan of blocks (left to right) for(blocky=y*blockheight; blocky < y*blockheight + blockheight; blocky++){ for (blockx = x*blockwidth; blockx < x*blockwidth + blockwidth ; blockx++){ //for each layer for(layercount = 0; layercount < (int) opts.dimensions*3; layercount++){ //get all values of all layers at blockx,blocky coordinates featVect.push_back(layers[layercount].at<float>(blockx,blocky)); } } } } /* Create a Mat array for each channel's intensity(H/S/V) and required * properties H/Ix(H)/Iy(H)/Ixx(H)/Iyy(H). * 3 channels x 5 properties = 15 layers*/ void LDFV::computeLayers(const Mat img, Mat* layers) { //initialize loop counter int x, y, chans, l; //split and place HSV layers inside the vector split(img,layers); /* Rearrange HSV in layers array to create separate feature vectors for each color */ layers[2].copyTo(layers[16]); layers[1].copyTo(layers[9]); layers[0].copyTo(layers[2]); //insert x,y layers and calculate derivatives for each channel for (chans=0; chans<3; chans++){ for(x=0; x<img.cols;x++) layers[chans*opts.dimensions].col(x) = Scalar::all(x); for(y=0; y<img.rows;y++) layers[chans*opts.dimensions+1].row(y) = Scalar::all(y); Sobel(layers[chans*opts.dimensions+2], layers[chans*opts.dimensions+3], CV_32FC1,1,0); Sobel(layers[chans*opts.dimensions+2], layers[chans*opts.dimensions+4], CV_32FC1,0,1); Sobel(layers[chans*opts.dimensions+2], layers[chans*opts.dimensions+5], CV_32FC1,2,0); Sobel(layers[chans*opts.dimensions+2], layers[chans*opts.dimensions+6], CV_32FC1,0,2); } /* Normalize values from range [0,255] to * [0,1] (floating point values for VLFeat) */ for( l = 0; l < (int)opts.dimensions*3; l++) normalize(layers[l],layers[l],0,1,NORM_MINMAX, CV_32FC1); } void LDFV::computeGMM(int x, int y, float* featVectorArray, VlGMM** gmm, vl_size numofdata) { //set the GMM parameters vl_gmm_set_initialization(gmm[y*opts.numofblocksX+x],VlGMMRand); vl_gmm_set_max_num_iterations (gmm[y*opts.numofblocksX+x], opts.maxiter) ; vl_gmm_set_num_repetitions(gmm[y*opts.numofblocksX+x], opts.maxrep); vl_gmm_set_verbosity(gmm[y*opts.numofblocksX+x],1); vl_gmm_set_covariance_lower_bound (gmm[y*opts.numofblocksX+x],opts.sigmaLowerBound); //compute GMM vl_gmm_cluster(gmm[y*opts.numofblocksX+x], featVectorArray, numofdata); } void LDFV::loadconfigxml(string configfile) { //Load all configuration from FileStorage fs; fs.open(configfile, FileStorage::READ); opts.numofblocksX = (int) fs["NUMOFBLOCKSX"]; opts.numofblocksY = (int) fs["NUMOFBLOCKSY"]; opts.LDFVfunction = (int) fs["Training-DBdescriptors-ReId-Folders"]; opts.numoftrainimgs = (int) fs["NumOfTrainingImages"]; opts.numoftestimgs = (int) fs["NumOfTestImages"]; opts.numofqueryimgs = (int) fs["NumOfQueryImages"]; opts.numofclusters = (int) fs["NumOfClusters"]; opts.dimensions = (int) fs["dimensions"]; opts.pathToTrainImages = (string) fs["pathToTrainImages"]; opts.pathToTestImages = (string) fs["pathToTestImages"]; opts.pathToQueryImages = (string) fs["pathToQueryImages"]; opts.queryImg = (string) fs["QueryImage"]; opts.maxiter = (int) fs["maxIterations"]; opts.maxrep = (int) fs["maxRepetitions"]; opts.sigmaLowerBound = (double) fs["sigmaLowerBound"]; } void LDFV::exportGMMparams(VlGMM** gmm) { int x,y,Idx; FILE * ofp = fopen("gmm_parameters.xml", "w"); fprintf(ofp, "<?xml version=\"1.0\"?>\n<opencv_storage>\n"); for (y=0; y<=opts.numofblocksY-1; y++){ for(x=0; x<=opts.numofblocksX-1; x++){ //export GMM sigmas/covariances float const * sigmas = (float *) vl_gmm_get_covariances(gmm[y*opts.numofblocksX+x]) ; fprintf(ofp, "<sigmas-block%02d type_id=\"opencv-matrix\">\n<rows>1</rows>\n<cols>%d</cols>\n<dt>f</dt>\n<data>", y*opts.numofblocksX+x, (int) opts.numofclusters* (int) opts.dimensions); for(Idx = 0; Idx < (int) opts.numofclusters* (int) opts.dimensions; Idx++) { fprintf(ofp, "%f ", ((float*)sigmas)[Idx]); } fprintf(ofp, "</data>\n</sigmas-block%02d>\n",y*opts.numofblocksX+x); //export GMM means float const * means = (float *) vl_gmm_get_means(gmm[y*opts.numofblocksX+x]) ; fprintf(ofp, "<means-block%02d type_id=\"opencv-matrix\">\n<rows>1</rows>\n<cols>%d</cols>\n<dt>f</dt>\n<data>", y*opts.numofblocksX+x, (int) opts.numofclusters* (int) opts.dimensions); for(Idx = 0; Idx < (int) opts.numofclusters* (int) opts.dimensions; Idx++) { fprintf(ofp, "%f ", ((float*)means)[Idx]); } fprintf(ofp, "</data>\n</means-block%02d>\n",y*opts.numofblocksX+x); //export GMM weights/priors of each cluster float const * weights = (float const*) vl_gmm_get_priors(gmm[y*opts.numofblocksX+x]) ; fprintf(ofp, "<weights-block%02d type_id=\"opencv-matrix\">\n<rows>1</rows>\n<cols>%d</cols>\n<dt>f</dt>\n<data>", y*opts.numofblocksX+x,(int) opts.numofclusters); for(Idx = 0; Idx < (int) opts.numofclusters; Idx++) { fprintf(ofp, "%f ", ((float*)weights)[Idx]); } fprintf(ofp, "</data>\n</weights-block%02d>\n",y*opts.numofblocksX+x); } } fprintf(ofp, "</opencv_storage>\n"); fclose(ofp); } void LDFV::importGMMparams(Mat* Sigmas,Mat* Means,Mat* Weights) { int x,y; char blocknum[10]; string blocksigma = "sigmas-"; string blockmeans = "means-"; string blockweights = "weights-"; string gmmfile = "gmm_parameters.xml"; FileStorage fs; fs.open(gmmfile, FileStorage::READ); for (y=0; y<opts.numofblocksY; y++){ for(x=0; x<opts.numofblocksX; x++){ sprintf(blocknum,"block%02d",y*opts.numofblocksX+x); //import from xml to OpenCV matrices fs[blocksigma + blocknum] >> Sigmas[y*opts.numofblocksX+x]; fs[blockmeans + blocknum] >> Means[y*opts.numofblocksX+x]; fs[blockweights + blocknum] >> Weights[y*opts.numofblocksX+x]; } } } void LDFV::importFisherVectors(Mat* FVs, bool testORquery) { char filename[15]; string pathToImages; string fullpath; int numofimgs; if(testORquery){ numofimgs = opts.numofqueryimgs; pathToImages = opts.pathToQueryImages; }else{ numofimgs = opts.numoftestimgs; pathToImages = opts.pathToTestImages; } for(int im=0; im<numofimgs+1; im++) { sprintf(filename,"%03d",im); fullpath = pathToImages + "fisher-" + filename + ".xml"; FileStorage fs(fullpath, FileStorage::READ); fs["final_descriptor"] >> FVs[im]; fs.release(); } } int LDFV::findMinDistancePic(Mat* FVs) { //A point to locate the minimum distance value Point p; Mat distances(1,opts.numoftestimgs,DataType<double>::type); for(int im=0; im<opts.numoftestimgs; im++){ distances.at<double>(0,im) = norm(FVs[im],FVs[opts.numoftestimgs],NORM_L2); } cout << distances << endl; FILE *ofp = fopen("test.csv","w+"); for(int i = 0 ; i < distances.cols;i++) { fprintf(ofp,"%F\t %d\n",distances.at<double>(0,i),i); } fclose(ofp); minMaxLoc(distances, 0, 0, &p); return p.x; } void LDFV::exportDistancesCSV(Mat* FVs, Mat* QFVs){ char buf[0x100]; Mat distances(1,opts.numoftestimgs,DataType<double>::type); for (int qim=0; qim<opts.numofqueryimgs; qim++){ for(int im=0; im<opts.numoftestimgs; im++){ distances.at<double>(0,im) = norm(FVs[im],QFVs[qim],NORM_L2); } snprintf(buf, sizeof(buf), "%03d.csv", qim); FILE *ofp = fopen(buf,"w+"); for(int i = 0 ; i < distances.cols;i++) { fprintf(ofp,"%F\t %d\n",distances.at<double>(0,i),i); } fclose(ofp); } }
33.5
143
0.69423
[ "vector" ]
fc70ead38760f9ab7ec2311ef42eb8b2eab3b7f4
30,377
cpp
C++
openstudiocore/src/model/GeneratorFuelCellAirSupply.cpp
Acidburn0zzz/OpenStudio
8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd
[ "MIT" ]
null
null
null
openstudiocore/src/model/GeneratorFuelCellAirSupply.cpp
Acidburn0zzz/OpenStudio
8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd
[ "MIT" ]
null
null
null
openstudiocore/src/model/GeneratorFuelCellAirSupply.cpp
Acidburn0zzz/OpenStudio
8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd
[ "MIT" ]
null
null
null
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products * derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works * may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior * written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY 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(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED * STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 "GeneratorFuelCellAirSupply.hpp" #include "GeneratorFuelCellAirSupply_Impl.hpp" #include "Model.hpp" #include "Model_Impl.hpp" #include "GeneratorFuelCell.hpp" #include "GeneratorFuelCell_Impl.hpp" #include "Node.hpp" #include "Node_Impl.hpp" #include "CurveCubic.hpp" #include "CurveCubic_Impl.hpp" #include "CurveQuadratic.hpp" #include "CurveQuadratic_Impl.hpp" #include <utilities/idd/IddFactory.hxx> #include <utilities/idd/IddEnums.hxx> #include <utilities/idd/OS_Generator_FuelCell_AirSupply_FieldEnums.hxx> #include "../utilities/idf/WorkspaceExtensibleGroup.hpp" #include "../utilities/units/Unit.hpp" #include "../utilities/core/Assert.hpp" namespace openstudio { namespace model { namespace detail { GeneratorFuelCellAirSupply_Impl::GeneratorFuelCellAirSupply_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle) : ModelObject_Impl(idfObject,model,keepHandle) { OS_ASSERT(idfObject.iddObject().type() == GeneratorFuelCellAirSupply::iddObjectType()); } GeneratorFuelCellAirSupply_Impl::GeneratorFuelCellAirSupply_Impl(const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle) : ModelObject_Impl(other,model,keepHandle) { OS_ASSERT(other.iddObject().type() == GeneratorFuelCellAirSupply::iddObjectType()); } GeneratorFuelCellAirSupply_Impl::GeneratorFuelCellAirSupply_Impl(const GeneratorFuelCellAirSupply_Impl& other, Model_Impl* model, bool keepHandle) : ModelObject_Impl(other,model,keepHandle) {} const std::vector<std::string>& GeneratorFuelCellAirSupply_Impl::outputVariableNames() const { static std::vector<std::string> result; return result; } IddObjectType GeneratorFuelCellAirSupply_Impl::iddObjectType() const { return GeneratorFuelCellAirSupply::iddObjectType(); } // This will clone both the GeneratorFuelCellAirSupply and its linked GeneratorFuelCell // and will return a reference to the GeneratorFuelCellAirSupply ModelObject GeneratorFuelCellAirSupply_Impl::clone(Model model) const { // We call the parent generator's Clone method which will clone both the fuelCell and airSupply GeneratorFuelCell fs = fuelCell(); GeneratorFuelCell fsClone = fs.clone(model).cast<GeneratorFuelCell>(); // We get the clone of the parent generator's airSupply so we can return that GeneratorFuelCellAirSupply hxClone = fsClone.airSupply(); return hxClone; } std::vector<IddObjectType> GeneratorFuelCellAirSupply_Impl::allowableChildTypes() const { std::vector<IddObjectType> result; result.push_back(IddObjectType::OS_Curve_Cubic); result.push_back(IddObjectType::OS_Curve_Quadratic); return result; } // Returns the children object std::vector<ModelObject> GeneratorFuelCellAirSupply_Impl::children() const { std::vector<ModelObject> result; boost::optional<CurveQuadratic> curveQ; boost::optional<CurveCubic> curveC; if ( (curveC = blowerPowerCurve()) ) { result.push_back(curveC.get()); } if ( (curveQ = airRateFunctionofElectricPowerCurve()) ) { result.push_back(curveQ.get()); } if ( (curveQ = airRateFunctionofFuelRateCurve()) ) { result.push_back(curveQ.get()); } return result; } // Get the parent GeneratorFuelCell GeneratorFuelCell GeneratorFuelCellAirSupply_Impl::fuelCell() const { boost::optional<GeneratorFuelCell> value; for (const GeneratorFuelCell& fc : this->model().getConcreteModelObjects<GeneratorFuelCell>()) { if (boost::optional<GeneratorFuelCellAirSupply> fcHX = fc.airSupply()) { if (fcHX->handle() == this->handle()) { value = fc; } } } OS_ASSERT(value); return value.get(); } boost::optional<Node> GeneratorFuelCellAirSupply_Impl::airInletNode() const { return getObject<ModelObject>().getModelObjectTarget<Node>(OS_Generator_FuelCell_AirSupplyFields::AirInletNodeName); } boost::optional<CurveCubic> GeneratorFuelCellAirSupply_Impl::blowerPowerCurve() const { return getObject<ModelObject>().getModelObjectTarget<CurveCubic>(OS_Generator_FuelCell_AirSupplyFields::BlowerPowerCurveName); } double GeneratorFuelCellAirSupply_Impl::blowerHeatLossFactor() const { boost::optional<double> value = getDouble(OS_Generator_FuelCell_AirSupplyFields::BlowerHeatLossFactor, true); if (!value) { LOG_AND_THROW(" does not have blowerHeatLossFactor."); } return value.get(); } std::string GeneratorFuelCellAirSupply_Impl::airSupplyRateCalculationMode() const { boost::optional<std::string> value = getString(OS_Generator_FuelCell_AirSupplyFields::AirSupplyRateCalculationMode,true); OS_ASSERT(value); return value.get(); } boost::optional<double> GeneratorFuelCellAirSupply_Impl::stoichiometricRatio() const { boost::optional<double> value = getDouble(OS_Generator_FuelCell_AirSupplyFields::StoichiometricRatio, true); return value; } boost::optional<CurveQuadratic> GeneratorFuelCellAirSupply_Impl::airRateFunctionofElectricPowerCurve() const { return getObject<ModelObject>().getModelObjectTarget<CurveQuadratic>(OS_Generator_FuelCell_AirSupplyFields::AirRateFunctionofElectricPowerCurveName); } boost::optional<double> GeneratorFuelCellAirSupply_Impl::airRateAirTemperatureCoefficient() const { boost::optional<double> value = getDouble(OS_Generator_FuelCell_AirSupplyFields::AirRateAirTemperatureCoefficient, true); return value; } boost::optional<CurveQuadratic> GeneratorFuelCellAirSupply_Impl::airRateFunctionofFuelRateCurve() const { return getObject<ModelObject>().getModelObjectTarget<CurveQuadratic>(OS_Generator_FuelCell_AirSupplyFields::AirRateFunctionofFuelRateCurveName); } std::string GeneratorFuelCellAirSupply_Impl::airIntakeHeatRecoveryMode() const { boost::optional<std::string> value = getString(OS_Generator_FuelCell_AirSupplyFields::AirIntakeHeatRecoveryMode,true); OS_ASSERT(value); return value.get(); } std::string GeneratorFuelCellAirSupply_Impl::airSupplyConstituentMode() const { boost::optional<std::string> value = getString(OS_Generator_FuelCell_AirSupplyFields::AirSupplyConstituentMode,true); OS_ASSERT(value); return value.get(); } boost::optional<unsigned int> GeneratorFuelCellAirSupply_Impl::numberofUserDefinedConstituents() const { boost::optional<unsigned int> value; boost::optional<int> temp = getInt(OS_Generator_FuelCell_AirSupplyFields::NumberofUserDefinedConstituents, true); if (temp) { if (temp >= 0) { value = temp; } } return value; } bool GeneratorFuelCellAirSupply_Impl::setAirInletNode(const Node& connection) { bool result = setPointer(OS_Generator_FuelCell_AirSupplyFields::AirInletNodeName, connection.handle()); return result; } void GeneratorFuelCellAirSupply_Impl::resetAirInletNode() { bool result = setString(OS_Generator_FuelCell_AirSupplyFields::AirInletNodeName, ""); OS_ASSERT(result); } bool GeneratorFuelCellAirSupply_Impl::setBlowerPowerCurve(const CurveCubic& cubicCurves) { bool result = setPointer(OS_Generator_FuelCell_AirSupplyFields::BlowerPowerCurveName, cubicCurves.handle()); return result; } void GeneratorFuelCellAirSupply_Impl::resetBlowerPowerCurve() { bool result = setString(OS_Generator_FuelCell_AirSupplyFields::BlowerPowerCurveName, ""); OS_ASSERT(result); } bool GeneratorFuelCellAirSupply_Impl::setBlowerHeatLossFactor(double blowerHeatLossFactor) { bool result = setDouble(OS_Generator_FuelCell_AirSupplyFields::BlowerHeatLossFactor, blowerHeatLossFactor); return result; } void GeneratorFuelCellAirSupply_Impl::resetBlowerHeatLossFactor() { bool result = setDouble(OS_Generator_FuelCell_AirSupplyFields::BlowerHeatLossFactor, 0); OS_ASSERT(result); } bool GeneratorFuelCellAirSupply_Impl::setAirSupplyRateCalculationMode(const std::string& airSupplyRateCalculationMode) { bool result = setString(OS_Generator_FuelCell_AirSupplyFields::AirSupplyRateCalculationMode, airSupplyRateCalculationMode); return result; } bool GeneratorFuelCellAirSupply_Impl::setStoichiometricRatio(double stoichiometricRatio) { bool result = setDouble(OS_Generator_FuelCell_AirSupplyFields::StoichiometricRatio, stoichiometricRatio); OS_ASSERT(result); return result; } void GeneratorFuelCellAirSupply_Impl::resetStoichiometricRatio() { bool result = setString(OS_Generator_FuelCell_AirSupplyFields::StoichiometricRatio, ""); OS_ASSERT(result); } bool GeneratorFuelCellAirSupply_Impl::setAirRateFunctionofElectricPowerCurve(const CurveQuadratic& quadraticCurves) { bool result = setPointer(OS_Generator_FuelCell_AirSupplyFields::AirRateFunctionofElectricPowerCurveName, quadraticCurves.handle()); return result; } void GeneratorFuelCellAirSupply_Impl::resetAirRateFunctionofElectricPowerCurve() { bool result = setString(OS_Generator_FuelCell_AirSupplyFields::AirRateFunctionofElectricPowerCurveName, ""); OS_ASSERT(result); } bool GeneratorFuelCellAirSupply_Impl::setAirRateAirTemperatureCoefficient(double airRateAirTemperatureCoefficient) { bool result = setDouble(OS_Generator_FuelCell_AirSupplyFields::AirRateAirTemperatureCoefficient, airRateAirTemperatureCoefficient); OS_ASSERT(result); return result; } void GeneratorFuelCellAirSupply_Impl::resetAirRateAirTemperatureCoefficient() { bool result = setDouble(OS_Generator_FuelCell_AirSupplyFields::AirRateAirTemperatureCoefficient, 0); OS_ASSERT(result); } bool GeneratorFuelCellAirSupply_Impl::setAirRateFunctionofFuelRateCurve(const CurveQuadratic& quadraticCurves) { bool result = setPointer(OS_Generator_FuelCell_AirSupplyFields::AirRateFunctionofFuelRateCurveName, quadraticCurves.handle()); return result; } void GeneratorFuelCellAirSupply_Impl::resetAirRateFunctionofFuelRateCurve() { bool result = setString(OS_Generator_FuelCell_AirSupplyFields::AirRateFunctionofFuelRateCurveName, ""); OS_ASSERT(result); } bool GeneratorFuelCellAirSupply_Impl::setAirIntakeHeatRecoveryMode(const std::string& airIntakeHeatRecoveryMode) { bool result = setString(OS_Generator_FuelCell_AirSupplyFields::AirIntakeHeatRecoveryMode, airIntakeHeatRecoveryMode); return result; } bool GeneratorFuelCellAirSupply_Impl::setAirSupplyConstituentMode(const std::string& airSupplyConstituentMode) { bool result = setString(OS_Generator_FuelCell_AirSupplyFields::AirSupplyConstituentMode, airSupplyConstituentMode); return result; } bool GeneratorFuelCellAirSupply_Impl::setNumberofUserDefinedConstituents(unsigned int numberofUserDefinedConstituents) { bool result = setInt(OS_Generator_FuelCell_AirSupplyFields::NumberofUserDefinedConstituents, numberofUserDefinedConstituents); return result; } void GeneratorFuelCellAirSupply_Impl::resetNumberofUserDefinedConstituents() { bool result = setInt(OS_Generator_FuelCell_AirSupplyFields::NumberofUserDefinedConstituents, 0); OS_ASSERT(result); } bool GeneratorFuelCellAirSupply_Impl::addConstituent(std::string name, double molarFraction) { WorkspaceExtensibleGroup eg = getObject<ModelObject>().pushExtensibleGroup().cast<WorkspaceExtensibleGroup>(); bool temp = false; bool ok = false; unsigned int num; if (numberofUserDefinedConstituents()) { num = numberofUserDefinedConstituents().get(); } else { num = 0; } //max number of constituents is 5 if (num < 5) { temp = eg.setString(OS_Generator_FuelCell_AirSupplyExtensibleFields::ConstituentName, name); ok = eg.setDouble(OS_Generator_FuelCell_AirSupplyExtensibleFields::MolarFraction, molarFraction); } if (temp && ok) { setNumberofUserDefinedConstituents(num + 1); } else { getObject<ModelObject>().eraseExtensibleGroup(eg.groupIndex()); } return temp; } void GeneratorFuelCellAirSupply_Impl::removeConstituent(unsigned groupIndex) { unsigned numberofDataPairs = numExtensibleGroups(); if (groupIndex < numberofDataPairs) { unsigned int num; getObject<ModelObject>().eraseExtensibleGroup(groupIndex); if (numberofUserDefinedConstituents()) { num = numberofUserDefinedConstituents().get(); setNumberofUserDefinedConstituents(num - 1); } else { setNumberofUserDefinedConstituents(numExtensibleGroups()); } } } void GeneratorFuelCellAirSupply_Impl::removeAllConstituents() { getObject<ModelObject>().clearExtensibleGroups(); resetNumberofUserDefinedConstituents(); } std::vector< std::pair<std::string, double> > GeneratorFuelCellAirSupply_Impl::constituents() { std::vector< std::pair<std::string, double> > result; std::vector<IdfExtensibleGroup> groups = extensibleGroups(); for (const auto & group : groups) { boost::optional<std::string> name = group.cast<WorkspaceExtensibleGroup>().getString(OS_Generator_FuelCell_AirSupplyExtensibleFields::ConstituentName); boost::optional<double> molarFraction = group.cast<WorkspaceExtensibleGroup>().getDouble(OS_Generator_FuelCell_AirSupplyExtensibleFields::MolarFraction); if (name && molarFraction) { result.push_back(std::make_pair(name.get(), molarFraction.get())); } } return result; } } // detail GeneratorFuelCellAirSupply::GeneratorFuelCellAirSupply(const Model& model, const Node& airInletNode, const CurveQuadratic& electricPowerCurve, const CurveQuadratic& fuelRateCurve, const CurveCubic& blowerPowerCurve) : ModelObject(GeneratorFuelCellAirSupply::iddObjectType(), model) { OS_ASSERT(getImpl<detail::GeneratorFuelCellAirSupply_Impl>()); bool ok = setAirInletNode(airInletNode); if (!ok) { remove(); LOG_AND_THROW("Unable to set " << briefDescription() << "'s airInletNode to " << airInletNode.briefDescription() << "."); } ok = setBlowerPowerCurve(blowerPowerCurve); if (!ok) { remove(); LOG_AND_THROW("Unable to set " << briefDescription() << "'s blowerPowerCurve to " << blowerPowerCurve.briefDescription() << "."); } setBlowerHeatLossFactor(1.0); setAirSupplyRateCalculationMode("AirRatiobyStoics"); setStoichiometricRatio(1.0); setAirRateFunctionofElectricPowerCurve(electricPowerCurve); setAirRateAirTemperatureCoefficient(0.00283); setAirRateFunctionofFuelRateCurve(fuelRateCurve); setAirIntakeHeatRecoveryMode("NoRecovery"); setAirSupplyConstituentMode("AmbientAir"); setNumberofUserDefinedConstituents(0); } GeneratorFuelCellAirSupply::GeneratorFuelCellAirSupply(const Model& model, const Node& airInletNode, const CurveQuadratic& electricPowerCurve, const CurveQuadratic& fuelRateCurve) : ModelObject(GeneratorFuelCellAirSupply::iddObjectType(), model) { OS_ASSERT(getImpl<detail::GeneratorFuelCellAirSupply_Impl>()); bool ok = setAirInletNode(airInletNode); if (!ok) { remove(); LOG_AND_THROW("Unable to set " << briefDescription() << "'s airInletNode to " << airInletNode.briefDescription() << "."); } CurveCubic curveCubic(model); curveCubic.setCoefficient1Constant(0); curveCubic.setCoefficient2x(0); curveCubic.setCoefficient3xPOW2(0); curveCubic.setCoefficient4xPOW3(0); curveCubic.setMinimumValueofx(-1.0e10); curveCubic.setMaximumValueofx(1.0e10); ok = setBlowerPowerCurve(curveCubic); if (!ok) { remove(); LOG_AND_THROW("Unable to set " << briefDescription() << "'s setBlowerPowerCurve to " << curveCubic.briefDescription() << "."); } setBlowerHeatLossFactor(1.0); setAirSupplyRateCalculationMode("AirRatiobyStoics"); setStoichiometricRatio(1.0); ok = setAirRateFunctionofElectricPowerCurve(electricPowerCurve); if (!ok) { remove(); LOG_AND_THROW("Unable to set " << briefDescription() << "'s electricPowerCurve to " << electricPowerCurve.briefDescription() << "."); } setAirRateAirTemperatureCoefficient(0.00283); ok = setAirRateFunctionofFuelRateCurve(fuelRateCurve); if (!ok) { remove(); LOG_AND_THROW("Unable to set " << briefDescription() << "'s fuelRateCurve to " << fuelRateCurve.briefDescription() << "."); } setAirIntakeHeatRecoveryMode("NoRecovery"); setAirSupplyConstituentMode("AmbientAir"); setNumberofUserDefinedConstituents(0); } GeneratorFuelCellAirSupply::GeneratorFuelCellAirSupply(const Model& model, const Node& airInletNode) : ModelObject(GeneratorFuelCellAirSupply::iddObjectType(), model) { OS_ASSERT(getImpl<detail::GeneratorFuelCellAirSupply_Impl>()); bool ok = setAirInletNode(airInletNode); if (!ok) { remove(); LOG_AND_THROW("Unable to set " << briefDescription() << "'s airInletNode to " << airInletNode.briefDescription() << "."); } CurveCubic curveCubic(model); curveCubic.setCoefficient1Constant(0); curveCubic.setCoefficient2x(0); curveCubic.setCoefficient3xPOW2(0); curveCubic.setCoefficient4xPOW3(0); curveCubic.setMinimumValueofx(-1.0e10); curveCubic.setMaximumValueofx(1.0e10); ok = setBlowerPowerCurve(curveCubic); if (!ok) { remove(); LOG_AND_THROW("Unable to set " << briefDescription() << "'s setBlowerPowerCurve to " << curveCubic.briefDescription() << "."); } setBlowerHeatLossFactor(1.0); setAirSupplyRateCalculationMode("AirRatiobyStoics"); setStoichiometricRatio(1.0); setAirRateAirTemperatureCoefficient(0.00283); setAirIntakeHeatRecoveryMode("NoRecovery"); setAirSupplyConstituentMode("AmbientAir"); setNumberofUserDefinedConstituents(0); } GeneratorFuelCellAirSupply::GeneratorFuelCellAirSupply(const Model& model) : ModelObject(GeneratorFuelCellAirSupply::iddObjectType(),model) { OS_ASSERT(getImpl<detail::GeneratorFuelCellAirSupply_Impl>()); //setAirInletNode(); //A new OA node is created on Forward Translation if one is not set, so this method can be left blank CurveCubic curveCubic(model); curveCubic.setCoefficient1Constant(0); curveCubic.setCoefficient2x(0); curveCubic.setCoefficient3xPOW2(0); curveCubic.setCoefficient4xPOW3(0); curveCubic.setMinimumValueofx(-1.0e10); curveCubic.setMaximumValueofx(1.0e10); curveCubic.setName("Blower Power Curve"); bool ok = setBlowerPowerCurve(curveCubic); if (!ok) { remove(); LOG_AND_THROW("Unable to set " << briefDescription() << "'s setBlowerPowerCurve to " << curveCubic.briefDescription() << "."); } setBlowerHeatLossFactor(1.0); setAirSupplyRateCalculationMode("AirRatiobyStoics"); setStoichiometricRatio(1.0); setAirRateAirTemperatureCoefficient(0.00283); setAirIntakeHeatRecoveryMode("NoRecovery"); setAirSupplyConstituentMode("AmbientAir"); setNumberofUserDefinedConstituents(0); CurveQuadratic curveQ(model); curveQ.setCoefficient1Constant(1.50976E-3); curveQ.setCoefficient2x(-7.76656E-7); curveQ.setCoefficient3xPOW2(1.30317E-10); curveQ.setMinimumValueofx(-1.0e10); curveQ.setMaximumValueofx(1.0e10); curveQ.setName("Air Rate Function of Electric Power Curve"); ok = setAirRateFunctionofElectricPowerCurve(curveQ); if (!ok) { remove(); LOG_AND_THROW("Unable to set " << briefDescription() << "'s setBlowerPowerCurve to " << curveQ.briefDescription() << "."); } CurveQuadratic curveQ2(model); curveQ2.setMinimumValueofx(-1.0e10); curveQ2.setMaximumValueofx(1.0e10); curveQ2.setCoefficient1Constant(0); curveQ2.setCoefficient2x(0); curveQ2.setCoefficient3xPOW2(0); curveQ2.setName("Air Rate Function of Fuel Rate Curve"); ok = setAirRateFunctionofFuelRateCurve(curveQ2); if (!ok) { remove(); LOG_AND_THROW("Unable to set " << briefDescription() << "'s setBlowerPowerCurve to " << curveQ2.briefDescription() << "."); } } IddObjectType GeneratorFuelCellAirSupply::iddObjectType() { return IddObjectType(IddObjectType::OS_Generator_FuelCell_AirSupply); } bool GeneratorFuelCellAirSupply::addConstituent(std::string name, double molarFraction) { return getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->addConstituent(name, molarFraction); } void GeneratorFuelCellAirSupply::removeConstituent(int groupIndex) { return getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->removeConstituent(groupIndex); } void GeneratorFuelCellAirSupply::removeAllConstituents() { return getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->removeAllConstituents(); } std::vector< std::pair<std::string, double> > GeneratorFuelCellAirSupply::constituents() { return getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->constituents(); } std::vector<std::string> GeneratorFuelCellAirSupply::airSupplyRateCalculationModeValues() { return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(), OS_Generator_FuelCell_AirSupplyFields::AirSupplyRateCalculationMode); } std::vector<std::string> GeneratorFuelCellAirSupply::airIntakeHeatRecoveryModeValues() { return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(), OS_Generator_FuelCell_AirSupplyFields::AirIntakeHeatRecoveryMode); } std::vector<std::string> GeneratorFuelCellAirSupply::airSupplyConstituentModeValues() { return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(), OS_Generator_FuelCell_AirSupplyFields::AirSupplyConstituentMode); } boost::optional<Node> GeneratorFuelCellAirSupply::airInletNode() const { return getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->airInletNode(); } boost::optional<CurveCubic> GeneratorFuelCellAirSupply::blowerPowerCurve() const { return getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->blowerPowerCurve(); } double GeneratorFuelCellAirSupply::blowerHeatLossFactor() const { return getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->blowerHeatLossFactor(); } std::string GeneratorFuelCellAirSupply::airSupplyRateCalculationMode() const { return getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->airSupplyRateCalculationMode(); } boost::optional<double> GeneratorFuelCellAirSupply::stoichiometricRatio() const { return getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->stoichiometricRatio(); } boost::optional<CurveQuadratic> GeneratorFuelCellAirSupply::airRateFunctionofElectricPowerCurve() const { return getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->airRateFunctionofElectricPowerCurve(); } boost::optional<double> GeneratorFuelCellAirSupply::airRateAirTemperatureCoefficient() const { return getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->airRateAirTemperatureCoefficient(); } boost::optional<CurveQuadratic> GeneratorFuelCellAirSupply::airRateFunctionofFuelRateCurve() const { return getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->airRateFunctionofFuelRateCurve(); } std::string GeneratorFuelCellAirSupply::airIntakeHeatRecoveryMode() const { return getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->airIntakeHeatRecoveryMode(); } std::string GeneratorFuelCellAirSupply::airSupplyConstituentMode() const { return getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->airSupplyConstituentMode(); } boost::optional<unsigned int> GeneratorFuelCellAirSupply::numberofUserDefinedConstituents() const { return getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->numberofUserDefinedConstituents(); } bool GeneratorFuelCellAirSupply::setAirInletNode(const Node& connection) { return getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->setAirInletNode(connection); } void GeneratorFuelCellAirSupply::resetAirInletNode() { getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->resetAirInletNode(); } bool GeneratorFuelCellAirSupply::setBlowerPowerCurve(const CurveCubic& cubicCurves) { return getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->setBlowerPowerCurve(cubicCurves); } void GeneratorFuelCellAirSupply::resetBlowerPowerCurve() { getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->resetBlowerPowerCurve(); } bool GeneratorFuelCellAirSupply::setBlowerHeatLossFactor(double blowerHeatLossFactor) { return getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->setBlowerHeatLossFactor(blowerHeatLossFactor); } void GeneratorFuelCellAirSupply::resetBlowerHeatLossFactor() { getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->resetBlowerHeatLossFactor(); } bool GeneratorFuelCellAirSupply::setAirSupplyRateCalculationMode(const std::string& airSupplyRateCalculationMode) { return getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->setAirSupplyRateCalculationMode(airSupplyRateCalculationMode); } bool GeneratorFuelCellAirSupply::setStoichiometricRatio(double stoichiometricRatio) { return getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->setStoichiometricRatio(stoichiometricRatio); } void GeneratorFuelCellAirSupply::resetStoichiometricRatio() { getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->resetStoichiometricRatio(); } bool GeneratorFuelCellAirSupply::setAirRateFunctionofElectricPowerCurve(const CurveQuadratic& quadraticCurves) { return getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->setAirRateFunctionofElectricPowerCurve(quadraticCurves); } void GeneratorFuelCellAirSupply::resetAirRateFunctionofElectricPowerCurve() { getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->resetAirRateFunctionofElectricPowerCurve(); } bool GeneratorFuelCellAirSupply::setAirRateAirTemperatureCoefficient(double airRateAirTemperatureCoefficient) { return getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->setAirRateAirTemperatureCoefficient(airRateAirTemperatureCoefficient); } void GeneratorFuelCellAirSupply::resetAirRateAirTemperatureCoefficient() { getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->resetAirRateAirTemperatureCoefficient(); } bool GeneratorFuelCellAirSupply::setAirRateFunctionofFuelRateCurve(const CurveQuadratic& quadraticCurves) { return getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->setAirRateFunctionofFuelRateCurve(quadraticCurves); } void GeneratorFuelCellAirSupply::resetAirRateFunctionofFuelRateCurve() { getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->resetAirRateFunctionofFuelRateCurve(); } bool GeneratorFuelCellAirSupply::setAirIntakeHeatRecoveryMode(const std::string& airIntakeHeatRecoveryMode) { return getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->setAirIntakeHeatRecoveryMode(airIntakeHeatRecoveryMode); } bool GeneratorFuelCellAirSupply::setAirSupplyConstituentMode(const std::string& airSupplyConstituentMode) { return getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->setAirSupplyConstituentMode(airSupplyConstituentMode); } bool GeneratorFuelCellAirSupply::setNumberofUserDefinedConstituents(unsigned int numberofUserDefinedConstituents) { return getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->setNumberofUserDefinedConstituents(numberofUserDefinedConstituents); } void GeneratorFuelCellAirSupply::resetNumberofUserDefinedConstituents() { getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->resetNumberofUserDefinedConstituents(); } GeneratorFuelCell GeneratorFuelCellAirSupply::fuelCell() const { return getImpl<detail::GeneratorFuelCellAirSupply_Impl>()->fuelCell(); } /// @cond GeneratorFuelCellAirSupply::GeneratorFuelCellAirSupply(std::shared_ptr<detail::GeneratorFuelCellAirSupply_Impl> impl) : ModelObject(std::move(impl)) {} /// @endcond } // model } // openstudio
42.248957
159
0.757119
[ "object", "vector", "model" ]
fc73601fb6c8b3b48709611f7455484b3d888ed3
7,575
cc
C++
content/browser/renderer_host/render_widget_host_view_win_browsertest.cc
kurli/chromium-crosswalk
f4c5d15d49d02b74eb834325e4dff50b16b53243
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/renderer_host/render_widget_host_view_win_browsertest.cc
kurli/chromium-crosswalk
f4c5d15d49d02b74eb834325e4dff50b16b53243
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/renderer_host/render_widget_host_view_win_browsertest.cc
kurli/chromium-crosswalk
f4c5d15d49d02b74eb834325e4dff50b16b53243
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <vector> #include "base/command_line.h" #include "base/win/metro.h" #include "content/browser/renderer_host/render_widget_host_view_win.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "content/public/common/content_switches.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_utils.h" #include "content/shell/browser/shell.h" #include "content/test/content_browser_test.h" #include "content/test/content_browser_test_utils.h" #include "ui/base/ime/composition_text.h" #include "ui/base/ime/text_input_type.h" #include "ui/base/ime/win/imm32_manager.h" #include "ui/base/ime/win/mock_tsf_bridge.h" #include "ui/base/ime/win/tsf_bridge.h" namespace content { namespace { class MockIMM32Manager : public ui::IMM32Manager { public: MockIMM32Manager() : window_handle_(NULL), input_mode_(ui::TEXT_INPUT_MODE_DEFAULT), call_count_(0) { } virtual ~MockIMM32Manager() {} virtual void SetTextInputMode(HWND window_handle, ui::TextInputMode input_mode) OVERRIDE { ++call_count_; window_handle_ = window_handle; input_mode_ = input_mode; } void Reset() { window_handle_ = NULL; input_mode_ = ui::TEXT_INPUT_MODE_DEFAULT; call_count_ = 0; } HWND window_handle() const { return window_handle_; } ui::TextInputMode input_mode() const { return input_mode_; } size_t call_count() const { return call_count_; } private: HWND window_handle_; ui::TextInputMode input_mode_; size_t call_count_; DISALLOW_COPY_AND_ASSIGN(MockIMM32Manager); }; // Testing class serving initialized RenderWidgetHostViewWin instance; class RenderWidgetHostViewWinBrowserTest : public ContentBrowserTest { public: RenderWidgetHostViewWinBrowserTest() {} virtual void SetUpOnMainThread() OVERRIDE { ContentBrowserTest::SetUpOnMainThread(); NavigateToURL(shell(), GURL("about:blank")); view_ = static_cast<RenderWidgetHostViewWin*>( RenderWidgetHostViewPort::FromRWHV( shell()->web_contents()->GetRenderViewHost()->GetView())); CHECK(view_); } protected: RenderWidgetHostViewWin* view_; }; } // namespace IN_PROC_BROWSER_TEST_F(RenderWidgetHostViewWinBrowserTest, TextInputTypeChanged) { ASSERT_TRUE(view_->m_hWnd); MockIMM32Manager* mock = new MockIMM32Manager(); mock->Reset(); view_->imm32_manager_.reset(mock); view_->TextInputTypeChanged(ui::TEXT_INPUT_TYPE_NONE, ui::TEXT_INPUT_MODE_EMAIL, false); EXPECT_EQ(1, mock->call_count()); EXPECT_EQ(view_->m_hWnd, mock->window_handle()); EXPECT_EQ(ui::TEXT_INPUT_MODE_EMAIL, mock->input_mode()); mock->Reset(); view_->TextInputTypeChanged(ui::TEXT_INPUT_TYPE_NONE, ui::TEXT_INPUT_MODE_EMAIL, false); EXPECT_EQ(0, mock->call_count()); } class RenderWidgetHostViewWinTSFTest : public ContentBrowserTest { public: RenderWidgetHostViewWinTSFTest() {} virtual void SetUpCommandLine(CommandLine* command_line) { command_line->AppendSwitch(switches::kEnableTextServicesFramework); } }; // crbug.com/151798 IN_PROC_BROWSER_TEST_F(RenderWidgetHostViewWinTSFTest, DISABLED_SwichToPasswordField) { ui::MockTSFBridge mock_bridge; ui::TSFBridge* old_bridge = ui::TSFBridge::ReplaceForTesting(&mock_bridge); GURL test_url = GetTestUrl("textinput", "ime_enable_disable_test.html"); NavigateToURL(shell(), test_url); WaitForLoadStop(shell()->web_contents()); RunAllPendingInMessageLoop(); EXPECT_EQ(ui::TEXT_INPUT_TYPE_NONE, mock_bridge.latest_text_iput_type()); // Focus to the text field, the IME should be enabled. bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( shell()->web_contents(), "window.domAutomationController.send(text01_focus());", &success)); EXPECT_TRUE(success); WaitForLoadStop(shell()->web_contents()); RunAllPendingInMessageLoop(); EXPECT_EQ(ui::TEXT_INPUT_TYPE_TEXT, mock_bridge.latest_text_iput_type()); // Focus to the password field, the IME should be disabled. success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( shell()->web_contents(), "window.domAutomationController.send(password02_focus());", &success)); EXPECT_TRUE(success); WaitForLoadStop(shell()->web_contents()); RunAllPendingInMessageLoop(); EXPECT_EQ(ui::TEXT_INPUT_TYPE_PASSWORD, mock_bridge.latest_text_iput_type()); ui::TSFBridge::ReplaceForTesting(old_bridge); } // crbug.com/151798 IN_PROC_BROWSER_TEST_F(RenderWidgetHostViewWinTSFTest, DISABLED_SwitchToSameField) { ui::MockTSFBridge mock_bridge; ui::TSFBridge* old_bridge = ui::TSFBridge::ReplaceForTesting(&mock_bridge); GURL test_url = GetTestUrl("textinput", "ime_enable_disable_test.html"); NavigateToURL(shell(), test_url); WaitForLoadStop(shell()->web_contents()); RunAllPendingInMessageLoop(); EXPECT_EQ(ui::TEXT_INPUT_TYPE_NONE, mock_bridge.latest_text_iput_type()); // Focus to the text field, the IME should be enabled. bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( shell()->web_contents(), "window.domAutomationController.send(text01_focus());", &success)); EXPECT_TRUE(success); WaitForLoadStop(shell()->web_contents()); RunAllPendingInMessageLoop(); EXPECT_EQ(ui::TEXT_INPUT_TYPE_TEXT, mock_bridge.latest_text_iput_type()); // Focus to another text field, the IME should be enabled. success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( shell()->web_contents(), "window.domAutomationController.send(text02_focus());", &success)); EXPECT_TRUE(success); WaitForLoadStop(shell()->web_contents()); RunAllPendingInMessageLoop(); EXPECT_EQ(ui::TEXT_INPUT_TYPE_TEXT, mock_bridge.latest_text_iput_type()); ui::TSFBridge::ReplaceForTesting(old_bridge); } // crbug.com/151798 IN_PROC_BROWSER_TEST_F(RenderWidgetHostViewWinTSFTest, DISABLED_SwitchToSamePasswordField) { ui::MockTSFBridge mock_bridge; ui::TSFBridge* old_bridge = ui::TSFBridge::ReplaceForTesting(&mock_bridge); GURL test_url = GetTestUrl("textinput", "ime_enable_disable_test.html"); NavigateToURL(shell(), test_url); WaitForLoadStop(shell()->web_contents()); RunAllPendingInMessageLoop(); EXPECT_EQ(ui::TEXT_INPUT_TYPE_NONE, mock_bridge.latest_text_iput_type()); // Focus to the password field, the IME should be disabled. bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( shell()->web_contents(), "window.domAutomationController.send(password01_focus());", &success)); EXPECT_TRUE(success); WaitForLoadStop(shell()->web_contents()); RunAllPendingInMessageLoop(); EXPECT_EQ(ui::TEXT_INPUT_TYPE_PASSWORD, mock_bridge.latest_text_iput_type()); // Focus to the another password field, the IME should be disabled. success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( shell()->web_contents(), "window.domAutomationController.send(password02_focus());", &success)); EXPECT_TRUE(success); WaitForLoadStop(shell()->web_contents()); RunAllPendingInMessageLoop(); EXPECT_EQ(ui::TEXT_INPUT_TYPE_PASSWORD, mock_bridge.latest_text_iput_type()); ui::TSFBridge::ReplaceForTesting(old_bridge); } } // namespace content
33.370044
79
0.738746
[ "vector" ]
fc8a72f750bc67e19b8fa7a56e3f1d6ba8b43bd5
2,436
cpp
C++
jansson/JsonAuto.cpp
a4lg/OTrP
da3ff451d8adbbefab045cebf1a6b924a8bb2664
[ "MIT" ]
null
null
null
jansson/JsonAuto.cpp
a4lg/OTrP
da3ff451d8adbbefab045cebf1a6b924a8bb2664
[ "MIT" ]
null
null
null
jansson/JsonAuto.cpp
a4lg/OTrP
da3ff451d8adbbefab045cebf1a6b924a8bb2664
[ "MIT" ]
null
null
null
/* Copyright (c) Microsoft Corporation. All Rights Reserved. */ #include "JsonAuto.h" JsonAuto::JsonAuto() { ptr = NULL; } JsonAuto::JsonAuto(const JsonAuto& value) { ptr = json_incref(value); } JsonAuto::JsonAuto(json_t* value, bool donateReference) { if (donateReference || !value) { ptr = value; } else { ptr = json_incref(value); } } JsonAuto::~JsonAuto() { if (ptr != NULL) { json_decref(ptr); } } json_t* JsonAuto::AddStringToObject(const char* name, const char* value) { JsonAuto str = json_string(value); if (str == NULL) { return NULL; } if (json_object_set(ptr, name, str)) { return NULL; } return str; } json_t* JsonAuto::AddIntegerToObject(const char* name, int value) { JsonAuto i = json_integer(value); if (i == NULL) { return NULL; } if (json_object_set(ptr, name, i)) { return NULL; } return i; } json_t* JsonAuto::AddObjectToObject(const char* name, json_t* obj) { if (obj == nullptr) { JsonAuto object = json_object(); if (object == NULL) { return NULL; } if (json_object_set(ptr, name, object)) { return NULL; } return object; } else { if (json_object_set(ptr, name, obj)) { return NULL; } return obj; } } json_t* JsonAuto::AddArrayToObject(const char* name) { JsonAuto object = json_array(); if (object == NULL) { return NULL; } if (json_object_set(ptr, name, object)) { return NULL; } return object; } json_t* JsonAuto::AddObjectToArray() { JsonAuto object = json_object(); if (object == NULL) { return NULL; } if (json_array_append(ptr, object)) { return NULL; } return object; } json_t* JsonAuto::AddIntegerToArray(int value) { JsonAuto i = json_integer(value); if (i == NULL) { return NULL; } if (json_array_append(ptr, i)) { return NULL; } return i; } json_t* JsonAuto::AddStringToArray(const char* value) { JsonAuto str = json_string(value); if (str == NULL) { return NULL; } if (json_array_append(ptr, str)) { return NULL; } return str; } json_t* JsonAuto::Detach(void) { json_t* obj = ptr; ptr = NULL; return obj; } void JsonAuto::Attach(json_t* obj) { ptr = obj; }
19.967213
74
0.569787
[ "object" ]
fc8ba2d750654ea745c2f6141973ffdd0ce7be45
11,732
cpp
C++
brds/brds~.cpp
TheTechnobear/Mi4Pd
f4aa6e936347a3952c928b925a03731331d1a627
[ "MIT" ]
74
2017-08-30T06:18:01.000Z
2022-03-15T19:54:33.000Z
brds/brds~.cpp
TheTechnobear/TB_puredata
f4aa6e936347a3952c928b925a03731331d1a627
[ "MIT" ]
15
2018-03-08T23:37:19.000Z
2022-01-17T09:49:38.000Z
brds/brds~.cpp
TheTechnobear/Mi4Pd
f4aa6e936347a3952c928b925a03731331d1a627
[ "MIT" ]
15
2017-10-18T04:56:06.000Z
2022-01-17T08:22:46.000Z
#include "m_pd.h" //IMPROVE - inlets //IMPROVE - variable buffer size #include <algorithm> #include "braids/macro_oscillator.h" #include "braids/envelope.h" #include "braids/vco_jitter_source.h" // TOOD // add parameters // trigger handling // sync handling // for signature_waveshaper, need abs inline int16_t abs(int16_t x) { return x <0.0f ? -x : x;} #include "braids/signature_waveshaper.h" static t_class *brds_tilde_class; inline float constrain(float v, float vMin, float vMax) { return std::max<float>(vMin,std::min<float>(vMax, v)); } inline int constrain(int v, int vMin, int vMax) { return std::max<int>(vMin,std::min<int>(vMax, v)); } typedef struct _brds_tilde { t_object x_obj; t_float f_dummy; t_float f_shape; t_float f_pitch; t_float f_trig; t_float f_fm; t_float f_modulation; t_float f_colour; t_float f_timbre; t_float f_ad_attack; t_float f_ad_decay; t_float f_ad_mod_vca; t_float f_ad_mod_timbre; t_float f_ad_mod_colour; t_float f_ad_mod_pitch; t_float f_ad_mod_fm; t_float f_paques; t_float f_transposition; t_float f_auto_trig; t_float f_meta_modulation; t_float f_vco_drift; t_float f_vco_flatten; t_float f_fm_cv_offset; // CLASS_MAINSIGNALIN = in_sync; t_inlet* x_in_pitch; t_inlet* x_in_shape; t_outlet* x_out; t_outlet* x_out_shape; float pitch_offset=0.0f; braids::MacroOscillator osc; braids::Envelope envelope; braids::SignatureWaveshaper ws; braids::VcoJitterSource jitter_source; int16_t previous_pitch; int16_t previous_shape; uint16_t gain_lp; bool trigger_detected_flag; bool trigger_flag; uint16_t trigger_delay; t_int block_size; t_int block_count; t_int last_n; t_int buf_size; uint8_t* sync_buf; int16_t* outint_buf; } t_brds_tilde; //define pure data methods extern "C" { t_int* brds_tilde_render(t_int *w); void brds_tilde_dsp(t_brds_tilde *x, t_signal **sp); void brds_tilde_free(t_brds_tilde *x); void* brds_tilde_new(t_floatarg f); void brds_tilde_setup(void); void brds_tilde_pitch(t_brds_tilde *x, t_floatarg f); void brds_tilde_shape(t_brds_tilde *x, t_floatarg f); void brds_tilde_colour(t_brds_tilde *x, t_floatarg f); void brds_tilde_timbre(t_brds_tilde *x, t_floatarg f); void brds_tilde_trigger(t_brds_tilde *x, t_floatarg f); } static const char *algo_values[] = { "CSAW", "/\\-_", "//-_", "FOLD", "uuuu", "SUB-", "SUB/", "SYN-", "SYN/", "//x3", "-_x3", "/\\x3", "SIx3", "RING", "////", "//uu", "TOY*", "ZLPF", "ZPKF", "ZBPF", "ZHPF", "VOSM", "VOWL", "VFOF", "HARM", "FM ", "FBFM", "WTFM", "PLUK", "BOWD", "BLOW", "FLUT", "BELL", "DRUM", "KICK", "CYMB", "SNAR", "WTBL", "WMAP", "WLIN", "WTx4", "NOIS", "TWNQ", "CLKN", "CLOU", "PRTC", "QPSK", " ", }; int getShape( float v) { float value = constrain(v, 0.0f, 1.0f); braids::MacroOscillatorShape ishape = static_cast<braids::MacroOscillatorShape>(value* (braids::MACRO_OSC_SHAPE_LAST - 1)); return ishape; } // puredata methods implementation -start t_int* brds_tilde_render(t_int *w) { t_brds_tilde *x = (t_brds_tilde *)(w[1]); t_sample *in_sync = (t_sample *)(w[2]); t_sample *out = (t_sample *)(w[3]); int n = (int)(w[4]); // Determine block size if (n != x->last_n) { // Plaits uses a block size of 24 max if (n > 24) { int block_size = 24; while (n > 24 && n % block_size > 0) { block_size--; } x->block_size = block_size; x->block_count = n / block_size; } else { x->block_size = n; x->block_count = 1; } x->last_n = n; } if(x->block_size> x->buf_size) { x->buf_size = x->block_size; delete [] x->sync_buf; delete [] x->outint_buf; x->sync_buf = new uint8_t[x->buf_size]; x->outint_buf= new int16_t[x->buf_size]; } x->envelope.Update(int(x->f_ad_attack * 8.0f ) , int(x->f_ad_decay * 8.0f) ); uint32_t ad_value = x->envelope.Render(); int ishape = getShape(x->f_shape); if (x->f_paques) { x->osc.set_shape(braids::MACRO_OSC_SHAPE_QUESTION_MARK); } else if (x->f_meta_modulation) { int16_t shape = getShape(x->f_fm); shape -= x->f_fm_cv_offset; if (shape > x->previous_shape + 2 || shape < x->previous_shape - 2) { x->previous_shape = shape; } else { shape = x->previous_shape; } shape = braids::MACRO_OSC_SHAPE_LAST * shape >> 11; shape += ishape; if (shape >= braids::MACRO_OSC_SHAPE_LAST_ACCESSIBLE_FROM_META) { shape = braids::MACRO_OSC_SHAPE_LAST_ACCESSIBLE_FROM_META; } else if (shape <= 0) { shape = 0; } braids::MacroOscillatorShape osc_shape = static_cast<braids::MacroOscillatorShape>(shape); x->osc.set_shape(osc_shape); } else { x->osc.set_shape((braids::MacroOscillatorShape) (ishape)); } int32_t timbre = int(x->f_timbre * 32767.0f); timbre += ad_value * x->f_ad_mod_timbre; int32_t colour = int(x->f_colour * 32767.0f); colour += ad_value * x->f_ad_mod_colour; x->osc.set_parameters(constrain(timbre,0,32767), constrain(colour,0,32767)); int32_t pitch = x->f_pitch + x->pitch_offset; if (! x->f_meta_modulation) { pitch += x->f_fm; } // Check if the pitch has changed to cause an auto-retrigger int32_t pitch_delta = pitch - x->previous_pitch; if (x->f_auto_trig && (pitch_delta >= 0x40 || -pitch_delta >= 0x40)) { x->trigger_detected_flag = true; } x->previous_pitch = pitch; pitch += x->jitter_source.Render(x->f_vco_drift); pitch += ad_value * x->f_ad_mod_pitch; if (pitch > 16383) { pitch = 16383; } else if (pitch < 0) { pitch = 0; } if (x->f_vco_flatten) { pitch = braids::Interpolate88(braids::lut_vco_detune, pitch << 2); } x->osc.set_pitch(pitch + x->f_transposition); if (x->trigger_flag) { x->osc.Strike(); x->envelope.Trigger(braids::ENV_SEGMENT_ATTACK); x->trigger_flag = false; } bool sync_zero = x->f_ad_mod_vca!=0 || x->f_ad_mod_timbre !=0 || x->f_ad_mod_colour !=0 || x->f_ad_mod_fm !=0; for (int j = 0; j < x->block_count; j++) { for (int i = 0; i < x->block_size; i++) { if(sync_zero) x->sync_buf[i] = 0; else x->sync_buf[i] = in_sync[i + (x->block_size * j)] * (1<<8) ; } x->osc.Render(x->sync_buf, x->outint_buf, x->block_size); for (int i = 0; i < x->block_size; i++) { out[i + (x->block_size * j)] = x->outint_buf[i] / 65536.0f ; } } // Copy to DAC buffer with sample rate and bit reduction applied. // int16_t sample = 0; // size_t decimation_factor = decimation_factors[settings.data().sample_rate]; // uint16_t bit_mask = bit_reduction_masks[settings.data().resolution]; // int32_t gain = settings.GetValue(SETTING_AD_VCA) ? ad_value : 65535; // uint16_t signature = settings.signature() * settings.signature() * 4095; // for (size_t i = 0; i < kBlockSize; ++i) { // if ((i % decimation_factor) == 0) { // sample = render_buffer[i] & bit_mask; // } // sample = sample * gain_lp >> 16; // gain_lp += (gain - gain_lp) >> 4; // int16_t warped = ws.Transform(sample); // render_buffer[i] = Mix(sample, warped, signature); // } // bool trigger_detected = gate_input.raised(); // sync_samples[playback_block][current_sample] = trigger_detected; // trigger_detected_flag = trigger_detected_flag | trigger_detected; // if (trigger_detected_flag) { // trigger_delay = settings.trig_delay() // ? (1 << settings.trig_delay()) : 0; // ++trigger_delay; // trigger_detected_flag = false; // } // if (trigger_delay) { // --trigger_delay; // if (trigger_delay == 0) { // trigger_flag = true; // } // } return (w + 5); // # args + 1 } void brds_tilde_dsp(t_brds_tilde *x, t_signal **sp) { // add the perform method, with all signal i/o dsp_add(brds_tilde_render, 4, x, sp[0]->s_vec, sp[1]->s_vec, // signal i/o (clockwise) sp[0]->s_n); } void brds_tilde_free(t_brds_tilde *x) { delete [] x->sync_buf; delete [] x->outint_buf; inlet_free(x->x_in_shape); inlet_free(x->x_in_pitch); outlet_free(x->x_out); outlet_free(x->x_out_shape); } void *brds_tilde_new(t_floatarg f) { t_brds_tilde *x = (t_brds_tilde *) pd_new(brds_tilde_class); x->previous_pitch = 0; x->previous_shape = 0; x->gain_lp = 0; x->trigger_detected_flag = false; x->trigger_flag = false; x->trigger_delay = 0; x->f_dummy = f; x->f_shape = 0.0f; x->f_pitch = 0.0f; x->f_trig = 0.0f; x->f_fm = 0.0f; x->f_modulation = 0.0f; x->f_colour = 0.0f; x->f_timbre = 0.0f; x->f_ad_attack = 0.0f; x->f_ad_decay = 0.0f; x->f_ad_mod_vca = 0.0f; x->f_ad_mod_timbre = 0.0f; x->f_ad_mod_colour = 0.0f; x->f_ad_mod_pitch = 0.0f; x->f_ad_mod_fm = 0.0f; x->f_paques = 0.0f; x->f_transposition = 0.0f; x->f_auto_trig = 0.0f; x->f_meta_modulation = 0.0f; x->f_vco_drift = 0.0f; x->f_vco_flatten = 0.0f; x->f_fm_cv_offset = 0.0f; x->x_in_shape = floatinlet_new (&x->x_obj, &x->f_shape); x->x_in_pitch = floatinlet_new (&x->x_obj, &x->f_pitch); x->x_out = outlet_new(&x->x_obj, &s_signal); x->x_out_shape = outlet_new(&x->x_obj, &s_symbol); // plaits is limited to block size < 24, // so this should never be need to increase x->buf_size = 48; x->sync_buf = new uint8_t[x->buf_size]; x->outint_buf= new int16_t[x->buf_size]; if(sys_getsr()!=48000.0f) { post("brds~.pd is designed for 96k, not %f, approximating pitch", sys_getsr()); if(sys_getsr()==44100) { x->pitch_offset=193.0f; } } x->osc.Init(); x->envelope.Init(); x->jitter_source.Init(); x->ws.Init(0x0000); return (void *)x; } void brds_tilde_pitch(t_brds_tilde *x, t_floatarg f) { x->f_pitch = f; } void brds_tilde_shape(t_brds_tilde *x, t_floatarg f) { x->f_shape = f; int shape = getShape(x->f_shape); outlet_symbol(x->x_out_shape, gensym(algo_values[shape])); } void brds_tilde_colour(t_brds_tilde *x, t_floatarg f) { x->f_colour = f; } void brds_tilde_timbre(t_brds_tilde *x, t_floatarg f) { x->f_timbre = f; } void brds_tilde_trigger(t_brds_tilde *x, t_floatarg f) { x->trigger_flag = f >= 1; } void brds_tilde_setup(void) { brds_tilde_class = class_new(gensym("brds~"), (t_newmethod) brds_tilde_new, (t_method) brds_tilde_free, sizeof(t_brds_tilde), CLASS_DEFAULT, A_DEFFLOAT, A_NULL); class_addmethod( brds_tilde_class, (t_method)brds_tilde_dsp, gensym("dsp"), A_NULL); CLASS_MAINSIGNALIN(brds_tilde_class, t_brds_tilde, f_dummy); class_addmethod(brds_tilde_class, (t_method) brds_tilde_pitch, gensym("pitch"), A_DEFFLOAT, A_NULL); class_addmethod(brds_tilde_class, (t_method) brds_tilde_shape, gensym("shape"), A_DEFFLOAT, A_NULL); class_addmethod(brds_tilde_class, (t_method) brds_tilde_colour, gensym("colour"), A_DEFFLOAT, A_NULL); class_addmethod(brds_tilde_class, (t_method) brds_tilde_timbre, gensym("timbre"), A_DEFFLOAT, A_NULL); class_addmethod(brds_tilde_class, (t_method) brds_tilde_trigger, gensym("trigger"), A_DEFFLOAT, A_NULL); } // puredata methods implementation - end
25.84141
125
0.621292
[ "render", "shape", "transform" ]
fc8c2f38596b24ea26262063a9a6467f750166a0
4,537
hpp
C++
include/deci/ast_t.hpp
masscry/deci.vm
e2126b6592f798b919de6219c32cbcc41f980e98
[ "MIT" ]
6
2019-07-25T08:54:17.000Z
2022-01-10T06:15:53.000Z
include/deci/ast_t.hpp
masscry/deci.vm
e2126b6592f798b919de6219c32cbcc41f980e98
[ "MIT" ]
7
2019-07-08T12:00:42.000Z
2019-07-14T18:05:56.000Z
include/deci/ast_t.hpp
masscry/deci.vm
e2126b6592f798b919de6219c32cbcc41f980e98
[ "MIT" ]
null
null
null
#pragma once #ifndef __DECI_AST_HEADER__ #define __DECI_AST_HEADER__ #include <fstream> #include <vector> namespace deci { class ast_item_t { ast_item_t* parent; public: ast_item_t* Parent() const { return this->parent; } void Parent(ast_item_t* parent) { this->parent = parent; } virtual const std::string &EndLocationTag() const; virtual int EndLocationPos() const; virtual int Generate(std::ostream& output, int pc) const = 0; ast_item_t(); virtual ~ast_item_t() = 0; }; class ast_number_t final: public ast_item_t { double value; public: int Generate(std::ostream& output, int pc) const override; ast_number_t(double value); ~ast_number_t(); }; class ast_identifier_t final: public ast_item_t { std::string value; public: int Generate(std::ostream& output, int pc) const override; ast_identifier_t(const std::string& value); ~ast_identifier_t(); }; class ast_arg_list_t final: public ast_item_t { std::vector<ast_item_t*> args; public: size_t Total() const; void Append(ast_item_t* item); int Generate(std::ostream& output, int pc) const override; ast_arg_list_t(); ~ast_arg_list_t(); }; class ast_postfix_t final: public ast_item_t { ast_arg_list_t* arglist; std::string identifier; public: int Generate(std::ostream& output, int pc) const override; ast_postfix_t(const std::string& identifier, ast_arg_list_t* arglist); ~ast_postfix_t(); }; class ast_binary_t final: public ast_item_t { std::string identifier; ast_item_t* a; ast_item_t* b; public: int Generate(std::ostream& output, int pc) const override; ast_binary_t(const std::string& identifier, ast_item_t* a, ast_item_t* b); ~ast_binary_t(); }; class ast_unary_t final: public ast_item_t { std::string identifier; ast_item_t* chain; public: int Generate(std::ostream& output, int pc) const override; ast_unary_t(const std::string& identifier, ast_item_t* chain); ~ast_unary_t(); }; class ast_return_t final: public ast_item_t { ast_item_t* chain; public: int Generate(std::ostream& output, int pc) const override; ast_return_t(ast_item_t* chain); ~ast_return_t(); }; class ast_set_t final: public ast_item_t { std::string identifier; ast_item_t* chain; public: int Generate(std::ostream& output, int pc) const override; ast_set_t(const std::string& identifier, ast_item_t* chain); ~ast_set_t(); }; class ast_t final: public ast_item_t { std::vector<ast_item_t*> statements; public: void Append(ast_item_t* item); int Generate(std::ostream& output, int pc) const override; ast_t(); ~ast_t(); }; class ast_exit_t final : public ast_item_t { public: int Generate(std::ostream &output, int pc) const override; ast_exit_t(); ~ast_exit_t(); }; class ast_if_t final: public ast_item_t { ast_item_t* condition; ast_t* true_path; ast_t* else_path; public: int Generate(std::ostream& output, int pc) const override; ast_if_t(ast_item_t* condition, ast_t* true_path, ast_t* else_path); ~ast_if_t(); }; class ast_loop_t: public ast_item_t { protected: mutable int end_loc_pos; public: int EndLocationPos() const override; ast_loop_t(); ~ast_loop_t(); }; class ast_for_t final: public ast_loop_t { std::string identifier; ast_item_t* start; ast_item_t* finish; ast_t* loop; ast_item_t* step; public: const std::string& EndLocationTag() const override; int Generate(std::ostream& output, int pc) const override; ast_for_t(const std::string& identifier, ast_item_t* start, ast_item_t* finish, ast_t* loop, ast_item_t* step); ~ast_for_t(); }; class ast_while_t final: public ast_loop_t { ast_item_t* condition; ast_t* loop; public: const std::string &EndLocationTag() const override; int Generate(std::ostream &output, int pc) const override; ast_while_t(ast_item_t* condition, ast_t* loop); ~ast_while_t(); }; class ast_repeat_t final: public ast_loop_t { ast_item_t* condition; ast_t* loop; public: const std::string& EndLocationTag() const override; int Generate(std::ostream& output, int pc) const override; ast_repeat_t(ast_item_t* condition, ast_t* loop); ~ast_repeat_t(); }; } // namespace deci #endif /* __DECI_AST_HEADER__ */
21.00463
115
0.672471
[ "vector" ]
fc8cdb34845f3bc9cd4ede3226bb9ae1295fc5d1
18,976
cpp
C++
src/nyx/features/gabor.cpp
friskluft/nyx
338fa587a358588dc1d01ce938864c69a391cb07
[ "MIT" ]
1
2021-09-09T18:57:23.000Z
2021-09-09T18:57:23.000Z
src/nyx/features/gabor.cpp
friskluft/nyx
338fa587a358588dc1d01ce938864c69a391cb07
[ "MIT" ]
null
null
null
src/nyx/features/gabor.cpp
friskluft/nyx
338fa587a358588dc1d01ce938864c69a391cb07
[ "MIT" ]
1
2021-09-17T14:51:21.000Z
2021-09-17T14:51:21.000Z
#define _USE_MATH_DEFINES // For M_PI, etc. #include <cmath> #include <omp.h> #include "gabor.h" void GaborFeature::calculate (LR& r) { const ImageMatrix& Im0 = r.aux_image_matrix; double GRAYthr; /* parameters set up in complience with the paper */ double gamma = 0.5, sig2lam = 0.56; int n = 38; double f0[7] = { 1,2,3,4,5,6,7 }; // frequencies for several HP Gabor filters double f0LP = 0.1; // frequencies for one LP Gabor filter double theta = 3.14159265 / 2; int ii; unsigned long originalScore = 0; readOnlyPixels im0_plane = Im0.ReadablePixels(); // Temp buffers // --1 ImageMatrix e2img; e2img.allocate (Im0.width, Im0.height); // --2 std::vector<double> auxC ((Im0.width + n - 1) * (Im0.height + n - 1) * 2); // --3 std::vector<double> auxG (n * n * 2); // compute the original score before Gabor GaborEnergy (Im0, e2img.writable_data_ptr(), auxC.data(), auxG.data(), f0LP, sig2lam, gamma, theta, n); readOnlyPixels pix_plane = e2img.ReadablePixels(); // N.B.: for the base of the ratios, the threshold is 0.4 of max energy, // while the comparison thresholds are Otsu. Moments2 local_stats; e2img.GetStats(local_stats); double max_val = local_stats.max__(); // //originalScore = (pix_plane.array() > max_val * 0.4).count(); // int cnt = 0; double cmp_a = max_val * 0.4; for (auto a : pix_plane) if (double(a) > cmp_a) cnt++; originalScore = cnt; if (fvals.size() != GaborFeature::num_features) fvals.resize (GaborFeature::num_features, 0.0); for (ii = 0; ii < GaborFeature::num_features; ii++) { unsigned long afterGaborScore = 0; writeablePixels e2_pix_plane = e2img.WriteablePixels(); GaborEnergy (Im0, e2_pix_plane.data(), auxC.data(), auxG.data(), f0[ii], sig2lam, gamma, theta, n); // //Moments2 local_stats2; //e2img.GetStats(local_stats2); //double max_val2 = local_stats2.max__(); // //e2_pix_plane.array() = (e2_pix_plane.array() / max_val2).unaryExpr(Moments2func(e2img.stats)); // GRAYthr = 0.25; // --Using simplified thresholding-- GRAYthr = e2img.Otsu(); // //afterGaborScore = (e2_pix_plane.array() > GRAYthr).count(); // afterGaborScore = 0; for (auto a : e2_pix_plane) if (double(a)/max_val > GRAYthr) afterGaborScore++; fvals[ii] = (double)afterGaborScore / (double)originalScore; } } void GaborFeature::save_value(std::vector<std::vector<double>>& feature_vals) { feature_vals[GABOR].resize(fvals.size()); for (int i = 0; i < fvals.size(); i++) feature_vals[GABOR][i] = fvals[i]; } // conv // // double *c; Result matrix (ma+mb-1)-by-(na+nb-1) // double *a; Larger matrix // double *b; Smaller matrix // int ma; Row size of a // int na; Column size of a // int mb; Row size of b // int nb; Column size of b void GaborFeature::conv_ddd ( double* c, double* a, double* b, int na, int ma, int nb, int mb) { double *p,*q; /* Pointer to elements in 'a' and 'c' matrices */ double wr,wi; /* Imaginary and real weights from matrix b */ int mc, nc; int k,l,i,j; double *r; /* Pointer to elements in 'b' matrix */ mc = ma + mb - 1; nc = (na + nb - 1) * 2; /* initalize the output matrix */ for (int j = 0; j < mc; ++j) /* For each element in b */ for (int i = 0; i < nc; ++i) c[j*nc+i] = 0; /* Perform convolution */ r = b; for (j = 0; j < mb; ++j) { /* For each element in b */ for (i = 0; i < nb; ++i) { wr = *(r++); /* Get weight from b matrix */ wi = *(r++); p = c + j*nc + i*2; /* Start at first row of a in c. */ q = a; for (l = 0; l < ma; l++) { /* For each row of a ... */ for (k = 0; k < na; k++) { *(p++) += *(q) * wr; /* multiply by the real weight and add. */ *(p++) += *(q++) * wi; /* multiply by the imaginary weight and add. */ } p += (nb-1)*2; /* Jump to next row position of a in c */ //*flopcnt += 2*ma*na; } } } } void GaborFeature::conv_dud( double* C, // must be zeroed before call const unsigned int* A, double* B, int na, int ma, int nb, int mb) { int ip, iq; // Pointer to elements in 'A' and 'C' matrices double wr, wi; // Imaginary and real weights from matrix B int mc, nc; int ir = 0; // Pointer to elements in 'b' matrix mc = ma + mb - 1; nc = (na + nb - 1) * 2; // initalize the output matrix int mcnc = mc * nc; for (int i = 0; i < mcnc; i++) C[i] = 0.0; for (int j = 0; j < mb; ++j) { // For each element in b for (int i = 0; i < nb; ++i) { // Get weight from B matrix wr = B[ir]; wi = B[ir+1]; ir += 2; // Start at first row of A in C ip = j * nc + i * 2; iq = 0; for (int l = 0; l < ma; l++) { // For each row of A ... for (int k = 0; k < na; k++) { // cache A[iq] double a = A[iq]; iq++; // multiply by the real weight and add C[ip] += a * wr; // multiply by the imaginary weight and add C[ip+1] += a * wi; ip += 2; } // Jump to next row position of A in C ip += (nb - 1) * 2; } } } } void GaborFeature::conv_parallel ( double* c, double* a, double* b, int na, int ma, int nb, int mb) { // double *p,*q; /* Pointer to elements in 'a' and 'c' matrices */ // double wr,wi; /* Imaginary and real weights from matrix b */ int mc, nc; // int k,l,i,j; // double *r; /* Pointer to elements in 'b' matrix */ mc = ma + mb - 1; nc = (na + nb - 1) * 2; /* initalize the output matrix */ //MM for (int j = 0; j < mc; ++j) /* For each element in b */ // for (int i = 0; i < nc; ++i) // c[j*nc+i] = 0; /* Perform convolution */ // r = b; // for (j = 0; j < mb; ++j) { /* For each element in b */ // for (i = 0; i < nb; ++i) { // wr = *(r++); /* Get weight from b matrix */ // wi = *(r++); // p = c + j*nc + i*2; /* Start at first row of a in c. */ // q = a; // for (l = 0; l < ma; l++) { /* For each row of a ... */ // for (k = 0; k < na; k++) { // *(p++) += *(q) * wr; /* multiply by the real weight and add. */ // *(p++) += *(q++) * wi; /* multiply by the imaginary weight and add. */ // } // p += (nb-1)*2; /* Jump to next row position of a in c */ // *flopcnt += 2*ma*na; // } // } // } #pragma omp parallel { //---double* cThread = new double[mc * nc]; std::vector<double> cThread(mc * nc); for (int aa = 0; aa < mc * nc; aa++) cThread[aa] = std::numeric_limits<double>::quiet_NaN(); #pragma omp for schedule(dynamic) for (int j = 0; j < mb; ++j) { /* For each element in b */ for (int i = 0; i < nb; ++i) { double* r = b + (j * nb + i) * 2; double wr = *(r++); /* Get weight from b matrix */ double wi = *(r); //--- double* p = cThread + j * nc + i * 2; /* Start at first row of a in c. */ int p = j * nc + i * 2; double* q = a; for (int l = 0; l < ma; l++) { /* For each row of a ... */ for (int k = 0; k < na; k++) { //MM *(p++) += *(q) * wr; /* multiply by the real weight and add. */ //MM *(p++) += *(q++) * wi; /* multiply by the imaginary weight and add. */ //MM: if (!std::isnan(*q)) { if (std::isnan(cThread[p]))//--- if (std::isnan(*p)) { cThread[p++] = *(q)*wr; //--- *(p++) = *(q)*wr; /* multiply by the real weight and add. */ cThread[p++] = *(q++) * wi; //--- *(p++) = *(q++) * wi; /* multiply by the imaginary weight and add. */ } else { cThread[p++] += *(q)*wr; //--- *(p++) += *(q)*wr; /* multiply by the real weight and add. */ cThread[p++] += *(q++) * wi; //--- *(p++) += *(q++) * wi; /* multiply by the imaginary weight and add. */ } } else { q++; p = p + 2; } } p += (nb - 1) * 2; /* Jump to next row position of a in c */ // *flopcnt += 2*ma*na; } } } #pragma omp critical { int p = 0; // index in cThread for (int j = 0; j < mc; ++j) { /* For each element in b */ for (int i = 0; i < nc; ++i) { c[j * nc + i] += cThread[p++]; //--- c[j * nc + i] += *(cThread++); } } } } } void GaborFeature::conv_parallel_dud( double* c, const unsigned int* a, double* b, int na, int ma, int nb, int mb) { // double *p,*q; /* Pointer to elements in 'a' and 'c' matrices */ // double wr,wi; /* Imaginary and real weights from matrix b */ int mc, nc; // int k,l,i,j; // double *r; /* Pointer to elements in 'b' matrix */ mc = ma + mb - 1; nc = (na + nb - 1) * 2; /* initalize the output matrix */ //MM for (int j = 0; j < mc; ++j) /* For each element in b */ // for (int i = 0; i < nc; ++i) // c[j*nc+i] = 0; /* Perform convolution */ // r = b; // for (j = 0; j < mb; ++j) { /* For each element in b */ // for (i = 0; i < nb; ++i) { // wr = *(r++); /* Get weight from b matrix */ // wi = *(r++); // p = c + j*nc + i*2; /* Start at first row of a in c. */ // q = a; // for (l = 0; l < ma; l++) { /* For each row of a ... */ // for (k = 0; k < na; k++) { // *(p++) += *(q) * wr; /* multiply by the real weight and add. */ // *(p++) += *(q++) * wi; /* multiply by the imaginary weight and add. */ // } // p += (nb-1)*2; /* Jump to next row position of a in c */ // *flopcnt += 2*ma*na; // } // } // } #pragma omp parallel { //---double* cThread = new double[mc * nc]; std::vector<double> cThread(mc * nc); for (int aa = 0; aa < mc * nc; aa++) cThread[aa] = std::numeric_limits<double>::quiet_NaN(); #pragma omp for schedule(dynamic) for (int j = 0; j < mb; ++j) { /* For each element in b */ for (int i = 0; i < nb; ++i) { double* r = b + (j * nb + i) * 2; double wr = *(r++); /* Get weight from b matrix */ double wi = *(r); //--- double* p = cThread + j * nc + i * 2; /* Start at first row of a in c. */ int p = j * nc + i * 2; const unsigned int* q = a; for (int l = 0; l < ma; l++) { /* For each row of a ... */ for (int k = 0; k < na; k++) { //MM *(p++) += *(q) * wr; /* multiply by the real weight and add. */ //MM *(p++) += *(q++) * wi; /* multiply by the imaginary weight and add. */ //MM: if (!std::isnan((double)*q)) { if (std::isnan(cThread[p]))//--- if (std::isnan(*p)) { cThread[p++] = *(q)*wr; //--- *(p++) = *(q)*wr; /* multiply by the real weight and add. */ cThread[p++] = *(q++) * wi; //--- *(p++) = *(q++) * wi; /* multiply by the imaginary weight and add. */ } else { cThread[p++] += *(q)*wr; //--- *(p++) += *(q)*wr; /* multiply by the real weight and add. */ cThread[p++] += *(q++) * wi; //--- *(p++) += *(q++) * wi; /* multiply by the imaginary weight and add. */ } } else { q++; p = p + 2; } } p += (nb - 1) * 2; /* Jump to next row position of a in c */ // *flopcnt += 2*ma*na; } } } #pragma omp critical { int p = 0; // index in cThread for (int j = 0; j < mc; ++j) { /* For each element in b */ for (int i = 0; i < nc; ++i) { c[j * nc + i] += cThread[p++]; //--- c[j * nc + i] += *(cThread++); } } } } } // Creates a normalized Gabor filter void GaborFeature::Gabor (double* Gex, double f0, double sig2lam, double gamma, double theta, double fi, int n) { //double* tx, * ty; double lambda = 2 * M_PI / f0; double cos_theta = cos(theta), sin_theta = sin(theta); double sig = sig2lam * lambda; double sum; //A double* Gex; int x, y; int nx = n; int ny = n; //A tx = new double[nx + 1]; std::vector<double> tx (nx + 1); //A ty = new double[ny + 1]; std::vector<double> ty (nx + 1); if (nx % 2 > 0) { tx[0] = -((nx - 1) / 2); for (x = 1; x < nx; x++) tx[x] = tx[x - 1] + 1; } else { tx[0] = -(nx / 2); for (x = 1; x < nx; x++) tx[x] = tx[x - 1] + 1; } if (ny % 2 > 0) { ty[0] = -((ny - 1) / 2); for (y = 1; y < ny; y++) ty[y] = ty[y - 1] + 1; } else { ty[0] = -(ny / 2); for (y = 1; y < ny; y++) ty[y] = ty[y - 1] + 1; } //A Gex = new double[n * n * 2]; sum = 0; for (y = 0; y < n; y++) { for (x = 0; x < n; x++) { double argm, xte, yte, rte, ge; xte = tx[x] * cos_theta + ty[y] * sin_theta; yte = ty[y] * cos_theta - tx[x] * sin_theta; rte = xte * xte + gamma * gamma * yte * yte; ge = exp(-1 * rte / (2 * sig * sig)); argm = xte * f0 + fi; Gex[y * n * 2 + x * 2] = ge * cos(argm); // ge .* exp(j.*argm); Gex[y * n * 2 + x * 2 + 1] = ge * sin(argm); sum += sqrt(pow(Gex[y * n * 2 + x * 2], 2) + pow(Gex[y * n * 2 + x * 2 + 1], 2)); } } // normalize for (y = 0; y < n; y++) for (x = 0; x < n * 2; x += 1) Gex[y * n * 2 + x] = Gex[y * n * 2 + x] / sum; } // Computes Gabor energy void GaborFeature::GaborEnergy ( const ImageMatrix& Im, PixIntens* /* double* */ out, double* auxC, double* Gexp, double f0, double sig2lam, double gamma, double theta, int n) { int n_gab = n; double fi = 0; Gabor (Gexp, f0, sig2lam, gamma, theta, fi, n_gab); readOnlyPixels pix_plane = Im.ReadablePixels(); #if 0 //=== Version 1 (using the cached image) for (int i = 0; i < (Im.width + n - 1) * (Im.height + n - 1) * 2; i++) { c[i] = 0; } //MM double *image = new double[Im.width * Im.height]; //std::vector<double> image(Im.width * Im.height); for (auto y = 0; y < Im.height; y++) for (auto x = 0; x < Im.width; x++) image[y * Im.width + x] = pix_plane(y, x); conv (c, image, Gexp, Im.width, Im.height, n, n); delete[] image; #endif //=== Version 2 conv_dud (auxC, pix_plane.data(), Gexp, Im.width, Im.height, n_gab, n_gab); decltype(Im.height) b = 0; for (auto y = (int)ceil((double)n / 2); b < Im.height; y++) { decltype(Im.width) a = 0; for (auto x = (int)ceil((double)n / 2); a < Im.width; x++) { if (std::isnan(auxC[y * 2 * (Im.width + n - 1) + x * 2]) || std::isnan(auxC[y * 2 * (Im.width + n - 1) + x * 2 + 1])) { out[b * Im.width + a] = (PixIntens) std::numeric_limits<double>::quiet_NaN(); a++; continue; } out[b * Im.width + a] = (PixIntens) sqrt(pow(auxC[y * 2 * (Im.width + n - 1) + x * 2], 2) + pow(auxC[y * 2 * (Im.width + n - 1) + x * 2 + 1], 2)); a++; } b++; } } void GaborFeature::reduce (size_t start, size_t end, std::vector<int>* ptrLabels, std::unordered_map <int, LR>* ptrLabelData) { for (auto i = start; i < end; i++) { int lab = (*ptrLabels)[i]; LR& r = (*ptrLabelData)[lab]; if (r.has_bad_data()) continue; // Skip calculation in case of bad data if ((int)r.fvals[MIN][0] == (int)r.fvals[MAX][0]) { r.fvals[GABOR].resize(GaborFeature::num_features, 0.0); continue; } GaborFeature gf; gf.calculate (r); gf.save_value (r.fvals); } }
33.64539
159
0.396817
[ "vector" ]
4759e5b9b4b1857aa32b0a90b28ac81f575acceb
8,135
cc
C++
audio/dsp/eigen_types_test.cc
foolish-hungry-b/test
5276d8169f398da068e5694eaf571c1cb1e25e06
[ "Apache-2.0" ]
58
2018-01-20T14:27:07.000Z
2022-01-26T03:09:02.000Z
audio/dsp/eigen_types_test.cc
foolish-hungry-b/test
5276d8169f398da068e5694eaf571c1cb1e25e06
[ "Apache-2.0" ]
1
2020-10-02T17:18:10.000Z
2020-10-02T17:23:00.000Z
audio/dsp/eigen_types_test.cc
foolish-hungry-b/test
5276d8169f398da068e5694eaf571c1cb1e25e06
[ "Apache-2.0" ]
30
2018-02-28T16:13:07.000Z
2022-03-31T00:38:54.000Z
/* * Copyright 2020-2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "audio/dsp/eigen_types.h" #include <vector> #include "audio/dsp/testing_util.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "audio/dsp/porting.h" // auto-added. namespace audio_dsp { namespace { using ::Eigen::ArrayXf; using ::Eigen::ArrayXXf; using ::Eigen::Dynamic; using ::Eigen::InnerStride; using ::Eigen::MatrixXf; using ::Eigen::Map; using ::Eigen::RowMajor; using ::Eigen::VectorXf; using RowMajorMatrixXf = Eigen::Matrix<float, Dynamic, Dynamic, RowMajor>; TEST(EigenTypesTest, TransposeToRowVector) { // The following should be transposed. { Eigen::ArrayXf x = Eigen::ArrayXf::Ones(20); Eigen::Transpose<Eigen::ArrayXf> y = TransposeToRowVector(x); EXPECT_EQ(y.rows(), 1); EXPECT_EQ(y.cols(), 20); y[0] *= 2; // Test that result is mutable. EXPECT_EQ(x[0], 2.0f); } { Eigen::VectorXf x = Eigen::VectorXf::Ones(20); auto y = TransposeToRowVector(x); EXPECT_EQ(y.rows(), 1); EXPECT_EQ(y.cols(), 20); auto y_segment = TransposeToRowVector(x.segment(5, 10)); EXPECT_EQ(y_segment.rows(), 1); EXPECT_EQ(y_segment.cols(), 10); y_segment[0] *= 2; EXPECT_EQ(x[5], 2.0f); } { auto y = TransposeToRowVector(Eigen::ArrayXf::Zero(20)); EXPECT_EQ(y.rows(), 1); EXPECT_EQ(y.cols(), 20); } // The following should be unchanged. { Eigen::ArrayXXf x = Eigen::ArrayXXf::Ones(5, 20); Eigen::ArrayXXf& y = TransposeToRowVector(x); EXPECT_EQ(y.rows(), 5); EXPECT_EQ(y.cols(), 20); y(0, 0) *= 2; EXPECT_EQ(x(0, 0), 2.0f); } { Eigen::RowVectorXf x(20); Eigen::RowVectorXf& y = TransposeToRowVector(x); EXPECT_EQ(y.rows(), 1); EXPECT_EQ(y.cols(), 20); } } TEST(EigenTypesTest, IsContiguous1DEigenType) { // Return true on Array, Vector, and Mapped Array and Vector types. EXPECT_TRUE(IsContiguous1DEigenType<ArrayXf>::Value); EXPECT_TRUE(IsContiguous1DEigenType<VectorXf>::Value); EXPECT_TRUE(IsContiguous1DEigenType<Map<ArrayXf>>::Value); EXPECT_TRUE(IsContiguous1DEigenType<Map<const VectorXf>>::Value); // Return true on segments of 1D contiguous arrays. EXPECT_TRUE(IsContiguous1DEigenType< decltype(ArrayXf().segment(0, 9))>::Value); // Return true on 1D matrix slices along the major direction. EXPECT_TRUE(IsContiguous1DEigenType< decltype(MatrixXf().col(0))>::Value); EXPECT_TRUE(IsContiguous1DEigenType< decltype(RowMajorMatrixXf().row(0))>::Value); // Return false on non-Eigen types. EXPECT_FALSE(IsContiguous1DEigenType<std::vector<float>>::Value); // Return false on 2D Eigen types. EXPECT_FALSE(IsContiguous1DEigenType<ArrayXXf>::Value); EXPECT_FALSE(IsContiguous1DEigenType<MatrixXf>::Value); // Return false on expressions whose elements aren't stored. EXPECT_FALSE(IsContiguous1DEigenType< decltype(ArrayXf::Random(9))>::Value); // Return false if inner stride isn't 1. using MappedWithStride2 = Map<VectorXf, 0, InnerStride<2>>; EXPECT_FALSE(IsContiguous1DEigenType<MappedWithStride2>::Value); EXPECT_FALSE(IsContiguous1DEigenType< decltype(ArrayXf().reverse())>::Value); EXPECT_FALSE(IsContiguous1DEigenType< decltype(MatrixXf().row(0))>::Value); EXPECT_FALSE(IsContiguous1DEigenType< decltype(RowMajorMatrixXf().col(0))>::Value); } // Test WrapContainer(absl::Span). TEST(EigenTypesTest, ContainerWrapperSpan) { int buffer[8]; auto buffer_const_span = absl::MakeConstSpan(buffer); auto x = WrapContainer(buffer_const_span); using XType = decltype(x); EXPECT_EQ(XType::Dims, 1); EXPECT_TRUE(XType::IsVectorAtCompileTime); EXPECT_FALSE(XType::IsResizable); EXPECT_EQ(x.size(), 8); EXPECT_TRUE(x.resize(8)); EXPECT_FALSE(x.resize(7)); EXPECT_EQ(x.AsMatrix(1).data(), buffer); auto buffer_span = absl::MakeSpan(buffer); auto y = WrapContainer(buffer_span); EXPECT_EQ(y.AsMatrix(1).data(), buffer); } // Test WrapContainer(std::vector). TEST(EigenTypesTest, ContainerWrapperVector) { std::vector<int> buffer; auto x = WrapContainer(buffer); using XType = decltype(x); EXPECT_EQ(XType::Dims, 1); EXPECT_TRUE(XType::IsVectorAtCompileTime); EXPECT_TRUE(XType::IsResizable); EXPECT_EQ(x.size(), 0); EXPECT_TRUE(x.resize(7)); EXPECT_EQ(x.size(), 7); EXPECT_EQ(buffer.size(), 7); EXPECT_EQ(x.AsMatrix(1).data(), buffer.data()); } // Test WrapContainer(Eigen::ArrayXXf). TEST(EigenTypesTest, ContainerWrapperEigenArray) { ArrayXXf buffer = ArrayXXf::Random(3, 4); auto x = WrapContainer(buffer); using XType = decltype(x); EXPECT_EQ(XType::Dims, 2); EXPECT_EQ(XType::RowsAtCompileTime, Dynamic); EXPECT_EQ(XType::ColsAtCompileTime, Dynamic); EXPECT_FALSE(XType::IsVectorAtCompileTime); EXPECT_TRUE(XType::IsResizable); EXPECT_EQ(x.rows(), 3); EXPECT_EQ(x.cols(), 4); EXPECT_FALSE(x.resize(7)); EXPECT_TRUE(x.resize(2, 7)); EXPECT_EQ(x.rows(), 2); EXPECT_EQ(x.cols(), 7); EXPECT_EQ(buffer.rows(), 2); EXPECT_EQ(buffer.cols(), 7); buffer = ArrayXXf::Random(2, 7); EXPECT_THAT(x.AsMatrix(3), EigenArrayEq(buffer)); } // Test WrapContainer(Eigen::MatrixXf). TEST(EigenTypesTest, ContainerWrapperEigenMatrix) { MatrixXf buffer = MatrixXf::Random(3, 4); auto x = WrapContainer(buffer); using XType = decltype(x); EXPECT_EQ(XType::Dims, 2); EXPECT_EQ(XType::RowsAtCompileTime, Dynamic); EXPECT_EQ(XType::ColsAtCompileTime, Dynamic); EXPECT_FALSE(XType::IsVectorAtCompileTime); EXPECT_TRUE(XType::IsResizable); EXPECT_EQ(x.rows(), 3); EXPECT_EQ(x.cols(), 4); EXPECT_FALSE(x.resize(7)); EXPECT_TRUE(x.resize(2, 7)); EXPECT_EQ(x.rows(), 2); EXPECT_EQ(x.cols(), 7); EXPECT_EQ(buffer.rows(), 2); EXPECT_EQ(buffer.cols(), 7); buffer = MatrixXf::Random(2, 7); EXPECT_THAT(x.AsMatrix(3), EigenArrayEq(buffer)); } // Test WrapContainer(Eigen::Block). TEST(EigenTypesTest, ContainerWrapperEigenBlock) { MatrixXf buffer = MatrixXf::Random(3, 4); auto row = buffer.row(1); auto x = WrapContainer(row); using XType = decltype(x); EXPECT_EQ(XType::Dims, 2); EXPECT_EQ(XType::RowsAtCompileTime, 1); EXPECT_EQ(XType::ColsAtCompileTime, Dynamic); EXPECT_TRUE(XType::IsVectorAtCompileTime); EXPECT_FALSE(XType::IsResizable); EXPECT_EQ(x.size(), 4); EXPECT_THAT(x.AsMatrix(1), EigenArrayEq(buffer.row(1))); } // Test WrapContainer(Eigen::VectorBlock). TEST(EigenTypesTest, ContainerWrapperEigenVectorBlock) { ArrayXf buffer = ArrayXf::Random(5); auto head = buffer.head(3); auto x = WrapContainer(head); using XType = decltype(x); EXPECT_EQ(XType::Dims, 2); EXPECT_EQ(XType::RowsAtCompileTime, Dynamic); EXPECT_EQ(XType::ColsAtCompileTime, 1); EXPECT_TRUE(XType::IsVectorAtCompileTime); EXPECT_FALSE(XType::IsResizable); EXPECT_EQ(x.size(), 3); EXPECT_THAT(x.AsMatrix(3), EigenArrayEq(buffer.head(3))); } // Test WrapContainer(Eigen::CWiseNullaryOp). TEST(EigenTypesTest, ContainerWrapperEigenCWiseNullaryOp) { auto constant_xpr = Eigen::ArrayXXf::Constant(3, 10, 4.2f); auto x = WrapContainer(constant_xpr); using XType = decltype(x); EXPECT_EQ(XType::Dims, 2); EXPECT_EQ(XType::RowsAtCompileTime, Dynamic); EXPECT_EQ(XType::ColsAtCompileTime, Dynamic); EXPECT_FALSE(XType::IsVectorAtCompileTime); EXPECT_FALSE(XType::IsResizable); EXPECT_EQ(x.rows(), 3); EXPECT_EQ(x.cols(), 10); ArrayXXf y = x.AsMatrix(3).eval(); EXPECT_EQ(y.rows(), 3); EXPECT_EQ(y.cols(), 10); EXPECT_EQ(y(1, 1), 4.2f); } } // namespace } // namespace audio_dsp
31.901961
75
0.702889
[ "vector" ]
476283b2045752010d96bb509d8a1810c1e04e42
4,494
cpp
C++
tools/disktool/src/WebWorker.cpp
DarkMaguz/CodingPiratesOS
7750224b87646ad376664bd1f826aae5112ea41c
[ "MIT" ]
1
2020-03-09T14:14:02.000Z
2020-03-09T14:14:02.000Z
tools/disktool/src/WebWorker.cpp
DarkMaguz/CodingPiratesOS
7750224b87646ad376664bd1f826aae5112ea41c
[ "MIT" ]
null
null
null
tools/disktool/src/WebWorker.cpp
DarkMaguz/CodingPiratesOS
7750224b87646ad376664bd1f826aae5112ea41c
[ "MIT" ]
2
2020-03-11T21:29:20.000Z
2020-07-06T20:20:18.000Z
/* * WebWorker.cpp * * Created on: Mar 13, 2022 * Author: magnus */ #include "WebWorker.h" #include "AssistantSourcePage.h" //#include <curlpp/cURLpp.hpp> #include <curlpp/Easy.hpp> #include <curlpp/Options.hpp> #include <tinyxml2.h> #include <string> #include <sstream> #include <iostream> #include <exception> WebWorker::WebWorker(AssistantSourcePage *sourcePage) : sourcePage(sourcePage) { } WebWorker::~WebWorker() { std::cout << "~WebWorker" << std::endl; // if (doc2) // delete doc2; } void WebWorker::Worker(void) { std::string url = "https://darkmagus.dk/cpos/images/content.xml"; std::stringstream ss; try { // That's all that is needed to do cleanup of used resources (RAII style). //curlpp::Cleanup curlCleanup; curlpp::Easy request; request.setOpt<curlpp::options::Url>(url); //myRequest.setOpt<curlpp::options::Timeout>(3); request.setOpt<curlpp::options::Verbose>(false); request.setOpt<curlpp::options::WriteStream>(&ss); request.perform(); } catch (curlpp::RuntimeError &e) { std::cout << e.what() << std::endl; } catch (curlpp::LogicError &e) { std::cout << e.what() << std::endl; } // auto target = ss.str().find_first_of('\n'); // std::cout << "###################" << std::endl; // std::cout << ss.str().substr(target+1) << std::endl; // std::cout << "###################" << std::endl; // std::cout << ss.str() << std::endl; std::map<std::string, std::vector<FileInfo>> images; tinyxml2::XMLDocument doc; //tinyxml2::XMLError xmlError = doc.LoadFile("content.xml"); tinyxml2::XMLError xmlError = doc.Parse(ss.str().c_str()); if (xmlError) { std::cout << "xmlError: " << xmlError << std::endl; //exit(xmlError); } else { auto rootElement = doc.RootElement(); auto distElement = rootElement->FirstChildElement("directory"); if (distElement == nullptr) std::cerr << "tinyxml: " << std::endl; while (distElement) { std::string distName = distElement->Attribute("name"); auto fileElement = distElement->FirstChildElement("file"); while (fileElement) { FileInfo fileInfo; std::string fileName = fileElement->Attribute("name"); auto fileExtPos = fileName.rfind('.'); auto fileExt = fileName.substr(fileExtPos + 1); auto versionPos = fileName.rfind('-') + 1; auto versionEndPos = fileName.find('.', versionPos); versionEndPos = fileName.find('.', versionEndPos + 1); versionEndPos = fileName.find('.', versionEndPos + 1); fileInfo.isIso = (fileExt == "iso"); fileInfo.version = fileName.substr(versionPos, versionEndPos - versionPos); fileInfo.fileName = fileName; fileInfo.distrubution = distName; fileInfo.url = fileInfo.distrubution + "/" + fileName; if (fileElement->Attribute("size")) fileInfo.size = std::atoll(fileElement->Attribute("size")); else fileInfo.size = 0; if (fileInfo.isIso) { fileInfo.buildLog = fileName.substr(0, versionEndPos) + ".build.log"; images[distName].push_back(fileInfo); } fileElement = fileElement->NextSiblingElement("file"); } distElement = distElement->NextSiblingElement("directory"); } } sourcePage->setImages(images); //sourcePage->notify(); } std::string WebWorker::CleanUpHTML(const std::string& html) { // Source: https://www.html-tidy.org/developer/ std::string cleanHTML; // const char* input = html.c_str(); // TidyBuffer output = {0}; // TidyBuffer errbuf = {0}; // int rc = -1; // Bool ok; // // TidyDoc tdoc = tidyCreate(); // Initialize "document" // // ok = tidyOptSetBool( tdoc, TidyXhtmlOut, yes ); // Convert to XHTML // if ( ok ) // rc = tidySetErrorBuffer( tdoc, &errbuf ); // Capture diagnostics // if ( rc >= 0 ) // rc = tidyParseString( tdoc, input ); // Parse the input // if ( rc >= 0 ) // rc = tidyCleanAndRepair( tdoc ); // Tidy it up! // if ( rc >= 0 ) // rc = tidyRunDiagnostics( tdoc ); // Kvetch // if ( rc > 1 ) // If error, force output. // rc = ( tidyOptSetBool(tdoc, TidyForceOutput, yes) ? rc : -1 ); // if ( rc >= 0 ) // rc = tidySaveBuffer( tdoc, &output ); // Pretty Print // // // if ( rc >= 0 ) // cleanHTML = (const char *)output.bp; // else // std::cout << "A severe error (" << rc << ") occurred while cleaning up HTML." << std::endl; // // tidyBufFree( &output ); // tidyBufFree( &errbuf ); // tidyRelease( tdoc ); return cleanHTML; }
27.072289
96
0.617713
[ "vector" ]
476f4b287531e181ff506120bf78cc4549c9de67
6,819
cxx
C++
PWG/FLOW/Base/AliStarTrack.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
114
2017-03-03T09:12:23.000Z
2022-03-03T20:29:42.000Z
PWG/FLOW/Base/AliStarTrack.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
19,637
2017-01-16T12:34:41.000Z
2022-03-31T22:02:40.000Z
PWG/FLOW/Base/AliStarTrack.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
1,021
2016-07-14T22:41:16.000Z
2022-03-31T05:15:51.000Z
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /***************************************************************** AliStarTrack: Event container for flow analysis origin: Mikolaj Krzewicki (mikolaj.krzewicki@cern.ch) *****************************************************************/ #include <string.h> #include <TObject.h> #include <TString.h> #include "AliStarTrack.h" ClassImp(AliStarTrack) //______________________________________________________________________________ AliStarTrack::AliStarTrack(): TObject(), fParams() { //ctor } //______________________________________________________________________________ AliStarTrack::AliStarTrack( const Float_t* params ): TObject(), fParams() { //ctor memcpy(fParams,params,fgkNparams*sizeof(Float_t)); } //______________________________________________________________________________ AliStarTrack::AliStarTrack( const AliStarTrack& track ): TObject(), fParams() { //copy ctor memcpy(fParams,track.fParams,fgkNparams*sizeof(Float_t)); } //______________________________________________________________________________ AliStarTrack& AliStarTrack::operator=( const AliStarTrack& track ) { //assignment if (this == &track) return *this; TObject::operator=(track); memcpy(fParams,track.fParams,fgkNparams*sizeof(Float_t)); return *this; } //______________________________________________________________________________ void AliStarTrack::SetParams( const Float_t* params ) { //set params memcpy(fParams,params,fgkNparams*sizeof(Float_t)); } //______________________________________________________________________________ AliStarTrack* AliStarTrack::Clone( const char* /*option*/) const { //clone "constructor" return new AliStarTrack(*this); } //______________________________________________________________________________ void AliStarTrack::Print( Option_t* option ) const { // print info // TNtuple* track: names are documented in the next 2 lines // tracks = new TNtuple("tracks","tracks", // "ID:Charge:Eta:Phi:Pt:Dca:nHits:nHitsFit:nHitsPoss:nHitsDedx:dEdx:nSigElect:nSigPi:nSigK:nSigProton" ) ; // TString optionstr(option); if ( optionstr.Contains("legend") ) { printf( " id charge eta phi pt dca nHits nFit nPoss ndEdx dEdx nSigElec nSigPi nSigK nSigPr\n") ; return; } Int_t id = (Int_t) fParams[0] ; // id - a unique integer for each track in this event Int_t charge = (Int_t) fParams[1] ; // +1 or -1 Float_t eta = (Float_t) fParams[2] ; // Pseudo-rapidity at the vertex Float_t phi = (Float_t) fParams[3] ; // Phi emission angle at the vertexcd Float_t pt = (Float_t) fParams[4] ; // Pt of the track at the vertex Float_t dca = (Float_t) fParams[5] ; // Magnitude of 3D DCA to vertex Int_t nHits = (Int_t) fParams[6] ; // Number of clusters available to the Kalman Filter Int_t nHitsFit = (Int_t) fParams[7] ; // Number of clusters used in the fit (after cuts) Int_t nHitsPoss = (Int_t) fParams[8] ; // Number of possible cluster on track (theoretical max) Int_t nHitsDedx = (Int_t) fParams[9] ; // Number of clusters used in the fit (after dEdx cuts) Float_t dEdx = 1.e6*(Float_t)fParams[10] ; // Measured dEdx (Note: GeV/cm so convert to keV/cm!!) Float_t nSigmaElectron = (Float_t) fParams[11] ; // Number of sigma from electron Bethe-Bloch curve Float_t nSigmaPion = (Float_t) fParams[12] ; // Number of sigma from pion Bethe-Bloch curve Float_t nSigmaKaon = (Float_t) fParams[13] ; // Number of sigma from kaon Bethe-Bloch curve Float_t nSigmaProton = (Float_t) fParams[14] ; // Number of sigma from proton Bethe-Bloch curve // Alternative way to access the data // nHitsPoss = (Int_t) ( fTracks->GetLeaf("nHitsPoss")->GetValue() ) ; // Note alternative method to retrieve data // Using the definition of the original NTuple // TrackTuple = new TNtuple("NTtracks","NTtracks", // "ID:Charge:Eta:Phi:Pt:Dca:nHits:nHitsFit:nHitsPoss:nHitsDedx:dEdx:nSigElect:nSigPi:nSigK:nSigProton" ) printf("%6d %4d %7.3f %7.3f %7.3f %7.4f %6d %5d %5d %5d %6.2f %6.2f %6.2f %6.2f %6.2f \n", id, charge, eta, phi, pt, dca, nHits, nHitsFit, nHitsPoss, nHitsDedx, dEdx, nSigmaElectron, nSigmaPion, nSigmaKaon, nSigmaProton ) ; } //______________________________________________________________________________ Int_t AliStarTrack::PID() const { // Note: This is a very simple PID selection scheme. More elaborate methods (with multiple cuts) may be required. // When you *are* using dEdx information, you must chose a finite number of good Dedx hits ... but the limit should // be about 2/3 of nHitsMin. This is because some clusters do not form good dEdx hits due to track // merging, etc., and so nHitsDedx is always less than nHitsFit. A rule of thumb says ~2/3 ratio. Int_t pid = 0 ; const Int_t nHitDedxMin = 15 ; // 10 to 20 is typical. nHitDedxMin is often chosen to be about 2/3 of nHitMin. const Float_t nSigmaPID = 2.0 ; // Number of Sigma cut to apply to PID bands // Test on Number of dE/dx hits required, return 0 if not enough hits if ( GetNHitsDedx() < nHitDedxMin ) return pid; // Begin PID if ( TMath::Abs( GetNSigElect() ) >= nSigmaPID ) { if ( TMath::Abs( GetNSigK() ) <= nSigmaPID ) { pid = 321 ; } if ( TMath::Abs( GetNSigProton() ) <= nSigmaPID ) { pid = 2212 ; } if ( TMath::Abs( GetNSigPi() ) <= nSigmaPID ) { pid = 211 ; } } // Pion is the default in case of ambiguity because it is most abundent. Don't re-arrange order, above. return pid ; }
42.354037
125
0.64203
[ "3d" ]
47714411aa3b6cdb7a7c9365d3dc26e507b9e2b2
5,977
cpp
C++
src/core/gui/FreeTypeFont.cpp
KCL-Planning/strategic-tactical-pandora
aa609af26a59e756b25212fa57fa72be937766e7
[ "BSD-2-Clause" ]
2
2019-01-27T05:17:06.000Z
2020-10-06T15:25:31.000Z
src/core/gui/FreeTypeFont.cpp
KCL-Planning/strategic-tactical-pandora
aa609af26a59e756b25212fa57fa72be937766e7
[ "BSD-2-Clause" ]
null
null
null
src/core/gui/FreeTypeFont.cpp
KCL-Planning/strategic-tactical-pandora
aa609af26a59e756b25212fa57fa72be937766e7
[ "BSD-2-Clause" ]
null
null
null
#include "FreeTypeFont.h" #include <glm/gtc/matrix_transform.hpp> FreeTypeFont::FreeTypeFont(const std::string& fontName, int screenWidth, int screenHeight, int fontSize) { m_fontName = fontName; m_screenWidth = screenWidth; m_screenHeight = screenHeight; m_fontSize = fontSize; shader_ = &GUIShader::getShader(); } FreeTypeFont::~FreeTypeFont() { glDeleteTextures(128, m_textureID); } bool FreeTypeFont::initialize() { FT_Library library; //Create a freetype library instance if (FT_Init_FreeType(&library)) { std::cerr << "Could not initialize the freetype library" << std::endl; return false; } FT_Face fontInfo; //Stores information on the loaded font //Now we attempt to load the font information if(FT_New_Face(library, m_fontName.c_str(), 0, &fontInfo)) { std::cerr << "Could not load the specified font" << std::endl; return false; } //FreeType uses heights which are one 64th of the size in pixels so //we set our font height by multiplying by 64. The 96x96 is the dots per inch FT_Set_Char_Size(fontInfo, (int)m_fontSize * 64, (int)m_fontSize * 64, 96, 96); //Generate 128 textures (each character gets its own texture) glGenTextures(128, m_textureID); for (unsigned char ch = 0; ch < 128; ++ch) { if (!generateCharacterTexture(ch, fontInfo)) { std::cerr << "Could not generate the texture for character: " << ch << std::endl; return false; } } FT_Done_Face(fontInfo); FT_Done_FreeType(library); float vertices [] = { 0.0f, 0.0f, 0.0f, (float)m_fontSize, 0.0f, 0.0f, (float)m_fontSize, (float)m_fontSize, 0.0f, 0.0f, (float)m_fontSize, 0.0f, }; glGenBuffers(1, &m_vertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 12, &vertices[0], GL_STATIC_DRAW); //Just initialize with something for now, the tex coords are updated //for each character printed float TexCoords [] = { 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f }; glGenBuffers(1, &m_TexCoordBuffer); glBindBuffer(GL_ARRAY_BUFFER, m_TexCoordBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 8, &TexCoords[0], GL_DYNAMIC_DRAW); return true; } bool FreeTypeFont::generateCharacterTexture(unsigned char ch, FT_Face fontInfo) { if(FT_Load_Glyph(fontInfo, FT_Get_Char_Index(fontInfo, ch), FT_LOAD_DEFAULT)) { return false; } FT_Glyph glyph; if(FT_Get_Glyph(fontInfo->glyph, &glyph)) { return false; } if (FT_Glyph_To_Bitmap(&glyph, ft_render_mode_normal, 0, 1)) { return false; } FT_BitmapGlyph bitmapGlyph = (FT_BitmapGlyph) glyph; int width = (bitmapGlyph->bitmap.width) ? bitmapGlyph->bitmap.width : 16; int rows = (bitmapGlyph->bitmap.rows) ? bitmapGlyph->bitmap.rows : 16; //Allocate space for our font texture (R, G, B, A) int imageSize = width * rows * 4; vector<unsigned char> imageData(imageSize); for (int i = 0; i < imageSize / 4; i++) { unsigned char gray = 0; if (bitmapGlyph->bitmap.buffer) { gray = bitmapGlyph->bitmap.buffer[i]; } imageData[i*4] = gray; imageData[(i*4)+1] = 0; imageData[(i*4)+2] = 0; imageData[(i*4)+3] = gray; //imageData[i*4] = gray; //imageData[(i*4)+1] = gray; //imageData[(i*4)+2] = gray; //imageData[(i*4)+3] = gray; } glBindTexture(GL_TEXTURE_2D, m_textureID[ch]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, rows, 0, GL_RGBA, GL_UNSIGNED_BYTE, &imageData[0]); m_glyphDimensions[ch] = std::make_pair(width, rows); m_glyphPositions[ch] = std::make_pair(bitmapGlyph->left, bitmapGlyph->top); m_glyphAdvances[ch] = fontInfo->glyph->advance.x / 64; return true; } void FreeTypeFont::printString(const glm::mat4& perspective_matrix, const std::string& str, float x, float y) { glPolygonMode( GL_FRONT_AND_BACK, GL_FILL); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glm::mat4 model_matrix(1.0f); model_matrix = glm::translate(model_matrix, glm::vec3(x, y, 0.0f)); for(string::size_type i = 0; i < str.size(); ++i) { int ch = int(str[i]); float vertices [] = { 0.0f, 0.0f, 0.0f, (float)m_glyphDimensions[ch].first, 0.0f, 0.0f, (float)m_glyphDimensions[ch].first, (float)m_glyphDimensions[ch].second, 0.0f, 0.0f, (float)m_glyphDimensions[ch].second, 0.0f, }; glm::mat4 local_model_matrix = glm::translate(model_matrix, glm::vec3((float)m_glyphPositions[ch].first, (float)m_glyphPositions[ch].second - m_glyphDimensions[ch].second, 0.0f)); glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(float) * 12, &vertices[0]); shader_->initialise(m_textureID[ch], m_vertexBuffer, m_TexCoordBuffer, local_model_matrix, perspective_matrix); glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer); glDrawArrays(GL_QUADS, 0, 4); model_matrix = glm::translate(model_matrix, glm::vec3((float)m_glyphAdvances[ch], 0.0f, 0.0f)); } glEnable(GL_DEPTH_TEST); } int FreeTypeFont::getWidth(const std::string& text) { int width = 0; for(string::size_type i = 0; i < text.size(); ++i) { int ch = int(text[i]); //width += m_glyphDimensions[ch].first + m_glyphAdvances[ch]; width += m_glyphAdvances[ch]; } return width; } int FreeTypeFont::getWidth(const char& c) { //return m_glyphDimensions[c].first + m_glyphAdvances[c]; return m_glyphAdvances[c]; }
31.130208
182
0.641124
[ "vector" ]
4772519fc317872a847fd7a69f56b537117fd878
842
cpp
C++
src/SceneDescription.cpp
diegomacario/Manta-Ray-Tracer
39fca8343f682ca318119ffd220af0234597bf9d
[ "MIT" ]
124
2017-10-24T00:11:02.000Z
2021-12-06T17:19:09.000Z
src/SceneDescription.cpp
diegomacario/Manta-Ray-Tracer
39fca8343f682ca318119ffd220af0234597bf9d
[ "MIT" ]
5
2017-10-24T21:11:47.000Z
2020-03-19T19:34:15.000Z
src/SceneDescription.cpp
diegomacario/Manta-Ray-Tracer
39fca8343f682ca318119ffd220af0234597bf9d
[ "MIT" ]
6
2017-10-24T20:29:25.000Z
2021-10-19T08:13:35.000Z
#include "SceneDescription.h" SceneDescription::SceneDescription(int width, int height, const std::string& outputFilename, const Point& eye, const Point& center, const Vector& up, float fovy) : width(width) , height(height) , outputFilename(outputFilename) , eye(eye) , center(center) , up(up) , fovy(fovy) { } SceneDescription::~SceneDescription() { } int SceneDescription::getWidth() { return width; } int SceneDescription::getHeight() { return height; } std::string SceneDescription::getOutputFilename() { return outputFilename; } Point SceneDescription::getEye() { return eye; } Point SceneDescription::getCenter() { return center; } Vector SceneDescription::getUpVec() { return up; } float SceneDescription::getFovy() { return fovy; }
16.509804
162
0.662708
[ "vector" ]
477763970b7e139a7be4bb247db7c8b6182df364
1,583
cpp
C++
random/appl_random_mgr.cpp
fboucher9/appl
bb90398cf9985d4cc0a2a079c4d49d891108e6d1
[ "MIT" ]
null
null
null
random/appl_random_mgr.cpp
fboucher9/appl
bb90398cf9985d4cc0a2a079c4d49d891108e6d1
[ "MIT" ]
null
null
null
random/appl_random_mgr.cpp
fboucher9/appl
bb90398cf9985d4cc0a2a079c4d49d891108e6d1
[ "MIT" ]
null
null
null
/* See LICENSE for license details */ /* */ #include <appl_status.h> #include <appl_predefines.h> #include <appl_types.h> #include <object/appl_object.h> #include <random/appl_random_mgr.h> #include <random/appl_random.h> #include <random/appl_random_pseudo.h> #include <random/appl_random_handle.h> #include <misc/appl_unused.h> #include <context/appl_context.h> #include <allocator/appl_allocator_handle.h> // // // enum appl_status appl_random_mgr::v_create_node( struct appl_random_descriptor const * const p_descriptor, struct appl_random * * const r_node) { appl_unused( p_descriptor, r_node); return appl_status_not_implemented; } // v_create_node() // // // enum appl_status appl_random_mgr::v_destroy_node( struct appl_random * const p_node) { appl_unused( p_node); return appl_status_not_implemented; } // v_destroy_node() // // // appl_random_mgr::appl_random_mgr( struct appl_context * const p_context) : appl_object( p_context) { } // // // appl_random_mgr::~appl_random_mgr() { } // // // enum appl_status appl_random_mgr::f_create_pseudo_node( unsigned long int const i_seed, struct appl_random * * const r_node) { enum appl_status e_status; e_status = appl_random_pseudo::s_create( m_context->v_allocator(), i_seed, r_node); return e_status; } // f_create_pseudo_node() /* end-of-file: appl_random_mgr.cpp */
14.794393
47
0.641819
[ "object" ]
4783f039c0675c7d4905366f6f816ab643751887
3,158
cpp
C++
common/Timer.cpp
caozhiyi/Hudp
85108e675d90985666d1d2a8f364015a467ae72f
[ "BSD-3-Clause" ]
57
2019-07-26T06:26:47.000Z
2022-03-22T13:12:12.000Z
common/Timer.cpp
caozhiyi/Hudp
85108e675d90985666d1d2a8f364015a467ae72f
[ "BSD-3-Clause" ]
1
2019-12-09T11:16:06.000Z
2020-04-09T12:22:23.000Z
common/Timer.cpp
caozhiyi/Hudp
85108e675d90985666d1d2a8f364015a467ae72f
[ "BSD-3-Clause" ]
20
2019-08-21T08:26:14.000Z
2021-11-21T09:58:48.000Z
#include "IMsg.h" #include "Timer.h" #include "ISocket.h" #include "HudpConfig.h" using namespace hudp; CTimer::CTimer() : _wait_time(__timer_empty_wait) { } CTimer::~CTimer() { Stop(); _notify.notify_one(); Join(); } uint64_t CTimer::AddTimer(uint32_t ms, std::shared_ptr<CMsg> ti) { _time_tool.Now(); uint64_t expiration_time = ms + _time_tool.GetMsec(); { std::unique_lock<std::mutex> lock(_mutex); auto iter = _timer_map.find(expiration_time); _timer_map[expiration_time].push_back(ti); ti->SetTimerId(expiration_time); } // wake up timer thread if (ms < _wait_time) { _notify.notify_one(); } return expiration_time; } void CTimer::RemoveTimer(std::shared_ptr<CMsg> ti) { { std::unique_lock<std::mutex> lock(_mutex); _timer_map.erase(ti->GetTimerId()); ti->SetTimerId(0); } _notify.notify_one(); } void CTimer::RemoveTimer(CMsg* ti) { { std::unique_lock<std::mutex> lock(_mutex); _timer_map.erase(ti->GetTimerId()); ti->SetTimerId(0); } _notify.notify_one(); } uint64_t CTimer::GetTimeStamp() { _time_tool.Now(); return _time_tool.GetMsec(); } void CTimer::Run() { std::vector<std::shared_ptr<CMsg>> timer_vec; std::list<std::shared_ptr<CMsg>> *cur_list = nullptr; uint64_t cur_timestemp = 0; bool timer_out = false; while (!_stop) { { cur_list = nullptr; timer_out = false; std::unique_lock<std::mutex> lock(_mutex); if (_timer_map.empty()) { _wait_time = __timer_empty_wait; } else { auto iter = _timer_map.begin(); cur_timestemp = iter->first; _time_tool.Now(); cur_list = &iter->second; if (iter->first > (uint64_t)_time_tool.GetMsec()) { _wait_time = iter->first - _time_tool.GetMsec(); } else { _wait_time = 0; timer_out = true; } } if (_wait_time > 0) { timer_out = _notify.wait_for(lock, std::chrono::milliseconds(_wait_time)) == std::cv_status::timeout; _time_tool.Now(); } // if timer out if (timer_out && cur_list && cur_timestemp > 0 && cur_timestemp <= (uint64_t)_time_tool.GetMsec()) { while (!cur_list->empty()) { timer_vec.push_back(cur_list->front()); cur_list->pop_front(); } _timer_map.erase(cur_timestemp); // timer is removed } else if (timer_out && cur_list && cur_timestemp == 0) { _timer_map.erase(cur_timestemp); } } if (timer_vec.size() > 0) { for (size_t i = 0; i < timer_vec.size(); i++) { auto sock = timer_vec[i]->GetSocket(); if (sock) { sock->TimerOut(timer_vec[i]); } } timer_vec.clear(); } } }
27.224138
117
0.525332
[ "vector" ]
4789342924514a4283ae84942c3aa7748a86ff19
3,392
cpp
C++
algo/sort/sort.cpp
slimccq/gist
2b08c9df81a979e0499b39fcaa644d446cd0c43a
[ "Apache-2.0" ]
null
null
null
algo/sort/sort.cpp
slimccq/gist
2b08c9df81a979e0499b39fcaa644d446cd0c43a
[ "Apache-2.0" ]
null
null
null
algo/sort/sort.cpp
slimccq/gist
2b08c9df81a979e0499b39fcaa644d446cd0c43a
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2016 ichenq@outlook.com. All rights reserved. // Distributed under the terms and conditions of the Apache License. // See accompanying files LICENSE. #include <assert.h> #include <string> #include <iostream> #include <chrono> #include <random> #include "sort.h" #include "merge_sort.h" #include "heap_sort.h" using namespace std; #ifdef NDEBUG #define EXPECT(cond) do { if (!(cond)) {int* p = 0; *p = 1;}} while(0) #else #define EXPECT(cond) assert(cond) #endif // now time in milliseconds static int64_t now_ms() { auto now = std::chrono::steady_clock::now(); return std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count(); } template <typename T> inline void printArray(const T arr[], int n) { for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << endl; } template <typename T> void do_sort(const std::string& algo, T arr[], int size) { if (algo == "bubble") { bubble_sort(arr, size); } else if (algo == "selection") { selection_sort(arr, size); } else if (algo == "insertion") { insertion_sort_aux(arr, size); } else if (algo == "shell") { shell_sort(arr, size); } else if (algo == "quick") { quick_sort(arr, size); } else if (algo == "merge") { merge_sort(arr, size); } else if (algo == "heap") { heap_sort(arr, size); } } const std::string all_sort_algo[] = {"bubble", "selection", "insertion", "shell", "quick", "merge", "heap"}; static void fill_random_array(int N, std::vector<int>& arr) { std::random_device rd; std::default_random_engine rnd(rd()); std::uniform_int_distribution<> dist(0, N); arr.resize(N); for (size_t i = 0; i < arr.size(); i++) { arr[i] = dist(rnd); } } static void test_sort_algo() { int N = 1000; std::vector<int> arr; fill_random_array(N, arr); std::vector<int> sorted = arr; std::sort(sorted.begin(), sorted.end()); EXPECT(std::is_sorted(sorted.begin(), sorted.end())); for (const std::string& algo : all_sort_algo) { std::vector<int> copy = arr; do_sort(algo, (int*)copy.data(), copy.size()); EXPECT(std::is_sorted(copy.begin(), copy.end())); EXPECT(copy == sorted); } } static double bench_random_input(const std::string& algo, int N, int T) { std::vector<int> arr; int64_t total = 0; for (int i = 0; i < T; i++) { arr.clear(); fill_random_array(N, arr); int64_t start = now_ms(); do_sort(algo, (int*)arr.data(), N); int64_t end = now_ms(); total += end - start; } return double(total) / 1000.0; } static void benchmark_sort(const std::string& algo1, const std::string& algo2, int N, int T) { double t1 = bench_random_input(algo1, N, T); double t2 = bench_random_input(algo2, N, T); printf("for %d random integers\n", N); printf("%s(%.2f) is %.2f times faster than %s(%.2f)\n", algo1.data(), t1, t2/t1, algo2.data(), t2); } int main(int argc, char* argv[]) { test_sort_algo(); if (argc != 5) { printf("Usage: %s N T algo1 algo2\n", argv[0]); return 1; } string algo1 = argv[1]; string algo2 = argv[2]; int N = atoi(argv[3]); int T = atoi(argv[4]); benchmark_sort(algo1, algo2, N, T); return 0; }
24.056738
108
0.587264
[ "vector" ]
4797338b6d73fda3ee26cc9cd13e55c854c0e874
881
cpp
C++
seminars/1/15/lambda/lambdaExample2.cpp
peshe/SDP20-21
af298e723c2934036048b26b168f8f8607fcec40
[ "CC0-1.0" ]
7
2020-10-05T09:32:28.000Z
2022-03-25T07:58:12.000Z
seminars/1/15/lambda/lambdaExample2.cpp
peshe/SDP20-21
af298e723c2934036048b26b168f8f8607fcec40
[ "CC0-1.0" ]
2
2020-11-16T20:41:04.000Z
2020-12-15T11:10:20.000Z
seminars/1/15/lambda/lambdaExample2.cpp
peshe/SDP20-21
af298e723c2934036048b26b168f8f8607fcec40
[ "CC0-1.0" ]
6
2020-10-09T15:46:55.000Z
2021-01-12T17:47:11.000Z
#include <iostream> #include <vector> #include <functional> using namespace std; bool isPrime(int n) { n = n<0 ? -n : n; for(int i = 2; i*i< n; ++i) { if(n % i == 0) { return false; } } return true; } int firstIndex(const vector<int>& arr, std::function<bool(int)> predicate) { for(int i = 0; i < arr.size(); ++i) { if(predicate(arr[i])) { return i; } } return -1; } int main() { vector<int> arr {15, 17, -2, 2, 4, 64, 12, 3, 7, 2, 18, 21}; auto even = [] (int n) { return n % 2 == 0; }; cout<< "first even: "<< firstIndex(arr, even)<< endl; cout<< "first divisible: "<< firstIndex(arr, [] (int n) { return n % 3 == 0; })<< endl; cout<< "first: "<< firstIndex(arr, [] (int n) { return n == 2; })<< endl; cout<< "first prime: "<< firstIndex(arr, isPrime)<< endl; }
22.589744
91
0.498297
[ "vector" ]
479bcc5447a0b1dfb50dfbda67e8d83e3b92c9a5
147
hpp
C++
include/xul/lang/object_base.hpp
hindsights/xul
666ce90742a9919d538ad5c8aad618737171e93b
[ "MIT" ]
2
2018-03-16T07:06:48.000Z
2018-04-02T03:02:14.000Z
include/xul/lang/object_base.hpp
hindsights/xul
666ce90742a9919d538ad5c8aad618737171e93b
[ "MIT" ]
null
null
null
include/xul/lang/object_base.hpp
hindsights/xul
666ce90742a9919d538ad5c8aad618737171e93b
[ "MIT" ]
1
2019-08-12T05:15:29.000Z
2019-08-12T05:15:29.000Z
#pragma once #include <xul/lang/object_impl.hpp> #include <assert.h> namespace xul { class object_base : public object_impl<object> { }; }
8.647059
46
0.70068
[ "object" ]
479da5c7ce290bcb35abdcd0a4250ce6c2679cc9
2,886
cc
C++
src/test/t_font.cc
rklogan/fontdiff
9e0d7c3ab7e4dfa07e533846c5b1c1743839a72d
[ "Apache-2.0" ]
null
null
null
src/test/t_font.cc
rklogan/fontdiff
9e0d7c3ab7e4dfa07e533846c5b1c1743839a72d
[ "Apache-2.0" ]
null
null
null
src/test/t_font.cc
rklogan/fontdiff
9e0d7c3ab7e4dfa07e533846c5b1c1743839a72d
[ "Apache-2.0" ]
null
null
null
#include "t_font.h" // Test Solutions const vector<string> pathToFonts = vector<string>({ "./src/assets/fonts/OpenSans-BoldItalic.ttf", "./src/assets/fonts/OpenSans-Bold.ttf", "./src/assets/fonts/OpenSans-ExtraBold.ttf", "./src/assets/fonts/OpenSans-ExtraBoldItalic.ttf", "./src/assets/fonts/OpenSans-Italic.ttf", "./src/assets/fonts/OpenSans-Light.ttf", "./src/assets/fonts/OpenSans-LightItalic.ttf", "./src/assets/fonts/OpenSans-Regular.ttf", "./src/assets/fonts/OpenSans-Semibold.ttf", "./src/assets/fonts/OpenSans-SemiboldItalic.ttf", "./src/assets/fonts/OpenSans-BoldItalic.ttf" }); const unsigned int weightDistances1[2][11] = { {700, 700, 800, 800, 400, 300, 300, 400, 600, 600, 700}, {686, 686, 786, 786, 386, 286, 286, 386, 586, 586, 686} }; const double weightDistances2[11] = {690.4, 690.4, 790.4, 790.4, 390.4, 290.4, 290.4, 390.4, 590.4, 590.4, 690.4}; const int italicAngles[11] = {-786432, 0, 0, -786432, -786432, 0, -786432, 0, 0, -786432, -786432}; TEST_CASE("Font::Load Single Argument") { for(auto it = pathToFonts.begin(); it != pathToFonts.end(); ++it) { auto font = fontdiff::Font::Load(*it); REQUIRE(font != NULL); delete(font); } } TEST_CASE("Font::Load Bad Argument") { auto font = fontdiff::Font::Load("ddfgijhdafgkjnsdf"); REQUIRE(font == NULL); delete(font); } TEST_CASE("Font::Load No Argument") { auto font = fontdiff::Font::Load(""); REQUIRE(font == NULL); delete(font); } TEST_CASE("Font::getWeightDistances") { for(int i{0}; i < pathToFonts.size(); ++i) { auto font = fontdiff::Font::Load(pathToFonts.at(i)); REQUIRE(font->at(0)->GetWeightDistance(0) == weightDistances1[0][i]); REQUIRE(font->at(0)->GetWeightDistance(14) == weightDistances1[1][i]); REQUIRE(font->at(0)->GetWeightDistance(9.6) == weightDistances2[i]); delete(font); } } TEST_CASE("Font::GetWidthDistance") { for(int i{0}; i < pathToFonts.size(); ++i) { auto font = fontdiff::Font::Load(pathToFonts.at(i)); REQUIRE(font->at(0)->GetWidthDistance(0) == 100); REQUIRE(font->at(0)->GetWidthDistance(12) == 88); REQUIRE(font->at(0)->GetWidthDistance(85.5) == 14.5); delete(font); } } TEST_CASE("Font::GetItalicAngle()") { for(int i{0}; i < pathToFonts.size(); ++i) { auto font = fontdiff::Font::Load(pathToFonts.at(i)); REQUIRE(font->at(0)->GetItalicAngle() == italicAngles[i]); delete(font); } } TEST_CASE("Font::IsCovering()") { for(int i{0}; i < pathToFonts.size(); ++i) { auto font = fontdiff::Font::Load(pathToFonts.at(i)); REQUIRE(font->at(0)->IsCovering(0) == 0); delete(font); } }
30.0625
85
0.588011
[ "vector" ]
47a17b99daa986cdbeda596e85c78a612a675236
1,637
hh
C++
renderer/src/AmbiSphericalConvolution.hh
facebookincubator/Audio360
171bfbfa69c4724026ef8d06a0f5155b1a9de32b
[ "MIT" ]
46
2018-04-27T20:37:51.000Z
2019-10-09T17:32:17.000Z
renderer/src/AmbiSphericalConvolution.hh
facebookarchive/Audio360
171bfbfa69c4724026ef8d06a0f5155b1a9de32b
[ "MIT" ]
1
2018-09-23T16:52:55.000Z
2018-09-23T16:52:55.000Z
renderer/src/AmbiSphericalConvolution.hh
facebookincubator/Audio360
171bfbfa69c4724026ef8d06a0f5155b1a9de32b
[ "MIT" ]
2
2018-04-27T21:28:16.000Z
2018-04-30T05:35:30.000Z
/* Copyright (c) 2018-present, Facebook, Inc. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. */ #pragma once #include "../../dsp/src/DSP.hh" #include "AmbiDefinitions.hh" #include <memory> #include <vector> namespace TBE { class AmbiSphericalConvolution { public: /// A class to binaurally spatialise an Ambisonic field. Input Ambisonics is assumed to be in ACN /// channel order, SN3D normalisation and SN3D normalisation (as proposed by the ambiX /// specification) \param maxBufferSize Maximum mono number of samples \param ambisonicIR Contains /// impulse response and Ambisonic order information AmbiSphericalConvolution(size_t maxBufferSize, AmbisonicIRContainer ambisonicIR); /// Process the input Ambisonic audio through the provided Ambisonic to binaural impulse responses /// \param ambisonicIn The Ambisonic audio input to be binaurally spatialised as an un-interleaved /// signal. ambisonicIn[0][0] = harmonic 0, ambisonicIn[1][0] = harmonic 1, etc \param binauralOut /// The rendered stereo binaural output as an un-interleaved signal. binauralOut[0][0] = left, /// binauralOut[1][0] right /// \param bufferLength The number of samples in a mono buffer void process(const float** ambisonicIn, float** binauralOut, int bufferLength); private: AmbisonicIRContainer irs_; size_t ambisonicOrder_{0}; size_t maxBufferSize_{0}; FBDSP dsp_; std::unique_ptr<float[]> tmpBuf_; std::unique_ptr<float[]> oddHmBuf_; std::unique_ptr<int[]> silenceCounts_; std::vector<TBE::FIR> ambiFir_; }; } // namespace TBE
36.377778
100
0.750764
[ "vector" ]
47a98c27ff78d671f295a94e482ef103e0fe82b5
216
cpp
C++
graphic/geometry.cpp
MihailJP/MiHaJong
b81168ab2696dd29af5c400b84c870a9b8a2f01e
[ "MIT" ]
13
2016-01-20T02:10:52.000Z
2022-03-08T15:51:36.000Z
graphic/geometry.cpp
MihailJP/MiHaJong
b81168ab2696dd29af5c400b84c870a9b8a2f01e
[ "MIT" ]
13
2020-09-28T12:57:52.000Z
2022-02-20T19:20:57.000Z
graphic/geometry.cpp
MihailJP/MiHaJong
b81168ab2696dd29af5c400b84c870a9b8a2f01e
[ "MIT" ]
4
2016-09-19T13:44:10.000Z
2022-02-18T08:13:37.000Z
#include "geometry.h" namespace mihajong_graphic { unsigned Geometry::WindowWidth = 1024; unsigned Geometry::WindowHeight = 768; //unsigned Geometry::WindowWidth = 1280; //unsigned Geometry::WindowHeight = 960; }
19.636364
40
0.763889
[ "geometry" ]
47b37f7901f0be883c06fe9179d9ed6b1c5848c8
1,358
cpp
C++
.LHP/.Lop11/.HSG/New folder/New folder (2)/B/B/B.cpp
sxweetlollipop2912/MaCode
661d77a2096e4d772fda2b6a7f80c84113b2cde9
[ "MIT" ]
null
null
null
.LHP/.Lop11/.HSG/New folder/New folder (2)/B/B/B.cpp
sxweetlollipop2912/MaCode
661d77a2096e4d772fda2b6a7f80c84113b2cde9
[ "MIT" ]
null
null
null
.LHP/.Lop11/.HSG/New folder/New folder (2)/B/B/B.cpp
sxweetlollipop2912/MaCode
661d77a2096e4d772fda2b6a7f80c84113b2cde9
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <queue> #include <vector> #define maxN 5002 #define minR -5000000000001 #define del -2 typedef int maxn; typedef long long maxa; typedef std::pair <maxn, maxa> pq_t; maxn n, K, N; maxa a[maxN], res; int imp[maxN]; void Prepare() { std::cin >> n >> K >> a[0], res = a[0]; N = 1; for (maxn i = 1; i < n; i++) { maxa x; std::cin >> x, res += x; if (x * a[N - 1] >= 0) a[N - 1] += x; else ++N, a[N - 1] = x; } } class cmp { public: bool operator() (const maxn x, const maxn y) { return a[x] > a[y]; } }; std::priority_queue <maxn, std::vector <maxn>, cmp> pqi, pqd; void Process() { maxn cnt = 1; maxa re_1 = res; for (maxn i = 1; i < N - 1; i++) if (a[i] < 0) pqi.push(i); std::fill(imp, imp + N, 1); while (!pqi.empty() && cnt < K) { maxn idx = pqi.top(); pqi.pop(); re_1 -= a[idx], imp[idx] = del, ++cnt; if (idx != 0 && (--imp[idx - 1]) == -1) pqd.push(idx - 1); if (idx != N - 1 && (--imp[idx + 1]) == -1) pqd.push(idx + 1); while (!pqi.empty() && imp[pqi.top()] != 1) pqi.pop(); } while (!pqd.empty()) { maxn idx = pqd.top(); pqd.pop(); if (!pqi.empty()) { maxn idx1 = pqi.top(); pqi.pop(); res = std::max(res, re_1 - a[idx] + a[idx1]); } else res = std::max(res, re_1 - a[idx]); } std::cout << res; } int main() { Prepare(); Process(); }
19.4
64
0.52651
[ "vector" ]
47b47c09e728186dbf2790c89db5d5eacb62e1f1
1,779
cpp
C++
source/serenum3.cpp
taogashi/mlib
56d0ac08205b3a09cac7ed97209454cc6262c924
[ "Unlicense", "MIT" ]
12
2020-07-08T04:21:44.000Z
2022-03-24T10:02:03.000Z
source/serenum3.cpp
taogashi/mlib
56d0ac08205b3a09cac7ed97209454cc6262c924
[ "Unlicense", "MIT" ]
null
null
null
source/serenum3.cpp
taogashi/mlib
56d0ac08205b3a09cac7ed97209454cc6262c924
[ "Unlicense", "MIT" ]
2
2020-07-22T09:00:40.000Z
2021-06-29T13:54:10.000Z
/*! \file serenum2.cpp Implementation of SerEnum_UsingRegistry() function. (c) Mircea Neacsu 2017. All rights reserved. */ #include <mlib/serenum.h> using namespace std; namespace mlib { /*! \ingroup serenum Enumerates all values under `HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM` to retrieve available COM ports. */ bool SerEnum_UsingRegistry (vector<int>& ports) { HKEY comm_key; if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"HARDWARE\\DEVICEMAP\\SERIALCOMM", 0, KEY_READ , &comm_key) != ERROR_SUCCESS) return false; //Get the max value name and max value lengths DWORD max_value_name_len = 0, max_value_len = 0, nvalues = 0; if (RegQueryInfoKey (comm_key, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &nvalues, &max_value_name_len, &max_value_len, nullptr, nullptr) != ERROR_SUCCESS) { RegCloseKey (comm_key); return false; } //Allocate some space for the value and value name wstring value_name(max_value_name_len+1, L'\0'); wstring value (max_value_len+1, L'\0'); //Enumerate all the values underneath HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM bool continue_enumeration = true; DWORD index = 0; while (continue_enumeration) { max_value_name_len = (DWORD)value_name.length (); max_value_len = (DWORD)(DWORD)value.length (); DWORD type; int port_num; DWORD ret = RegEnumValue (comm_key, index, &value_name[0], &max_value_name_len, nullptr, &type, (BYTE*)&value[0], &max_value_len); continue_enumeration = (ret == ERROR_SUCCESS); if (continue_enumeration) { if ((type == REG_SZ) && swscanf (value.c_str (), L"COM%d", &port_num) == 1) ports.push_back (port_num); //Prepare for the next loop index++; } } return true; } }
28.238095
134
0.698707
[ "vector" ]
47ba7f736214c7884f1778db659649c5e03b72a3
3,225
hpp
C++
dcgmi/MigIdParser.hpp
deepio/DCGM
d10273f18fb3d425da752ab6bb7e07af3d18caec
[ "Apache-2.0" ]
85
2021-02-03T19:58:50.000Z
2022-03-21T08:00:11.000Z
dcgmi/MigIdParser.hpp
deepio/DCGM
d10273f18fb3d425da752ab6bb7e07af3d18caec
[ "Apache-2.0" ]
19
2021-03-19T08:13:58.000Z
2022-03-17T02:50:41.000Z
dcgmi/MigIdParser.hpp
deepio/DCGM
d10273f18fb3d425da752ab6bb7e07af3d18caec
[ "Apache-2.0" ]
17
2021-02-04T06:47:30.000Z
2022-03-21T22:14:03.000Z
/* * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cstdint> #include <ostream> #include <string> #include <string_view> #include <variant> namespace DcgmNs { constexpr std::string_view CutUuidPrefix(std::string_view value) noexcept { if (value.substr(0, 4) == "MIG-") { value.remove_prefix(4); } if (value.substr(0, 4) == "GPU-") { value.remove_prefix(4); } return value; } struct ParsedUnknown { bool operator==(ParsedUnknown const &) const; }; struct ParsedGpu { std::string gpuUuid; explicit ParsedGpu(std::string_view uuid); bool operator==(ParsedGpu const &) const; }; struct ParsedGpuI { std::string gpuUuid; std::uint32_t instanceId = -1; ParsedGpuI(std::string_view uuid, std::uint32_t instanceId); bool operator==(ParsedGpuI const &) const; }; struct ParsedGpuCi { std::string gpuUuid; std::uint32_t instanceId = -1; std::uint32_t computeInstanceId = -1; ParsedGpuCi(std::string_view uuid, std::uint32_t instanceId, std::uint32_t computeInstanceId); bool operator==(ParsedGpuCi const &) const; }; using ParseResult = std::variant<ParsedGpu, ParsedGpuI, ParsedGpuCi, ParsedUnknown>; std::ostream &operator<<(std::ostream &os, ParseResult const &val); /** * Parses possible GPU or Instance or Compute Instance Ids * @param value String representation in one of the allowed forms. See notes. * @return One of the following possible values: * \retval \c ParsedUnknown Parsing failed * \retval \c ParsedGpu The value was parsed as a GpuId and the returned object will has ParsedGpu::gpuUuid value. * \retval \c ParsedGpuI The value was parsed as a GpuInstanceId and the returned object has ParsedGpuI::gpuUuid * and ParsedGpuI::instanceId values. * \retval \c ParsedGpuCi The value was parsed as a GpuComputeInstanceId and the * returned object has ParsedGpuCi::gpuUuid, ParsedGpuCi::instanceId, and * ParsedGpuCi::computeInstanceId values. */ ParseResult ParseInstanceId(std::string_view value); } // namespace DcgmNs namespace std { template <> struct hash<DcgmNs::ParsedUnknown> { size_t operator()(DcgmNs::ParsedUnknown const &) const; }; template <> struct hash<DcgmNs::ParsedGpu> { size_t operator()(DcgmNs::ParsedGpu const &) const; }; template <> struct hash<DcgmNs::ParsedGpuI> { size_t operator()(DcgmNs::ParsedGpuI const &) const; }; template <> struct hash<DcgmNs::ParsedGpuCi> { size_t operator()(DcgmNs::ParsedGpuCi const &) const; }; } // namespace std
27.330508
119
0.693643
[ "object" ]
47bfca0e90b21d7b582e59f3e665629f51d009c8
4,409
cpp
C++
apps/HVCC_SG_GRADP_FORCE/init.cpp
Guo-astro/Simulations
55c04dd1811993ef4099ea009af89fbd265c4241
[ "MIT" ]
null
null
null
apps/HVCC_SG_GRADP_FORCE/init.cpp
Guo-astro/Simulations
55c04dd1811993ef4099ea009af89fbd265c4241
[ "MIT" ]
null
null
null
apps/HVCC_SG_GRADP_FORCE/init.cpp
Guo-astro/Simulations
55c04dd1811993ef4099ea009af89fbd265c4241
[ "MIT" ]
null
null
null
#include "header.h" void Initialize(PS::ParticleSystem<RealPtcl>& sph_system) { for (PS::S32 i = 0; i < sph_system.getNumberOfParticleLocal(); ++i) { sph_system[i].smth = PARAM::SMTH * pow(sph_system[i].mass / sph_system[i].dens, 1.0 / (PS::F64) (PARAM::Dim)); sph_system[i].setPressure(); } } double f1(double t, double x, double v) { return v; } double f2(double t, double x, double v) { return -pow(x, 1.5) - 2.0 / t * v; } double getPhi(double x) { double a = 9.999995857999977E-01; double b = -3.215355146247138E-04; double c = -1.667864474453594E-01; double d = 5.252845006191754E-04; double e = 1.155630978128144E-02; double f = 1.050795977407310E-03; double g = -1.389661348847463E-03; double h = 2.648078982351008E-04; double i = -1.692465157938468E-05; double phi = a + b * pow(x, 1) + c * pow(x, 2) + d * pow(x, 3) + e * pow(x, 4) + f * pow(x, 5) + g * pow(x, 6) + h * pow(x, 7) + i * pow(x, 8); return phi; } double getPhi_dash(double x) { double a = -3.257098683322130E-04; double b = -3.335390631705378E-01; double c = 1.494801635423298E-03; double d = 4.629812975807299E-02; double e = 5.242083986884144E-03; double f = -8.358773124387748E-03; double g = 1.867615193618750E-03; double h = -1.388085203319444E-04; double i = 2.998565502661576E-07; double phi = a + b * pow(x, 1) + c * pow(x, 2) + d * pow(x, 3) + e * pow(x, 4) + f * pow(x, 5) + g * pow(x, 6) + h * pow(x, 7) + i * pow(x, 8); return phi; } double fRand(double fMin, double fMax) { double f = (double) rand() / RAND_MAX; return fMin + f * (fMax - fMin); } void SetupIC_Polytrope_Dens_Relaxation(PS::ParticleSystem<RealPtcl>& sph_system, PS::F64* end_time) { std::vector<RealPtcl> ptcl; const PS::F64 Radi = PARAM::xi - 0.005; *end_time = 10000; const PS::F64 dx = 1 / 8; PS::S32 id = 0; int ptcl_num = 10000; int shell_num = 5000; double shell_width = PARAM::poly_r / shell_num; double mass = PARAM::poly_M / ptcl_num; for (int i = 0; i < shell_num - 1; i++) { const PS::F64 _r = shell_width * i; const PS::F64 _r_next = shell_width * (i + 1); double current_phi = getPhi(_r); double current_phi_dash = getPhi_dash(_r); double current_phi_next = getPhi(_r_next); double current_phi_dash_next = getPhi_dash(_r_next); double inner_mass = -4.0 * M_PI * _r * _r * current_phi_dash; double inner_mass_next = -4.0 * M_PI * _r_next * _r_next * current_phi_dash_next; int ptcl_num_inshell = (inner_mass_next - inner_mass) / mass; for (int i = 0; i < ptcl_num_inshell; i++) { double costheta = fRand(-1, 1); double phi = fRand(0, 2.0 * M_PI); double x = _r_next * sqrt(1. - costheta * costheta) * cos(phi); double y = _r_next * sqrt(1. - costheta * costheta) * sin(phi); double z = _r_next * costheta; if (sqrt(x * x + y * y + z * z) <= _r) { continue; } RealPtcl ith; ith.pos.x = x; ith.pos.y = y; ith.pos.z = z; ith.dens = pow(current_phi, 1.5); ith.mass = mass; ith.pres = 0.5 * pow(ith.dens, 2.0); ith.eng = 2.5; ith.id = id++; ptcl.push_back(ith); } } for (PS::U32 i = 0; i < ptcl.size(); ++i) { ptcl[i].smth = pow(ptcl[i].mass / ptcl[i].dens, 1 / 3); } if (PS::Comm::getRank() == 0) { const PS::S32 numPtclLocal = ptcl.size(); sph_system.setNumberOfParticleLocal(numPtclLocal); for (PS::U32 i = 0; i < ptcl.size(); ++i) { sph_system[i] = ptcl[i]; } std::cout << "Ptcls num: " << numPtclLocal << std::endl; } else { sph_system.setNumberOfParticleLocal(0); } } void SetupIC_Restart_Polytrope_Dens_Relaxation(PS::ParticleSystem<RealPtcl>& sph_system, PS::F64* end_time) { *end_time = 1000000 * 0.74 * 1e6 * PARAM::yr / PARAM::ST; FileHeader header; #ifdef RESTART sph_system.readParticleAscii<FileHeader>( "CO_0.2_0.4_mass/ascii/HVCC_imp_7.00/HVCC_0313.txt", header); #else sph_system.readParticleAscii("result/0800.dat", header); PS::U32 ptcl_size = sph_system.getNumberOfParticleGlobal(); std::cout << "setup...ptcl num " << ptcl_size << std::endl; //Reset Energy for (PS::S32 i = 0; i < sph_system.getNumberOfParticleLocal(); ++i) { // sph_system[i].eng = sph_system[i].pres / ((PARAM::GAMMA - 1) * sph_system[i].dens); // sph_system[i].smth = pow(sph_system[i].mass / sph_system[i].dens, 1.0 / (PS::F64) (PARAM::Dim)); // std::cout << "dens " << pow(sph_system[i].mass / sph_system[i].dens, 1. / 3.) << " " << sph_system[i].smth << std::endl; } #endif }
31.949275
144
0.640054
[ "vector" ]
47c9b43e872853000e03ac0c82fc6db20063db22
8,905
cpp
C++
tech/Game/Scene.cpp
nbtdev/teardrop
fa9cc8faba03a901d1d14f655a04167e14cd08ee
[ "MIT" ]
null
null
null
tech/Game/Scene.cpp
nbtdev/teardrop
fa9cc8faba03a901d1d14f655a04167e14cd08ee
[ "MIT" ]
null
null
null
tech/Game/Scene.cpp
nbtdev/teardrop
fa9cc8faba03a901d1d14f655a04167e14cd08ee
[ "MIT" ]
null
null
null
/****************************************************************************** Copyright (c) 2015 Teardrop Games Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ #include "Scene.h" #include "Component_Render.h" #include "TerrainZone.h" #include "ZoneObject.h" #include "LoadListener.h" #include "Asset/LandscapeAsset.h" #include "Game/Component_Physics.h" #include "Physics/Physics.h" #include "Physics/World.h" #include "Physics/CollisionFilter.h" #include "Reflection/Reflection.h" #include "Util/StringUtil.h" #include "Util/_String.h" #include "Util/Logger.h" #include "Util/Environment.h" #include "Util/SystemManager.h" #include "Math/MathUtil.h" #include "Memory/Memory.h" #include <algorithm> using namespace Teardrop; //--------------------------------------------------------------------------- const static float TIMESTEP = 1.f/60.f; //--------------------------------------------------------------------------- Scene::Scene() { m_currentZone = Zone::INVALID; m_pWorld = 0; m_accumTime = 0; } //--------------------------------------------------------------------------- Scene::~Scene() { } //--------------------------------------------------------------------------- bool Scene::initialize() { // create the zone(s) from the LandscapeAsset data Zone* zone = createZone(TerrainZone::getClassDef(), 0); setCurrentZone(*zone); return true; } //--------------------------------------------------------------------------- World* Scene::getWorld() { return m_pWorld; } //--------------------------------------------------------------------------- void Scene::setupCollisionFilters() { if (!m_pWorld) return; // set up default collisions CollisionFilter* pF = m_pWorld->getOrCreateCollisionFilter(); pF->disableCollisionBetween(COLLISION_LAYER_RAGDOLL, COLLISION_LAYER_CHARACTER_PROXY); pF->disableCollisionBetween(COLLISION_LAYER_RAGDOLL, COLLISION_LAYER_RAGDOLL); m_pWorld->applyCollisionFilter(); } //--------------------------------------------------------------------------- bool Scene::destroy() { for (Zones::iterator it = m_zones.begin(); it != m_zones.end(); ++it) { (*it).pZone->destroy(); delete (*it).pZone; } m_zones.clear(); if (m_pWorld) { //PhysicsSystem* pSys = static_cast<PhysicsSystem*>( // Environment::get().pSystemMgr->getActiveSystem(System::SYSTEM_PHYSICS)); //pSys->removeWorldFromDebugger(m_pWorld); m_pWorld->release(); delete m_pWorld; m_pWorld = 0; } return true; } //--------------------------------------------------------------------------- bool Scene::update(float deltaT) { m_accumTime += deltaT; while (m_accumTime > TIMESTEP) { if (m_pWorld) { if (!m_pWorld->update(TIMESTEP)) return false; } m_accumTime -= TIMESTEP; } // probably should update visible neighbors too? m_zones[m_currentZone].pZone->update(deltaT); return true; } //--------------------------------------------------------------------------- const Vector4& Scene::getAmbientLight() const { return m_zones[m_currentZone].pZone->getAmbient(); } //--------------------------------------------------------------------------- Zone* Scene::createZone(const char* type, LoadListener* pCB) { if (!type) return 0; // use reflection to create the instance return createZone(Reflection::ClassDef::findClassDef(type), pCB); } //--------------------------------------------------------------------------- Zone* Scene::createZone(Reflection::ClassDef* pClassDef, LoadListener* pCB) { if (!pClassDef) return 0; ZoneNode node; node.pZone = static_cast<Zone*>(pClassDef->createInstance()); #if 0 if (!_stricmp("terrain", type)) node.pZone = TD_NEW TerrainZone; else node.pZone = TD_NEW Zone; // plain zone #endif // 0 node.pZone->setId(m_zones.size()); node.pZone->m_pScene = this; node.pZone->m_pLoadListener = pCB; m_zones.push_back(node); return node.pZone; } //--------------------------------------------------------------------------- void Scene::destroyZone(Zone* pZone) { if (!pZone) { return; } // remove this guy from the neighbor list first size_t id = pZone->getId(); ZoneNode& zn = m_zones[id]; for (ZoneNeighbors::iterator it = zn.neighbors.begin(); it != zn.neighbors.end(); ++it) { ZoneNode& node = m_zones[*it]; ZoneNeighbors::iterator n = std::find(node.neighbors.begin(), node.neighbors.end(), id); if (n != node.neighbors.end()) { node.neighbors.erase(n); } } // then delete the Zone delete zn.pZone; // then remove the node itself std::remove(m_zones.begin(), m_zones.end(), zn); } //--------------------------------------------------------------------------- bool Scene::addNeighbor(const Zone *pMe, const Zone* pNeighbor) { if (!pMe || !pNeighbor) { return false; } m_zones[pMe->getId()].neighbors.push_back(pNeighbor->getId()); m_zones[pNeighbor->getId()].neighbors.push_back(pMe->getId()); return true; } //--------------------------------------------------------------------------- Zone* Scene::getCurrentZone() const { if (m_currentZone == Zone::INVALID) { return 0; } return m_zones[m_currentZone].pZone; } //--------------------------------------------------------------------------- bool Scene::setCurrentZone(const Zone& zone) { m_currentZone = zone.getId(); return true; } //--------------------------------------------------------------------------- bool Scene::getVisibleObjects( const Plane* frustum, ZoneObjects& objects) const { // for now, they are *all* visible if (m_currentZone <= m_zones.size()) { return m_zones[m_currentZone].pZone->getVisibleObjects(frustum, objects); } return false; } //--------------------------------------------------------------------------- bool Scene::findObjectsWithinRadius( ZoneObjects& objects, const Vector4& origin, float radius, FilterFunc fn) const { return m_zones[m_currentZone].pZone->getObjectsWithinRadius( origin, radius, objects, fn); } //--------------------------------------------------------------------------- bool Scene::getIntersectingObjects( /*in*/const Ray& ray, /*out*/ZoneObjects& objects, bool sort, bool precise ) const { if (precise) { // use the collision engine to do the raycast if (m_pWorld) { void* pCollidable[64]; size_t collidableCount = 64; if (m_pWorld->castRay(ray, pCollidable, collidableCount)) { // whatever the collidable is, it should point to a PhysicsComponent // instance, and from that we can get the component host and // fill out the object list objects.reserve(collidableCount); for (size_t i=0; i<collidableCount; ++i) { PhysicsComponent* pComp = static_cast<PhysicsComponent*>(pCollidable[i]); if (pComp) { ZoneObject* pObj = dynamic_cast<ZoneObject*>(pComp->getHost()); objects.push_back(pObj); } } return (0 != objects.size()); } } } else { // use the coarse AABB intersection testing return m_zones[m_currentZone].pZone->getIntersectingObjects( ray, objects, sort); } return false; } //--------------------------------------------------------------------------- bool Scene::getIntersectionPoints( /*in*/const Ray& ray, /*out*/Vector4* pPoints, /*inout*/size_t& pointCount ) { if (m_pWorld) return m_pWorld->castRay(ray, pPoints, pointCount); return false; } //--------------------------------------------------------------------------- void Scene::findAllObjectsOfType( /*in*/const Reflection::ClassDef* pClass, /*out*/ZoneObjects& list) { list.clear(); // brute force -- go through all objects and compare their derived // classdef against pClass Zone* pZone = m_zones[m_currentZone].pZone; for(ZoneObjects::iterator it = pZone->m_objects.begin(); it != pZone->m_objects.end(); ++it) { if (*it && (*it)->getDerivedClassDef() == pClass) list.push_back(*it); } }
27.828125
87
0.573723
[ "object" ]
47d4fba9ba7d28312a101b70555a7a59749d0014
2,745
hpp
C++
engine/engine/gems/serialization/json.hpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
1
2020-04-14T13:55:16.000Z
2020-04-14T13:55:16.000Z
engine/engine/gems/serialization/json.hpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
4
2020-09-25T22:34:29.000Z
2022-02-09T23:45:12.000Z
engine/engine/gems/serialization/json.hpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
1
2022-01-28T16:37:51.000Z
2022-01-28T16:37:51.000Z
/* Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited. */ #pragma once #include <map> #include <string> #include <utility> #include "engine/core/optional.hpp" #include "third_party/nlohmann/json.hpp" namespace isaac { // We are using nlohmann::json as JSON using Json = nlohmann::json; namespace serialization { // Loads and parses a JSON object from a file Json LoadJsonFromFile(const std::string& filename); // Parses a JSON object from a text string // @deprecated Json LoadJsonFromText(const std::string& text); // Loads and parses a JSON object from a file without ASSERT // Returns nullopt in case of failure std::optional<Json> TryLoadJsonFromFile(const std::string& filename); // Writes JSON to a file bool WriteJsonToFile(const std::string& filename, const Json& json); // Merges two JSON objects into one Json MergeJson(const Json& a, const Json& b); // Replace keys in the top level of json. In the key_map, the first value is the existing key to // replace and second value is the new key with which to replace it. // Returns the number of keys that were replaced (renaming a key to same name counts as a // replacement). int ReplaceJsonKeys(const std::map<std::string, std::string>& key_map, Json& json); // Parses a JSON object from a text string std::optional<Json> ParseJson(const std::string& text); // Helper class for merging multiple JSON files and/or objects into one JSON object class JsonMerger { public: JsonMerger() {} // Add JSON file to be merged JsonMerger& withFile(const std::string& json_filename) & { json_ = MergeJson(json_, LoadJsonFromFile(json_filename)); return *this; } // Add JSON file to be merged JsonMerger&& withFile(const std::string& json_filename) && { json_ = MergeJson(json_, LoadJsonFromFile(json_filename)); return std::move(*this); } // Add JSON object to be merged JsonMerger& withJson(const Json& json) & { json_ = MergeJson(json_, json); return *this; } // Add JSON object to be merged JsonMerger&& withJson(const Json& json) && { json_ = MergeJson(json_, json); return std::move(*this); } // Convert to JSON using a copy operator Json() const& { return json_; } // Convert to JSON using a move operator Json() && { return std::move(json_); } private: // JSON being merged Json json_; }; } // namespace serialization } // namespace isaac
29.516129
96
0.730055
[ "object" ]
47d5de830346c18969c8206587d0fe9923b81bd5
787
cpp
C++
Cpp_Primer_5E_Learning/Chapter3/E3.20.cpp
feiwofeifeixiaowo/CppPrimer5thAnswer
c22fb5f9369d05cafb7f3d8d75b4f499de4c2105
[ "MIT" ]
null
null
null
Cpp_Primer_5E_Learning/Chapter3/E3.20.cpp
feiwofeifeixiaowo/CppPrimer5thAnswer
c22fb5f9369d05cafb7f3d8d75b4f499de4c2105
[ "MIT" ]
null
null
null
Cpp_Primer_5E_Learning/Chapter3/E3.20.cpp
feiwofeifeixiaowo/CppPrimer5thAnswer
c22fb5f9369d05cafb7f3d8d75b4f499de4c2105
[ "MIT" ]
null
null
null
// // Created by Xiyun on 16/9/18. // E3.20 // #include <iostream> #include <vector> using namespace std; int main() { char con; int input; vector<int> ivec; cout << "input some int num:" << endl; while(cin >> input) { ivec.push_back(input); cout << "are you continue? (y/n)" << endl; cin >> con; if(con != 'Y' && con != 'y') break; cout << "input some int num:" << endl; } for(decltype(ivec.size())i = 0; i != ivec.size(); ++i) { cout << ivec[i] + ivec[i+1]<< "\t"; } cout << "Section A" << endl; for(decltype(ivec.size())i = 0; i != ivec.size(); ++i) { cout << ivec[i] + ivec[ivec.size() -1 - i]<< "\t"; } cout << "Section B" << endl; return 0; }
19.195122
58
0.467598
[ "vector" ]
47d9dbea3d73e9bfb4d22dce5090e6c7ff39427e
456
cpp
C++
Csgo Loader/client/src/util/io.cpp
Verfired/Csgo-Loader
f545bad20063a12eab16dfec26e2edb9205bc0ae
[ "BSL-1.0" ]
null
null
null
Csgo Loader/client/src/util/io.cpp
Verfired/Csgo-Loader
f545bad20063a12eab16dfec26e2edb9205bc0ae
[ "BSL-1.0" ]
null
null
null
Csgo Loader/client/src/util/io.cpp
Verfired/Csgo-Loader
f545bad20063a12eab16dfec26e2edb9205bc0ae
[ "BSL-1.0" ]
1
2021-03-02T13:51:26.000Z
2021-03-02T13:51:26.000Z
#include "../include.h" #include "io.h" bool io::read_file(const std::string_view path, std::vector<char>& out) { std::ifstream file(path.data(), std::ios::binary); if (!file.good()) { log_error("{} isnt valid.", path); return false; } file.unsetf(std::ios::skipws); file.seekg(0, std::ios::end); const size_t size = file.tellg(); file.seekg(0, std::ios::beg); out.resize(size); file.read(&out[0], size); file.close(); return true; }
18.24
73
0.633772
[ "vector" ]
c51b45d28cd5ebdc02918693cfb2f2e9678ee026
1,305
cpp
C++
Animation/ScalarInterpolator.cpp
jess22664/x3ogre
9de430859d877407ae0308908390c9fa004b0e84
[ "MIT" ]
1
2021-09-18T12:50:35.000Z
2021-09-18T12:50:35.000Z
Animation/ScalarInterpolator.cpp
jess22664/x3ogre
9de430859d877407ae0308908390c9fa004b0e84
[ "MIT" ]
null
null
null
Animation/ScalarInterpolator.cpp
jess22664/x3ogre
9de430859d877407ae0308908390c9fa004b0e84
[ "MIT" ]
null
null
null
/* * ScalarInterpolator.cpp * * Created on: 28.03.2014 * Author: parojtbe */ #include "ScalarInterpolator.h" #include <OgreControllerManager.h> #include <OgrePredefinedControllers.h> #include <OgreAnimationState.h> namespace X3D { const std::vector<float>& ScalarInterpolator::key() const { return _key; } void ScalarInterpolator::key(const std::vector<float>& key) { _key = key; } const std::vector<float>& ScalarInterpolator::keyValue() const { return _keyValue; } void ScalarInterpolator::keyValue(const std::vector<float>& keyValue) { _keyValue = keyValue; } void ScalarInterpolator::set_fraction(const std::shared_ptr<TimeSensor>& time) { _time = time; } void ScalarInterpolator::controlAnimation(Ogre::AnimationState* anim) { if(not _time) { throw std::runtime_error("ScalarInterpolator requires Route from TimeSensor "); } anim->setEnabled(true); anim->setLoop(_time->loop()); Ogre::ControllerFunctionRealPtr func(new Ogre::LinearControllerFunction(_key, _keyValue, 1.0/_time->cycleInterval())); Ogre::ControllerValueRealPtr dst(new Ogre::AnimationStateControllerValue(anim)); auto& mgr = Ogre::ControllerManager::getSingleton(); mgr.createController(mgr.getFrameTimeSource(), dst, func); } } /* namespace X3D */
24.622642
122
0.720307
[ "vector" ]
c5279aaabe152a7139eb227316204909cac4d07a
838
cpp
C++
src/sea.cpp
PK1210/rafale-flight
ec30026b96982bf98325e01b47f44061cf18a9ec
[ "MIT" ]
null
null
null
src/sea.cpp
PK1210/rafale-flight
ec30026b96982bf98325e01b47f44061cf18a9ec
[ "MIT" ]
null
null
null
src/sea.cpp
PK1210/rafale-flight
ec30026b96982bf98325e01b47f44061cf18a9ec
[ "MIT" ]
null
null
null
#include "sea.h" Sea::Sea(float side) { this->position = glm::vec3(0, 0, 0); static const GLfloat vertex_buffer_data[] = { side, 0.0f, side, -side, 0.0f, side, -side, 0.0f, -side, side, 0.0f, side, side, 0.0f, -side, -side, 0.0f, -side }; this->object = create3DObject(GL_TRIANGLES, 2*3, vertex_buffer_data , COLOR_SEA_BLUE, GL_FILL); } void Sea::draw(glm::mat4 VP) { Matrices.model = glm::mat4(1.0f); glm::mat4 translate = glm::translate (this->position); // glTranslatef // glm::mat4 rotate = glm::rotate((float) (this->rotation * M_PI / 180.0f), glm::vec3(1, 0, 0)); Matrices.model *= translate; glm::mat4 MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(this->object); }
31.037037
103
0.593079
[ "object", "model" ]
c52bc3048e8700395ddd1de9679f4df50619720c
1,667
cc
C++
src/q_301_350/q0344.cc
vNaonLu/daily-leetcode
2830c2cd413d950abe7c6d9b833c771f784443b0
[ "MIT" ]
2
2021-09-28T18:41:03.000Z
2021-09-28T18:42:57.000Z
src/q_301_350/q0344.cc
vNaonLu/Daily_LeetCode
30024b561611d390931cef1b22afd6a5060cf586
[ "MIT" ]
16
2021-09-26T11:44:20.000Z
2021-11-28T06:44:02.000Z
src/q_301_350/q0344.cc
vNaonLu/daily-leetcode
2830c2cd413d950abe7c6d9b833c771f784443b0
[ "MIT" ]
1
2021-11-22T09:11:36.000Z
2021-11-22T09:11:36.000Z
#include <gtest/gtest.h> #include <iostream> #include <vector> using namespace std; /** * This file is generated by leetcode_add.py v1.0 * * 344. * Reverse String * * ––––––––––––––––––––––––––––– Description ––––––––––––––––––––––––––––– * * Write a function that reverses a string. The input string is given as * an array of characters ‘s’ * You must do this by modifying the input array <a * href="https://en.wikipedia.org/wiki/In-place_algorithm" * target="_blank">in-place</a> with ‘O(1)’ extra memory. * * ––––––––––––––––––––––––––––– Constraints ––––––––––––––––––––––––––––– * * • ‘1 ≤ s.length ≤ 10⁵’ * • ‘s[i]’ is a <a href="https://en.wikipedia.org/wiki/ASCII#Printable_characters" target="_blank">printable ascii character</a>. * */ struct q344 : public ::testing::Test { // Leetcode answer here class Solution { public: void reverseString(vector<char>& s) { int l = 0, r = s.size() - 1; char tmp = ' '; while (l <= r) { tmp = s[r]; s[r--] = s[l]; s[l++] = tmp; } } }; class Solution *solution; }; TEST_F(q344, sample_input01) { solution = new Solution(); vector<char> s = {'h', 'e', 'l', 'l', 'o'}; vector<char> exp = {'o', 'l', 'l', 'e', 'h'}; solution->reverseString(s); // Assume the first argument is answer. EXPECT_EQ(s, exp); delete solution; } TEST_F(q344, sample_input02) { solution = new Solution(); vector<char> s = {'H', 'a', 'n', 'n', 'a', 'h'}; vector<char> exp = {'h', 'a', 'n', 'n', 'a', 'H'}; solution->reverseString(s); // Assume the first argument is answer. EXPECT_EQ(s, exp); delete solution; }
26.046875
132
0.543491
[ "vector" ]
c52bdd59d36f2a053509d0add8a5cf51d5c3e10e
10,179
hpp
C++
include/Options.hpp
AugustoRuiz/dskgen
8585d24312d127f6269b3e8b870ea1ffdc4ee933
[ "MIT" ]
6
2016-01-13T12:55:52.000Z
2020-05-08T12:58:31.000Z
include/Options.hpp
AugustoRuiz/dskgen
8585d24312d127f6269b3e8b870ea1ffdc4ee933
[ "MIT" ]
1
2017-12-18T23:36:47.000Z
2017-12-18T23:36:47.000Z
include/Options.hpp
AugustoRuiz/dskgen
8585d24312d127f6269b3e8b870ea1ffdc4ee933
[ "MIT" ]
7
2017-11-26T12:41:42.000Z
2021-11-16T17:30:50.000Z
#ifndef _DSKGEN_OPTIONS_H_ #define _DSKGEN_OPTIONS_H_ #include <string> #include <fstream> #include <iostream> #include <json/json.h> #include "Types.hpp" #include "FileToProcess.hpp" using namespace std; class Options { public: Options() { }; string OutputFileName; string BootFile; CatalogType Catalog; DiskType OutputDiskType; u8 NumSides; struct XDPB DiskParams; vector<FileToProcess> FilesToProcess; void AddFile(const FileToProcess &f) { this->FilesToProcess.push_back(f); } FileToProcess GetBootFile() { FileToProcess result; for (vector<FileToProcess>::iterator it = FilesToProcess.begin(); it != FilesToProcess.end(); ++it) { if (it->SourcePath == BootFile) { result = *it; break; } } return result; } void SetCatalogType(const string &catStr) { this->Catalog = ParseCatalogType(catStr); } void SetDiskType(const string &diskStr) { this->OutputDiskType = ParseDiskType(diskStr); if (this->OutputDiskType == DSK_SYSTEM) { this->DiskParams.recordsPerTrack = 36; this->DiskParams.blockShift = 3; this->DiskParams.blockMask = 7; this->DiskParams.extentMask = 0; this->DiskParams.numBlocks = 170; this->DiskParams.dirEntries = 63; this->DiskParams.allocationLo = 0x00; this->DiskParams.allocationHi = 0xC0; this->DiskParams.checksumLength = 16; this->DiskParams.reservedTracks = 2; this->DiskParams.firstSectorNumber = 0x41; this->DiskParams.sectorsPerTrack = 9; this->DiskParams.gapRW = 42; this->DiskParams.gapF = 82; this->DiskParams.fillerByte = 0xE9; this->DiskParams.sectSizeInRecords = 4; this->DiskParams.sidesInterleaved = 0; } else if (this->OutputDiskType == DSK_DATA) { this->DiskParams.recordsPerTrack = 36; this->DiskParams.blockShift = 3; this->DiskParams.blockMask = 7; this->DiskParams.extentMask = 0; this->DiskParams.numBlocks = 179; this->DiskParams.dirEntries = 63; this->DiskParams.allocationLo = 0x00; this->DiskParams.allocationHi = 0xC0; this->DiskParams.checksumLength = 16; this->DiskParams.reservedTracks = 0; this->DiskParams.firstSectorNumber = 0xC1; this->DiskParams.sectorsPerTrack = 9; this->DiskParams.gapRW = 42; this->DiskParams.gapF = 82; this->DiskParams.fillerByte = 0xE9; this->DiskParams.sectSizeInRecords = 4; this->DiskParams.sidesInterleaved = 0; } else if (this->OutputDiskType == DSK_IBM) { this->DiskParams.recordsPerTrack = 32; this->DiskParams.blockShift = 3; this->DiskParams.blockMask = 7; this->DiskParams.extentMask = 0; this->DiskParams.numBlocks = 155; this->DiskParams.dirEntries = 63; this->DiskParams.allocationLo = 0x00; this->DiskParams.allocationHi = 0xC0; this->DiskParams.checksumLength = 16; this->DiskParams.reservedTracks = 1; this->DiskParams.firstSectorNumber = 0x01; this->DiskParams.sectorsPerTrack = 8; this->DiskParams.gapRW = 42; this->DiskParams.gapF = 80; this->DiskParams.fillerByte = 0xE9; this->DiskParams.sectSizeInRecords = 4; this->DiskParams.sidesInterleaved = 0; } else if (this->OutputDiskType == DSK_PCW720) { this->DiskParams.recordsPerTrack = 0x24; this->DiskParams.blockShift = 4; this->DiskParams.blockMask = 0x0F; this->DiskParams.extentMask = 0; this->DiskParams.numBlocks = 0x164; this->DiskParams.dirEntries = 0xFF; this->DiskParams.allocationLo = 0x00; this->DiskParams.allocationHi = 0xF0; this->DiskParams.checksumLength = 0x40; this->DiskParams.reservedTracks = 1; this->DiskParams.firstSectorNumber = 0x01; this->DiskParams.sectorsPerTrack = 9; this->DiskParams.gapRW = 0x2A; this->DiskParams.gapF = 0x52; this->DiskParams.fillerByte = 0xE9; this->DiskParams.sectSizeInRecords = 4; this->DiskParams.sidesInterleaved = 1; } else if (this->OutputDiskType == DSK_PCW1440) { this->DiskParams.recordsPerTrack = 0x48; this->DiskParams.blockShift = 5; this->DiskParams.blockMask = 0x1F; this->DiskParams.extentMask = 0; this->DiskParams.numBlocks = 0x164; this->DiskParams.dirEntries = 0xFF; this->DiskParams.allocationLo = 0x00; this->DiskParams.allocationHi = 0xC0; this->DiskParams.checksumLength = 0x40; this->DiskParams.reservedTracks = 1; this->DiskParams.firstSectorNumber = 0x01; this->DiskParams.sectorsPerTrack = 9; this->DiskParams.gapRW = 0x1B; this->DiskParams.gapF = 0x54; this->DiskParams.fillerByte = 0xE9; this->DiskParams.sectSizeInRecords = 4; this->DiskParams.sidesInterleaved = 1; } else if (this->OutputDiskType == DSK_ROMDOS_D1) { this->DiskParams.recordsPerTrack = 0x24; this->DiskParams.blockShift = 4; this->DiskParams.blockMask = 0x0F; this->DiskParams.extentMask = 0; this->DiskParams.numBlocks = 0x59; this->DiskParams.dirEntries = 0x3F; this->DiskParams.allocationLo = 0x00; this->DiskParams.allocationHi = 0xC0; this->DiskParams.checksumLength = 0x40; this->DiskParams.reservedTracks = 0; this->DiskParams.firstSectorNumber = 0x01; this->DiskParams.sectorsPerTrack = 9; this->DiskParams.gapRW = 0x1B; this->DiskParams.gapF = 0x54; this->DiskParams.fillerByte = 0xE9; this->DiskParams.sectSizeInRecords = 4; this->DiskParams.sidesInterleaved = 1; } else { this->DiskParams.recordsPerTrack = 36; this->DiskParams.blockShift = 3; this->DiskParams.blockMask = 7; this->DiskParams.extentMask = 0; this->DiskParams.numBlocks = 179; this->DiskParams.dirEntries = 63; this->DiskParams.allocationLo = 0x00; this->DiskParams.allocationHi = 0xC0; this->DiskParams.checksumLength = 16; this->DiskParams.reservedTracks = 0; this->DiskParams.firstSectorNumber = 0xC1; this->DiskParams.sectorsPerTrack = 9; this->DiskParams.gapRW = 42; this->DiskParams.gapF = 82; this->DiskParams.fillerByte = 0xE9; this->DiskParams.sectSizeInRecords = 4; this->DiskParams.sidesInterleaved = 0; } } void ParseFile(string& configFile) { //cout << "Parsing options file '" << configFile << "'."; ifstream file(configFile, ifstream::binary); if (file.good()) { Json::Value root; file >> root; string tmpStr = root.get("catalog", "none").asString(); //cout << "Catalog: " << tmpStr << endl; this->SetCatalogType(tmpStr); tmpStr = root.get("diskType", "system").asString(); //cout << "Disk Type: " << tmpStr << endl; this->SetDiskType(tmpStr); this->NumSides = (u8)root.get("sides", "1").asUInt(); //cout << "Num sides: " << (int)this->NumSides << endl; if (root["boot"] != Json::nullValue) { //cout << "Boot file: " << root["boot"].asString() << endl; this->BootFile = root["boot"].asString(); } if (this->OutputDiskType == DSK_CUSTOM) { Json::Value diskParams = root["diskParams"]; if (!diskParams.isNull()) { // Get the XDPB specified parameters... if (diskParams["spt"] != Json::nullValue) { this->DiskParams.recordsPerTrack = (u16)diskParams["spt"].asUInt(); } if (diskParams["bsh"] != Json::nullValue) { this->DiskParams.blockShift = (u8)diskParams["bsh"].asUInt(); } if (diskParams["blm"] != Json::nullValue) { this->DiskParams.blockMask = (u8)diskParams["blm"].asUInt(); } if (diskParams["exm"] != Json::nullValue) { this->DiskParams.extentMask = (u8)diskParams["exm"].asUInt(); } if (diskParams["dsm"] != Json::nullValue) { this->DiskParams.numBlocks = (u16)diskParams["dsm"].asUInt(); } if (diskParams["drm"] != Json::nullValue) { this->DiskParams.dirEntries = (u16)diskParams["drm"].asUInt(); } if (diskParams["al0"] != Json::nullValue) { this->DiskParams.allocationLo = (u8)diskParams["al0"].asUInt(); } if (diskParams["al1"] != Json::nullValue) { this->DiskParams.allocationHi = (u8)diskParams["al1"].asUInt(); } if (diskParams["cks"] != Json::nullValue) { this->DiskParams.checksumLength = (u16)diskParams["cks"].asUInt(); } if (diskParams["off"] != Json::nullValue) { this->DiskParams.reservedTracks = (u16)diskParams["off"].asUInt(); } if (diskParams["fsn"] != Json::nullValue) { this->DiskParams.firstSectorNumber = (u8)diskParams["fsn"].asUInt(); } if (diskParams["sectorsPerTrack"] != Json::nullValue) { this->DiskParams.sectorsPerTrack = (u8)diskParams["sectorsPerTrack"].asUInt(); } if (diskParams["gapRW"] != Json::nullValue) { this->DiskParams.gapRW = (u8)diskParams["gapRW"].asUInt(); } if (diskParams["gapF"] != Json::nullValue) { this->DiskParams.gapF = (u8)diskParams["gapF"].asUInt(); } if (diskParams["fillerByte"] != Json::nullValue) { this->DiskParams.fillerByte = (u8)diskParams["fillerByte"].asUInt(); } if (diskParams["sectsizeInRecords"] != Json::nullValue) { this->DiskParams.sectSizeInRecords = (u8)diskParams["sectSizeInRecords"].asUInt(); } if (diskParams["sidesInterleaved"] != Json::nullValue) { this->DiskParams.sidesInterleaved = (u8)diskParams["sidesInterleaved"].asUInt(); } } } const Json::Value files = root["files"]; if (files != Json::Value::null) { for (Json::Value::iterator it = files.begin(); it != files.end(); ++it) { Json::Value current = *it; FileToProcess f; if (current["path"] == Json::nullValue) { throw "A file was found without path in configration file."; } //cout << "File: " << current["path"].asString() << endl; f.SetSourcePath(current["path"].asString()); f.Header = ParseHeaderType(current.get("header", "none").asString()); f.AmsdosType = ParseAmsdosFileType(current.get("amsdosType", "").asString()); f.LoadAddress = (u16)current.get("loadAddress", 0).asUInt(); f.ExecutionAddress = (u16)current.get("executionAddress", 0).asUInt(); f.Hidden = (bool)current.get("system", false).asBool(); this->FilesToProcess.push_back(f); } } } else { cout << "Config file '" << configFile << "' not found!" << endl; } } }; #endif
35.34375
103
0.661656
[ "vector" ]
c5354ace783036b99bb96acf95f8071bb56ea7dc
1,471
hpp
C++
src/way_speed_map.hpp
ccebrand/route-annotator
e139e93550ad60cd29b5e230a3146929dfeb29b6
[ "BSD-3-Clause" ]
29
2016-04-26T09:48:31.000Z
2022-03-21T12:34:42.000Z
src/way_speed_map.hpp
ccebrand/route-annotator
e139e93550ad60cd29b5e230a3146929dfeb29b6
[ "BSD-3-Clause" ]
45
2016-05-18T23:12:56.000Z
2022-01-03T15:07:55.000Z
src/way_speed_map.hpp
ccebrand/route-annotator
e139e93550ad60cd29b5e230a3146929dfeb29b6
[ "BSD-3-Clause" ]
15
2017-03-06T00:21:42.000Z
2021-07-26T06:43:23.000Z
#ifndef WAY_SPEED_MAP_H #define WAY_SPEED_MAP_H #include <fstream> #include <iostream> #include <sparsepp/spp.h> #include <vector> #include "types.hpp" using spp::sparse_hash_map; class WaySpeedMap { public: /** * Do-nothing constructor */ WaySpeedMap(); /** * Loads from,to,speed data from a single file */ WaySpeedMap(const std::string &input_filename); /** * Loads way,speed data from multiple files */ WaySpeedMap(const std::vector<std::string> &input_filenames); /** * Parses and loads another CSV file into the existing data */ void loadCSV(const std::string &input_filename); /** * Adds a single way, speed key value pair */ inline void add(const wayid_t &way, const bool &mph, const std::uint32_t &speed); /** * Checks if a way exists in the map */ bool hasKey(const wayid_t &way) const; /** * Gets the value for a ways. * @throws a runtime_exception if the way is not found. */ segment_speed_t getValue(const wayid_t &way) const; /** * Given a list of ways, returns the speed for each way. * If ways don't exist, the value in the result array will be INVALID_SPEED * There should be at least 1 values in in the `route` array */ std::vector<segment_speed_t> getValues(const std::vector<wayid_t> &ways) const; private: sparse_hash_map<wayid_t, segment_speed_t> annotations; }; #endif
22.984375
85
0.649898
[ "vector" ]
c53626fac179f020a76a0a41eb289e277557fc76
751
cpp
C++
OmegaUp/Cool-Editor.cpp
JFAlexanderS/Contest-Archive
ef1415e56b3e46a16cb28aab05bfba4ada56edb4
[ "MIT" ]
2
2016-04-16T17:40:53.000Z
2018-11-09T06:09:26.000Z
OmegaUp/Cool-Editor.cpp
JFAlexanderS/Contest-Archive
ef1415e56b3e46a16cb28aab05bfba4ada56edb4
[ "MIT" ]
null
null
null
OmegaUp/Cool-Editor.cpp
JFAlexanderS/Contest-Archive
ef1415e56b3e46a16cb28aab05bfba4ada56edb4
[ "MIT" ]
null
null
null
//https://omegaup.com/arena/problem/Cool-Editor# #include <cstdio> #include <string> #include <vector> using namespace std; int mind, totes=1000000, mkill, words; int dead[1005], curlen[1005]; char inp[1005]; vector<string> slist(1005); int main() { scanf("%d", &words); for(int i=1; i<=words; i++) { scanf("%s", inp); slist[i]=inp; if(slist[i].size()>slist[mind].size()) { mind=i; } curlen[i]=slist[i].size(); } for(int i=0; i<slist[mind].size(); i++) { mkill=0; for(int j=1; j<=words; j++) { if(!dead[j] && slist[mind][i]==slist[j][i]) curlen[j]--; else curlen[j]++, dead[j]=1; if(curlen[j]>mkill) mkill=curlen[j]; } if(mkill<totes) totes=mkill; } printf("%d\n", totes); return 0; }
16.326087
48
0.576565
[ "vector" ]
c53939c31e296c699a1ea18be20d84e547cf109b
4,847
cc
C++
mogura-src/ParserAction.cc
mynlp/enju
d984a630b30b95de16f3b715277e95dc6fbe15b4
[ "Apache-2.0" ]
48
2016-10-11T06:07:02.000Z
2022-03-02T16:26:25.000Z
mogura-src/ParserAction.cc
mynlp/enju
d984a630b30b95de16f3b715277e95dc6fbe15b4
[ "Apache-2.0" ]
7
2017-02-13T09:14:34.000Z
2019-01-18T06:06:29.000Z
mogura-src/ParserAction.cc
mynlp/enju
d984a630b30b95de16f3b715277e95dc6fbe15b4
[ "Apache-2.0" ]
18
2016-11-13T23:14:28.000Z
2022-01-12T15:21:44.000Z
#include <stdexcept> #include "ParserAction.h" namespace mogura { //////////////////////////////////////////////////////////////////////////////// /// Action classes //////////////////////////////////////////////////////////////////////////////// class Shift : public ParserAction { protected: Shift(void) {} friend class ParserActionList; public: bool applyImpl(Grammar &, ParserState &s) const { return s.shift(); } bool applicable(Grammar &, const ParserState &s) const { return ! s._words.empty(); } std::string asString(void) const { return "shift"; } ActionCode getCode(void) const { return ActionCode(ACT_SHIFT); } }; class ReduceBase : public ParserAction { public: std::string asString(void) const { return _schema->getName(); } ActionCode getCode(void) const { return _code; } protected: ReduceBase(const Schema *schema, ActionCode code) : _schema(schema), _code(code) {} friend class ParserActionList; protected: const Schema *_schema; ActionCode _code; }; class ReduceUnary : public ReduceBase { protected: ReduceUnary(const Schema *schema, ActionCode code) : ReduceBase(schema, code) { assert(schema->isUnary()); } friend class ParserActionList; public: bool applyImpl(Grammar &g, ParserState &s) const { return s.reduceUnary(g, _schema); } bool applicable(Grammar &g, const ParserState &s) const { if (s._stack.empty()) { return false; } lilfes::IPTrailStack iptrail(g.getMachine()); lilfes::FSP mother(g.getMachine()); return g.applyIdSchemaUnary(_schema->getLilfesType(), s._stack.at(0)->_sign, mother); } }; class ReduceBinary : public ReduceBase { protected: ReduceBinary(const Schema *schema, ActionCode code) : ReduceBase(schema, code) { assert(schema->isBinary()); } friend class ParserActionList; public: bool applyImpl(Grammar &g, ParserState &s) const { return s.reduceBinary(g, _schema); } bool applicable(Grammar &g, const ParserState &s) const { if (s._stack.size() < 2) { return false; } lilfes::IPTrailStack iptrail(g.getMachine()); lilfes::FSP mother(g.getMachine()); return g.applyIdSchemaBinary(_schema->getLilfesType(), s._stack.at(1)->_sign, s._stack.at(0)->_sign, mother); } }; //////////////////////////////////////////////////////////////////////////////// /// Action list initialization //////////////////////////////////////////////////////////////////////////////// void makeVector( lilfes::machine *m, lilfes::FSP fsp, Schema::Type type, std::vector<const Schema*> &v ) { std::vector<lilfes::FSP> fspv; lilfes::list_to_vector(*m, fsp, fspv); v.clear(); for (std::vector<lilfes::FSP>::const_iterator it = fspv.begin(); it != fspv.end(); ++it) { v.push_back(new Schema(type, it->GetType())); } } typedef std::vector<const Schema*> SchemaList; bool getSchemaList( lilfes::machine *m, Grammar &g, SchemaList &leftHead, SchemaList &rightHead, SchemaList &unary ) { leftHead.clear(); rightHead.clear(); unary.clear(); lilfes::FSP leftFsp(m); lilfes::FSP rightFsp(m); lilfes::FSP unaryFsp(m); if (! g.getSchemaList(leftFsp, rightFsp, unaryFsp)) { return false; } makeVector(m, leftFsp, Schema::LEFT_HEAD, leftHead); makeVector(m, rightFsp, Schema::RIGHT_HEAD, rightHead); makeVector(m, unaryFsp, Schema::UNARY, unary); return true; } void add( const ParserAction *a, ParserActionList::ListT &list, ParserActionList::IndexT &index ) { list.push_back(a); if (index.find(a->asString()) != index.end()) { throw std::runtime_error("parser action \"" + a->asString() + "\"is registered twice"); } index[a->asString()] = a; } bool ParserActionList::init(Grammar &g, const cfg::Grammar &cfg) { add(new Shift(), _actions, _index); SchemaList leftHead; SchemaList rightHead; SchemaList unary; if (! getSchemaList(g.getMachine(), g, leftHead, rightHead, unary)) { return false; } for (SchemaList::const_iterator it = leftHead.begin(); it != leftHead.end(); ++it) { ActionCode code(ACT_REDUCE2, cfg._rule.getID((*it)->getName())); add(new ReduceBinary(*it, code), _actions, _index); } for (SchemaList::const_iterator it = rightHead.begin(); it != rightHead.end(); ++it) { ActionCode code(ACT_REDUCE2, cfg._rule.getID((*it)->getName())); add(new ReduceBinary(*it, code), _actions, _index); } for (SchemaList::const_iterator it = unary.begin(); it != unary.end(); ++it) { ActionCode code(ACT_REDUCE1, cfg._rule.getID((*it)->getName())); add(new ReduceUnary(*it, code), _actions, _index); } return true; } } // namespace mogura
25.510526
117
0.60326
[ "vector" ]
c53e44bc907e3c289dbdcce12b335616c243b514
27,870
hpp
C++
mango/src/graphics/graphics_types.hpp
pethipet/Mango
f89a93a11df365440ce7a8fb48f8336eac2c63f0
[ "Apache-2.0" ]
3
2020-05-12T09:30:41.000Z
2020-10-04T21:27:03.000Z
mango/src/graphics/graphics_types.hpp
pethipet/Mango
f89a93a11df365440ce7a8fb48f8336eac2c63f0
[ "Apache-2.0" ]
1
2020-03-21T20:34:10.000Z
2020-03-22T13:58:41.000Z
mango/src/graphics/graphics_types.hpp
pethipet/Mango
f89a93a11df365440ce7a8fb48f8336eac2c63f0
[ "Apache-2.0" ]
3
2020-06-24T16:32:44.000Z
2020-08-14T14:44:20.000Z
//! \file graphics_types.hpp //! \author Paul Himmler //! \version 1.0 //! \date 2021 //! \copyright Apache License 2.0 #ifndef MANGO_GRAPHICS_TYPES_HPP #define MANGO_GRAPHICS_TYPES_HPP //! \cond NO_COND #define GLM_FORCE_SILENT_WARNINGS 1 //! \endcond #include <glm/gtx/matrix_major_storage.hpp> #include <mango/types.hpp> namespace mango { // // Enum classes and types. Everything in here has suffix gfx_. // //! \brief A shared handle for a \a graphics_device_object. template <typename T> using gfx_handle = std::shared_ptr<T>; //! \brief Creates a \a gfx_handle of a \a graphics_device_object. //! \param[in] args Arguments for the \a T object's constructor. //! \return A \a gfx_handle that owns the newly created object. template <typename T, typename... Args> gfx_handle<T> make_gfx_handle(Args&&... args) { return std::make_shared<T>(std::forward<Args>(args)...); } //! \brief Cast a \a graphics_device_object managed by a \a gfx_handle moving the \a gfx_handle. //! \param[in] old \a gfx_handle of type \a F to cast from. //! \return A \a gfx_handle holding the object pointer casted from \a F to \a T. template <typename T, typename F> gfx_handle<T> static_gfx_handle_cast(gfx_handle<F>&& old) { return std::static_pointer_cast<T>(std::move(old)); } //! \brief Cast a \a graphics_device_object managed by a \a gfx_handle. //! \param[in] old \a gfx_handle of type \a F to cast from. //! \return A \a gfx_handle holding the object pointer casted from \a F to \a T. template <typename T, typename F> gfx_handle<T> static_gfx_handle_cast(const gfx_handle<F>& old) { return std::static_pointer_cast<T>(old); } //! \brief A unique identifier for \a graphics_device_objects. using gfx_uid = int64; //! \brief An invalid \a gfx_uid. static const gfx_uid invalid_uid = -1; //! \brief Interface for all objects on the gpu or interactong with the gpu. class gfx_device_object { public: //! \brief Queries an integer type id for the specific \a gfx_device_object. //! \return An integer type id for the specific \a gfx_device_object. virtual int32 get_type_id() const = 0; //! \brief Returns the native handle for the specific \a gfx_device_object. //! \return A void* representing the native handle of the specific \a gfx_device_object. virtual void* native_handle() const = 0; //! \brief Queries an unique identifier for the specific \a gfx_device_object. //! \return An unique identifier for the specific \a gfx_device_object. gfx_uid get_uid() const { return uid; } // void invalidate_uid() // { // int32 low = get_uid_low(); // int32 high = get_uid_high(); // // set_uid(low + 1, high); // } private: //! \brief The unique identifier of the specific \a gfx_device_object. gfx_uid uid; protected: gfx_device_object() { static int32 uid_p0 = 0; set_uid(uid_p0, 0); uid_p0++; } //! \brief Sets the unique identifier of the specific \a gfx_device_object. //! \param[in] low The 32 least significant bits of the \a gfx_uid. //! \param[in] high The 32 most significant bits of the \a gfx_uid. void set_uid(int32 low, int32 high) { uid = (((uint64_t)high) << 32) | ((uint64_t)low); } //! \brief Gets the 32 most significant bits of the \a gfx_uid. //! \return The 32 most significant bits of the \a gfx_uid. int32 get_uid_high() { return uid >> 32; } //! \brief Gets the 32 least significant bits of the \a gfx_uid. //! \return The 32 least significant bits of the \a gfx_uid. int32 get_uid_low() { return static_cast<int32>(uid); } }; //! \brief Type used to identify shader stages. enum class gfx_shader_stage_type : uint8 { shader_stage_unknown = 0, shader_stage_vertex = 1 << 0, shader_stage_tesselation_control = 1 << 1, shader_stage_tesselation_evaluation = 1 << 2, shader_stage_geometry = 1 << 3, shader_stage_fragment = 1 << 4, shader_stage_compute = 1 << 5, shader_stage_last = shader_stage_compute }; MANGO_ENABLE_BITMASK_OPERATIONS(gfx_shader_stage_type) //! \brief Shader resource types. enum class gfx_shader_resource_type : uint8 { shader_resource_unknown = 0, shader_resource_constant_buffer, //! Uniform buffer shader_resource_texture, //! Sampled image shader_resource_image_storage, //! Image store shader_resource_buffer_storage, //! Storage buffer shader_resource_sampler, //! Seperate texture sampler shader_resource_input_attachment, //! Special type used for render pass input attachments shader_resource_last = shader_resource_input_attachment }; //! \brief Shader resource access. enum class gfx_shader_resource_access : uint8 { shader_access_unknown = 0, shader_access_static, shader_access_dynamic, shader_access_last = shader_access_dynamic }; //! \brief Describes the topology of primitives used for rendering and interpreting geometry data. enum class gfx_primitive_topology : uint8 { primitive_topology_unknown = 0, primitive_topology_point_list, primitive_topology_line_list, primitive_topology_line_loop, primitive_topology_line_strip, primitive_topology_triangle_list, primitive_topology_triangle_strip, primitive_topology_triangle_fan, primitive_topology_last = primitive_topology_triangle_fan }; //! \brief Describes the rate at which an vertex attribute is changed. enum class gfx_vertex_input_rate : uint8 { per_vertex, per_instance }; //! \brief All kinds of format values. //! \details These are OpenGl values for now. enum class gfx_format : uint32 { invalid = 0x0, // vertex attribute formats and buffer format types t_byte = 0x1400, t_unsigned_byte = 0x1401, t_short = 0x1402, t_unsigned_short = 0x1403, t_half_float = 0x140b, t_double = 0x140a, t_fixed = 0x140c, t_float = 0x1406, t_float_vec2 = 0x8b50, t_float_vec3 = 0x8b51, t_float_vec4 = 0x8b52, t_int = 0x1404, t_int_vec2 = 0x8b53, t_int_vec3 = 0x8b54, t_int_vec4 = 0x8b55, t_unsigned_int = 0x1405, t_unsigned_int_vec2 = 0x8dc6, t_unsigned_int_vec3 = 0x8dc7, t_unsigned_int_vec4 = 0x8dc8, t_unsigned_byte_3_3_2 = 0x8032, t_unsigned_byte_2_3_3_rev = 0x8362, t_unsigned_short_5_6_5 = 0x8363, t_unsigned_short_5_6_5_rev = 0x8364, t_unsigned_short_4_4_4_4 = 0x8033, t_unsigned_short_4_4_4_4_rev = 0x8365, t_unsigned_short_5_5_5_1 = 0x8034, t_unsigned_short_1_5_5_5_rev = 0x8366, t_unsigned_int_8_8_8_8 = 0x8035, t_unsigned_int_8_8_8_8_rev = 0x8367, t_unsigned_int_10_10_10_2 = 0x8036, t_unsigned_int_2_10_10_10_rev = 0x8368, t_int_2_10_10_10_rev = 0x8d9f, // internal_formats r8 = 0x8229, r16 = 0x822a, r16f = 0x822d, r32f = 0x822e, r8i = 0x8231, r16i = 0x8233, r32i = 0x8235, r8ui = 0x8232, r16ui = 0x8234, r32ui = 0x8236, rg8 = 0x822b, rg16 = 0x822c, rg16f = 0x822f, rg32f = 0x8230, rg8i = 0x8237, rg16i = 0x8239, rg32i = 0x823b, rg8ui = 0x8238, rg16ui = 0x823a, rg32ui = 0x823c, rgb4 = 0x804f, rgb5 = 0x8050, rgb8 = 0x8051, rgb10 = 0x8052, rgb12 = 0x8053, rgb16 = 0x8054, srgb8 = 0x8c41, srgb8_alpha8 = 0x8c43, rgb8ui = 0x8d7d, rgb8i = 0x8d8f, rgb16f = 0x881b, rgb16ui = 0x8d77, rgb16i = 0x8d89, rgb32f = 0x8815, rgb32i = 0x8d83, rgb32ui = 0x8d71, rgba2 = 0x8055, rgba4 = 0x8056, rgb5_a1 = 0x8057, rgba8 = 0x8058, rgb10_a2 = 0x8059, rgba12 = 0x805a, rgba16 = 0x805b, rgba16f = 0x881a, rgba32f = 0x8814, rgba8i = 0x8d8e, rgba16i = 0x8d88, rgba32i = 0x8d82, rgba8ui = 0x8d7c, rgba16ui = 0x8d76, rgba32ui = 0x8d70, depth_component32f = 0x8cac, depth_component16 = 0x81a5, depth_component24 = 0x81a6, depth_component32 = 0x81a7, depth24_stencil8 = 0x88f0, depth32f_stencil8 = 0x8cad, // pixel formats depth_component = 0x1902, stencil_index = 0x1901, depth_stencil = 0x84f9, red = 0x1903, green = 0x1904, blue = 0x1905, rg = 0x8227, rgb = 0x1907, bgr = 0x80e0, rgba = 0x1908, bgra = 0x80e1, red_integer = 0x8d94, green_integer = 0x8d95, blue_integer = 0x8d96, rg_integer = 0x8228, rgb_integer = 0x8d98, bgr_integer = 0x8d9a, rgba_integer = 0x8d99, bgra_integer = 0x8d9b, format_last = bgra_integer }; //! \brief Describes a viewport. struct gfx_viewport { float x; //!< The upper left corner x position. float y; //!< The upper left corner y position. float width; //!< The viewport width. float height; //!< The viewport height. }; //! \brief Describes a scissor rectangle. struct gfx_scissor_rectangle { int32 x_offset; //!< The upper left corner x offset. int32 y_offset; //!< The upper left corner y offset. int32 x_extent; //!< The extent in x direction. int32 y_extent; //!< The extent in y direction. }; //! \brief Describes how a polygon should be drawn. enum class gfx_polygon_mode : uint8 { polygon_mode_unknown = 0, polygon_mode_fill, polygon_mode_line, polygon_mode_point, polygon_mode_last = polygon_mode_point }; //! \brief Describing the cull mode and face. enum class gfx_cull_mode_flag_bits : uint8 { mode_none = 0, mode_back = 1 << 0, mode_front = 1 << 1, mode_front_and_back = mode_back | mode_front, mode_last = mode_front_and_back }; MANGO_ENABLE_BITMASK_OPERATIONS(gfx_cull_mode_flag_bits) //! \brief Describes the order vertices required to be seen as front- or back-facing. enum class gfx_front_face : uint8 { counter_clockwise, clockwise }; //! \brief Describes the order vertices required to be seen as front- or back-facing. enum class gfx_sample_count : uint8 { sample_unknown = 0, sample_1_bit, sample_2_bit, sample_4_bit, sample_8_bit, sample_16_bit, sample_32_bit, sample_64_bit, sample_last = sample_64_bit }; //! \brief Compare operator used for depth and stencil tests. enum class gfx_compare_operator : uint8 { compare_operator_unknown = 0, compare_operator_never, compare_operator_less, compare_operator_equal, compare_operator_less_equal, compare_operator_greater, compare_operator_not_equal, compare_operator_greater_equal, compare_operator_always, compare_operator_last = compare_operator_always }; //! \brief Stencil operations used for stencil test. enum class gfx_stencil_operation : uint8 { stencil_operation_unknown = 0, stencil_operation_keep, stencil_operation_zero, stencil_operation_replace, stencil_operation_increment_and_clamp, stencil_operation_decrement_and_clamp, stencil_operation_increment_and_wrap, stencil_operation_decrement_and_wrap, stencil_operation_invert, stencil_operation_last = stencil_operation_invert }; //! \brief The blend factor used for blend operations. enum class gfx_blend_factor : uint8 { blend_factor_unknown = 0, blend_factor_zero, blend_factor_one, blend_factor_src_color, blend_factor_one_minus_src_color, blend_factor_dst_color, blend_factor_one_minus_dst_color, blend_factor_src_alpha, blend_factor_one_minus_src_alpha, blend_factor_dst_alpha, blend_factor_one_minus_dst_alpha, blend_factor_constant_color, blend_factor_one_minus_constant_color, blend_factor_constant_alpha, blend_factor_one_minus_constant_alpha, blend_factor_src_alpha_saturate, blend_factor_src1_color, blend_factor_one_minus_src1_color, blend_factor_src1_alpha, blend_factor_one_minus_src1_alpha, blend_factor_last = blend_factor_one_minus_src1_alpha }; //! \brief The blend operations. enum class gfx_blend_operation : uint8 { blend_operation_unknown = 0, blend_operation_add, blend_operation_subtract, blend_operation_reverse_subtract, blend_operation_take_min, blend_operation_take_max, blend_operation_last = blend_operation_take_max }; //! \brief Describing framebuffer logical operations. enum class gfx_logic_operator : uint8 { logic_unknown = 0, logic_clear = 1, logic_and = 2, logic_and_reverse = 3, logic_copy = 4, logic_and_inverted = 5, logic_no_op = 6, logic_xor = 7, logic_or = 8, logic_nor = 9, logic_equivalent = 10, logic_invert = 11, logic_or_reverse = 12, logic_copy_inverted = 13, logic_or_inverted = 14, logic_nand = 15, logic_set = 16, logic_last = logic_set }; //! \brief Describing the update face for dynamic stencil mask updates. enum class gfx_stencil_face_flag_bits : uint8 { stencil_face_none = 0, stencil_face_back_bit = 1 << 0, stencil_face_front_bit = 1 << 1, stencil_face_front_and_back_bit = stencil_face_back_bit | stencil_face_front_bit, stencil_face_last = stencil_face_front_and_back_bit }; MANGO_ENABLE_BITMASK_OPERATIONS(gfx_stencil_face_flag_bits) //! \brief Describing a selection of color components. enum class gfx_color_component_flag_bits : uint8 { component_none = 0, component_r = 1 << 0, component_g = 1 << 1, component_b = 1 << 2, component_a = 1 << 3, components_rgb = component_r | component_g | component_r, components_rgba = components_rgb | component_a, components_last = components_rgba }; MANGO_ENABLE_BITMASK_OPERATIONS(gfx_color_component_flag_bits) //! \brief Indicate which dynamic state is taken from dynamic state commands. //! \details Can be extended in the future. enum class gfx_dynamic_state_flag_bits : uint16 { dynamic_state_none = 0, dynamic_state_viewport = 1 << 0, dynamic_state_scissor = 1 << 1, dynamic_state_line_width = 1 << 2, dynamic_state_depth_bias = 1 << 3, dynamic_state_blend_constants = 1 << 4, dynamic_state_stencil_compare_mask_reference = 1 << 5, dynamic_state_stencil_write_mask = 1 << 6, dynamic_state_last = dynamic_state_stencil_write_mask }; MANGO_ENABLE_BITMASK_OPERATIONS(gfx_dynamic_state_flag_bits) //! \brief Specification of barrier bits. enum class gfx_barrier_bit : uint16 { unknown_barrier_bit = 0, vertex_attrib_array_barrier_bit = 1 << 0, element_array_barrier_bit = 1 << 1, uniform_barrier_bit = 1 << 2, texture_fetch_barrier_bit = 1 << 3, shader_image_access_barrier_bit = 1 << 4, command_barrier_bit = 1 << 5, pixel_buffer_barrier_bit = 1 << 6, texture_update_barrier_bit = 1 << 7, buffer_update_barrier_bit = 1 << 8, framebuffer_barrier_bit = 1 << 9, transform_feedback_barrier_bit = 1 << 10, atomic_counter_barrier_bit = 1 << 11, shader_storage_barrier_bit = 1 << 12, query_buffer_barrier_bit = 1 << 13, last_barrier_bit = query_buffer_barrier_bit }; MANGO_ENABLE_BITMASK_OPERATIONS(gfx_barrier_bit) //! \brief Bit specification for clearing attachments. enum class gfx_clear_attachment_flag_bits : uint8 { clear_flag_none = 0, clear_flag_draw_buffer0 = 1 << 0, clear_flag_draw_buffer1 = 1 << 1, clear_flag_draw_buffer2 = 1 << 2, clear_flag_draw_buffer3 = 1 << 3, clear_flag_draw_buffer4 = 1 << 4, clear_flag_draw_buffer5 = 1 << 5, clear_flag_depth_buffer = 1 << 6, clear_flag_stencil_buffer = 1 << 7, clear_flag_all_draw_buffers = clear_flag_draw_buffer0 | clear_flag_draw_buffer1 | clear_flag_draw_buffer2, clear_flag_depth_stencil_buffer = clear_flag_depth_buffer | clear_flag_stencil_buffer, clear_flag_last = clear_flag_depth_stencil_buffer }; MANGO_ENABLE_BITMASK_OPERATIONS(gfx_clear_attachment_flag_bits) //! \brief The targets buffer can be bound to. enum class gfx_buffer_target : uint8 { buffer_target_unknown = 0, buffer_target_vertex, buffer_target_index, buffer_target_uniform, buffer_target_shader_storage, buffer_target_texture, buffer_target_last = buffer_target_texture }; //! \brief Bit specification providing access information for buffers. enum class gfx_buffer_access : uint8 { buffer_access_none = 0, buffer_access_dynamic_storage = 1 << 0, buffer_access_mapped_access_read = 1 << 1, buffer_access_mapped_access_write = 1 << 2, buffer_access_mapped_access_read_write = buffer_access_mapped_access_read | buffer_access_mapped_access_write, buffer_access_last = buffer_access_mapped_access_read_write }; MANGO_ENABLE_BITMASK_OPERATIONS(gfx_buffer_access) //! \brief The type of textures. enum class gfx_texture_type : uint8 { texture_type_unknown = 0, texture_type_1d, texture_type_2d, texture_type_3d, texture_type_1d_array, texture_type_2d_array, texture_type_cube_map, texture_type_cube_map_array, texture_type_rectangle, texture_type_buffer, texture_type_2d_multisample, texture_type_2d_multisample_array, texture_type_last = texture_type_2d_multisample_array }; //! \brief The filter possibilities for samplers. enum class gfx_sampler_filter : uint8 { sampler_filter_unknown = 0, sampler_filter_nearest, sampler_filter_linear, sampler_filter_nearest_mipmap_nearest, sampler_filter_linear_mipmap_nearest, sampler_filter_nearest_mipmap_linear, sampler_filter_linear_mipmap_linear, sampler_filter_last = sampler_filter_linear_mipmap_linear }; //! \brief Defines sampler edge case handling. enum class gfx_sampler_edge_wrap : uint8 { sampler_edge_wrap_unknown = 0, sampler_edge_wrap_repeat, sampler_edge_wrap_repeat_mirrored, sampler_edge_wrap_clamp_to_edge, sampler_edge_wrap_clamp_to_border, sampler_edge_wrap_clamp_to_edge_mirrored, sampler_edge_wrap_last = sampler_edge_wrap_clamp_to_edge_mirrored }; // TODO Should these be in here? //! \brief A boolean in the glsl std140 layout. struct std140_bool { //! \cond NO_COND std140_bool(const bool& b) { pad = 0; v = b ? 1 : 0; } std140_bool() : pad(0) { } operator bool&() { return v; } void operator=(const bool& o) { pad = 0; v = o; } private: union { bool v; int32 pad; }; //! \endcond }; //! \brief An integer in the glsl std140 layout. struct std140_int { //! \cond NO_COND std140_int(const int& i) { v = i; } std140_int() : v(0) { } operator int32&() { return v; } void operator=(const int& o) { v = o; } private: int32 v; //! \endcond }; //! \brief A float in the glsl std140 layout. struct std140_float { //! \cond NO_COND std140_float(const float& f) { v = f; } std140_float() : v(0) { } operator float&() { return v; } void operator=(const float& o) { v = o; } private: float v; //! \endcond }; //! \brief A float in the glsl std140 layout for arrays. struct std140_float_array { //! \cond NO_COND std140_float_array(const float& f) { v = f; } std140_float_array() : v(0) { } operator float&() { return v; } void operator=(const float& o) { v = o; } private: float v; float p0 = 0.0f; float p1 = 0.0f; float p2 = 0.0f; //! \endcond }; //! \brief A vec2 in the glsl std140 layout. struct std140_vec2 { //! \cond NO_COND std140_vec2(const vec2& vec) : v(vec) { } std140_vec2() : v(vec2(0.0f)) { } operator vec2&() { return v; } void operator=(const vec2& o) { v = o; } float& operator[](int i) { return v[i]; } private: vec2 v; //! \endcond }; //! \brief A vec3 in the glsl std140 layout. struct std140_vec3 { //! \cond NO_COND std140_vec3(const vec3& vec) : v(vec) { } std140_vec3() : v(vec3(0.0f)) { } operator vec3&() { return v; } void operator=(const vec3& o) { v = o; } float& operator[](int i) { return v[i]; } private: vec3 v; float pad = 0.0f; //! \endcond }; //! \brief A vec4 in the glsl std140 layout. struct std140_vec4 { //! \cond NO_COND std140_vec4(const vec4& vec) : v(vec) { } std140_vec4() : v(vec4(0.0f)) { } operator vec4&() { return v; } void operator=(const vec4& o) { v = o; } float& operator[](int i) { return v[i]; } private: vec4 v; //! \endcond }; //! \brief A mat3 in the glsl std140 layout. struct std140_mat3 { //! \cond NO_COND std140_mat3(const mat3& mat) : c0(mat[0]) , c1(mat[1]) , c2(mat[2]) { } std140_mat3() : c0() , c1() , c2() { } void operator=(const mat3& o) { c0 = o[0]; c1 = o[1]; c2 = o[2]; } vec3& operator[](int i) { switch (i) { case 0: return c0; case 1: return c1; case 2: return c2; default: MANGO_ASSERT(false, "3D Matrix has only 3 columns!"); // TODO Paul: Ouch! } } operator mat3() { return glm::colMajor3(vec3(c0), vec3(c1), vec3(c2)); } private: std140_vec3 c0; std140_vec3 c1; std140_vec3 c2; //! \endcond }; //! \brief A mat4 in the glsl std140 layout. struct std140_mat4 { //! \cond NO_COND std140_mat4(const mat4& mat) : c0(mat[0]) , c1(mat[1]) , c2(mat[2]) , c3(mat[3]) { } std140_mat4() : c0() , c1() , c2() , c3() { } void operator=(const mat4& o) { c0 = o[0]; c1 = o[1]; c2 = o[2]; c3 = o[3]; } vec4& operator[](int i) { switch (i) { case 0: return c0; case 1: return c1; case 2: return c2; case 3: return c3; default: MANGO_ASSERT(false, "4D Matrix has only 4 columns!"); // TODO Paul: Ouch! } } operator mat4() { return glm::colMajor4(vec4(c0), vec4(c1), vec4(c2), vec4(c3)); } private: std140_vec4 c0; std140_vec4 c1; std140_vec4 c2; std140_vec4 c3; //! \endcond }; } // namespace mango #endif // MANGO_GRAPHICS_TYPES_HPP
30.727674
118
0.540079
[ "geometry", "render", "object", "3d" ]
c548125c4ef98d3f11a0f4a21c41a879437ab988
2,197
cpp
C++
vox.render/physics/shape/sphere_collider_shape.cpp
SummerTree/DigitalVox4
2eb718abcaccc4cd1dde3b0f28090c197c1905d4
[ "MIT" ]
6
2022-01-23T04:58:50.000Z
2022-03-16T06:11:38.000Z
vox.render/physics/shape/sphere_collider_shape.cpp
SummerTree/DigitalVox4
2eb718abcaccc4cd1dde3b0f28090c197c1905d4
[ "MIT" ]
null
null
null
vox.render/physics/shape/sphere_collider_shape.cpp
SummerTree/DigitalVox4
2eb718abcaccc4cd1dde3b0f28090c197c1905d4
[ "MIT" ]
1
2022-01-20T05:53:59.000Z
2022-01-20T05:53:59.000Z
// Copyright (c) 2022 Feng Yang // // I am making my contributions/submissions to this project solely in my // personal capacity and am not conveying any rights to any intellectual // property of any third parties. #include "sphere_collider_shape.h" #include "../physics_manager.h" #ifdef _DEBUG #include "mesh/mesh_renderer.h" #include "mesh/wireframe_primitive_mesh.h" #include "scene.h" #include "material/unlit_material.h" #endif namespace vox { namespace physics { SphereColliderShape::SphereColliderShape() { _nativeGeometry = std::make_shared<PxSphereGeometry>(_radius * std::max(std::max(_scale.x, _scale.y), _scale.z)); _nativeShape = PhysicsManager::_nativePhysics()->createShape(*_nativeGeometry, *_nativeMaterial, true); _nativeShape->setQueryFilterData(PxFilterData(PhysicsManager::_idGenerator++, 0, 0, 0)); setLocalPose(_pose); } float SphereColliderShape::radius() { return _radius; } void SphereColliderShape::setRadius(float value) { _radius = value; static_cast<PxSphereGeometry *>(_nativeGeometry.get())->radius = value * std::max(std::max(_scale.x, _scale.y), _scale.z); _nativeShape->setGeometry(*_nativeGeometry); #ifdef _DEBUG _syncSphereGeometry(); #endif } void SphereColliderShape::setWorldScale(const Vector3F &scale) { ColliderShape::setWorldScale(scale); _scale = scale; static_cast<PxSphereGeometry *>(_nativeGeometry.get())->radius = _radius * std::max(std::max(_scale.x, _scale.y), _scale.z); _nativeShape->setGeometry(*_nativeGeometry); #ifdef _DEBUG _syncSphereGeometry(); #endif } #ifdef _DEBUG void SphereColliderShape::setEntity(EntityPtr value) { ColliderShape::setEntity(value); auto renderer = _entity->addComponent<MeshRenderer>(); renderer->setMaterial(std::make_shared<UnlitMaterial>()); renderer->setMesh(WireframePrimitiveMesh::createSphereWireFrame(value->scene()->device(), 1)); _syncSphereGeometry(); } void SphereColliderShape::_syncSphereGeometry() { if (_entity) { auto radius = static_cast<PxSphereGeometry *>(_nativeGeometry.get())->radius; _entity->transform->setScale(radius, radius, radius); } } #endif } }
30.513889
128
0.730542
[ "mesh", "transform" ]
c55a58e944f04b11fb01ee7bfe5062d380ffa927
25,713
cpp
C++
production/libs/fog/Fog/Src/Fog/Core/Tools/InternedString.cpp
Lewerow/DetailIdentifier
bd5e0b3b55b5ce5b24db51ae45ed53298d331687
[ "MIT" ]
null
null
null
production/libs/fog/Fog/Src/Fog/Core/Tools/InternedString.cpp
Lewerow/DetailIdentifier
bd5e0b3b55b5ce5b24db51ae45ed53298d331687
[ "MIT" ]
null
null
null
production/libs/fog/Fog/Src/Fog/Core/Tools/InternedString.cpp
Lewerow/DetailIdentifier
bd5e0b3b55b5ce5b24db51ae45ed53298d331687
[ "MIT" ]
null
null
null
// [Fog-Core] // // [License] // MIT, See COPYING file in package // [Precompiled Headers] #if defined(FOG_PRECOMP) #include FOG_PRECOMP #endif // FOG_PRECOMP // [Dependencies] #include <Fog/Core/Global/Init_p.h> #include <Fog/Core/Memory/MemMgr.h> #include <Fog/Core/Threading/Lock.h> #include <Fog/Core/Tools/Hash.h> #include <Fog/Core/Tools/HashUtil.h> #include <Fog/Core/Tools/InternedString.h> #include <Fog/Core/Tools/StringUtil.h> namespace Fog { // ============================================================================ // [Fog::InternedStringNodeW] // ============================================================================ struct FOG_NO_EXPORT InternedStringNodeW { InternedStringNodeW* next; Static<StringW> string; }; // ============================================================================ // [Fog::InternedStringHashW] // ============================================================================ struct FOG_NO_EXPORT InternedStringHashW { // -------------------------------------------------------------------------- // [Construction / Destruction] // -------------------------------------------------------------------------- InternedStringHashW(); ~InternedStringHashW(); // -------------------------------------------------------------------------- // [Add] // -------------------------------------------------------------------------- StringDataW* addStubA(const char* sData, size_t sLength, uint32_t hashCode); StringDataW* addStubW(const CharW* sData, size_t sLength, uint32_t hashCode); void addList(InternedStringW* listData, size_t listLength); // -------------------------------------------------------------------------- // [Lookup] // -------------------------------------------------------------------------- StringDataW* lookupStubA(const char* sData, size_t sLength, uint32_t hashCode) const; StringDataW* lookupStubW(const CharW* sData, size_t sLength, uint32_t hashCode) const; // -------------------------------------------------------------------------- // [Management] // -------------------------------------------------------------------------- void _rehash(size_t capacity); InternedStringNodeW* _cleanup(); // -------------------------------------------------------------------------- // [Members] // -------------------------------------------------------------------------- //! @brief Count of buckets. size_t _capacity; //! @brief Count of nodes. size_t _length; //! @brief Count of buckets we will expand to if length exceeds _expandLength. size_t _expandCapacity; //! @brief Count of nodes to grow. size_t _expandLength; //! @brief Nodes. InternedStringNodeW** _data; InternedStringNodeW* _staticData[1]; }; // ============================================================================ // [Fog::InternedStringHashW - Construction / Destruction] // ============================================================================ InternedStringHashW::InternedStringHashW() { _capacity = 1; _length = 0; _expandCapacity = 1; _expandLength = HashUtil::getClosestPrime(0); _data = _staticData; _staticData[0] = NULL; } InternedStringHashW::~InternedStringHashW() { if (_data != _staticData) MemMgr::free(_data); } // ============================================================================ // [Fog::InternedStringHashW - Add] // ============================================================================ StringDataW* InternedStringHashW::addStubA(const char* sData, size_t sLength, uint32_t hashCode) { uint32_t hashMod = hashCode % _capacity; InternedStringNodeW** pPrev = &_data[hashMod]; InternedStringNodeW* node = *pPrev; while (node) { StringDataW* d = node->string->_d; if (d->length == sLength && StringUtil::eq(d->data, sData, sLength)) return d->addRef(); pPrev = &node->next; node = *pPrev; } node = reinterpret_cast<InternedStringNodeW*>( MemMgr::alloc(sizeof(InternedStringNodeW) + StringDataW::getSizeOf(sLength))); if (FOG_IS_NULL(node)) return NULL; StringDataW* d = reinterpret_cast<StringDataW*>(node + 1); d->reference.init(2); d->vType = VAR_TYPE_STRING_W | VAR_FLAG_STRING_INTERNED; d->hashCode = hashCode; d->capacity = sLength; d->length = sLength; StringUtil::copy(d->data, sData, sLength); node->next = NULL; node->string->_d = d; *pPrev = node; if (++_length >= _expandLength) _rehash(_expandCapacity); return d; } StringDataW* InternedStringHashW::addStubW(const CharW* sData, size_t sLength, uint32_t hashCode) { uint32_t hashMod = hashCode % _capacity; InternedStringNodeW** pPrev = &_data[hashMod]; InternedStringNodeW* node = *pPrev; while (node) { StringDataW* d = node->string->_d; if (d->length == sLength && StringUtil::eq(d->data, sData, sLength)) return d->addRef(); pPrev = &node->next; node = *pPrev; } node = reinterpret_cast<InternedStringNodeW*>( MemMgr::alloc(sizeof(InternedStringNodeW) + StringDataW::getSizeOf(sLength))); if (FOG_IS_NULL(node)) return NULL; StringDataW* d = reinterpret_cast<StringDataW*>(node + 1); d->reference.init(2); d->vType = VAR_TYPE_STRING_W | VAR_FLAG_STRING_INTERNED; d->hashCode = hashCode; d->capacity = sLength; d->length = sLength; StringUtil::copy(d->data, sData, sLength); node->next = NULL; node->string->_d = d; *pPrev = node; if (++_length >= _expandLength) _rehash(_expandCapacity); return d; } void InternedStringHashW::addList(InternedStringW* listData, size_t listLength) { if (_length + listLength >= _expandLength) { size_t expandCapacity = HashUtil::getClosestPrime((_length + listLength) / 10 * 11); _rehash(expandCapacity); } for (size_t i = 0; i < listLength; i++) { StringDataW* d = listData[i]._string->_d; const CharW* sData = d->data; size_t sLength = d->length; FOG_ASSERT(sLength > 0); uint32_t hashMod = d->hashCode % _capacity; InternedStringNodeW** pPrev = &_data[hashMod]; InternedStringNodeW* node = *pPrev; while (node) { StringDataW* node_d = node->string->_d; if (node_d->length == sLength && StringUtil::eq(node_d->data, sData, sLength)) { listData[i]._string->_d = node_d->addRef(); d->reference.init(0); d = NULL; break; } pPrev = &node->next; node = *pPrev; } if (d) { node = reinterpret_cast<InternedStringNodeW*>(reinterpret_cast<uint8_t*>(d) - sizeof(InternedStringNodeW)); node->next = NULL; *pPrev = node; } } } // ============================================================================ // [Fog::InternedStringHashW - Lookup] // ============================================================================ StringDataW* InternedStringHashW::lookupStubA(const char* sData, size_t sLength, uint32_t hashCode) const { uint32_t hashMod = hashCode % _capacity; InternedStringNodeW* node = _data[hashMod]; while (node) { StringDataW* d = node->string->_d; if (d->length == sLength && StringUtil::eq(d->data, sData, sLength)) return d->addRef(); node = node->next; } return NULL; } StringDataW* InternedStringHashW::lookupStubW(const CharW* sData, size_t sLength, uint32_t hashCode) const { uint32_t hashMod = hashCode % _capacity; InternedStringNodeW* node = _data[hashMod]; while (node) { StringDataW* d = node->string->_d; if (d->length == sLength && StringUtil::eq(d->data, sData, sLength)) return d->addRef(); node = node->next; } return NULL; } // ============================================================================ // [Fog::InternedStringHashW - Management] // ============================================================================ void InternedStringHashW::_rehash(size_t capacity) { InternedStringNodeW** oldData = _data; InternedStringNodeW** newData = (InternedStringNodeW**)MemMgr::calloc(sizeof(InternedStringNodeW*) * capacity); if (FOG_IS_NULL(newData)) return; size_t i, len = _capacity; for (i = 0; i < len; i++) { InternedStringNodeW* node = oldData[i]; while (node) { uint32_t hashMod = node->string->_d->hashCode % capacity; InternedStringNodeW* next = node->next; node->next = newData[hashMod]; newData[hashMod] = node; node = next; } } _capacity = capacity; if (_capacity <= SIZE_MAX / 19) _expandLength = (_capacity * 19) / 20; else _expandLength = size_t(double(_capacity) * 0.95); if (oldData != _staticData) MemMgr::free(oldData); _data = newData; } InternedStringNodeW* InternedStringHashW::_cleanup() { InternedStringNodeW* unusedNodes = NULL; InternedStringNodeW** data = _data; size_t i, len = _capacity; size_t removedCount = 0; for (i = 0; i < len; i++) { InternedStringNodeW** pPrev = &data[i]; InternedStringNodeW* node = *pPrev; while (node) { InternedStringNodeW* next = node->next; if ((node->string->_d->vType & VAR_FLAG_STRING_CACHED) == 0 && node->string->_d->reference.cmpXchg(1, 0)) { *pPrev = next; node->next = unusedNodes; unusedNodes = node; node = next; removedCount++; } else { pPrev = &node->next; node = next; } } } _length -= removedCount; if (_length < _capacity / 4) { _rehash(HashUtil::getClosestPrime((_length / 10) * 11)); } return unusedNodes; } // ============================================================================ // [Fog::InternedStringW - Global] // ============================================================================ static Static<Lock> InternedStringW_lock; static Static<InternedStringHashW> InternedStringW_hash; static Static<InternedStringW> InternedStringW_oEmpty; // ============================================================================ // [Fog::InternedStringW - Construction / Destruction] // ============================================================================ static void FOG_CDECL InternedStringW_ctor(InternedStringW* self) { self->_string->_d = fog_api.stringw_oEmpty->_d->addRef(); } static void FOG_CDECL InternedStringW_ctorCopy(InternedStringW* self, const InternedStringW* other) { self->_string->_d = other->_string->_d->addRef(); } static err_t FOG_CDECL InternedStringW_ctorStubA(InternedStringW* self, const StubA* stub, uint32_t options) { const char* sData = stub->getData(); size_t sLength = stub->getComputedLength(); if (!sLength) { self->_string->_d = fog_api.stringw_oEmpty->_d->addRef(); return ERR_OK; } uint32_t hashCode = HashUtil::hash(StubA(sData, sLength)); AutoLock locked(InternedStringW_lock); StringDataW* d; if ((options & INTERNED_STRING_OPTION_LOOKUP) != 0) { d = InternedStringW_hash->lookupStubA(sData, sLength, hashCode); if (FOG_IS_NULL(d)) { self->_string->_d = fog_api.stringw_oEmpty->_d->addRef(); return ERR_RT_OBJECT_NOT_FOUND; } } else { d = InternedStringW_hash->addStubA(sData, sLength, hashCode); if (FOG_IS_NULL(d)) { self->_string->_d = fog_api.stringw_oEmpty->_d->addRef(); return ERR_RT_OUT_OF_MEMORY; } } self->_string->_d = d; return ERR_OK; } static err_t FOG_CDECL InternedStringW_ctorStubW(InternedStringW* self, const StubW* stub, uint32_t options) { const CharW* sData = stub->getData(); size_t sLength = stub->getComputedLength(); if (!sLength) { self->_string->_d = fog_api.stringw_oEmpty->_d->addRef(); return ERR_OK; } uint32_t hashCode = HashUtil::hash(StubW(sData, sLength)); AutoLock locked(InternedStringW_lock); StringDataW* d; if ((options & INTERNED_STRING_OPTION_LOOKUP) != 0) { d = InternedStringW_hash->lookupStubW(sData, sLength, hashCode); if (FOG_IS_NULL(d)) { self->_string->_d = fog_api.stringw_oEmpty->_d->addRef(); return ERR_RT_OBJECT_NOT_FOUND; } } else { d = InternedStringW_hash->addStubW(sData, sLength, hashCode); if (FOG_IS_NULL(d)) { self->_string->_d = fog_api.stringw_oEmpty->_d->addRef(); return ERR_RT_OUT_OF_MEMORY; } } self->_string->_d = d; return ERR_OK; } static err_t FOG_CDECL InternedStringW_ctorStringW(InternedStringW* self, const StringW* str, uint32_t options) { StringDataW* d = str->_d; if ((d->vType & VAR_FLAG_STRING_INTERNED) != 0) { self->_string->_d = d->addRef(); return ERR_OK; } if (d->length == 0) { self->_string->_d = fog_api.stringw_oEmpty->_d->addRef(); return ERR_OK; } uint32_t hashCode = str->getHashCode(); AutoLock locked(InternedStringW_lock); if ((options & INTERNED_STRING_OPTION_LOOKUP) != 0) { d = InternedStringW_hash->lookupStubW(d->data, d->length, hashCode); if (FOG_IS_NULL(d)) { self->_string->_d = fog_api.stringw_oEmpty->_d->addRef(); return ERR_RT_OBJECT_NOT_FOUND; } } else { d = InternedStringW_hash->addStubW(d->data, d->length, hashCode); if (FOG_IS_NULL(d)) { self->_string->_d = fog_api.stringw_oEmpty->_d->addRef(); return ERR_RT_OUT_OF_MEMORY; } } self->_string->_d = d; return ERR_OK; } static void FOG_CDECL InternedStringW_dtor(InternedStringW* self) { StringDataW* d = self->_string->_d; if (d != NULL) d->reference.dec(); } // ============================================================================ // [Fog::InternedStringW - Set] // ============================================================================ static err_t FOG_CDECL InternedStringW_setStubA(InternedStringW* self, const StubA* stub, uint32_t options) { const char* sData = stub->getData(); size_t sLength = stub->getComputedLength(); if (!sLength) { atomicPtrXchg(&self->_string->_d, fog_api.stringw_oEmpty->_d->addRef())->reference.dec(); return ERR_OK; } uint32_t hashCode = HashUtil::hash(StubA(sData, sLength)); AutoLock locked(InternedStringW_lock); StringDataW* d; if ((options & INTERNED_STRING_OPTION_LOOKUP) != 0) { d = InternedStringW_hash->lookupStubA(sData, sLength, hashCode); if (FOG_IS_NULL(d)) return ERR_RT_OBJECT_NOT_FOUND; } else { d = InternedStringW_hash->addStubA(sData, sLength, hashCode); if (FOG_IS_NULL(d)) return ERR_RT_OUT_OF_MEMORY; } atomicPtrXchg(&self->_string->_d, d)->reference.dec(); return ERR_OK; } static err_t FOG_CDECL InternedStringW_setStubW(InternedStringW* self, const StubW* stub, uint32_t options) { const CharW* sData = stub->getData(); size_t sLength = stub->getComputedLength(); if (!sLength) { atomicPtrXchg(&self->_string->_d, fog_api.stringw_oEmpty->_d->addRef())->reference.dec(); return ERR_OK; } uint32_t hashCode = HashUtil::hash(StubW(sData, sLength)); AutoLock locked(InternedStringW_lock); StringDataW* d; if ((options & INTERNED_STRING_OPTION_LOOKUP) != 0) { d = InternedStringW_hash->lookupStubW(sData, sLength, hashCode); if (FOG_IS_NULL(d)) return ERR_RT_OBJECT_NOT_FOUND; } else { d = InternedStringW_hash->addStubW(sData, sLength, hashCode); if (FOG_IS_NULL(d)) return ERR_RT_OUT_OF_MEMORY; } atomicPtrXchg(&self->_string->_d, d)->reference.dec(); return ERR_OK; } static err_t FOG_CDECL InternedStringW_setStringW(InternedStringW* self, const StringW* str, uint32_t options) { StringDataW* d = str->_d; if ((d->vType & VAR_FLAG_STRING_INTERNED) != 0 || d->length == 0) { atomicPtrXchg(&self->_string->_d, d->addRef())->reference.dec(); return ERR_OK; } uint32_t hashCode = str->getHashCode(); AutoLock locked(InternedStringW_lock); if ((options & INTERNED_STRING_OPTION_LOOKUP) != 0) { d = InternedStringW_hash->lookupStubW(d->data, d->length, hashCode); if (FOG_IS_NULL(d)) return ERR_RT_OBJECT_NOT_FOUND; } else { d = InternedStringW_hash->addStubW(d->data, d->length, hashCode); if (FOG_IS_NULL(d)) return ERR_RT_OUT_OF_MEMORY; } atomicPtrXchg(&self->_string->_d, d)->reference.dec(); return ERR_OK; } static err_t FOG_CDECL InternedStringW_setInterned(InternedStringW* self, const InternedStringW* str) { atomicPtrXchg(&self->_string->_d, str->_string->_d->addRef())->reference.dec(); return ERR_OK; } // ============================================================================ // [Fog::InternedStringW - Reset] // ============================================================================ static void FOG_CDECL InternedStringW_reset(InternedStringW* self) { atomicPtrXchg(&self->_string->_d, fog_api.stringw_oEmpty->_d->addRef())->reference.dec(); } // ============================================================================ // [Fog::InternedStringW - Eq] // ============================================================================ static bool FOG_CDECL InternedStringW_eq(const InternedStringW* a, const InternedStringW* b) { return a->_string->_d == b->_string->_d; } // ============================================================================ // [Fog::InternedStringCacheW - Cleanup] // ============================================================================ static void FOG_CDECL InternedStringW_cleanup(void) { InternedStringNodeW* node; { AutoLock locked(InternedStringW_lock); node = InternedStringW_hash->_cleanup(); } while (node) { InternedStringNodeW* next = node->next; MemMgr::free(node); node = next; } } static void FOG_CDECL InternedStringW_cleanupFunc(void* closure, uint32_t reason) { InternedStringW::cleanup(); } // ============================================================================ // [Fog::InternedStringCacheW - Create] // ============================================================================ static FOG_INLINE void InternedStringCacheW_chcopy(CharW* dst, const char* src, size_t length) { for (size_t i = 0; i < length; i++) dst[i] = src[i]; } static InternedStringCacheW* FOG_CDECL InternedStringCacheW_create(const char* sData, size_t sLength, size_t listLength) // const char* strings, size_t length, size_t count) { // First subtract two NULL terminators if contained sData[]. This can happed // in case that sizeof() keyword was used to obtain count of characters in // sData. if (sLength >= 2 && sData[sLength-1] == '\0' && sData[sLength-2] == '\0') sLength--; // Detect count of list items. if (listLength == DETECT_LENGTH) listLength = StringUtil::countOf(sData, sLength, '\0', CASE_SENSITIVE); // InternedStringNodeW + InternedStringW + StringDataW + CharW[], sizeof(size_t) == alignment. size_t itemSize = sizeof(InternedStringW) + sizeof(InternedStringNodeW) + sizeof(StringDataW) - sizeof(CharW) + sizeof(size_t); size_t allocSize = sizeof(InternedStringCacheW) + itemSize * listLength + sizeof(CharW) * (sLength - listLength); InternedStringCacheW* self = reinterpret_cast<InternedStringCacheW*>(MemMgr::alloc(allocSize)); if (FOG_IS_NULL(self)) return NULL; self->_length = listLength; const char* sMark = sData; const char* sPtr = sData; const char* sEnd = sData + sLength; InternedStringW* pListBase = reinterpret_cast<InternedStringW*>(self + 1); InternedStringW* pList = pListBase; uint8_t* pData = reinterpret_cast<uint8_t*>(pListBase + listLength); size_t counter = 0; #if defined(FOG_DEBUG) uint8_t* pEnd = pData + allocSize; #endif // FOG_DEBUG for (;;) { if (sPtr[0] == 0) { InternedStringNodeW* node = reinterpret_cast<InternedStringNodeW*>(pData); pData += sizeof(InternedStringNodeW); StringDataW* d = reinterpret_cast<StringDataW*>(pData); pData += sizeof(StringDataW) - sizeof(CharW); size_t len = (size_t)(sPtr - sMark); node->next = NULL; node->string->_d = d; d->reference.init(2); d->vType = VAR_TYPE_STRING_W | VAR_FLAG_STRING_INTERNED | VAR_FLAG_STRING_CACHED; d->hashCode = HashUtil::hash(StubA(sMark, len)); d->length = len; d->capacity = len; InternedStringCacheW_chcopy(d->data, sMark, len); d->data[len] = 0; pData = (uint8_t*)((size_t)pData + (sizeof(CharW) * len + sizeof(size_t) - 1) & ~(size_t)(sizeof(size_t) - 1)); pList->_string->_d = d; pList++; counter++; if (++sPtr == sEnd) break; sMark = sPtr; } else sPtr++; } FOG_ASSERT(listLength == counter); FOG_ASSERT(pData <= pEnd); AutoLock locked(InternedStringW_lock); InternedStringW_hash->addList(pListBase, listLength); return self; } // ============================================================================ // [Fog::InternedStringCacheW - Global] // ============================================================================ static const char InternedStringCacheW_data[] = { "1.0\0" "#cdata-section\0" "#comment\0" "#document\0" "#document-fragment\0" "#text\0" "ANI\0" "APNG\0" "BMP\0" "GIF\0" "ICO\0" "JPEG\0" "LBM\0" "MNG\0" "PCX\0" "PNG\0" "PNM\0" "TGA\0" "TIFF\0" "USERPROFILE\0" "UTF-8\0" "XBM\0" "XML\0" "XPM\0" "a\0" "actualFrame\0" "angle\0" "ani\0" "apng\0" "bmp\0" "circle\0" "clip\0" "clip-path\0" "clip-rule\0" "clipPath\0" "color\0" "comp-op\0" "compression\0" "cursor\0" "cx\0" "cy\0" "d\0" "defs\0" "depth\0" "direction\0" "display\0" "dx\0" "dy\0" "ellipse\0" "enable-background\0" "encoding\0" "fill\0" "fill-opacity\0" "fill-rule\0" "filter\0" "flood-color\0" "flood-opacity\0" "font\0" "font-family\0" "font-size\0" "font-size-adjust\0" "font-stretch\0" "font-style\0" "font-variant\0" "font-weight\0" "framesCount\0" "fx\0" "fy\0" "g\0" "gif\0" "gradientTransform\0" "gradientUnits\0" "height\0" "ico\0" "id\0" "image\0" "image-rendering\0" "jfi\0" "jfif\0" "jpg\0" "jpeg\0" "lbm\0" "lengthAdjust\0" "letter-spacing\0" "lighting-color\0" "line\0" "linearGradient\0" "marker\0" "marker_end\0" "marker_mid\0" "marker_start\0" "mask\0" "mng\0" "name\0" "none\0" "offset\0" "opacity\0" "overflow\0" "path\0" "pattern\0" "patternTransform\0" "patternUnits\0" "pcx\0" "planes\0" "png\0" "pnm\0" "points\0" "polygon\0" "polyline\0" "preserveAspectRatio\0" "progress\0" "quality\0" "r\0" "radialGradient\0" "ras\0" "rect\0" "rotate\0" "rx\0" "ry\0" "shape-rendering\0" "skipFileHeader\0" "solidColor\0" "spreadMethod\0" "standalone\0" "stop\0" "stop-color\0" "stop-opacity\0" "stroke\0" "stroke-dasharray\0" "stroke-dashoffset\0" "stroke-linecap\0" "stroke-linejoin\0" "stroke-miterlimit\0" "stroke-opacity\0" "stroke-width\0" "style\0" "svg\0" "symbol\0" "text\0" "text-decoration\0" "text-rendering\0" "textLength\0" "textPath\0" "tga\0" "tif\0" "tiff\0" "transform\0" "tref\0" "tspan\0" "use\0" "version\0" "view\0" "viewBox\0" "visibility\0" "width\0" "word_spacing\0" "x\0" "x1\0" "x2\0" "xbm\0" "xlink:href\0" "xml\0" "xpm\0" "y\0" "y1\0" "y2\0" // -------------------------------------------------------------------------- // [Fog/Core - EventLoop] // -------------------------------------------------------------------------- "Core.Default\0" "Core.Win\0" "Core.Mac\0" "UI.Win\0" "UI.Mac\0" "UI.X11\0" }; // ============================================================================ // [Init / Fini] // ============================================================================ FOG_NO_EXPORT void InternedString_init(void) { // -------------------------------------------------------------------------- // [Funcs] // -------------------------------------------------------------------------- fog_api.internedstringw_ctor = InternedStringW_ctor; fog_api.internedstringw_ctorCopy = InternedStringW_ctorCopy; fog_api.internedstringw_ctorStubA = InternedStringW_ctorStubA; fog_api.internedstringw_ctorStubW = InternedStringW_ctorStubW; fog_api.internedstringw_ctorStringW = InternedStringW_ctorStringW; fog_api.internedstringw_dtor = InternedStringW_dtor; fog_api.internedstringw_setStubA = InternedStringW_setStubA; fog_api.internedstringw_setStubW = InternedStringW_setStubW; fog_api.internedstringw_setStringW = InternedStringW_setStringW; fog_api.internedstringw_setInterned = InternedStringW_setInterned; fog_api.internedstringw_reset = InternedStringW_reset; fog_api.internedstringw_eq = InternedStringW_eq; fog_api.internedstringw_cleanup = InternedStringW_cleanup; fog_api.internedstringcachew_create = InternedStringCacheW_create; // -------------------------------------------------------------------------- // [Data] // -------------------------------------------------------------------------- InternedStringW_oEmpty->_string->_d = fog_api.stringw_oEmpty->_d; fog_api.internedstringw_oEmpty = &InternedStringW_oEmpty; InternedStringW_lock.init(); InternedStringW_hash.init(); MemMgr::registerCleanupFunc(InternedStringW_cleanupFunc, NULL); fog_api.internedstringcachew_oInstance = InternedStringCacheW::create( InternedStringCacheW_data, FOG_ARRAY_SIZE(InternedStringCacheW_data), STR_COUNT); } FOG_NO_EXPORT void InternedString_fini(void) { MemMgr::unregisterCleanupFunc(InternedStringW_cleanupFunc, NULL); InternedStringW_hash.destroy(); InternedStringW_lock.destroy(); fog_api.internedstringcachew_oInstance = NULL; } } // Fog namespace
25.508929
129
0.577646
[ "shape", "transform" ]
c55dd9e309e22a61e5c889f52c292bc7c6b5a31e
1,715
cpp
C++
src/engine/GameEngine.cpp
nickfourtimes/overbourn
4fe0260222c454d9651b9fd6a5597148bdf0900d
[ "MIT" ]
null
null
null
src/engine/GameEngine.cpp
nickfourtimes/overbourn
4fe0260222c454d9651b9fd6a5597148bdf0900d
[ "MIT" ]
1
2020-06-08T14:31:17.000Z
2020-06-08T14:31:17.000Z
src/engine/GameEngine.cpp
nickfourtimes/overbourn
4fe0260222c454d9651b9fd6a5597148bdf0900d
[ "MIT" ]
null
null
null
#include <iostream> #include <stdlib.h> #include "common.h" #include "engine/GameEngine.h" using namespace std; /************************************************************************************************** DATA */ GameEngine* GameEngine::m_instance = NULL; GameScreen* m_screen; ScreenInfo* m_screenInfo; /************************************************************************************************** {CON|DE}STRUCTORS */ GameEngine::GameEngine() { return; } GameEngine::~GameEngine() { return; } /************************************************************************************************** METHODS */ GameEngine* GameEngine::Instance() { if (!m_instance) { m_instance = new GameEngine(); } return m_instance; } SDL_Surface* GameEngine::CreateMainSDLSurface(int width, int height, int depth, Uint32 flags) { m_sdlSurface = SDL_SetVideoMode(width, height, depth, flags); if (m_sdlSurface == NULL) { cout << "ERROR: SDL_CreateRGBSurface() failed: " << SDL_GetError(); } else { m_screenInfo = new ScreenInfo(); m_screenInfo->current_h = m_sdlSurface->h; m_screenInfo->current_w = m_sdlSurface->w; } return m_sdlSurface; } SDL_Surface* GameEngine::GetMainSurface() { return m_sdlSurface; } void GameEngine::PushScreen(GameScreen* screen) { m_screen = screen; return; } void GameEngine::PopScreen() { m_screen = NULL; return; } void GameEngine::Process(Uint32 code, SDL_Event event) { m_screen->Process(code, event); return; } void GameEngine::Update(Uint32 ticks) { m_screen->Update(ticks); return; } void GameEngine::Render(Uint32 code) { m_screen->Render(code); return; } ScreenInfo* GameEngine::GetScreenInfo() { return m_screenInfo; }
18.44086
120
0.588921
[ "render" ]
c56865480ff31baafe2b915050b2a1fd2207ab2f
10,698
hpp
C++
relational_operators/RelationalOperator.hpp
udippant/incubator-quickstep
8169306c2923d68235ba3c0c8df4c53f5eee9a68
[ "Apache-2.0" ]
1
2021-08-22T19:16:59.000Z
2021-08-22T19:16:59.000Z
relational_operators/RelationalOperator.hpp
udippant/incubator-quickstep
8169306c2923d68235ba3c0c8df4c53f5eee9a68
[ "Apache-2.0" ]
null
null
null
relational_operators/RelationalOperator.hpp
udippant/incubator-quickstep
8169306c2923d68235ba3c0c8df4c53f5eee9a68
[ "Apache-2.0" ]
null
null
null
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 QUICKSTEP_RELATIONAL_OPERATORS_RELATIONAL_OPERATOR_HPP_ #define QUICKSTEP_RELATIONAL_OPERATORS_RELATIONAL_OPERATOR_HPP_ #include <cstddef> #include <string> #include <vector> #include "catalog/CatalogTypedefs.hpp" #include "query_execution/QueryContext.hpp" #include "relational_operators/WorkOrder.hpp" #include "storage/StorageBlockInfo.hpp" #include "utility/Macros.hpp" #include "glog/logging.h" #include "tmb/id_typedefs.h" namespace tmb { class MessageBus; } namespace quickstep { class StorageManager; class WorkOrderProtosContainer; class WorkOrdersContainer; /** \addtogroup RelationalOperators * @{ */ /** * @brief An operator in a relational query plan. The query plan is * a directed acyclic graph of RelationalOperators. **/ class RelationalOperator { public: /** * @brief Virtual destructor. **/ virtual ~RelationalOperator() {} /** * @brief Enumeration of the operator types. **/ enum OperatorType { kAggregation = 0, kBuildAggregationExistenceMap, kBuildHash, kBuildLIPFilter, kCreateIndex, kCreateTable, kDelete, kDestroyAggregationState, kDestroyHash, kDropTable, kFinalizeAggregation, kInitializeAggregation, kInnerJoin, kInsert, kLeftAntiJoin, kLeftOuterJoin, kLeftSemiJoin, kNestedLoopsJoin, kSample, kSaveBlocks, kSelect, kSortMergeRun, kSortRunGeneration, kTableGenerator, kTextScan, kUnionAll, kUpdate, kWindowAggregation, kMockOperator }; /** * @brief Get the type of the operator. **/ virtual OperatorType getOperatorType() const = 0; /** * @brief Get the name of this relational operator. * * @return The name of this relational operator. */ virtual std::string getName() const = 0; /** * @brief Generate all the next WorkOrders for this RelationalOperator. * * @note If a RelationalOperator has blocking dependencies, it should not * generate workorders unless all of the blocking dependencies have been * met. * * @note If a RelationalOperator is not parallelizeable on a block-level, then * only one WorkOrder consisting of all the work for this * RelationalOperator should be generated. * * @param container A pointer to a WorkOrdersContainer to be used to store the * generated WorkOrders. * @param query_context The QueryContext that stores query execution states. * @param storage_manager The StorageManager to use. * @param scheduler_client_id The TMB client ID of the scheduler thread. * @param bus A pointer to the TMB. * * @return Whether the operator has finished generating work orders. If \c * false, the execution engine will invoke this method after at least * one pending work order has finished executing. **/ virtual bool getAllWorkOrders(WorkOrdersContainer *container, QueryContext *query_context, StorageManager *storage_manager, const tmb::client_id scheduler_client_id, tmb::MessageBus *bus) = 0; /** * @brief For the distributed version, generate all the next WorkOrder protos * for this RelationalOperator * * @note If a RelationalOperator has blocking dependencies, it should not * generate workorders unless all of the blocking dependencies have been * met. * * @note If a RelationalOperator is not parallelizeable on a block-level, then * only one WorkOrder consisting of all the work for this * RelationalOperator should be generated. * * @param container A pointer to a WorkOrderProtosContainer to be used to * store the generated WorkOrder protos. * * @return Whether the operator has finished generating work order protos. If * \c false, the execution engine will invoke this method after at * least one pending work order has finished executing. **/ virtual bool getAllWorkOrderProtos(WorkOrderProtosContainer *container) = 0; /** * @brief Update Catalog upon the completion of this RelationalOperator, if * necessary. * **/ virtual void updateCatalogOnCompletion() { } /** * @brief Inform this RelationalOperator that ALL the dependencies which break * the pipeline have been met. * * @note This function is only relevant in certain operators like HashJoin * which have a pipeline breaking dependency on BuildHash operator. * Such operators can start generating WorkOrders when all the pipeline * breaking dependencies are met. **/ inline void informAllBlockingDependenciesMet() { blocking_dependencies_met_ = true; } /** * @brief Receive input blocks for this RelationalOperator. * * @param input_block_id The ID of the input block. * @param relation_id The ID of the relation that produced this input_block. * @param part_id The partition ID of 'input_block_id'. **/ virtual void feedInputBlock(const block_id input_block_id, const relation_id input_relation_id, const partition_id part_id) {} /** * @brief Signal the end of feeding of input blocks for this * RelationalOperator. * * @param rel_id ID of the relation that finished producing blocks. * * @note A RelationalOperator that does not override this method can use \c * done_feeding_input_relation_ member variable to figure out that this * event was received. However, this does not distinguish between input * relations. If the operator uses more than one input relation, it will * need to override to this method to figure when the event is called * for each of its relations. * * @note This method is invoke for both streaming and non-streaming operators. * In the streaming case, this corresponds to end input to specified * relation. In both the cases, this corresponds to event of the end of * execution of downstream operator feeding input to this operator by * specified relation. **/ virtual void doneFeedingInputBlocks(const relation_id rel_id) { done_feeding_input_relation_ = true; } /** * @brief Get the InsertDestination index in the QueryContext, if used by * this RelationalOperator for storing the output of the workorders' * execution. * * @return If there is an InsertDestination for this RelationalOperator, * return the non-negative id, otherwise return * kInvalidInsertDestinationId. **/ virtual QueryContext::insert_destination_id getInsertDestinationID() const { return QueryContext::kInvalidInsertDestinationId; } /** * @brief Get the relation ID of the output relation. * * @note If a derived RelationalOperator produces a output relation using * InsertDestination, it should override this virtual method to return * its relation_id. * * @note If a derived RelationalOperator (e.g., DeleteOperator) does not use * InsertDestination to write blocks to the output, it should also * override this virtual method to return its relation_id. **/ virtual const relation_id getOutputRelationID() const { return -1; } /** * @brief Callback to receive feedback messages from work orders. * * @param message Feedback message received by the Foreman from work order on * behalf of the relational operator. * @note The relational operator needs to override this default * implementation to receive messages. Most operators don't need to use * this API. Only multi-pass operators like the sort-merge-runs * operator and the text-scan operator (with parallelized loads) will * need to use this API to convey information from work orders to the * relational operator. **/ virtual void receiveFeedbackMessage( const WorkOrder::FeedbackMessage &message) { LOG(FATAL) << "Received a feedback message on default interface. " << "Operator has no implementation."; } /** * @brief Set the index of this operator in the query plan DAG. * * @param operator_index The index of this operator in the query plan DAG. **/ void setOperatorIndex(const std::size_t operator_index) { op_index_ = operator_index; } /** * @brief Get the index of this operator in the query plan DAG. * * @return The index of this operator in the query plan DAG. */ std::size_t getOperatorIndex() const { return op_index_; } /** * @brief Deploy a group of LIPFilters to this operator. */ void deployLIPFilters(const QueryContext::lip_deployment_id lip_deployment_index) { lip_deployment_index_ = lip_deployment_index; } protected: /** * @brief Constructor * * @param query_id The ID of the query to which this operator belongs. * @param blocking_dependencies_met If those dependencies which break the * pipeline have been met. **/ explicit RelationalOperator(const std::size_t query_id, const bool blocking_dependencies_met = false) : query_id_(query_id), blocking_dependencies_met_(blocking_dependencies_met), done_feeding_input_relation_(false), lip_deployment_index_(QueryContext::kInvalidLIPDeploymentId) {} const std::size_t query_id_; bool blocking_dependencies_met_; bool done_feeding_input_relation_; std::size_t op_index_; QueryContext::lip_deployment_id lip_deployment_index_; private: DISALLOW_COPY_AND_ASSIGN(RelationalOperator); }; /** @} */ } // namespace quickstep #endif // QUICKSTEP_RELATIONAL_OPERATORS_RELATIONAL_OPERATOR_HPP_
34.178914
97
0.697046
[ "vector" ]
c56bf6a99c82f3ef48b63a4de11e5acb95806a32
2,704
cpp
C++
src/main.cpp
gregoriobenatti/bmp-dds-dds-bmp
84ca5081b92a23bbe288f5011e0dd98e78518743
[ "MIT" ]
null
null
null
src/main.cpp
gregoriobenatti/bmp-dds-dds-bmp
84ca5081b92a23bbe288f5011e0dd98e78518743
[ "MIT" ]
null
null
null
src/main.cpp
gregoriobenatti/bmp-dds-dds-bmp
84ca5081b92a23bbe288f5011e0dd98e78518743
[ "MIT" ]
null
null
null
#include "BMPFile.h" #include "DDSFile.h" #include "Converter.h" #include <iostream> #include <string> #include <array> #include <vector> #include <iterator> #include <sstream> #include <fstream> const std::string BMP = "bmp"; const std::string DDS = "dds"; const std::string HELP = "help"; const std::string MAN = "man"; void help() { std::cout << "\n\n--- BMP-DDS-DDS-BMP ---\n" << std::endl; std::cout << "Arguments --> INPUT.FILE\n" << "Need to be a file in the same directory as the executable\n" << "./converter input.file\n\n\n" << std::endl; } std::string toLowerCase(std::string s) { std::transform(s.begin(), s.end(), s.begin(), ::tolower); return s; } std::string getFileExtension(std::string inputFile) { std::string fileExtension = toLowerCase(inputFile.substr(inputFile.find_last_of(".") + 1)); std::cout << "\nInput file type: " << fileExtension << std::endl; std::cout << "Convert to: " << ((fileExtension == BMP) ? DDS : BMP) << std::endl; return fileExtension; } void convertTo(std::string fileExtension, std::string fileName) { std::cout << "[Converting] Geting file information." <<std::endl; std::cout << "[Converting] Start convert file." <<std::endl; std::shared_ptr<BMPFile> pBMPFile(new BMPFile); std::shared_ptr<DDSFile> pDDSFile(new DDSFile); std::shared_ptr<Converter> converter(new Converter); if (fileExtension == BMP) { BMPSTRUCT bmp = pBMPFile->BMPInit(fileName); converter->convertBMPToDDS(bmp.fileHeader, bmp.infoHeader, bmp.pixels); } else if (fileExtension == DDS) { DDSSTRUCT dds = pDDSFile->DDSInit(fileName); converter->convertDDSToBMP(dds.header, dds.dataBuffer); } else { std::cout << "File not supported." << std::endl; } std::cout << "[Converting] Finish convert file." <<std::endl; } int main(int argc, char* argv[]) { try { std::string arg1 = toLowerCase(argv[1]); if (arg1 == HELP || arg1 == MAN) { help(); } else { std::string fileExtension = getFileExtension(argv[1]); std::cout << "\n[Start] bmp-dds-dds-bmp." <<std::endl; if ((fileExtension != BMP) && (fileExtension != DDS)) { std::cout << "Error! File not supported --> " << argv[1] << std::endl; return 1; } convertTo(fileExtension, argv[1]); std::cout << "[Finish] bmp-dds-dds-bmp." <<std::endl; } } catch (...) { std::cout << "Error! " << std::endl; return 1; } return 0; }
25.271028
95
0.566198
[ "vector", "transform" ]
c56e23f981cf38d8a417a20857eeea916d00e73a
604
cpp
C++
generator/cities_boundaries_checker.cpp
smartyw/organicmaps
9b10eb9d3ed6833861cef294c2416cc98b15e10d
[ "Apache-2.0" ]
4,879
2015-09-30T10:56:36.000Z
2022-03-31T18:43:03.000Z
generator/cities_boundaries_checker.cpp
smartyw/organicmaps
9b10eb9d3ed6833861cef294c2416cc98b15e10d
[ "Apache-2.0" ]
7,549
2015-09-30T10:52:53.000Z
2022-03-31T22:04:22.000Z
generator/cities_boundaries_checker.cpp
smartyw/organicmaps
9b10eb9d3ed6833861cef294c2416cc98b15e10d
[ "Apache-2.0" ]
1,493
2015-09-30T10:43:06.000Z
2022-03-21T09:16:49.000Z
#include "generator/cities_boundaries_checker.hpp" #include "geometry/rect2d.hpp" namespace generator { CitiesBoundariesChecker::CitiesBoundariesChecker(CitiesBoundaries const & citiesBoundaries) { for (auto const & cb : citiesBoundaries) m_tree.Add(cb, cb.m_bbox.ToRect()); } bool CitiesBoundariesChecker::InCity(m2::PointD const & point) const { bool result = false; m_tree.ForEachInRect(m2::RectD(point, point), [&](indexer::CityBoundary const & cityBoundary) { if (result) return; result = cityBoundary.HasPoint(point); }); return result; } } // namespace generator
23.230769
97
0.731788
[ "geometry" ]
c56f9d41f16845682eed6ad4ac1569230779f0f8
6,959
cpp
C++
SirEngineThe3rdLib/src/platform/windows/graphics/vk/vkMeshManager.cpp
giordi91/SirEngineThe3rd
551328144f513e7e7ea9af03327672096baae610
[ "MIT" ]
114
2020-12-03T10:25:21.000Z
2022-03-16T20:06:15.000Z
SirEngineThe3rdLib/src/platform/windows/graphics/vk/vkMeshManager.cpp
giordi91/SirEngineThe3rd
551328144f513e7e7ea9af03327672096baae610
[ "MIT" ]
null
null
null
SirEngineThe3rdLib/src/platform/windows/graphics/vk/vkMeshManager.cpp
giordi91/SirEngineThe3rd
551328144f513e7e7ea9af03327672096baae610
[ "MIT" ]
3
2021-01-11T16:22:26.000Z
2022-01-29T16:41:09.000Z
#include "platform/windows/graphics/vk/vkMeshManager.h" #include "SirEngine/io/binaryFile.h" #include "SirEngine/io/fileUtils.h" #include "SirEngine/log.h" #include "platform/windows/graphics/vk/vk.h" #include "platform/windows/graphics/vk/vkBufferManager.h" namespace SirEngine::vk { void VkMeshManager::cleanup() { uint32_t count = m_nameToHandle.binCount(); for (uint32_t i = 0; i < count; ++i) { if (m_nameToHandle.isBinUsed(i)) { const MeshHandle handle = m_nameToHandle.getValueAtBin(i); free(handle); } } } MeshHandle VkMeshManager::loadMesh(const char *path) { SE_CORE_INFO("Loading mesh {0}", path); const bool res = fileExists(path); assert(res); // lets check whether or not the mesh has been loaded already const std::string name = getFileName(path); MeshData *meshData; MeshHandle handle{}; bool found = m_nameToHandle.get(name.c_str(), handle); if (!found) { std::vector<char> binaryData; readAllBytes(path, binaryData); const auto *const mapper = getMapperData<ModelMapperData>(binaryData.data()); const uint32_t indexCount = mapper->indexDataSizeInByte / sizeof(int); // lets get the vertex data auto *vertexData = reinterpret_cast<float *>(binaryData.data() + sizeof(BinaryFileHeader)); auto *indexData = reinterpret_cast<int *>(binaryData.data() + sizeof(BinaryFileHeader) + mapper->vertexDataSizeInByte); // upload the data on the GPU uint32_t index; meshData = &m_meshPool.getFreeMemoryData(index); meshData->indexCount = indexCount; meshData->vertexCount = mapper->vertexCount; uint32_t totalSize = indexCount * sizeof(int); meshData->idxBuffHandle = vk::BUFFER_MANAGER->allocate( totalSize, indexData, frameConcatenation(name.c_str(), "-indexBuffer"), totalSize / sizeof(int), sizeof(int), BufferManager::BUFFER_FLAGS_BITS::INDEX_BUFFER | BufferManager::BUFFER_FLAGS_BITS::IS_STATIC | BufferManager::BUFFER_FLAGS_BITS::GPU_ONLY); meshData->indexBuffer = vk::BUFFER_MANAGER->getNativeBuffer(meshData->idxBuffHandle); // load bounding box glm::vec3 minP = {mapper->boundingBox[0], mapper->boundingBox[1], mapper->boundingBox[2]}; glm::vec3 maxP = {mapper->boundingBox[3], mapper->boundingBox[4], mapper->boundingBox[5]}; BoundingBox box{minP, maxP, {}}; meshData->entityID = static_cast<uint32_t>(m_boundingBoxes.size()); m_boundingBoxes.pushBack(box); // data is now loaded need to create handle etc handle = MeshHandle{(MAGIC_NUMBER_COUNTER << 16) | index}; meshData->magicNumber = MAGIC_NUMBER_COUNTER; // build the runtime mesh VkMeshRuntime meshRuntime{}; meshRuntime.indexCount = meshData->indexCount; meshRuntime.indexBuffer = meshData->indexBuffer; meshRuntime.vertexBuffer = meshData->vertexBuffer; meshRuntime.positionRange = mapper->positionRange; meshRuntime.normalsRange = mapper->normalsRange; meshRuntime.uvRange = mapper->uvRange; meshRuntime.tangentsRange = mapper->tangentsRange; // storing the handle and increasing the magic count m_nameToHandle.insert(name.c_str(), handle); ++MAGIC_NUMBER_COUNTER; BufferHandle positionsHandle = vk::BUFFER_MANAGER->allocate( mapper->vertexDataSizeInByte, vertexData, frameConcatenation(name.c_str(), "-meshBuffer"), static_cast<int>(mapper->vertexDataSizeInByte / 4u), sizeof(float), BufferManager::BUFFER_FLAGS_BITS::VERTEX_BUFFER | BufferManager::BUFFER_FLAGS_BITS::IS_STATIC | BufferManager::BUFFER_FLAGS_BITS::GPU_ONLY); meshData->vtxBuffHandle = positionsHandle; meshRuntime.vertexBuffer = vk::BUFFER_MANAGER->getNativeBuffer(meshData->vtxBuffHandle); meshData->vertexBuffer = meshRuntime.vertexBuffer; meshData->meshRuntime = meshRuntime; } SE_CORE_INFO("Mesh already loaded, returning handle:{0}", name); return handle; } void VkMeshManager::bindMesh(const MeshHandle handle, VkWriteDescriptorSet *set, const VkDescriptorSet descriptorSet, VkDescriptorBufferInfo *info, const uint32_t bindFlags, const uint32_t startIdx) const { assertMagicNumber(handle); uint32_t idx = getIndexFromHandle(handle); const MeshData &data = m_meshPool.getConstRef(idx); if ((bindFlags & MESH_ATTRIBUTE_FLAGS::POSITIONS) > 0) { // actual information of the descriptor, in this case it is our mesh buffer info[0].buffer = data.vertexBuffer; info[0].offset = data.meshRuntime.positionRange.m_offset; info[0].range = data.meshRuntime.positionRange.m_size; // Binding 0: Object mesh buffer set[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; set[0].dstSet = descriptorSet; set[0].dstBinding = startIdx + 0; set[0].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; set[0].pBufferInfo = &info[0]; set[0].descriptorCount = 1; } if ((bindFlags & MESH_ATTRIBUTE_FLAGS::NORMALS) > 0) { info[1].buffer = data.vertexBuffer; info[1].offset = data.meshRuntime.normalsRange.m_offset; info[1].range = data.meshRuntime.normalsRange.m_size; set[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; set[1].dstSet = descriptorSet; set[1].dstBinding = startIdx + 1; set[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; set[1].pBufferInfo = &info[1]; set[1].descriptorCount = 1; } if ((bindFlags & MESH_ATTRIBUTE_FLAGS::UV) > 0) { info[2].buffer = data.vertexBuffer; info[2].offset = data.meshRuntime.uvRange.m_offset; info[2].range = data.meshRuntime.uvRange.m_size; set[2].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; set[2].dstSet = descriptorSet; set[2].dstBinding = startIdx + 2; set[2].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; set[2].pBufferInfo = &info[2]; set[2].descriptorCount = 1; } if ((bindFlags & MESH_ATTRIBUTE_FLAGS::TANGENTS) > 0) { info[3].buffer = data.vertexBuffer; info[3].offset = data.meshRuntime.tangentsRange.m_offset; info[3].range = data.meshRuntime.tangentsRange.m_size; set[3].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; set[3].dstSet = descriptorSet; set[3].dstBinding = startIdx + 3; set[3].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; set[3].pBufferInfo = &info[3]; set[3].descriptorCount = 1; } } void VkMeshManager::free(const MeshHandle handle) { assertMagicNumber(handle); uint32_t index = getIndexFromHandle(handle); MeshData &data = m_meshPool[index]; vk::BUFFER_MANAGER->free(data.vtxBuffHandle); vk::BUFFER_MANAGER->free(data.idxBuffHandle); // invalidating magic number data = {}; // adding the index to the free list m_meshPool.free(index); } } // namespace SirEngine::vk
37.616216
80
0.694496
[ "mesh", "object", "vector" ]
c57614d99452a569c33da3e8c4e6d67af3021b65
1,336
cpp
C++
walter/katana/WalterIn/FaceSetCook.cpp
all-in-one-of/OpenWalter
c2034f7fac20b36ffe3e500c01d40b87e84e2b97
[ "libtiff" ]
187
2018-08-14T19:06:20.000Z
2022-03-04T06:03:25.000Z
walter/katana/WalterIn/FaceSetCook.cpp
all-in-one-of/OpenWalter
c2034f7fac20b36ffe3e500c01d40b87e84e2b97
[ "libtiff" ]
9
2018-08-22T15:34:48.000Z
2019-11-27T13:45:21.000Z
walter/katana/WalterIn/FaceSetCook.cpp
all-in-one-of/OpenWalter
c2034f7fac20b36ffe3e500c01d40b87e84e2b97
[ "libtiff" ]
41
2018-08-14T19:06:09.000Z
2021-09-04T20:01:10.000Z
#include "AbcCook.h" #include "ArrayPropUtils.h" #include "ScalarPropUtils.h" #include "ArbitraryGeomParamUtils.h" #include <FnAttribute/FnAttribute.h> #include <FnAttribute/FnDataBuilder.h> namespace WalterIn { void cookFaceset(AbcCookPtr ioCook, FnAttribute::GroupBuilder & oStaticGb) { Alembic::AbcGeom::IFaceSetPtr objPtr( new Alembic::AbcGeom::IFaceSet(*(ioCook->objPtr), Alembic::AbcGeom::kWrapExisting)); Alembic::AbcGeom::IFaceSetSchema schema = objPtr->getSchema(); Alembic::Abc::ICompoundProperty userProp = schema.getUserProperties(); Alembic::Abc::ICompoundProperty arbGeom = schema.getArbGeomParams(); std::string abcUser = "abcUser."; processUserProperties(ioCook, userProp, oStaticGb, abcUser); processArbGeomParams(ioCook, arbGeom, oStaticGb); oStaticGb.set("type", FnAttribute::StringAttribute("faceset")); // IFaceSetSchema doesn't expose this yet const Alembic::AbcCoreAbstract::PropertyHeader * propHeader = schema.getPropertyHeader(".faces"); if (propHeader != NULL) { arrayPropertyToAttr(schema, *propHeader, "geometry.faces", kFnKatAttributeTypeInt, ioCook, oStaticGb); } } }
32.585366
78
0.650449
[ "geometry" ]
c576a4f8e20336e7b970085b000bc79a72373279
923
cxx
C++
Algorithms/Sorting/quicksort2.cxx
will-crawford/HackerRank
74965480ee6a51603eb320e5982b0943fdaf1302
[ "MIT" ]
null
null
null
Algorithms/Sorting/quicksort2.cxx
will-crawford/HackerRank
74965480ee6a51603eb320e5982b0943fdaf1302
[ "MIT" ]
null
null
null
Algorithms/Sorting/quicksort2.cxx
will-crawford/HackerRank
74965480ee6a51603eb320e5982b0943fdaf1302
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; inline ostream &operator<< (ostream &os, vector<int> &v) { auto i = begin(v), j = end(v); if ( i != j ) { os << *i; while ( ++i != j ) os << ' ' << *i; } return os; } void quickSort(vector <int> &arr) { vector<int> left, equal, right; int p = arr[0]; for ( auto i : arr ) ( i < p ? left : i == p ? equal : right ).emplace_back (i); if ( left.size() > 1 ) quickSort(left); if ( right.size() > 1 ) quickSort(right); copy( begin(right), end(right), copy( begin(equal), end(equal), copy( begin(left), end(left), begin(arr) ) ) ); cout << arr << endl; } int main() { int n; cin >> n; vector <int> arr(n); for(int i = 0; i < (int)n; ++i) { cin >> arr[i]; } quickSort(arr); return 0; }
19.638298
67
0.447454
[ "vector" ]
c576a820d5032c968c4dde065b27b5b51ece2f45
2,361
cpp
C++
src/lib/client/InfraredStateChangeNotifications.cpp
gerickson/openhlx
f23a825ca56ee226db393da14d81a7d4e9ae0b33
[ "Apache-2.0" ]
1
2021-05-21T21:10:09.000Z
2021-05-21T21:10:09.000Z
src/lib/client/InfraredStateChangeNotifications.cpp
gerickson/openhlx
f23a825ca56ee226db393da14d81a7d4e9ae0b33
[ "Apache-2.0" ]
12
2021-06-12T16:42:30.000Z
2022-02-01T18:44:42.000Z
src/lib/client/InfraredStateChangeNotifications.cpp
gerickson/openhlx
f23a825ca56ee226db393da14d81a7d4e9ae0b33
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2019-2021 Grant Erickson * 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. * */ /** * @file * This file implements derived objects for a HLX client infrared * remote control object data model state change notifications * (SCNs). * */ #include "InfraredStateChangeNotifications.hpp" #include <OpenHLX/Utilities/Assert.hpp> #include <OpenHLX/Client/StateChangeNotificationTypes.hpp> using namespace HLX::Common; using namespace HLX::Model; namespace HLX { namespace Client { namespace StateChange { /** * @brief * This is the class default constructor. * */ InfraredDisabledNotification :: InfraredDisabledNotification(void) : NotificationBasis(), mDisabled(true) { return; } /** * @brief * This is the class initializer. * * This initializes the infrared remote control disabled property * state change notification with the specified disabled state. * * @param[in] aDisabled An immutable reference to the disabled * state that changed. * * @retval kStatus_Success If successful. * */ Status InfraredDisabledNotification :: Init(const DisabledType &aDisabled) { Status lRetval = kStatus_Success; lRetval = NotificationBasis::Init(kStateChangeType_InfraredDisabled); nlREQUIRE_SUCCESS(lRetval, done); mDisabled = aDisabled; done: return (lRetval); } /** * @brief * Return the infrared remote control state change disabled state property. * * @returns * The disabled state of the infrared remote control whose state changed. * */ InfraredDisabledNotification :: DisabledType InfraredDisabledNotification :: GetDisabled(void) const { return (mDisabled); } }; // namespace StateChange }; // namespace Client }; // namespace HLX
22.701923
78
0.703515
[ "object", "model" ]
c5770c84276739e075eb994724431320db0dddb7
1,578
cpp
C++
src/game/Vector2D.cpp
padawin/RogueCard
7a5d04fa2d7be47c1542b6d4908e277ccbbd01fc
[ "MIT" ]
null
null
null
src/game/Vector2D.cpp
padawin/RogueCard
7a5d04fa2d7be47c1542b6d4908e277ccbbd01fc
[ "MIT" ]
null
null
null
src/game/Vector2D.cpp
padawin/RogueCard
7a5d04fa2d7be47c1542b6d4908e277ccbbd01fc
[ "MIT" ]
null
null
null
#include "Vector2D.hpp" #include <math.h> Vector2D::Vector2D() { m_iX = 0; m_iY = 0; } Vector2D::Vector2D(const float x, const float y) { m_iX = x; m_iY = y; } float Vector2D::getLength() { return sqrtf(powf(m_iX, 2.0) + powf(m_iY, 2.0)); } float Vector2D::getX() { return m_iX; } float Vector2D::getY() { return m_iY; } void Vector2D::setX(const float x) { m_iX = x; } void Vector2D::setY(const float y) { m_iY = y; } void Vector2D::set(Vector2DCoord coord, const float value) { if (coord == VECTOR_X) { setX(value); } else { setY(value); } } void Vector2D::normalize() { float l = getLength(); if (l > 0) { // we never want to attempt to divide by 0 (*this) *= 1 / l; } } // Vector operations Vector2D Vector2D::operator+(const Vector2D& v2) const { return Vector2D(m_iX + v2.m_iX, m_iY + v2.m_iY); } Vector2D Vector2D::operator-(const Vector2D& v2) const { return Vector2D(m_iX - v2.m_iX, m_iY - v2.m_iY); } Vector2D Vector2D::operator*(float scalar) { return Vector2D(m_iX * scalar, m_iY * scalar); } Vector2D Vector2D::operator/(float scalar) { return Vector2D(m_iX / scalar, m_iY / scalar); } Vector2D& operator+=(Vector2D& v1, const Vector2D& v2) { v1.m_iX += v2.m_iX; v1.m_iY += v2.m_iY; return v1; } Vector2D& operator-=(Vector2D& v1, const Vector2D& v2) { v1.m_iX -= v2.m_iX; v1.m_iY -= v2.m_iY; return v1; } Vector2D& operator*=(Vector2D& v1, float scalar) { v1.m_iX *= scalar; v1.m_iY *= scalar; return v1; } Vector2D& operator/=(Vector2D& v1, float scalar) { v1.m_iX /= scalar; v1.m_iY /= scalar; return v1; }
17.533333
60
0.653359
[ "vector" ]
c5790e33a24f29ce42a26aa0f2c61e0c4021c61e
17,766
cxx
C++
Podd/THaDetMap.cxx
MarkKJones/analyzer
5f02974888b1655b9e7b9440a708b98ae9477af8
[ "BSD-3-Clause" ]
7
2016-01-26T19:37:26.000Z
2019-02-18T20:50:39.000Z
Podd/THaDetMap.cxx
MarkKJones/analyzer
5f02974888b1655b9e7b9440a708b98ae9477af8
[ "BSD-3-Clause" ]
108
2015-02-01T04:17:40.000Z
2021-10-30T14:54:45.000Z
Podd/THaDetMap.cxx
MarkKJones/analyzer
5f02974888b1655b9e7b9440a708b98ae9477af8
[ "BSD-3-Clause" ]
57
2015-05-08T17:14:11.000Z
2022-03-24T16:38:40.000Z
//*-- Author : Ole Hansen 16/05/00 ////////////////////////////////////////////////////////////////////////// // // THaDetMap // // The standard detector map for a Hall A detector. // ////////////////////////////////////////////////////////////////////////// #include "THaDetMap.h" #include "Decoder.h" #include <iostream> #include <iomanip> #include <stdexcept> #include <sstream> #include <vector> #include <algorithm> using namespace std; using namespace Decoder; #define ALL(c) (c).begin(), (c).end() // "Database" of known frontend module numbers and types // FIXME: load from db_cratemap class ModuleDef { public: Int_t model; // model identifier ChannelType type; // Module type }; static const vector<ModuleDef> module_list { { 1875, ChannelType::kCommonStopTDC }, { 1877, ChannelType::kCommonStopTDC }, { 1881, ChannelType::kADC }, { 1872, ChannelType::kCommonStopTDC }, { 3123, ChannelType::kADC }, { 1182, ChannelType::kADC }, { 792, ChannelType::kADC }, { 775, ChannelType::kCommonStopTDC }, { 767, ChannelType::kCommonStopTDC }, { 3201, ChannelType::kCommonStopTDC }, { 6401, ChannelType::kCommonStopTDC }, { 1190, ChannelType::kCommonStopTDC }, { 250, ChannelType::kMultiFunctionADC }, }; //_____________________________________________________________________________ void THaDetMap::Module::SetModel( Int_t mod ) { model = mod; auto it = find_if(ALL(module_list), [mod]( const ModuleDef& m ) { return m.model == mod; }); if( it != module_list.end() ) type = it->type; else type = ChannelType::kUndefined; } //_____________________________________________________________________________ void THaDetMap::Module::SetResolution( Double_t res ) { resolution = res; } //_____________________________________________________________________________ void THaDetMap::Module::SetTDCMode( Bool_t cstart ) { cmnstart = cstart; if( cstart && type == ChannelType::kCommonStopTDC ) type = ChannelType::kCommonStartTDC; else if( !cstart && type == ChannelType::kCommonStartTDC ) type = ChannelType::kCommonStopTDC; } //_____________________________________________________________________________ void THaDetMap::Module::MakeTDC() { if( IsCommonStart() ) type = ChannelType::kCommonStartTDC; else type = ChannelType::kCommonStopTDC; } //_____________________________________________________________________________ void THaDetMap::Module::MakeADC() { type = ChannelType::kADC; } //_____________________________________________________________________________ void THaDetMap::CopyMap( const ModuleVec_t& map ) { // Deep-copy the vector of module pointers fMap.reserve(map.capacity()); for( const auto& m : map ) { fMap.emplace_back( #if __cplusplus >= 201402L std::make_unique<Module>(*m) #else new Module(*m) #endif ); } } //_____________________________________________________________________________ THaDetMap::THaDetMap( const THaDetMap& rhs ) : fStartAtZero(rhs.fStartAtZero) { // Copy constructor CopyMap(rhs.fMap); } //_____________________________________________________________________________ THaDetMap& THaDetMap::operator=( const THaDetMap& rhs ) { // THaDetMap assignment operator if( this != &rhs ) { fMap.clear(); CopyMap(rhs.fMap); fStartAtZero = rhs.fStartAtZero; } return *this; } //_____________________________________________________________________________ Int_t THaDetMap::AddModule( UInt_t crate, UInt_t slot, UInt_t chan_lo, UInt_t chan_hi, UInt_t first, Int_t model, Int_t refindex, Int_t refchan, UInt_t plane, UInt_t signal ) { // Add a module to the map. // Logical channels can run either "with" or "against" the physical channel // numbers: // lo<=hi : lo -> first // hi -> first+hi-lo // // lo>hi : hi -> first // lo -> first+lo-hi // // To indicate the second case, The flag "reverse" is set to true in the // module. The fields lo and hi are reversed so that lo<=hi always. // bool reverse = (chan_lo > chan_hi); #if __cplusplus >= 201402L auto pm = make_unique<Module>(); #else auto pm = unique_ptr<Module>(new THaDetMap::Module); #endif Module& m = *pm; m.crate = crate; m.slot = slot; if( reverse ) { m.lo = chan_hi; m.hi = chan_lo; } else { m.lo = chan_lo; m.hi = chan_hi; } m.first = first; m.model = model; m.refindex = refindex; m.refchan = refchan; m.plane = plane; m.signal = signal; m.SetResolution(0.0); m.reverse = reverse; m.cmnstart = false; // Set the module type using our lookup table of known model numbers. // If the model is not predefined, this can be done manually later with // calls to MakeADC()/MakeTDC(). if( model != 0 ) { auto it = find_if(ALL(module_list), [model]( const ModuleDef& m ) { return m.model == model; }); if( it != module_list.end() ) m.type = it->type; else m.type = ChannelType::kUndefined; // return -1; // Unknown module TODO do when module_list is in a database } else m.type = ChannelType::kUndefined; fMap.push_back(std::move(pm)); return static_cast<Int_t>(GetSize()); } //_____________________________________________________________________________ THaDetMap::Module* THaDetMap::Find( UInt_t crate, UInt_t slot, UInt_t chan ) { // Return the module containing crate, slot, and channel chan. // If several matching modules exist (which mean the map is misconfigured), // only the first one is returned. If none match, return nullptr. // Since the map is usually small and not necessarily sorted, a simple // linear search is done. auto found = find_if( ALL(fMap), [crate,slot,chan](const unique_ptr<Module>& d) { return ( d->crate == crate && d->slot == slot && d->lo <= chan && chan <= d->hi ); }); return (found != fMap.end()) ? found->get() : nullptr; } //_____________________________________________________________________________ Int_t THaDetMap::Fill( const vector<Int_t>& values, UInt_t flags ) { // Fill the map with 'values'. Depending on 'flags', the values vector // is interpreted as a 4-, 5-, 6- or 7-tuple: // // The first 4 values are interpreted as (crate,slot,start_chan,end_chan) // Each of the following flags causes one more value to be used as part of // the tuple for each module: // // kFillLogicalChannel - Logical channel number for 'start_chan'. // kFillModel - The module's hardware model number (see AddModule()) // kFillRefChan - Reference channel (for pipeline TDCs etc.) // kFillRefIndex - Reference index (for pipeline TDCs etc.) // kFillPlane - Which plane in detector (for Hall C) // kFillSignal - Which signal type (for Hall C) // // If more than one flag is present, the numbers will be interpreted // in the order the flags are listed above. // Example: // flags = kFillModel | kFillRefChan // ==> // the vector is interpreted as a series of 6-tuples in the order // (crate,slot,start_chan,end_chan,model,refchan). // // If kFillLogicalChannel is not set then the first logical channel numbers // are automatically calculated for each module, assuming the numbers are // sequential. // // By default, an existing map is overwritten. If the flag kDoNotClear // is present, then the data are appended. // // The return value is the number of modules successfully added, // or negative if an error occurred. typedef vector<Int_t>::size_type vsiz_t; if( (flags & kFillLogicalChannel) && (flags & kSkipLogicalChannel) ) // Bad combination of flags return -128; if( (flags & kDoNotClear) == 0 ) Clear(); vsiz_t tuple_size = 4; if( flags & kFillLogicalChannel || flags & kSkipLogicalChannel ) tuple_size++; if( flags & kFillModel ) tuple_size++; if( flags & kFillRefChan ) tuple_size++; if( flags & kFillRefIndex ) tuple_size++; if( flags & kFillPlane ) tuple_size++; if( flags & kFillSignal ) tuple_size++; // For historical reasons, logical channel numbers start at 1 UInt_t prev_first = 1, prev_nchan = 0; // Defaults for optional values UInt_t first = 0; Int_t plane = 0, signal = 0, model = 0, rchan = -1, ref = -1; Int_t ret = 0; for( vsiz_t i = 0; i < values.size(); i += tuple_size ) { // For compatibility with older maps, crate < 0 means end of data if( values[i] < 0 ) break; // Now we require a full tuple if( i + tuple_size > values.size() ) { ret = -127; break; } vsiz_t k = 4; if( flags & kFillLogicalChannel ) { first = values[i + k++]; if( first == 0 ) // This map appears to start counting channels at zero // This is actually the exception. For historical reasons (Fortran), // most maps start counting at 1. // This flag is used by the hit iterators only; existing Decode() // methods will not be affected. fStartAtZero = true; } else { if( flags & kSkipLogicalChannel ) { ++k; } first = prev_first + prev_nchan; } if( flags & kFillModel ) model = values[i + k++]; if( flags & kFillRefChan ) rchan = values[i + k++]; if( flags & kFillRefIndex ) ref = values[i + k++]; if( flags & kFillPlane ) plane = values[i + k++]; if( flags & kFillSignal ) signal = values[i + k++]; auto crate = static_cast<UInt_t>(values[i]); auto slot = static_cast<UInt_t>(values[i+1]); auto ch_lo = static_cast<UInt_t>(values[i+2]); auto ch_hi = static_cast<UInt_t>(values[i+3]); ret = AddModule(crate, slot, ch_lo, ch_hi, first, model, ref, rchan, plane, signal); if( ret <= 0 ) break; prev_first = first; prev_nchan = GetNchan(ret - 1); } return ret; } //_____________________________________________________________________________ UInt_t THaDetMap::GetTotNumChan() const { // Get sum of the number of channels of all modules in the map. This is // typically the total number of hardware channels used by the detector. UInt_t sum = 0; for( const auto & m : fMap ) sum += m->GetNchan(); return sum; } //_____________________________________________________________________________ void THaDetMap::GetMinMaxChan( UInt_t& min, UInt_t& max, ECountMode mode ) const { // Put the minimum and maximum logical or reference channel numbers // into min and max. If refidx is true, check refindex, else check logical // channel numbers. min = kMaxInt; max = kMinInt; bool do_ref = (mode == kRefIndex); for( const auto& m : fMap ) { UInt_t m_min = do_ref ? m->refindex : m->first; UInt_t m_max = do_ref ? m->refindex : m->first + m->hi - m->lo; if( m_min < min ) min = m_min; if( m_max > max ) max = m_max; } } //_____________________________________________________________________________ void THaDetMap::Print( Option_t* ) const { // Print the contents of the map cout << "Size: " << GetSize() << endl; for( const auto& m : fMap ) { cout << " " << setw(5) << m->crate << setw(5) << m->slot << setw(5) << m->lo << setw(5) << m->hi << setw(5) << m->first << setw(5) << m->model; if( m->IsADC() ) cout << setw(4) << " ADC"; if( m->IsTDC() ) cout << setw(4) << " TDC"; cout << setw(5) << m->refchan << setw(5) << m->refindex << setw(8) << m->resolution << setw(5) << m->plane << setw(5) << m->signal << endl; } } //_____________________________________________________________________________ void THaDetMap::Reset() { // Clear() the map and reset the array size to zero, freeing memory. Clear(); fMap.shrink_to_fit(); // FWIW } //_____________________________________________________________________________ void THaDetMap::Sort() { // Sort the map by crate/slot/low channel sort( ALL(fMap), []( const unique_ptr<Module>& a, const unique_ptr<Module>& b) { if( a->crate < b->crate ) return true; if( a->crate > b->crate ) return false; if( a->slot < b->slot ) return true; if( a->slot > b->slot ) return false; return (a->lo < b->lo); }); } //============================================================================= THaDetMap::Iterator THaDetMap::MakeIterator( const THaEvData& evdata ) { return THaDetMap::Iterator(*this, evdata); } //_____________________________________________________________________________ THaDetMap::MultiHitIterator THaDetMap::MakeMultiHitIterator( const THaEvData& evdata ) { return THaDetMap::MultiHitIterator(*this, evdata); } //_____________________________________________________________________________ THaDetMap::Iterator::Iterator( THaDetMap& detmap, const THaEvData& evdata, bool do_init ) : fDetMap(detmap), fEvData(evdata), fMod(nullptr), fNMod(fDetMap.GetSize()), fNTotChan(fDetMap.GetTotNumChan()), fNChan(0), fIMod(-1), fIChan(-1) { fHitInfo.ev = fEvData.GetEvNum(); // Initialize iterator state to point to the first item if( do_init ) ++(*this); } //_____________________________________________________________________________ string THaDetMap::Iterator::msg( const char* txt ) const { // Format message string for exceptions ostringstream ostr; ostr << "Event " << fHitInfo.ev << ", "; ostr << "channel " << fHitInfo.crate << "/" << fHitInfo.slot << "/" << fHitInfo.chan << "/" << fHitInfo.hit << ": "; if( txt and *txt ) ostr << txt; else ostr << "Unspecified error."; return ostr.str(); } #define CRATE_SLOT( x ) (x).crate, (x).slot static inline bool LOOPDONE( Int_t i, UInt_t n ) { return i < 0 or static_cast<UInt_t>(i) >= n; } static inline bool NO_NEXT( Int_t& i, UInt_t n ) { return i >= static_cast<Int_t>(n) or ++i >= static_cast<Int_t>(n); } //_____________________________________________________________________________ THaDetMap::Iterator& THaDetMap::Iterator::operator++() { // Advance iterator to next active channel nextmod: if( LOOPDONE(fIChan, fNChan) ) { if( NO_NEXT(fIMod, fNMod) ) { fHitInfo.reset(); return *this; } fMod = fDetMap.GetModule(fIMod); if( !fMod ) throw std::logic_error("NULL detector map module. Program bug. " "Call expert."); fHitInfo.set_crate_slot(fMod); fHitInfo.module = fEvData.GetModule(CRATE_SLOT(fHitInfo)); fNChan = fEvData.GetNumChan(CRATE_SLOT(fHitInfo)); fIChan = -1; } nextchan: if( NO_NEXT(fIChan, fNChan) ) goto nextmod; UInt_t chan = fEvData.GetNextChan(CRATE_SLOT(fHitInfo), fIChan); if( chan < fMod->lo or chan > fMod->hi ) goto nextchan; // Not one of my channels UInt_t nhit = fEvData.GetNumHits(CRATE_SLOT(fHitInfo), chan); fHitInfo.chan = chan; fHitInfo.nhit = nhit; if( nhit == 0 ) { ostringstream ostr; ostr << "No hits on active " << (fHitInfo.type == ChannelType::kADC ? "ADC" : "TDC") << " channel. Should never happen. Decoder bug. Call expert."; throw std::logic_error(msg(ostr.str().c_str())); } // If multiple hits on a TDC channel take the one earliest in time. // For a common-stop TDC, this is actually the last hit. fHitInfo.hit = (fHitInfo.type == ChannelType::kCommonStopTDC) ? nhit - 1 : 0; // Determine logical channel. Decode() methods that use this hit iterator // should always assume that logical channel numbers start counting from zero. Int_t lchan = fMod->ConvertToLogicalChannel(chan); if( fDetMap.fStartAtZero ) ++lchan; // ConvertToLogicalChannel subtracts 1; undo that here if( lchan < 0 or static_cast<UInt_t>(lchan) >= size() ) { ostringstream ostr; size_t lmin = 1, lmax = size(); // Apparent range in the database file if( fDetMap.fStartAtZero ) { --lmin; --lmax; } ostr << "Illegal logical detector channel " << lchan << "." << "Must be between " << lmin << " and " << lmax << ". Fix database."; throw std::invalid_argument(msg(ostr.str().c_str())); } fHitInfo.lchan = lchan; return *this; } //_____________________________________________________________________________ void THaDetMap::Iterator::reset() { // Reset iterator to first element, if any fNMod = fDetMap.GetSize(); fIMod = fIChan = -1; fHitInfo.reset(); ++(*this); } //_____________________________________________________________________________ THaDetMap::MultiHitIterator::MultiHitIterator( THaDetMap& detmap, const THaEvData& evdata, bool do_init ) : Iterator(detmap, evdata, false), fIHit(-1) { if( do_init ) ++(*this); } //_____________________________________________________________________________ THaDetMap::Iterator& THaDetMap::MultiHitIterator::operator++() { // Advance iterator to next active hit or channel, allowing multiple hits // per channel nexthit: if( LOOPDONE(fIHit, fHitInfo.nhit) ) { Iterator::operator++(); if( !Iterator::operator bool() ) return *this; fIHit = -1; } if( NO_NEXT(fIHit, fHitInfo.nhit) ) goto nexthit; fHitInfo.hit = fIHit; // overwrite value of single-hit case (0 or nhit-1) return *this; } //_____________________________________________________________________________ void THaDetMap::MultiHitIterator::reset() { fIHit = -1; Iterator::reset(); } //_____________________________________________________________________________ ClassImp(THaDetMap)
31.5
119
0.651413
[ "vector", "model" ]
c585e0e2d8a6ecb3e696da34830891fefefc5116
527
cpp
C++
Week-4/Day-22-frequencySort.cpp
utkarshavardhana/may-leetcoding-challenge
4f7600c943460029c595a3b2d85f86e68d7b7066
[ "MIT" ]
1
2020-05-02T04:21:54.000Z
2020-05-02T04:21:54.000Z
Week-4/Day-22-frequencySort.cpp
utkarshavardhana/may-leetcoding-challenge
4f7600c943460029c595a3b2d85f86e68d7b7066
[ "MIT" ]
null
null
null
Week-4/Day-22-frequencySort.cpp
utkarshavardhana/may-leetcoding-challenge
4f7600c943460029c595a3b2d85f86e68d7b7066
[ "MIT" ]
null
null
null
class Solution { public: string frequencySort(string s) { unordered_map<char, int> m; for(char c : s) m[c]++; map<int, vector<char>, greater<int>> ma; for(auto it=m.begin(); it!=m.end(); it++) { ma[(*it).second].push_back((*it).first); } string res; for(auto it=ma.begin(); it!=ma.end(); it++) { for(char c : (*it).second) { res += string((*it).first, c); } } return res; } };
27.736842
54
0.436433
[ "vector" ]
c58965f805354037690eb69e38b29dc0e330c87f
14,164
cpp
C++
lib/MC/MCAnalysis/MCObjectSymbolizer.cpp
pwnzen-mobile/llvm_dagger_9.0
ee097dc2a0cd194002fd54e574703de5094b12f1
[ "Apache-2.0" ]
4
2019-09-17T05:21:40.000Z
2021-12-20T19:25:18.000Z
lib/MC/MCAnalysis/MCObjectSymbolizer.cpp
pwnzen-mobile/llvm_dagger_9.0
ee097dc2a0cd194002fd54e574703de5094b12f1
[ "Apache-2.0" ]
null
null
null
lib/MC/MCAnalysis/MCObjectSymbolizer.cpp
pwnzen-mobile/llvm_dagger_9.0
ee097dc2a0cd194002fd54e574703de5094b12f1
[ "Apache-2.0" ]
2
2020-05-23T04:07:53.000Z
2021-11-11T04:17:23.000Z
//===-- lib/MC/MCObjectSymbolizer.cpp -------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/MC/MCAnalysis/MCObjectSymbolizer.h" #include "llvm/ADT/SmallString.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCInst.h" #include "llvm/MC/MCDisassembler/MCRelocationInfo.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Object/MachO.h" #include "llvm/Object/SymbolSize.h" #include "llvm/Support/Debug.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> using namespace llvm; using namespace object; #define DEBUG_TYPE "mcobjectsymbolizer" //===- Helpers ------------------------------------------------------------===// static bool RelocRelocOffsetComparator(const object::RelocationRef &LHS, const object::RelocationRef &RHS) { return LHS.getOffset() < RHS.getOffset(); } static bool RelocU64OffsetComparator(const object::RelocationRef &LHS, uint64_t RHSOffset) { return LHS.getOffset() < RHSOffset; } //===- MCMachObjectSymbolizer ---------------------------------------------===// MCMachObjectSymbolizer::MCMachObjectSymbolizer( MCContext &Ctx, std::unique_ptr<MCRelocationInfo> RelInfo, const MachOObjectFile &MOOF, uint64_t VMAddrSlide) : MCObjectSymbolizer(Ctx, std::move(RelInfo), MOOF), MOOF(MOOF), StubsStart(0), StubsCount(0), StubSize(0), StubsIndSymIndex(0), VMAddrSlide(VMAddrSlide) { for (const SectionRef &Section : MOOF.sections()) { StringRef Name; Section.getName(Name); if (Name == "__stubs") { SectionRef StubsSec = Section; if (MOOF.is64Bit()) { MachO::section_64 S = MOOF.getSection64(StubsSec.getRawDataRefImpl()); StubsIndSymIndex = S.reserved1; StubSize = S.reserved2; } else { MachO::section S = MOOF.getSection(StubsSec.getRawDataRefImpl()); StubsIndSymIndex = S.reserved1; StubSize = S.reserved2; } assert(StubSize && "Mach-O stub entry size can't be zero!"); StubsStart = StubsSec.getAddress(); StubsCount = StubsSec.getSize(); StubsCount /= StubSize; } } // Also look for the init/exit func sections. for (const SectionRef &Section : MOOF.sections()) { StringRef Name; Section.getName(Name); // FIXME: We should use the S_ section type instead of the name. if (Name == "__mod_init_func") { DEBUG(dbgs() << "Found __mod_init_func section!\n"); Section.getContents(ModInitContents); } else if (Name == "__mod_exit_func") { DEBUG(dbgs() << "Found __mod_exit_func section!\n"); Section.getContents(ModExitContents); } } } // FIXME: Only do the translations for addresses actually inside the object. uint64_t MCMachObjectSymbolizer::getEffectiveLoadAddr(uint64_t Addr) { return Addr + VMAddrSlide; } uint64_t MCMachObjectSymbolizer::getOriginalLoadAddr(uint64_t EffectiveAddr) { return EffectiveAddr - VMAddrSlide; } ArrayRef<uint64_t> MCMachObjectSymbolizer::getStaticInitFunctions() { // FIXME: We only handle 64bit mach-o assert(MOOF.is64Bit()); size_t EntrySize = 8; size_t EntryCount = ModInitContents.size() / EntrySize; return makeArrayRef( reinterpret_cast<const uint64_t *>(ModInitContents.data()), EntryCount); } ArrayRef<uint64_t> MCMachObjectSymbolizer::getStaticExitFunctions() { // FIXME: We only handle 64bit mach-o assert(MOOF.is64Bit()); size_t EntrySize = 8; size_t EntryCount = ModExitContents.size() / EntrySize; return makeArrayRef( reinterpret_cast<const uint64_t *>(ModExitContents.data()), EntryCount); } StringRef MCMachObjectSymbolizer::findExternalFunctionAt(uint64_t Addr) { Addr = getOriginalLoadAddr(Addr); // FIXME: also, this can all be done at the very beginning, by iterating over // all stubs and creating the calls to outside functions. Is it worth it // though? if (!StubSize) return StringRef(); uint64_t StubIdx = (Addr - StubsStart) / StubSize; if (StubIdx >= StubsCount) return StringRef(); uint32_t SymtabIdx = MOOF.getIndirectSymbolTableEntry(MOOF.getDysymtabLoadCommand(), StubIdx); symbol_iterator SI = MOOF.getSymbolByIndex(SymtabIdx); assert(SI != MOOF.symbol_end() && "Stub wasn't found in the symbol table!"); const MachO::nlist_64 &SymNList = MOOF.getSymbol64TableEntry(SI->getRawDataRefImpl()); if ((SymNList.n_type & MachO::N_TYPE) != MachO::N_UNDF) return StringRef(); Expected<StringRef> SymNameOrErr = SI->getName(); if (auto ec = SymNameOrErr.takeError()) report_fatal_error(std::move(ec)); StringRef SymName = *SymNameOrErr; assert(SymName.front() == '_' && "Mach-O symbol doesn't start with '_'!"); return SymName.substr(1); } uint64_t MCMachObjectSymbolizer::getEntrypoint() { uint64_t EntryFileOffset = 0; // Look for LC_MAIN first. for (auto LC : MOOF.load_commands()) { if (LC.C.cmd == MachO::LC_MAIN) { EntryFileOffset = MOOF.getEntryPointCommand(LC).entryoff; break; } } // If we did find LC_MAIN, compute the virtual address, by looking for the // segment that it points into. if (EntryFileOffset) { for (auto LC : MOOF.load_commands()) { if (LC.C.cmd == MachO::LC_SEGMENT_64) { auto S64LC = MOOF.getSegment64LoadCommand(LC); if (S64LC.fileoff <= EntryFileOffset && S64LC.fileoff + S64LC.filesize > EntryFileOffset) return EntryFileOffset + S64LC.vmaddr; } if (LC.C.cmd == MachO::LC_SEGMENT) { auto SLC = MOOF.getSegmentLoadCommand(LC); if (SLC.fileoff <= EntryFileOffset && SLC.fileoff + SLC.filesize > EntryFileOffset) return EntryFileOffset + SLC.vmaddr; } } } // We tried harder, but none of our tricks worked, fall back to the common // implementation for good. return MCObjectSymbolizer::getEntrypoint(); } void MCMachObjectSymbolizer:: tryAddingPcLoadReferenceComment(raw_ostream &cStream, int64_t Value, uint64_t Address) { if (const RelocationRef *R = findRelocationAt(Address)) { const MCExpr *RelExpr = RelInfo->createExprForRelocation(*R); if (!RelExpr || RelExpr->evaluateAsAbsolute(Value) == false) return; } uint64_t Addr = Value; if (const SectionRef *S = findSectionContaining(Addr)) { uint64_t SAddr = S->getAddress(); StringRef Name; if (auto ec = S->getName(Name)) report_fatal_error(ec.message()); if (Name == "__cstring") { StringRef Contents; if (auto ec = S->getContents(Contents)) report_fatal_error(ec.message()); Contents = Contents.substr(Addr - SAddr); cStream << " ## literal pool for: \""; cStream.write_escaped(Contents.substr(0, Contents.find_first_of(0))); cStream << "\""; } } } //===- MCObjectSymbolizer -------------------------------------------------===// MCObjectSymbolizer::MCObjectSymbolizer( MCContext &Ctx, std::unique_ptr<MCRelocationInfo> RelInfo, const ObjectFile &Obj) : MCSymbolizer(Ctx, std::move(RelInfo)), Obj(Obj), SymbolSizes(computeSymbolSizes(Obj)) { buildSectionList(); } uint64_t MCObjectSymbolizer::getEntrypoint() { for (const SymbolRef &Symbol : Obj.symbols()) { Expected<StringRef> NameOrErr = Symbol.getName(); if (auto ec = NameOrErr.takeError()) report_fatal_error(std::move(ec)); StringRef Name = *NameOrErr; if (Name == "main" || Name == "_main") { Expected<uint64_t> EntrypointOrErr = Symbol.getAddress(); if (auto ec = EntrypointOrErr.takeError()) report_fatal_error(std::move(ec)); return *EntrypointOrErr; } } return 0; } uint64_t MCObjectSymbolizer::getEffectiveLoadAddr(uint64_t Addr) { return Addr; } uint64_t MCObjectSymbolizer::getOriginalLoadAddr(uint64_t Addr) { return Addr; } bool MCObjectSymbolizer:: tryAddingSymbolicOperand(MCInst &MI, raw_ostream &cStream, int64_t Value, uint64_t Address, bool IsBranch, uint64_t Offset, uint64_t InstSize) { if (IsBranch) { StringRef ExtFnName = findExternalFunctionAt((uint64_t)Value); if (!ExtFnName.empty()) { MCSymbol *Sym = Ctx.getOrCreateSymbol(ExtFnName); const MCExpr *Expr = MCSymbolRefExpr::create(Sym, Ctx); MI.addOperand(MCOperand::createExpr(Expr)); return true; } } if (const RelocationRef *R = findRelocationAt(Address + Offset)) { if (const MCExpr *RelExpr = RelInfo->createExprForRelocation(*R)) { MI.addOperand(MCOperand::createExpr(RelExpr)); return true; } // Only try to create a symbol+offset expression if there is no relocation. return false; } // Interpret Value as a branch target. if (IsBranch == false) return false; uint64_t SymbolOffset; MCSymbol *Sym = findContainingFunction(Value, SymbolOffset); if (!Sym) return false; const MCExpr *Expr = MCSymbolRefExpr::create(Sym, Ctx); if (SymbolOffset) { const MCExpr *Off = MCConstantExpr::create(SymbolOffset, Ctx); Expr = MCBinaryExpr::createAdd(Expr, Off, Ctx); } MI.addOperand(MCOperand::createExpr(Expr)); return true; } MCSymbol *MCObjectSymbolizer:: findContainingFunction(uint64_t Addr, uint64_t &Offset) { if (AddrToFunctionSymbol.empty()) buildAddrToFunctionSymbolMap(); const FunctionSymbol FS(Addr); auto SB = AddrToFunctionSymbol.begin(); auto SI = std::upper_bound(SB, AddrToFunctionSymbol.end(), FS); if (SI == AddrToFunctionSymbol.begin()) return 0; // Iterate backwards until we find the first symbol in the list that // covers Addr. This doesn't work if [SI->Addr, SI->Addr+SI->Size) // overlap, but it does work for symbols that have the same address // and zero size. --SI; const uint64_t SymAddr = SI->Addr; MCSymbol *Sym = 0; Offset = Addr - SymAddr; do { if (SymAddr == Addr || SymAddr + SI->Size > Addr) Sym = SI->Sym; } while (SI != SB && (--SI)->Addr == SymAddr); return Sym; } void MCObjectSymbolizer::buildAddrToFunctionSymbolMap() { size_t SymI = 0; for (const SymbolRef &Symbol : Obj.symbols()) { Expected<uint64_t> SymAddrOrErr = Symbol.getAddress(); if (auto ec = SymAddrOrErr.takeError()) report_fatal_error(std::move(ec)); uint64_t SymAddr = *SymAddrOrErr; uint64_t SymSize = SymbolSizes[SymI].second; assert(SymbolSizes[SymI].first == Symbol); ++SymI; Expected<StringRef> SymNameOrErr = Symbol.getName(); if (auto ec = SymNameOrErr.takeError()) report_fatal_error(std::move(ec)); StringRef SymName = *SymNameOrErr; Expected<SymbolRef::Type> SymType = Symbol.getType(); if (SymName.empty() || SymType.get() != SymbolRef::ST_Function) continue; MCSymbol *Sym = Ctx.getOrCreateSymbol(SymName); AddrToFunctionSymbol.push_back(FunctionSymbol(SymAddr, SymSize, Sym)); } std::stable_sort(AddrToFunctionSymbol.begin(), AddrToFunctionSymbol.end()); } void MCObjectSymbolizer:: tryAddingPcLoadReferenceComment(raw_ostream &cStream, int64_t Value, uint64_t Address) { } StringRef MCObjectSymbolizer::findExternalFunctionAt(uint64_t Addr) { return StringRef(); } // SortedSections implementation. const SectionRef * MCObjectSymbolizer::findSectionContaining(uint64_t Addr) const { const SectionInfo *SecInfo = findSectionInfoContaining(Addr); if (!SecInfo) return nullptr; return &SecInfo->Section; } const MCObjectSymbolizer::SectionInfo * MCObjectSymbolizer::findSectionInfoContaining(uint64_t Addr) const { return const_cast<MCObjectSymbolizer*>(this)->findSectionInfoContaining(Addr); } MCObjectSymbolizer::SectionInfo * MCObjectSymbolizer::findSectionInfoContaining(uint64_t Addr) { auto EndIt = SortedSections.end(), It = std::lower_bound(SortedSections.begin(), EndIt, Addr); if (It == EndIt) return nullptr; uint64_t SAddr = It->Section.getAddress(); uint64_t SSize = It->Section.getSize(); if (Addr >= SAddr + SSize || Addr < SAddr) return nullptr; return &*It; } const RelocationRef *MCObjectSymbolizer::findRelocationAt(uint64_t Addr) const { const SectionInfo *SecInfo = findSectionInfoContaining(Addr); if (!SecInfo) return nullptr; // FIXME: Offset vs Addr ? auto RI = std::lower_bound(SecInfo->Relocs.begin(), SecInfo->Relocs.end(), Addr, RelocU64OffsetComparator); if (RI == SecInfo->Relocs.end()) return nullptr; return &*RI; } void MCObjectSymbolizer::buildSectionList() { for (const SectionRef &Section : Obj.sections()) SortedSections.push_back(Section); std::sort(SortedSections.begin(), SortedSections.end()); uint64_t PrevSecEnd = 0; for (auto &SecInfo : SortedSections) { // First build the relocation map for this section. buildRelocationByAddrMap(SecInfo); // Also, sanity check that we don't have overlapping sections. uint64_t SAddr = SecInfo.Section.getAddress(); uint64_t SSize = SecInfo.Section.getSize(); if (PrevSecEnd > SAddr) llvm_unreachable("Inserting overlapping sections"); PrevSecEnd = std::max(PrevSecEnd, SAddr + SSize); } } void MCObjectSymbolizer::buildRelocationByAddrMap( MCObjectSymbolizer::SectionInfo &SecInfo) { for (const RelocationRef &Reloc : SecInfo.Section.relocations()) SecInfo.Relocs.push_back(Reloc); std::stable_sort(SecInfo.Relocs.begin(), SecInfo.Relocs.end(), RelocRelocOffsetComparator); } MCObjectSymbolizer * llvm::createMCObjectSymbolizer(MCContext &Ctx, const object::ObjectFile &Obj, std::unique_ptr<MCRelocationInfo> &&RelInfo) { if (const MachOObjectFile *MOOF = dyn_cast<MachOObjectFile>(&Obj)) return new MCMachObjectSymbolizer(Ctx, std::move(RelInfo), *MOOF); return new MCObjectSymbolizer(Ctx, std::move(RelInfo), Obj); }
33.327059
80
0.675657
[ "object" ]
c5909264c334d1678ce62f96c1df3478cc75771a
109,517
cpp
C++
Src/lunaui/status-bar/StatusBarServicesConnector.cpp
ericblade/luna-sysmgr
82d5d7ced4ba21d3802eb2c8ae063236b6562331
[ "Apache-2.0" ]
null
null
null
Src/lunaui/status-bar/StatusBarServicesConnector.cpp
ericblade/luna-sysmgr
82d5d7ced4ba21d3802eb2c8ae063236b6562331
[ "Apache-2.0" ]
1
2021-02-20T13:12:15.000Z
2021-02-20T13:12:15.000Z
Src/lunaui/status-bar/StatusBarServicesConnector.cpp
ericblade/luna-sysmgr
82d5d7ced4ba21d3802eb2c8ae063236b6562331
[ "Apache-2.0" ]
null
null
null
/* @@@LICENSE * * Copyright (c) 2010-2012 Hewlett-Packard Development Company, L.P. * * 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. * * LICENSE@@@ */ #include "StatusBar.h" #include "StatusBarServicesConnector.h" #include "cjson/json.h" #include "HostBase.h" #include "Localization.h" #include "Preferences.h" #include "DeviceInfo.h" #include "BtDeviceClass.h" #include "SystemService.h" #include <string.h> #include <map> #define AP_MODE_PHONE 1 #define AP_MODE_WIFI 2 #define AP_MODE_BLUETOOTH 3 static StatusBarServicesConnector* s_instance = 0; const char* StatusBarServicesConnector::m_chargeSource[StatusBarServicesConnector::kNumChargeSources] = {"usb", "inductive"}; StatusBarServicesConnector::StatusBarServicesConnector() { unsigned int codes[] = {2,3,6}; m_SIMRejectCodes = std::vector<unsigned int>(codes, codes + sizeof(codes) / sizeof(int)); // all profiles m_bluetoothProfiles.resize(7); m_bluetoothProfiles[0] = "hfg"; m_bluetoothProfiles[1] = "a2dp"; m_bluetoothProfiles[2] = "pan"; m_bluetoothProfiles[3] = "hid"; m_bluetoothProfiles[4] = "spp"; m_bluetoothProfiles[5] = "hf"; m_bluetoothProfiles[6] = "mapc"; // profiles for Device Menu m_bluetoothMenuProfiles.clear(); m_bluetoothMenuProfiles.insert("hfg"); m_bluetoothMenuProfiles.insert("a2dp"); m_bluetoothMenuProfiles.insert("hf"); m_bluetoothMenuProfiles.insert("mapc"); m_bluetoothProfileStates.clear(); m_powerdConnected = false; m_batteryLevel = 0; m_charging = false; //Flags to hold the SIM Status m_simBad = false; m_simLocked = false; m_ruim = false; m_callFwdStatusRequested = false; //Flag to hold the limited service status m_phoneInLimitedService = false; m_phoneRadioState = false; m_phoneService = NoService; m_airplaneMode = false; m_initialAirplaneModeStatus = true; m_airplaneModeTriggered = false; m_apModePhone = false; m_apModeWifi = false; m_apModeBluetooth = false; m_msmStartingRadiosInProgress = false; m_msmModePhone = false; m_msmModeWifi = false; m_msmModeBluetooth = false; m_phoneType = PHONE_TYPE_UNKNOWN; m_demoBuild = false; m_rssi = 0; sprintf(m_carrierText, "Palm"); m_showBlankStatusOnLimited = false; m_bluetoothRadionOn = false; m_btRadioTurningOn = false; m_wifiSSID.clear(); m_wifiRadioOn = false; m_wifiConnected = false; m_wifiFindNetworksReq = 0; m_bluetoothDeviceListReq = 0; m_vpnConnected = false; m_connectedVpnInfo.clear(); m_pendingVpnProfile.clear(); m_phoneEventNetworkPayload.clear(); m_hideDataIcon = false; m_isInternetConnectionAvailable = false; m_cmPayloadBuffer.clear(); init(); } StatusBarServicesConnector* StatusBarServicesConnector::instance() { if(s_instance) return s_instance; s_instance = new StatusBarServicesConnector(); return s_instance; } StatusBarServicesConnector::~StatusBarServicesConnector() { } void StatusBarServicesConnector::init() { LSError lserror; LSErrorInit(&lserror); bool ret = LSRegister(NULL, &m_service, &lserror); if (!ret) goto error; ret = LSGmainAttach(m_service, HostBase::instance()->mainLoop(), &lserror); if (!ret) goto error; // Register for powerd service coming on bus ret = LSCall(m_service, "palm://com.palm.bus/signal/registerServerStatus", "{\"serviceName\":\"com.palm.power\"}", statusBarPowerdServiceUpCallback, NULL, NULL, &lserror); if (!ret) goto error; // Register for battery status updates ret = LSCall(m_service, "palm://com.palm.bus/signal/addmatch", "{\"category\":\"/com/palm/power\",\"method\":\"batteryStatus\"}", statusBarPowerdBatteryEventsCallback, NULL, NULL, &lserror); if (!ret) goto error; // Register for charger status updates ret = LSCall(m_service, "palm://com.palm.bus/signal/addmatch", "{\"category\":\"/com/palm/power\",\"method\":\"USBDockStatus\"}", statusBarPowerdChargerEventsCallback, NULL, NULL, &lserror); if (!ret) goto error; // Register for telephony service coming on bus ret = LSCall(m_service, "palm://com.palm.lunabus/signal/registerServerStatus", "{\"serviceName\":\"com.palm.telephony\"}", statusBarTelephonyServiceUpCallback, NULL, NULL, &lserror); if (!ret) goto error; // Register for BT Monitor service coming on bus ret = LSCall(m_service, "palm://com.palm.lunabus/signal/registerServerStatus", "{\"serviceName\":\"com.palm.btmonitor\"}", statusBarBtMonitorServiceUpCallback, NULL, NULL, &lserror); if (!ret) goto error; // Register for Bluetooth service coming on bus ret = LSCall(m_service, "palm://com.palm.lunabus/signal/registerServerStatus", "{\"serviceName\":\"com.palm.bluetooth\"}", statusBarBluetoothServiceUpCallback, NULL, NULL, &lserror); if (!ret) goto error; // Register for WAN service coming on bus ret = LSCall(m_service, "palm://com.palm.lunabus/signal/registerServerStatus", "{\"serviceName\":\"com.palm.wan\"}", statusBarWanServiceUpCallback, NULL, NULL, &lserror); if (!ret) goto error; // Register for ConnectionManager service coming on bus ret = LSCall(m_service, "palm://com.palm.lunabus/signal/registerServerStatus", "{\"serviceName\":\"com.palm.connectionmanager\"}", statusBarConnMgrServiceUpCallback, NULL, NULL, &lserror); if (!ret) goto error; // Register for WiFi service coming on bus if(DeviceInfo::instance()->wifiAvailable()) { ret = LSCall(m_service, "palm://com.palm.lunabus/signal/registerServerStatus", "{\"serviceName\":\"com.palm.wifi\"}", statusBarWiFiServiceUpCallback, NULL, NULL, &lserror); if (!ret) goto error; } // Register for VPN service coming on bus ret = LSCall(m_service, "palm://com.palm.lunabus/signal/registerServerStatus", "{\"serviceName\":\"com.palm.vpn\"}", statusBarVpnServiceUpCallback, NULL, NULL, &lserror); if (!ret) goto error; // Query the build name ret = LSCall(m_service, "palm://com.palm.preferences/systemProperties/Get", "{\"key\":\"com.palm.properties.buildName\"}", statusBarGetBuildNameCallback, NULL, NULL, &lserror); if (!ret) goto error; // Query the initial battery status ret = LSCall(m_service, "palm://com.palm.power/com/palm/power/batteryStatusQuery", "{ }", statusBarPowerdBatteryEventsCallback, NULL, NULL, &lserror); if (!ret) goto error; // Query the initial charger status ret = LSCall(m_service, "palm://com.palm.power/com/palm/power/chargerStatusQuery", "{ }", statusBarPowerdChargerEventsCallback, NULL, NULL, &lserror); if (!ret) goto error; // Query the initial charger status ret = LSCall(m_service, "palm://com.palm.systemservice/time/getSystemTime", "{\"subscribe\":true}", statusBarGetSystemTimeCallback, NULL, NULL, &lserror); if (!ret) goto error; connect(Preferences::instance(),SIGNAL(signalAirplaneModeChanged(bool)), SLOT(slotAirplaneModeChanged(bool))); connect(Preferences::instance(),SIGNAL(signalRoamingIndicatorChanged()), SLOT(slotRoamingIndicatorChanged())); connect(SystemService::instance(), SIGNAL(signalEnterBrickMode(bool)), SLOT(slotEnterBrickMode(bool))); connect(SystemService::instance(), SIGNAL(signalExitBrickMode()), SLOT(slotExitBrickMode())); error: if (LSErrorIsSet(&lserror)) { LSErrorPrint(&lserror, stderr); LSErrorFree(&lserror); } } void StatusBarServicesConnector::setDemoBuild(bool demo) { m_demoBuild = true; sprintf(m_carrierText, "Palm"); Q_EMIT signalCarrierTextChanged(m_carrierText); m_rssi = 5; updateRSSIIcon(true, (StatusBar::IndexRSSI)(StatusBar::RSSI_0 + m_rssi)); } void StatusBarServicesConnector::slotAirplaneModeChanged(bool enabled) { bool prev = m_airplaneMode; m_airplaneMode = enabled; if(!m_initialAirplaneModeStatus) { // Airplane Mode was changed via the Device Menu, so turn the radios ON/OFF. setAirplaneMode(m_airplaneMode); } else { m_initialAirplaneModeStatus = false; if(m_phoneRadioState == false) { if(!prev && m_airplaneMode) { // System Prefs response came after we received the Radio Power state, so update the icon to reflect // the fact that we are in Airplane Mode (at boot time) // Note that we have a separate icon for airplane mode, so we will ask the icon to // disable itself sprintf(m_carrierText, "%s", LOCALIZED("Airplane Mode").c_str()); updateRSSIIcon(false, StatusBar::RSSI_FLIGHT_MODE); Q_EMIT signalCarrierTextChanged(m_carrierText); } } // update the system menu if(m_airplaneMode) Q_EMIT signalAirplaneModeState(AirplaneModeOn); else Q_EMIT signalAirplaneModeState(AirplaneModeOff); } } void StatusBarServicesConnector::setAirplaneMode(bool on) { m_airplaneModeTriggered = true; m_apModePhone = false; m_apModeWifi = false; m_apModeBluetooth = false; if(on) { // Turn ON airplane mode g_message("StatusBar - Enabling Airplane Mode"); Q_EMIT signalAirplaneModeState(AirplaneModeTurningOn); Preferences::instance()->saveWifiState(m_wifiRadioOn); Preferences::instance()->saveBluetoothState(m_bluetoothRadionOn); //Turn off Wifi BT and Phone if (m_bluetoothRadionOn || m_btRadioTurningOn) { g_message("StatusBar - BT is on. Turning it off"); setBluetoothOnState(false); } else { g_message("StatusBar - BT is off."); updateAirplaneModeProgress(AP_MODE_BLUETOOTH); } if(PHONE_TYPE_UNKNOWN != m_phoneType && PHONE_TYPE_NONE != m_phoneType) { g_message("StatusBar - Phone is on. Turning it off"); setTelephonyPowerState(false, true); } else { //For WiFi only devices, modem type is NONE. Update the Airplane Mode progess so that it won't be stuck waiting for the radio status. g_message("StatusBar - Phone Type is None."); updateAirplaneModeProgress(AP_MODE_PHONE); } if (m_wifiRadioOn) { g_message("StatusBar - WiFi is on. Turning it off"); setWifiOnState(false); } else { g_message("StatusBar - WiFi is off"); updateAirplaneModeProgress(AP_MODE_WIFI); } } else { // Turn OFF airplane mode g_message("StatusBar - Disabling Airplane Mode"); Q_EMIT signalAirplaneModeState(AirplaneModeTurningOff); if(PHONE_TYPE_UNKNOWN != m_phoneType && PHONE_TYPE_NONE != m_phoneType) { g_message("StatusBar UI - Turning on phone radio"); setTelephonyPowerState(true, true); } //If Radio was turned on while in Airplane Mode, update the airplane progress if(m_phoneRadioState) { updateAirplaneModeProgress(AP_MODE_PHONE); } //Turn on Wifi Bt if(Preferences::instance()->wifiState()) { // Wifi was ON before, so turn it back on g_message("StatusBar - Turning on WiFi"); setWifiOnState(true); } else { updateAirplaneModeProgress(AP_MODE_WIFI); } if(Preferences::instance()->bluetoothState()) { // Bluetooth was ON before, so turn it back on g_message("StatusBar - Turning on BT"); setBluetoothOnState(true); } else { updateAirplaneModeProgress(AP_MODE_BLUETOOTH); } } } void StatusBarServicesConnector::setRadioStatesForMSMMode(bool on) { if(on) { // Turn ON radios for MSM mode g_message("StatusBar - Leaving MSM mode, Turning radion ON"); if(m_msmStartingRadiosInProgress) return; m_msmStartingRadiosInProgress = true; if(PHONE_TYPE_UNKNOWN != m_phoneType && PHONE_TYPE_NONE != m_phoneType) { if(!m_airplaneMode) { if(m_msmModePhone) { g_message("StatusBar UI - Turning on phone radio"); setTelephonyPowerState(true, false, true); } } } if(m_msmModeBluetooth) { g_message("StatusBar - Turning on BT"); setBluetoothOnState(true); } if(m_msmModeWifi) { g_message("StatusBar - Turning on WiFi"); setWifiOnState(true); } m_msmModeBluetooth = false; m_msmModeWifi = false; m_msmModePhone = false; } else { g_message("StatusBar - Entering MSM mode, Turning radios OFF"); m_msmStartingRadiosInProgress = false; if(PHONE_TYPE_UNKNOWN != m_phoneType && PHONE_TYPE_NONE != m_phoneType) { if(!m_airplaneMode) { if(m_phoneRadioState) { m_msmModePhone = true; g_message("StatusBar - Phone is on. Turning it off"); setTelephonyPowerState(false, false, true); } else { m_msmModePhone = false; } } } if (m_bluetoothRadionOn || m_btRadioTurningOn) { m_msmModeBluetooth = true; m_bluetoothRadionOn = false; g_message("StatusBar - BT is on. Turning it off"); setBluetoothOnState(false); } else { m_msmModeBluetooth = false; } if (m_wifiRadioOn) { m_msmModeWifi = true; g_message("StatusBar - WiFi is on. Turning it off"); setWifiOnState(false); } else { m_msmModeWifi = false; } //Clear all VPN state as well. Q_EMIT signalVpnStateChanged(false); } } void StatusBarServicesConnector::updateAirplaneModeProgress(int radio) { bool done = false; if(!m_airplaneModeTriggered) return; g_message("StatusBar - Updating Airplane Mode Progress: %d", radio); if(radio == AP_MODE_PHONE) { m_apModePhone = true; } else if(radio == AP_MODE_WIFI) { m_apModeWifi = true; } else if(radio == AP_MODE_BLUETOOTH) { m_apModeBluetooth = true; } if (m_phoneType != PHONE_TYPE_NONE && m_phoneType != PHONE_TYPE_UNKNOWN) done = m_apModePhone && m_apModeWifi && m_apModeBluetooth; else done = m_apModeWifi && m_apModeBluetooth; if (done) { g_message("StatusBar - Enable / Disable Airplane Mode complete - Updating Device Menu"); m_airplaneModeTriggered = false; if(m_airplaneMode) Q_EMIT signalAirplaneModeState(AirplaneModeOn); else Q_EMIT signalAirplaneModeState(AirplaneModeOff); } } void StatusBarServicesConnector::slotRoamingIndicatorChanged() { if(Preferences::instance()->roamingIndicator() == "none") { m_showBlankStatusOnLimited = true; } } bool StatusBarServicesConnector::statusBarGetBuildNameCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; g_message("StatusBar - statusBarGetBuildNameCallback %s", LSMessageGetPayload(message)); struct json_object* root = json_tokener_parse(LSMessageGetPayload(message)); struct json_object* label = 0; label = json_object_object_get(root, "returnValue"); if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) { if(json_object_get_boolean(label)) { const char* string = 0; label = json_object_object_get(root, "com.palm.properties.buildName"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { string = json_object_get_string(label); if(string) { if(!strcasecmp(string, "nova-demo")) { s_instance->setDemoBuild(true); } } } } } if (root && !is_error(root)) json_object_put(root); return true; } bool StatusBarServicesConnector::statusBarPowerdServiceUpCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->powerdServiceUpCallback(handle, message, ctxt); } bool StatusBarServicesConnector::powerdServiceUpCallback(LSHandle* handle, LSMessage* message, void* ctxt) { g_message("StatusBar - powerdServiceUpCallback %s", LSMessageGetPayload(message)); struct json_object* connectedObj = NULL; struct json_object* json = json_tokener_parse(LSMessageGetPayload(message)); if (json && !is_error(json)) { if (!json_object_object_get_ex(json, "connected", &connectedObj)) { g_critical("Unable to connected obj"); goto exit; } bool origState = m_powerdConnected; m_powerdConnected = json_object_get_boolean(connectedObj); if(!m_powerdConnected) { Q_EMIT signalBatteryLevelUpdated(-1); } if (origState != m_powerdConnected) { Q_EMIT signalPowerdConnectionStateChanged(m_powerdConnected); } } exit: if (json && !is_error(json)) json_object_put(json); return true; } bool StatusBarServicesConnector::statusBarPowerdBatteryEventsCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->powerdBatteryEventsCallback(handle, message, ctxt); } bool StatusBarServicesConnector::powerdBatteryEventsCallback(LSHandle* handle, LSMessage* message, void* ctxt) { g_message("StatusBar - powerdBatteryEventsCallback %s", LSMessageGetPayload(message)); // Look for percent_ui struct json_object* json = json_tokener_parse(LSMessageGetPayload(message)); struct json_object* percentObj = NULL; if (json && !is_error(json)) { if (!json_object_object_get_ex(json, "percent_ui", &percentObj)) { g_critical("Unable to get percent_ui for battery state"); goto exit; } m_batteryLevel = json_object_get_int(percentObj); Q_EMIT signalBatteryLevelUpdated(m_batteryLevel); } exit: if (json && !is_error(json)) json_object_put(json); return true; } bool StatusBarServicesConnector::statusBarPowerdChargerEventsCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->powerdChargerEventsCallback(handle, message, ctxt); } bool StatusBarServicesConnector::powerdChargerEventsCallback(LSHandle* handle, LSMessage* message, void* ctxt) { g_message("StatusBar - powerdChargerEventsCallback %s", LSMessageGetPayload(message)); struct json_object* chargingObj = NULL; bool origState = m_charging; struct json_object* json = json_tokener_parse(LSMessageGetPayload(message)); if (json && !is_error(json)) { if (!json_object_object_get_ex(json, "Charging", &chargingObj)) { g_critical("Charging field is missing!"); goto exit; } // Default to not charging unless we find out otherwise m_charging = json_object_get_boolean(chargingObj); // Check if we're charging -- usb or inductive /*for (int j = 0; j < kNumChargeSources; j++) { if (strcmp(json_object_get_string(typeObj), m_chargeSource[j]) == 0) { if (json_object_object_get_ex(json, "connected", &connectedObj)) { if (json_object_get_boolean(connectedObj)) { m_charging = true; } } } }*/ if (m_charging != origState) { Q_EMIT signalChargingStateUpdated(m_charging); } } exit: if (json && !is_error(json)) json_object_put(json); return true; } bool StatusBarServicesConnector::statusBarPlatformQueryCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->platformQueryCallback(handle, message, ctxt); } bool StatusBarServicesConnector::platformQueryCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; g_message("StatusBar - platformQueryCallback %s", LSMessageGetPayload(message)); struct json_object* root = json_tokener_parse(LSMessageGetPayload(message)); struct json_object* label = 0; label = json_object_object_get(root, "returnValue"); if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) { if(json_object_get_boolean(label)) { const char* string = 0; label = json_object_object_get(root, "extended"); if (label && !is_error(label) && json_object_is_type(label, json_type_object)) { struct json_object* ext = label; label = json_object_object_get(ext, "platformType"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { const char* type = json_object_get_string(label); if(type) { if(!strcmp(type, "gsm")) { m_phoneType = PHONE_TYPE_GSM; }else if(!strcmp(type, "cdma")) { m_phoneType = PHONE_TYPE_CDMA; }else if(!strcmp(type, "none")) { m_phoneType = PHONE_TYPE_NONE; } Q_EMIT signalPhoneTypeUpdated(); } } label = json_object_object_get(ext, "capabilities"); if (label && !is_error(label) && json_object_is_type(label, json_type_object)) { label = json_object_object_get(label, "ruim"); if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) { m_ruim = json_object_get_boolean(label); } } } } } if (root && !is_error(root)) json_object_put(root); if((m_phoneType != PHONE_TYPE_UNKNOWN) && !m_signalMsgPayloadBuffer.empty()) { telephonySignalEventsCallback(NULL, m_signalMsgPayloadBuffer.c_str(), NULL); m_signalMsgPayloadBuffer.clear(); } return true; } void StatusBarServicesConnector::updateRSSIIcon(bool show, StatusBar::IndexRSSI index) { if(!Preferences::instance()->useDualRSSI()) { Q_EMIT signalRssiIndexChanged(show, index); } else { if((!show) || (index == StatusBar::RSSI_FLIGHT_MODE) || (index == StatusBar::RSSI_ERROR)) { Q_EMIT signalRssiIndexChanged(show, index); Q_EMIT signalRssi1xIndexChanged(false, StatusBar::RSSI_1X_0); } else if ((index == StatusBar::RSSI_EV_0) || (index == StatusBar::RSSI_0)) { Q_EMIT signalRssiIndexChanged(show, StatusBar::RSSI_EV_0); Q_EMIT signalRssi1xIndexChanged(show, StatusBar::RSSI_1X_0); } else { Q_EMIT signalRssiIndexChanged(show, index); } } } void StatusBarServicesConnector::updateRSSI1xIcon(bool show, StatusBar::IndexRSSI1x index) { Q_EMIT signalRssi1xIndexChanged(show, index); } bool StatusBarServicesConnector::statusBarTelephonyServiceUpCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->telephonyServiceUpCallback(handle, message, ctxt); } bool StatusBarServicesConnector::telephonyServiceUpCallback(LSHandle* handle, LSMessage* message, void* ctxt) { g_message("StatusBar - telephonyServiceUpCallback %s", LSMessageGetPayload(message)); struct json_object* json = json_tokener_parse(LSMessageGetPayload(message)); if (json && !is_error(json)) { json_object* label = json_object_object_get(json, "connected"); if (label && json_object_is_type(label, json_type_boolean)) { bool connected = json_object_get_boolean(label); if (connected) { // telephony service up. //Flag to hold the SIM Status m_simBad = false; m_simLocked = false; //Flag to hold the limited service status m_phoneInLimitedService = false; //callForwardNotificationSession = false bool result; LSError lsError; LSErrorInit(&lsError); // Get the Phone Type result = LSCall(handle, "palm://com.palm.telephony/platformQuery", "{ }", statusBarPlatformQueryCallback, NULL, NULL, &lsError); if (!result) goto error; // Get the Initial Power Radio State and subscribe to Power events result = LSCall(handle, "palm://com.palm.telephony/powerQuery", "{\"subscribe\":true}", statusBarTelephonyPowerEventsCallback, NULL, NULL, &lsError); if (!result) goto error; // Subscribe for Telephony Signal notifications result = LSCall(handle, "palm://com.palm.telephony/subscribe", "{\"events\":\"signal\"}", statusBarTelephonySignalEventsCallback, NULL, NULL, &lsError); if (!result) goto error; // Subscribe for Telephony Network notifications result = LSCall(handle, "palm://com.palm.telephony/subscribe", "{\"events\":\"network\"}", statusBarTelephonyNetworkEventsCallback, NULL, NULL, &lsError); if (!result) goto error; // Get the Initial Values for SIM Status result = LSCall(m_service, "palm://com.palm.telephony/simStatusQuery", "{\"subscribe\": true}", statusBarTelephonySIMEventsCallback, NULL, NULL, &lsError); if (!result) goto error; // Get the Initial Values for TTY Status result = LSCall(m_service, "palm://com.palm.telephony/ttyQuery", "{\"subscribe\": true}", statusBarTelephonyTTYEventsCallback, NULL, NULL, &lsError); if (!result) goto error; // Get the Initial Values for HAC Status result = LSCall(m_service, "palm://com.palm.telephony/hacQuery", "{\"subscribe\": true}", statusBarTelephonyHACEventsCallback, NULL, NULL, &lsError); if (!result) goto error; m_callFwdStatusRequested = false; error: if (LSErrorIsSet(&lsError)) { LSErrorPrint(&lsError, stderr); LSErrorFree(&lsError); } } else { // TIL disconnected handleTILDisconnected(); } } json_object_put(json); } return true; } void StatusBarServicesConnector::handleTILDisconnected() { g_warning("StatusBar - Telephony Service not available on the bus!"); // simulate a power off event handlePowerStatus("off", false); } void StatusBarServicesConnector::requestNetworkAndSignalStatus() { bool result; LSError lsError; LSErrorInit(&lsError); // Request current Network Status result = LSCall(m_service, "palm://com.palm.telephony/networkStatusQuery", "{ }", statusBarTelephonyNetworkEventsCallback, NULL, NULL, &lsError); if (!result) goto error; // Request current Signal Strength status result = LSCall(m_service, "palm://com.palm.telephony/signalStrengthQuery", "{ }", statusBarTelephonySignalEventsCallback, NULL, NULL, &lsError); if (!result) goto error; error: if (LSErrorIsSet(&lsError)) { LSErrorPrint(&lsError, stderr); LSErrorFree(&lsError); } } bool StatusBarServicesConnector::statusBarTelephonyPowerEventsCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->telephonyPowerEventsCallback(handle, message, ctxt); } bool StatusBarServicesConnector::telephonyPowerEventsCallback(LSHandle* handle, LSMessage* message, void* ctxt) { g_message("StatusBar - telephonyPowerEventsCallback %s", LSMessageGetPayload(message)); struct json_object* root = json_tokener_parse(LSMessageGetPayload(message)); struct json_object* label = 0; label = json_object_object_get(root, "eventPower"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { // Event const char* radioState = 0; radioState = json_object_get_string(label); if(radioState) { handlePowerStatus(radioState); } } else { // response to Query label = json_object_object_get(root, "returnValue"); if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) { bool result = json_object_get_boolean(label); if(result) { label = json_object_object_get(root, "extended"); if (label && !is_error(label) && json_object_is_type(label, json_type_object)) { label = json_object_object_get(label, "powerState"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { const char* radioState = 0; radioState = json_object_get_string(label); if(radioState) { handlePowerStatus(radioState, true); } } } } else { } } else { } } if (root && !is_error(root)) json_object_put(root); return true; } void StatusBarServicesConnector::handlePowerStatus(const char* radioState, bool queryResponse) { if (strcmp(radioState, "on") == 0) { if(m_phoneRadioState && !queryResponse) { g_warning("StatusBarI - Phone Notification - Duplicate eventPower? (ON)"); return; } m_phoneRadioState = true; if (m_phoneType == PHONE_TYPE_NONE) { sprintf(m_carrierText, "HP webOS"); } else if (m_phoneType == PHONE_TYPE_GSM) { sprintf(m_carrierText, "%s", LOCALIZED("Network search...").c_str()); } else { sprintf(m_carrierText, "%s", LOCALIZED("Searching...").c_str()); } Q_EMIT signalCarrierTextChanged(m_carrierText); if(queryResponse) { requestNetworkAndSignalStatus(); } updateRSSIIcon(true, StatusBar::RSSI_0); if(!m_phoneEventNetworkPayload.empty()) { telephonyNetworkEventsCallback(NULL, m_phoneEventNetworkPayload.c_str(), NULL); m_phoneEventNetworkPayload.clear(); } } else { m_phoneRadioState = false; if (m_airplaneMode) { //Airplane mode now has its own icon in the status bar, so hide //the rssi icon when we go into airplane mode sprintf(m_carrierText, "%s", LOCALIZED("Airplane Mode").c_str()); updateRSSIIcon(false, StatusBar::RSSI_FLIGHT_MODE); } else { sprintf(m_carrierText, "%s", LOCALIZED("Phone offline").c_str()); updateRSSIIcon(false, StatusBar::RSSI_0); } Q_EMIT signalCarrierTextChanged(m_carrierText); Q_EMIT signalWanIndexChanged(false, StatusBar::WAN_OFF); Q_EMIT signalCallForwardStateChanged(false); Q_EMIT signalRoamingStateChanged(false); if(m_callFwdStatusRequested) { // this.callForwardNotificationSession.cancel(); // $$$ m_callFwdStatusRequested = false; } } } bool StatusBarServicesConnector::statusBarTelephonyNetworkEventsCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; const char* payload = LSMessageGetPayload(message); return s_instance->telephonyNetworkEventsCallback(handle, payload, ctxt); } bool StatusBarServicesConnector::telephonyNetworkEventsCallback(LSHandle* handle, const char* payload, void* ctxt) { g_message("StatusBar - telephonyNetworkEventsCallback %s", payload); struct json_object* root = json_tokener_parse(payload); struct json_object* label = 0; label = json_object_object_get(root, "eventNetwork"); if (label && !is_error(label) && json_object_is_type(label, json_type_object)) { // Event if(m_phoneRadioState) { const char* string = 0; struct json_object* event = label; label = json_object_object_get(event, "state"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { string = json_object_get_string(label); if(string) { handleNetworkStatus(string, event); } } } else { // didn't receive the power on notification yet, so save the message until then m_phoneEventNetworkPayload = payload; } } else { // response to Query label = json_object_object_get(root, "returnValue"); if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) { bool result = json_object_get_boolean(label); if(result) { label = json_object_object_get(root, "extended"); if (label && !is_error(label) && json_object_is_type(label, json_type_object)) { struct json_object* event = label; label = json_object_object_get(event, "state"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { const char* state = 0; state = json_object_get_string(label); if(state) { handleNetworkStatus(state, event); } } } } } } if (root && !is_error(root)) json_object_put(root); return true; } bool StatusBarServicesConnector::validSIMRejectCode(unsigned int code) { for(unsigned int x = 0; x < m_SIMRejectCodes.size(); x++) { if(m_SIMRejectCodes[x] == code) return true; } return false; } void StatusBarServicesConnector::handleNetworkStatus(const char* networkState, struct json_object* event) { if(!m_phoneRadioState) return; //If it is wifi only device, update the status bar with default carrier text and return. if (m_phoneType == PHONE_TYPE_NONE) { sprintf(m_carrierText, "HP webOS"); Q_EMIT signalCarrierTextChanged(m_carrierText); return; } struct json_object* label = 0; const char* string = 0; const char* registration = 0; m_phoneInLimitedService = false; label = json_object_object_get(event, "registration"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { registration = json_object_get_string(label); } if(strcmp(networkState, "service") == 0) { m_phoneService = Service; if(m_demoBuild) { sprintf(m_carrierText, "Palm"); } else { label = json_object_object_get(event, "networkName"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { string = json_object_get_string(label); if(string) { sprintf(m_carrierText, "%s",string); } } if(registration) { if(!strcmp(registration, "home")) { Q_EMIT signalRoamingStateChanged(false); } else if(!strcmp(registration, "roaming") || !strcmp(registration, "roamblink")){ Q_EMIT signalRoamingStateChanged(true); } } } m_simLocked = false; if(!m_callFwdStatusRequested && m_phoneType == PHONE_TYPE_GSM) requestCallForwardStatus(); } else if(strcmp(networkState, "noservice") == 0) { m_phoneService = NoService; if (m_simLocked) { sprintf(m_carrierText, "%s", LOCALIZED("SIM lock").c_str()); } else if(registration) { if(!strcmp(registration, "searching")) { // SEARCHING m_phoneService = Searching; if (m_phoneType == PHONE_TYPE_GSM) { sprintf(m_carrierText, "%s", LOCALIZED("Network search...").c_str()); } else { sprintf(m_carrierText, "%s", LOCALIZED("Searching...").c_str()); } } else { if (m_simBad && (m_phoneType == PHONE_TYPE_GSM || m_ruim)) { sprintf(m_carrierText, "%s", LOCALIZED("Check SIM").c_str()); } else { sprintf(m_carrierText, "%s", LOCALIZED("No service").c_str()); } } } Q_EMIT signalRoamingStateChanged(false); Q_EMIT signalCallForwardStateChanged(false); if(m_callFwdStatusRequested) { //this.callForwardNotificationSession.cancel(); // $$$ m_callFwdStatusRequested = false; } } else if(strcmp(networkState, "limited") == 0) { m_phoneService = Limited; if (m_simBad) { sprintf(m_carrierText, "%s", LOCALIZED("Check SIM-SOS only").c_str()); } else if(m_simLocked) { sprintf(m_carrierText, "%s", LOCALIZED("SIM lock-SOS only").c_str()); } else { sprintf(m_carrierText, "%s", LOCALIZED("SOS Only").c_str()); } if (registration && !strcmp(registration, "denied")) { label = json_object_object_get(event, "causeCode"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { string = json_object_get_string(label); if(string) { int cause = atoi(string); if(m_showBlankStatusOnLimited && cause == 0) { sprintf(m_carrierText, " "); } } } } Q_EMIT signalRoamingStateChanged(false); m_phoneInLimitedService = true; updateRSSIIcon(true, StatusBar::RSSI_0); } else { sprintf(m_carrierText, "%s", LOCALIZED("No service").c_str()); Q_EMIT signalRoamingStateChanged(false); } Q_EMIT signalCarrierTextChanged(m_carrierText); } bool StatusBarServicesConnector::statusBarTelephonySignalEventsCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; const char* payload = LSMessageGetPayload(message); return s_instance->telephonySignalEventsCallback(handle, payload, ctxt); } bool StatusBarServicesConnector::telephonySignalEventsCallback(LSHandle* handle, const char* messagePayload, void* ctxt) { struct json_object* root = json_tokener_parse(messagePayload); struct json_object* label = 0; struct json_object* signalValues = 0; g_message("StatusBar - telephonySignalEventsCallback %s", messagePayload); label = json_object_object_get(root, "eventSignal"); if (label && !is_error(label) && json_object_is_type(label, json_type_object)) { // Event if(m_phoneRadioState) { const char* string = 0; //struct json_object* event = label; if(m_phoneType == PHONE_TYPE_UNKNOWN) { updateRSSIIcon(true, StatusBar::RSSI_0); if(handle != NULL || ctxt != NULL) // to avoid re-buffering the same data m_signalMsgPayloadBuffer = messagePayload; // Request the phone type bool result; LSError lsError; LSErrorInit(&lsError); result = LSCall(handle, "palm://com.palm.telephony/platformQuery", "{ }", statusBarPlatformQueryCallback, NULL, NULL, &lsError); if (LSErrorIsSet(&lsError)) { LSErrorPrint(&lsError, stderr); LSErrorFree(&lsError); } } else if(m_phoneInLimitedService) { updateRSSIIcon(true, StatusBar::RSSI_0); } else if(m_demoBuild) { m_rssi = 5; updateRSSIIcon(true, (StatusBar::IndexRSSI)(StatusBar::RSSI_0 + m_rssi)); } else if(m_phoneType == PHONE_TYPE_GSM) { label = json_object_object_get(label, "bars"); if (label && !is_error(label) && json_object_is_type(label, json_type_int)) { m_rssi = json_object_get_int(label); if(m_rssi < 0) m_rssi = 0; updateRSSIIcon(true, (StatusBar::IndexRSSI)(StatusBar::RSSI_0 + m_rssi)); } } else if(m_phoneType == PHONE_TYPE_CDMA){ signalValues = label; label = json_object_object_get(signalValues, "value"); if (label && !is_error(label) && json_object_is_type(label, json_type_int)) { m_rssi = json_object_get_int(label); if(!Preferences::instance()->useDualRSSI()) { if (m_rssi >= 0) { if(m_rssi > 5) m_rssi = 5; // display at most 5 bars updateRSSIIcon(true, (StatusBar::IndexRSSI)(StatusBar::RSSI_0 + m_rssi)); } else { updateRSSIIcon(true, StatusBar::RSSI_ERROR); } } else { int rssiev = 0; int rssi1x = 0; label = json_object_object_get(signalValues, "value1x"); if (label && !is_error(label) && json_object_is_type(label, json_type_int)) { rssi1x = json_object_get_int(label); if(rssi1x < 0) rssi1x = 0; if(rssi1x > 5) rssi1x = 5; } label = json_object_object_get(signalValues, "valueEvdo"); if (label && !is_error(label) && json_object_is_type(label, json_type_int)) { rssiev = json_object_get_int(label); if(rssiev < 0) rssiev = 0; if(rssiev > 5) rssiev = 5; } updateRSSIIcon(true, (StatusBar::IndexRSSI)(StatusBar::RSSI_EV_0 + rssiev)); updateRSSI1xIcon(true, (StatusBar::IndexRSSI1x)(StatusBar::RSSI_1X_0 + rssiev)); } } } } } else { // response to Query label = json_object_object_get(root, "returnValue"); if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) { bool result = json_object_get_boolean(label); if(result) { if(m_phoneInLimitedService) { updateRSSIIcon(true, StatusBar::RSSI_0); } else if(m_demoBuild) { m_rssi = 5; updateRSSIIcon(true, (StatusBar::IndexRSSI)(StatusBar::RSSI_0 + m_rssi)); } else if(m_phoneType == PHONE_TYPE_GSM) { label = json_object_object_get(root, "bars"); if (label && !is_error(label) && json_object_is_type(label, json_type_int)) { m_rssi = json_object_get_int(label); if(m_rssi < 0) m_rssi = 0; updateRSSIIcon(true, (StatusBar::IndexRSSI)(StatusBar::RSSI_0 + m_rssi)); } } else if(m_phoneType == PHONE_TYPE_CDMA){ label = json_object_object_get(root, "extended"); if (label && !is_error(label) && json_object_is_type(label, json_type_object)) { signalValues = label; label = json_object_object_get(signalValues, "value"); if (label && !is_error(label) && json_object_is_type(label, json_type_int)) { m_rssi = json_object_get_int(label); if(!Preferences::instance()->useDualRSSI()) { if (m_rssi >= 0) { if(m_rssi > 5) m_rssi = 5; // display at most 5 bars updateRSSIIcon(true, (StatusBar::IndexRSSI)(StatusBar::RSSI_0 + m_rssi)); } else { updateRSSIIcon(true, StatusBar::RSSI_ERROR); } } else { int rssiev = 0; int rssi1x = 0; label = json_object_object_get(signalValues, "value1x"); if (label && !is_error(label) && json_object_is_type(label, json_type_int)) { rssi1x = json_object_get_int(label); if(rssi1x < 0) rssi1x = 0; if(rssi1x > 5) rssi1x = 5; } label = json_object_object_get(signalValues, "valueEvdo"); if (label && !is_error(label) && json_object_is_type(label, json_type_int)) { rssiev = json_object_get_int(label); if(rssiev < 0) rssiev = 0; if(rssiev > 5) rssiev = 5; } updateRSSIIcon(true, (StatusBar::IndexRSSI)(StatusBar::RSSI_EV_0 + rssiev)); updateRSSI1xIcon(true, (StatusBar::IndexRSSI1x)(StatusBar::RSSI_1X_0 + rssiev)); } } } } } } } if (root && !is_error(root)) json_object_put(root); return true; } bool StatusBarServicesConnector::statusBarTelephonySIMEventsCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->telephonySIMEventsCallback(handle, message, ctxt); } bool StatusBarServicesConnector::telephonySIMEventsCallback(LSHandle* handle, LSMessage* message, void* ctxt) { struct json_object* root = json_tokener_parse(LSMessageGetPayload(message)); struct json_object* label = 0; g_message("StatusBar - handleNetworkStatusQueryNotification %s", LSMessageGetPayload(message)); if(m_phoneRadioState) { label = json_object_object_get(root, "extended"); if (label && !is_error(label) && json_object_is_type(label, json_type_object)) { label = json_object_object_get(label, "state"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { char* state = json_object_get_string(label); if (state) { if (!strcmp(state, "simnotfound") || !strcmp(state, "siminvalid")) { m_simBad = true; if (m_phoneService == NoService) { sprintf(m_carrierText, "%s", LOCALIZED("Check SIM").c_str()); } else if (m_phoneService == Limited) { sprintf(m_carrierText, "%s", LOCALIZED("Check SIM-SOS only").c_str()); } } else if (!strcmp(state, "simready")) { if(m_phoneService == Limited) { sprintf(m_carrierText, "%s", LOCALIZED("SOS Only").c_str()); } else if(m_phoneService == NoService) { sprintf(m_carrierText, "%s", LOCALIZED("No service").c_str()); } else if(m_phoneService == Searching) { if (m_phoneType == PHONE_TYPE_GSM) { sprintf(m_carrierText, "%s", LOCALIZED("Network search...").c_str()); } else { sprintf(m_carrierText, "%s", LOCALIZED("Searching...").c_str()); } } m_simBad = false; m_simLocked = false; } else if (!strcmp(state, "pinrequired") || !strcmp(state, "pukrequired") || !strcmp(state, "pinpermblocked")) { m_simLocked = true; if (m_phoneInLimitedService) { sprintf(m_carrierText, "%s", LOCALIZED("Check SIM-SOS only").c_str()); } else { sprintf(m_carrierText, "%s", LOCALIZED("SIM lock").c_str()); } } Q_EMIT signalCarrierTextChanged(m_carrierText); } } } } if (root && !is_error(root)) json_object_put(root); return true; } void StatusBarServicesConnector::setTelephonyPowerState(bool on, bool saveState, bool msmMode) { bool result; LSError lsError; LSErrorInit(&lsError); char params[64]; char power[10]; char save[10]; sprintf(power, on ? "\"on\"" : (!msmMode ? "\"off\"" : "\"default\"")); sprintf(save, saveState ? "true" : "false"); sprintf(params, "{\"state\":%s,\"save\":%s}", power, save); result = LSCall(m_service, "palm://com.palm.telephony/powerSet", params, statusBarTelephonyPowerStateChangeCallback, NULL, NULL, &lsError); if (LSErrorIsSet(&lsError)) { LSErrorPrint(&lsError, stderr); LSErrorFree(&lsError); } } bool StatusBarServicesConnector::statusBarTelephonyPowerStateChangeCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->telephonyPowerStateChangeCallback(handle, message, ctxt); } bool StatusBarServicesConnector::telephonyPowerStateChangeCallback(LSHandle* handle, LSMessage* message, void* ctxt) { struct json_object* root = json_tokener_parse(LSMessageGetPayload(message)); struct json_object* label = 0; g_message("StatusBar - telephonyPowerStateChangeCallback %s", LSMessageGetPayload(message)); updateAirplaneModeProgress(AP_MODE_PHONE); label = json_object_object_get(root, "returnValue"); if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) { bool success = json_object_get_boolean(label); if(!success) g_warning("StatusBar - Error Phone Radio : %s", LSMessageGetPayload(message)); } if (root && !is_error(root)) json_object_put(root); return true; } bool StatusBarServicesConnector::statusBarTelephonyTTYEventsCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->telephonyTTYEventsCallback(handle, message, ctxt); } bool StatusBarServicesConnector::telephonyTTYEventsCallback(LSHandle* handle, LSMessage* message, void* ctxt) { struct json_object* root = json_tokener_parse(LSMessageGetPayload(message)); struct json_object* label = 0; g_message("StatusBar - telephonyTTYEventsCallback %s", LSMessageGetPayload(message)); label = json_object_object_get(root, "returnValue"); if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) { bool success = json_object_get_boolean(label); if(!success) goto Done; } label = json_object_object_get(root, "extended"); if (label && !is_error(label) && json_object_is_type(label, json_type_object)) { label = json_object_object_get(label, "mode"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { char* mode = json_object_get_string(label); if (mode) { if (!strcmp(mode, "full")) { Q_EMIT signalTTYStateChanged(true); } else { Q_EMIT signalTTYStateChanged(false); } } } } Done: if (root && !is_error(root)) json_object_put(root); return true; } bool StatusBarServicesConnector::statusBarTelephonyHACEventsCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->telephonyHACEventsCallback(handle, message, ctxt); } bool StatusBarServicesConnector::telephonyHACEventsCallback(LSHandle* handle, LSMessage* message, void* ctxt) { struct json_object* root = json_tokener_parse(LSMessageGetPayload(message)); struct json_object* label = 0; g_message("StatusBar - telephonyHACEventsCallback %s", LSMessageGetPayload(message)); label = json_object_object_get(root, "returnValue"); if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) { bool success = json_object_get_boolean(label); if(!success) goto Done; } label = json_object_object_get(root, "extended"); if (label && !is_error(label) && json_object_is_type(label, json_type_object)) { label = json_object_object_get(label, "enabled"); if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) { if (json_object_get_boolean(label)) { Q_EMIT signalHACStateChanged(true); } else { Q_EMIT signalHACStateChanged(false); } } else { Q_EMIT signalHACStateChanged(false); } } Done: if (root && !is_error(root)) json_object_put(root); return true; } bool StatusBarServicesConnector::statusBarWanServiceUpCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->wanServiceUpCallback(handle, message, ctxt); } bool StatusBarServicesConnector::wanServiceUpCallback(LSHandle* handle, LSMessage* message, void* ctxt) { g_message("StatusBar - wanServiceUpCallback %s", LSMessageGetPayload(message)); struct json_object* json = json_tokener_parse(LSMessageGetPayload(message)); if (json && !is_error(json)) { json_object* label = json_object_object_get(json, "connected"); if (label && json_object_is_type(label, json_type_boolean)) { bool connected = json_object_get_boolean(label); if (connected) { // WAN service up. bool result; LSError lsError; LSErrorInit(&lsError); //Subscribe to wan status Notifications. result = LSCall(handle, "palm://com.palm.wan/getstatus", "{\"subscribe\":true}", statusBarWanStatusEventsCallback, NULL, NULL, &lsError); if (!result) goto error; error: if (LSErrorIsSet(&lsError)) { LSErrorPrint(&lsError, stderr); LSErrorFree(&lsError); } } else { // WAN disconnected Q_EMIT signalWanIndexChanged(false, StatusBar::WAN_OFF); m_cmPayloadBuffer.clear(); } } json_object_put(json); } return true; } bool StatusBarServicesConnector::statusBarWanStatusEventsCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; const char* payload = LSMessageGetPayload(message); return s_instance->wanStatusEventsCallback(handle, payload, ctxt); } bool StatusBarServicesConnector::wanStatusEventsCallback(LSHandle* handle, const char* messagePayload, void* ctxt) { struct json_object* root = json_tokener_parse(messagePayload); struct json_object* label = 0; json_object* array = 0; const char *string = 0; g_message("StatusBar - wanStatusEventsCallback %s", messagePayload); label = json_object_object_get(root, "returnValue"); if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) { bool success = json_object_get_boolean(label); if(!success) goto Done; } label = json_object_object_get(root, "networkstatus"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { string = json_object_get_string(label); if(!strcmp(string, "attached")){ const char *networkType = 0; label = json_object_object_get(root, "networktype"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { networkType = json_object_get_string(label); } array = json_object_object_get(root, "connectedservices"); if (array && !is_error(array) && json_object_is_type(array, json_type_array) && (json_object_array_length(array) > 0)) { for (int i=0; i<json_object_array_length(array); i++) { label = json_object_array_get_idx(array, i); if (label && !is_error(label) && json_object_is_type(label, json_type_object)) { const char *connectstatus = 0; json_object* serviceArray = 0; label = json_object_object_get(label, "connectstatus"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { connectstatus = json_object_get_string(label); } label = json_object_array_get_idx(array, i); serviceArray = json_object_object_get(label, "service"); if (serviceArray && !is_error(serviceArray) && json_object_is_type(serviceArray, json_type_array) && (json_object_array_length(serviceArray) > 0)) { int internetIndex = -1; for (int s=0; s<json_object_array_length(serviceArray); s++) { string = json_object_get_string(json_object_array_get_idx(serviceArray, s)); if (string && !strcmp(string, "internet")) { internetIndex = s; break; } } if(internetIndex != -1) { if(handle != NULL || ctxt != NULL) // to avoid re-buffering the same data m_cmPayloadBuffer = messagePayload; if(m_wifiConnected && m_hideDataIcon) goto Done; const char *dataaccess = 0; label = json_object_object_get(root, "dataaccess"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { dataaccess = json_object_get_string(label); } if(!strcmp(connectstatus, "active") && !strcmp(dataaccess, "usable")) { Q_EMIT signalWanIndexChanged(true, getWanIndex(true, networkType)); } else if(!strcmp(connectstatus, "dormant") && !strcmp(dataaccess, "usable")) { Q_EMIT signalWanIndexChanged(true, getWanIndex(false, networkType)); } else { Q_EMIT signalWanIndexChanged(false, StatusBar::WAN_OFF); } break; } } } } } else { Q_EMIT signalWanIndexChanged(false, StatusBar::WAN_OFF); m_cmPayloadBuffer.clear(); } } else { Q_EMIT signalWanIndexChanged(false, StatusBar::WAN_OFF); m_cmPayloadBuffer.clear(); } } Done: if (root && !is_error(root)) json_object_put(root); return true; } StatusBar::IndexWAN StatusBarServicesConnector::getWanIndex(bool connected, const char* type) { StatusBar::IndexWAN index = StatusBar::WAN_OFF; if(connected) { if(!strcmp(type, "1x")) { index = StatusBar::WAN_CONNECTED_1X; } else if(!strcmp(type, "edge")) { index = StatusBar::WAN_CONNECTED_EDGE; } else if(!strcmp(type, "evdo")) { if(!Preferences::instance()->show3GForEvdo()) index =StatusBar:: WAN_CONNECTED_EVDO; else index = StatusBar::WAN_CONNECTED_EVDO3G; } else if(!strcmp(type, "gprs")) { index = StatusBar::WAN_CONNECTED_GPRS; } else if(!strcmp(type, "umts")) { index = StatusBar::WAN_CONNECTED_UMTS; } else if(!strcmp(type, "hsdpa")) { index = StatusBar::WAN_CONNECTED_HSDPA; } else if(!strcmp(type, "hspa-4g")) { index = StatusBar::WAN_CONNECTED_HSPA_4G; } } else { // DORMANT if(!strcmp(type, "1x")) { index = StatusBar::WAN_DORMANT_1X; } else if(!strcmp(type, "evdo")) { if(!Preferences::instance()->show3GForEvdo()) index = StatusBar::WAN_DORMANT_EVDO; else index = StatusBar::WAN_DORMANT_EVDO3G; } } return index; } bool StatusBarServicesConnector::statusBarBtMonitorServiceUpCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->btMonitorServiceUpCallback(handle, message, ctxt); } bool StatusBarServicesConnector::btMonitorServiceUpCallback(LSHandle* handle, LSMessage* message, void* ctxt) { g_message("StatusBar - btMonitorServiceUpCallback %s", LSMessageGetPayload(message)); struct json_object* json = json_tokener_parse(LSMessageGetPayload(message)); if (json && !is_error(json)) { json_object* label = json_object_object_get(json, "connected"); if (label && json_object_is_type(label, json_type_boolean)) { bool connected = json_object_get_boolean(label); if (connected) { // BT Monitor service up. bool result; LSError lsError; LSErrorInit(&lsError); m_btRadioTurningOn = false; m_bluetoothRadionOn = false; updateAirplaneModeProgress(AP_MODE_BLUETOOTH); //Subscribe to BT Monitor Notifications. result = LSCall(handle, "palm://com.palm.btmonitor/monitor/subscribenotifications", "{\"subscribe\":true}", statusBarBtMonitorEventsCallback, NULL, NULL, &lsError); if (!result) goto error; error: if (LSErrorIsSet(&lsError)) { LSErrorPrint(&lsError, stderr); LSErrorFree(&lsError); } } else { // BT Monitor disconnected // Simulate Radio off. Remove the Bluetooth icon from the status bar m_bluetoothRadionOn = false; Q_EMIT signalBluetoothIndexChanged(m_bluetoothRadionOn, StatusBar::BLUETOOTH_OFF); Q_EMIT signalBluetoothPowerStateChanged(RADIO_OFF); // All profiles must be disconnected m_bluetoothProfileStates.clear(); } } json_object_put(json); } return true; } bool StatusBarServicesConnector::statusBarBtMonitorEventsCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->btMonitorEventsCallback(handle, message, ctxt); } bool StatusBarServicesConnector::btMonitorEventsCallback(LSHandle* handle, LSMessage* message, void* ctxt) { struct json_object* root = json_tokener_parse(LSMessageGetPayload(message)); struct json_object* label = 0; const char *string = 0; bool updateBtIcon = false; g_message("StatusBar - btMonitorEventsCallback %s", LSMessageGetPayload(message)); label = json_object_object_get(root, "radio"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { const char *radio = json_object_get_string(label); if(radio) { if(!strcmp(radio, "on")) { // For now, show that the radio is on and assume nothing is connected m_bluetoothRadionOn = true; m_btRadioTurningOn = false; Q_EMIT signalBluetoothIndexChanged(m_bluetoothRadionOn, StatusBar::BLUETOOTH_ON); Q_EMIT signalBluetoothPowerStateChanged(RADIO_ON); // Determine if any profiles are connected requestBluetoothConnectedProfilesInfo(); } else if(!strcmp(radio, "turningon")) { m_btRadioTurningOn = true; Q_EMIT signalBluetoothPowerStateChanged(RADIO_TURNING_ON); } else if(!strcmp(radio, "turningoff") || !strcmp(radio, "off")) { m_bluetoothRadionOn = false; m_btRadioTurningOn = false; Q_EMIT signalBluetoothIndexChanged(m_bluetoothRadionOn, StatusBar::BLUETOOTH_OFF); Q_EMIT signalBluetoothPowerStateChanged(RADIO_OFF); // All profiles must be disconnected m_bluetoothProfileStates.clear(); } } } label = json_object_object_get(root, "notification"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { const char *notif = json_object_get_string(label); if(notif) { if(!strcmp(notif, "notifnradioturningon")) { m_btRadioTurningOn = true; Q_EMIT signalBluetoothPowerStateChanged(RADIO_TURNING_ON); } else if(!strcmp(notif, "notifnradioon")) { // Radio is on, but notification can be sent even when connections are present m_bluetoothRadionOn = true; m_btRadioTurningOn = false; Q_EMIT signalBluetoothIndexChanged(m_bluetoothRadionOn, StatusBar::BLUETOOTH_ON); Q_EMIT signalBluetoothPowerStateChanged(RADIO_ON); updateAirplaneModeProgress(AP_MODE_BLUETOOTH); updateBluetoothIcon(); } else if(!strcmp(notif, "notifnradiooff")) { // Radio is off. Remove the Bluetooth icon from the status bar m_bluetoothRadionOn = false; Q_EMIT signalBluetoothIndexChanged(m_bluetoothRadionOn, StatusBar::BLUETOOTH_OFF); Q_EMIT signalBluetoothPowerStateChanged(RADIO_OFF); updateAirplaneModeProgress(AP_MODE_BLUETOOTH); // All profiles must be disconnected m_bluetoothProfileStates.clear(); } } } if (root && !is_error(root)) json_object_put(root); return true; } void StatusBarServicesConnector::requestBluetoothConnectedProfilesInfo() { bool result; LSError lsError; LSErrorInit(&lsError); result = LSCall(m_service, "palm://com.palm.bluetooth/prof/profgetstate", "{\"profile\":\"all\"}", statusBarBtConnectedProfilesInfoCallback, NULL, NULL, &lsError); if (LSErrorIsSet(&lsError)) { LSErrorPrint(&lsError, stderr); LSErrorFree(&lsError); } } bool StatusBarServicesConnector::statusBarBtConnectedProfilesInfoCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->btConnectedProfilesInfoCallback(handle, message, ctxt); } bool StatusBarServicesConnector::btConnectedProfilesInfoCallback(LSHandle* handle, LSMessage* message, void* ctxt) { struct json_object* root = json_tokener_parse(LSMessageGetPayload(message)); struct json_object* profArray = 0; struct json_object* prof = 0; struct json_object* label = 0; const char* state; const char* address; const char* name; bool connected = false; g_message("StatusBar - btConnectedProfilesInfoCallback %s", LSMessageGetPayload(message)); m_bluetoothProfileStates.clear(); for(unsigned int i = 0; i < m_bluetoothProfiles.size(); i++) { state = 0; address = 0; name = 0; profArray = json_object_object_get(root, m_bluetoothProfiles[i].c_str()); if (profArray && !is_error(profArray) && json_object_is_type(profArray, json_type_array)) { for(int x = 0; x < json_object_array_length(profArray); x++) { prof = json_object_array_get_idx(profArray, x); if (prof && !is_error(prof) && json_object_is_type(prof, json_type_object)) { label = json_object_object_get(prof, "state"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { state = json_object_get_string(label); } label = json_object_object_get(prof, "address"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { address = json_object_get_string(label); } label = json_object_object_get(prof, "name"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { name = json_object_get_string(label); } if(state) { if(!strcmp(state, "connected") && address) { connected = true; m_bluetoothProfileStates[m_bluetoothProfiles[i] + std::string(address)].status = BT_CONNECTED; m_bluetoothProfileStates[m_bluetoothProfiles[i] + std::string(address)].address = std::string(address); m_bluetoothProfileStates[m_bluetoothProfiles[i] + std::string(address)].name = name ? std::string(name) : ""; if (m_bluetoothMenuProfiles.find(m_bluetoothProfiles[i]) != m_bluetoothMenuProfiles.end()) { Q_EMIT signalBluetoothConnStateChanged(true, name ? name : ""); } } } } } } } if(connected) { Q_EMIT signalBluetoothIndexChanged(true, StatusBar::BLUETOOTH_CONNECTED); } if (root && !is_error(root)) json_object_put(root); return true; } void StatusBarServicesConnector::requestCallForwardStatus() { bool result; LSError lsError; LSErrorInit(&lsError); result = LSCall(m_service, "palm://com.palm.telephony/forwardQuery", "{\"condition\": \"unconditional\", \"bearer\": \"defaultbearer\", \"subscribe\":true, \"network\":false}", statusBarCallForwardRequestCallback, NULL, NULL, &lsError); m_callFwdStatusRequested = true; if (LSErrorIsSet(&lsError)) { LSErrorPrint(&lsError, stderr); LSErrorFree(&lsError); } } bool StatusBarServicesConnector::statusBarCallForwardRequestCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->callForwardRequestCallback(handle, message, ctxt); } bool StatusBarServicesConnector::callForwardRequestCallback(LSHandle* handle, LSMessage* message, void* ctxt) { struct json_object* root = json_tokener_parse(LSMessageGetPayload(message)); struct json_object* label = 0; struct json_object* ext = 0; bool callFwdActive = false; bool found = false; g_message("StatusBar - callForwardRequestCallback %s", LSMessageGetPayload(message)); //For CDMA, do not show the Call Forwarding Icon. if(m_phoneType == PHONE_TYPE_CDMA) return true; label = json_object_object_get(root, "returnValue"); if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) { bool success = json_object_get_boolean(label); if(success) { ext = json_object_object_get(root, "extended"); if (ext && !is_error(ext) && json_object_is_type(ext, json_type_object)) { const char* condition = 0; label = json_object_object_get(ext, "condition"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { condition = json_object_get_string(label); } if(condition && (!strcmp(condition, "unconditional") || !strcmp(condition, "allforwarding"))) { // only update icon for unconditional and all forwarding; // others aren't interesting struct json_object* statusArray = 0; struct json_object* status = 0; const char* bearer = 0; bool activated = false; statusArray = json_object_object_get(ext, "status"); if (statusArray && !is_error(statusArray) && json_object_is_type(statusArray, json_type_array)) { for(int i = 0; i < json_object_array_length(statusArray); i++) { status = json_object_array_get_idx(statusArray, i); if (status && !is_error(status) && json_object_is_type(status, json_type_object)) { label = json_object_object_get(status, "bearer"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { bearer = json_object_get_string(label); } label = json_object_object_get(status, "activated"); if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) { activated = json_object_get_boolean(label); if(bearer && (!strcmp(bearer, "voice") || !strcmp(bearer, "default") || !strcmp(bearer, "defaultbearer"))) { // we only care about voice/default bearers if(activated) callFwdActive = true; found = true; } } } if(found) break; } } } } } } if(found) Q_EMIT signalCallForwardStateChanged(callFwdActive); if (root && !is_error(root)) json_object_put(root); return true; } bool StatusBarServicesConnector::statusBarBluetoothServiceUpCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->bluetoothServiceUpCallback(handle, message, ctxt); } bool StatusBarServicesConnector::bluetoothServiceUpCallback(LSHandle* handle, LSMessage* message, void* ctxt) { g_message("StatusBar - bluetoothServiceUpCallback %s", LSMessageGetPayload(message)); struct json_object* json = json_tokener_parse(LSMessageGetPayload(message)); if (json && !is_error(json)) { json_object* label = json_object_object_get(json, "connected"); if (label && json_object_is_type(label, json_type_boolean)) { bool connected = json_object_get_boolean(label); if (connected) { // Bluetooth service up. bool result; LSError lsError; LSErrorInit(&lsError); //Subscribe to Bluetooth Profile Notifications. result = LSCall(handle, "palm://com.palm.bluetooth/prof/subscribenotifications", "{\"subscribe\":true}", statusBarBluetoothEventsCallback, NULL, NULL, &lsError); if (!result) goto error; //Subscribe to Bluetooth Gap Notifications. result = LSCall(handle, "palm://com.palm.bluetooth/gap/subscribenotifications", "{\"subscribe\":true}", statusBarBluetoothEventsCallback, NULL, NULL, &lsError); error: if (LSErrorIsSet(&lsError)) { LSErrorPrint(&lsError, stderr); LSErrorFree(&lsError); } } else { // Bluetooth disconnected // Simulate Power Off. Remove the Bluetooth icon from the status bar m_bluetoothRadionOn = false; Q_EMIT signalBluetoothIndexChanged(m_bluetoothRadionOn, StatusBar::BLUETOOTH_OFF); Q_EMIT signalBluetoothPowerStateChanged(RADIO_OFF); // All profiles must be disconnected m_bluetoothProfileStates.clear(); } } json_object_put(json); } return true; } bool StatusBarServicesConnector::statusBarBluetoothEventsCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->bluetoothEventsCallback(handle, message, ctxt); } bool StatusBarServicesConnector::bluetoothEventsCallback(LSHandle* handle, LSMessage* message, void* ctxt) { struct json_object* root = json_tokener_parse(LSMessageGetPayload(message)); struct json_object* label = 0; const char *string = 0; int error = 0; bool updateIcon = false; g_message("StatusBar - bluetoothEventsCallback %s", LSMessageGetPayload(message)); label = json_object_object_get(root, "returnValue"); if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) { bool success = json_object_get_boolean(label); if(!success) { // Simulate Power Off. Remove the Bluetooth icon from the status bar m_bluetoothRadionOn = false; Q_EMIT signalBluetoothIndexChanged(m_bluetoothRadionOn, StatusBar::BLUETOOTH_OFF); Q_EMIT signalBluetoothPowerStateChanged(RADIO_OFF); // All profiles must be disconnected m_bluetoothProfileStates.clear(); goto Done; } } m_btRadioTurningOn = false; label = json_object_object_get(root, "notification"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { const char *notification = 0; const char *profile = 0; const char *address = 0; const char *name = 0; int profIndex = -1; std::string profKey; notification = json_object_get_string(label); label = json_object_object_get(root, "profile"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { profile = json_object_get_string(label); if(profile) { for(unsigned int i = 0; i < m_bluetoothProfiles.size(); i++) { if(!strcmp(profile, m_bluetoothProfiles[i].c_str())) { profIndex = i; break; } } } } label = json_object_object_get(root, "address"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { address = json_object_get_string(label); } label = json_object_object_get(root, "name"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { name = json_object_get_string(label); } if(address && (profIndex != -1)) { profKey = m_bluetoothProfiles[profIndex] + address; } label = json_object_object_get(root, "error"); if (label && !is_error(label) && json_object_is_type(label, json_type_int)) { error = json_object_get_int(label); } if(notification) { if(!strcmp(notification, "notifndevremoved")) { // Device Removed } else if(!strcmp(notification, "notifnconnecting")) { if((profIndex != -1) && (address != 0)) { Q_EMIT signalBluetoothIndexChanged(true, StatusBar::BLUETOOTH_CONNECTING); m_bluetoothProfileStates[profKey].status = BT_CONNECTING; m_bluetoothProfileStates[profKey].address = address; m_bluetoothProfileStates[profKey].name = name ? name : ""; if (m_bluetoothMenuProfiles.find(m_bluetoothProfiles[profIndex]) != m_bluetoothMenuProfiles.end()) { if(!isDeviceConnectedOnMenuProfiles(address)) updateBtDeviceInfo(&(m_bluetoothProfileStates[profKey])); Q_EMIT signalBluetoothConnStateChanged(true, name ? name : ""); } } } else if(!strcmp(notification, "notifnconnected")) { if((profIndex != -1) && (address != 0)) { if(error == 0) { m_bluetoothProfileStates[profKey].status = BT_CONNECTED; m_bluetoothProfileStates[profKey].address = address; m_bluetoothProfileStates[profKey].name = name ? name : ""; if (m_bluetoothMenuProfiles.find(m_bluetoothProfiles[profIndex]) != m_bluetoothMenuProfiles.end()) { updateBtDeviceInfo(&(m_bluetoothProfileStates[profKey])); Q_EMIT signalBluetoothConnStateChanged(true, name ? name : ""); } } else { // Error reported const char* alreadyConnectedAddress = 0; label = json_object_object_get(root, "alreadyconnectedaddr"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { alreadyConnectedAddress = json_object_get_string(label); } if(alreadyConnectedAddress) { m_bluetoothProfileStates[profKey].status = BT_CONNECTED; m_bluetoothProfileStates[profKey].address = alreadyConnectedAddress; if (m_bluetoothMenuProfiles.find(m_bluetoothProfiles[profIndex]) != m_bluetoothMenuProfiles.end()) { updateBtDeviceInfo(&(m_bluetoothProfileStates[profKey])); Q_EMIT signalBluetoothConnStateChanged(true, name ? name : ""); } } else { if(m_bluetoothProfileStates.find(profKey) != m_bluetoothProfileStates.end()) { m_bluetoothProfileStates[profKey].status = BT_DISCONNECTED; if (m_bluetoothMenuProfiles.find(m_bluetoothProfiles[profIndex]) != m_bluetoothMenuProfiles.end()) { if(!isDeviceConnectedOnMenuProfiles(address)) { updateBtDeviceInfo(&(m_bluetoothProfileStates[profKey])); Q_EMIT signalBluetoothConnStateChanged(false, ""); } } m_bluetoothProfileStates.erase(profKey); } } } updateIcon = true; } } else if(!strcmp(notification, "notifndisconnecting")) { if((profIndex != -1) && (address != 0)) { m_bluetoothProfileStates[profKey].status = BT_DISCONNECTING; if (m_bluetoothMenuProfiles.find(m_bluetoothProfiles[profIndex]) != m_bluetoothMenuProfiles.end()) { if(!isDeviceConnectedOnMenuProfiles(address)) updateBtDeviceInfo(&(m_bluetoothProfileStates[profKey])); } updateIcon = true; } } else if(!strcmp(notification, "notifndisconnected")) { if((profIndex != -1) && (address != 0)) { if(m_bluetoothProfileStates.find(profKey) != m_bluetoothProfileStates.end()) { m_bluetoothProfileStates[profKey].status = BT_DISCONNECTED; if (m_bluetoothMenuProfiles.find(m_bluetoothProfiles[profIndex]) != m_bluetoothMenuProfiles.end()) { if(!isDeviceConnectedOnMenuProfiles(address)) { updateBtDeviceInfo(&(m_bluetoothProfileStates[profKey])); Q_EMIT signalBluetoothConnStateChanged(false, ""); } } m_bluetoothProfileStates.erase(profKey); } updateIcon = true; } } else if(!strcmp(notification, "notifnconnectacceptrequest")) { }else if(!strcmp(notification, "notifndevrenamed")) { std::map<std::string, BluetoothProfState>::iterator it; for(it = m_bluetoothProfileStates.begin(); it != m_bluetoothProfileStates.end(); it++) { if(!strcmp((*it).second.address.c_str(), address)) { (*it).second.name = name ? name : ""; updateBtDeviceInfo(&((*it).second)); if(((*it).second.status == BT_CONNECTED) || ((*it).second.status == BT_CONNECTING)) { Q_EMIT signalBluetoothConnStateChanged(true, name ? name : ""); } } } updateIcon = true; } } } Done: if(updateIcon) updateBluetoothIcon(); if (root && !is_error(root)) json_object_put(root); return true; } void StatusBarServicesConnector::updateBluetoothIcon() { StatusBar::IndexBluetooth state = StatusBar::BLUETOOTH_ON; std::map<std::string, BluetoothProfState>::iterator it; for(it = m_bluetoothProfileStates.begin(); it != m_bluetoothProfileStates.end(); it++) { if((*it).second.status == BT_CONNECTING) state = StatusBar::BLUETOOTH_CONNECTING; if((*it).second.status == BT_CONNECTED) { state = StatusBar::BLUETOOTH_CONNECTED; break; } } Q_EMIT signalBluetoothIndexChanged(true, state); } void StatusBarServicesConnector::updateBtDeviceInfo(BluetoothProfState* info) { t_bluetoothDevice deviceInfo; sprintf(deviceInfo.displayName, "%s", info->name.c_str()); sprintf(deviceInfo.btAddress, "%s", info->address.c_str()); deviceInfo.cod = 0; switch(info->status) { case BT_DISCONNECTED: { sprintf(deviceInfo.connectionState, "disconnected"); deviceInfo.showConnected = false; } break; case BT_CONNECTING: { sprintf(deviceInfo.connectionState, "connecting"); deviceInfo.showConnected = false; } break; case BT_CONNECTED: { sprintf(deviceInfo.connectionState, "connected"); deviceInfo.showConnected = true; } break; case BT_DISCONNECTING: { sprintf(deviceInfo.connectionState, "disconnecting"); deviceInfo.showConnected = false; } break; } Q_EMIT signalBluetoothUpdateDeviceStatus(&deviceInfo); } void StatusBarServicesConnector::setBluetoothOnState(bool on) { bool result; LSError lsError; LSErrorInit(&lsError); char params[64]; if(on) { sprintf(params, "{\"visible\":false,\"connectable\":true}"); result = LSCall(m_service, "palm://com.palm.btmonitor/monitor/radioon", params, statusBarBluetoothTurnOnCallback, NULL, NULL, &lsError); } else { result = LSCall(m_service, "palm://com.palm.btmonitor/monitor/radiooff", "{}", statusBarBluetoothTurnOffCallback, NULL, NULL, &lsError); } if (LSErrorIsSet(&lsError)) { LSErrorPrint(&lsError, stderr); LSErrorFree(&lsError); } } bool StatusBarServicesConnector::statusBarBluetoothTurnOnCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->bluetoothTurnOnCallback(handle, message, ctxt); } bool StatusBarServicesConnector::bluetoothTurnOnCallback(LSHandle* handle, LSMessage* message, void* ctxt) { struct json_object* root = json_tokener_parse(LSMessageGetPayload(message)); struct json_object* header = 0; struct json_object* label = 0; g_message("StatusBar - bluetoothTurnOnCallback %s", LSMessageGetPayload(message)); label = json_object_object_get(root, "returnValue"); if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) { if(json_object_get_boolean(label)) { Q_EMIT signalBluetoothTurnedOn(); goto Done; } else { g_warning("StatusBar - Error Bluetooth Radio : %s", LSMessageGetPayload(message)); updateAirplaneModeProgress(AP_MODE_BLUETOOTH); } } Done: if (root && !is_error(root)) json_object_put(root); return true; } bool StatusBarServicesConnector::statusBarBluetoothTurnOffCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->bluetoothTurnOffCallback(handle, message, ctxt); } bool StatusBarServicesConnector::bluetoothTurnOffCallback(LSHandle* handle, LSMessage* message, void* ctxt) { struct json_object* root = json_tokener_parse(LSMessageGetPayload(message)); struct json_object* label = 0; g_message("StatusBar - bluetoothTurnOffCallback %s", LSMessageGetPayload(message)); label = json_object_object_get(root, "returnValue"); if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) { if(!json_object_get_boolean(label)) { g_warning("StatusBar - Error Bluetooth Radio : %s", LSMessageGetPayload(message)); updateAirplaneModeProgress(AP_MODE_BLUETOOTH); } } if (root && !is_error(root)) json_object_put(root); return true; } void StatusBarServicesConnector::requestTrustedBluetoothDevicesList() { bool result; LSError lsError; LSErrorInit(&lsError); if(m_bluetoothDeviceListReq) { LSCallCancel(m_service, m_bluetoothDeviceListReq, &lsError); m_bluetoothDeviceListReq = 0; } result = LSCall(m_service, "palm://com.palm.bluetooth/gap/gettrusteddevices", "{ }", statusBarBluetoothTruestedListCallback, NULL, &m_bluetoothDeviceListReq, &lsError); if (LSErrorIsSet(&lsError)) { LSErrorPrint(&lsError, stderr); LSErrorFree(&lsError); } } void StatusBarServicesConnector::cancelBluetoothDevicesListRequest() { bool result; LSError lsError; LSErrorInit(&lsError); if(m_bluetoothDeviceListReq) { LSCallCancel(m_service, m_bluetoothDeviceListReq, &lsError); m_bluetoothDeviceListReq = 0; } if (LSErrorIsSet(&lsError)) { LSErrorPrint(&lsError, stderr); LSErrorFree(&lsError); } } bool StatusBarServicesConnector::statusBarBluetoothTruestedListCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->bluetoothTruestedListCallback(handle, message, ctxt); } bool StatusBarServicesConnector::bluetoothTruestedListCallback(LSHandle* handle, LSMessage* message, void* ctxt) { struct json_object* root = json_tokener_parse(LSMessageGetPayload(message)); struct json_object* label = 0; struct json_object* devicesArray = 0; struct json_object* deviceInfo = 0; g_message("StatusBar - bluetoothTruestedListCallback %s", LSMessageGetPayload(message)); label = json_object_object_get(root, "returnValue"); if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) { if(!json_object_get_boolean(label)) { Q_EMIT signalBluetoothTrustedDevicesUpdate(0, NULL); goto Done; } } devicesArray = json_object_object_get(root, "trusteddevices"); if (devicesArray && !is_error(devicesArray) && json_object_is_type(devicesArray, json_type_array)) { int nEntries = json_object_array_length(devicesArray); t_bluetoothDevice devices[nEntries]; int nDevicesOnMenu = 0; for(int x = 0; x < nEntries; x++) { sprintf(devices[nDevicesOnMenu].displayName, "%s", ""); sprintf(devices[nDevicesOnMenu].btAddress, "%s", ""); sprintf(devices[nDevicesOnMenu].connectionState, "%s", ""); devices[nDevicesOnMenu].cod = 0; devices[nDevicesOnMenu].showConnected = false; deviceInfo = json_object_array_get_idx(devicesArray, x); if (deviceInfo && !is_error(deviceInfo) && json_object_is_type(deviceInfo, json_type_object)) { label = json_object_object_get(deviceInfo, "address"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { sprintf(devices[nDevicesOnMenu].btAddress, "%s", json_object_get_string(label)); } label = json_object_object_get(deviceInfo, "name"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { sprintf(devices[nDevicesOnMenu].displayName, "%s", json_object_get_string(label)); } label = json_object_object_get(deviceInfo, "status"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { sprintf(devices[nDevicesOnMenu].connectionState, "%s", json_object_get_string(label)); } label = json_object_object_get(deviceInfo, "cod"); if (label && !is_error(label) && json_object_is_type(label, json_type_int)) { devices[nDevicesOnMenu].cod = json_object_get_int(label); } if(BtDeviceClass::isHFGSupported(devices[nDevicesOnMenu].cod) || BtDeviceClass::isPhone(devices[nDevicesOnMenu].cod) || BtDeviceClass::isA2DPSupported(devices[nDevicesOnMenu].cod)) { if(!strcmp(devices[nDevicesOnMenu].connectionState, "connected")) { std::string hfgKey = std::string("hfg") + devices[nDevicesOnMenu].btAddress; std::string a2dpKey = std::string("a2dp") + devices[nDevicesOnMenu].btAddress; std::string hfKey = std::string("hf") + devices[nDevicesOnMenu].btAddress; std::string mapKey = std::string("mapc") + devices[nDevicesOnMenu].btAddress; if(((m_bluetoothProfileStates.find(hfgKey) != m_bluetoothProfileStates.end()) && (m_bluetoothProfileStates[hfgKey].status = BT_CONNECTED)) || ((m_bluetoothProfileStates.find(a2dpKey) != m_bluetoothProfileStates.end()) && (m_bluetoothProfileStates[a2dpKey].status = BT_CONNECTED)) || ((m_bluetoothProfileStates.find(mapKey) != m_bluetoothProfileStates.end()) && (m_bluetoothProfileStates[mapKey].status = BT_CONNECTED)) || ((m_bluetoothProfileStates.find(hfKey) != m_bluetoothProfileStates.end()) && (m_bluetoothProfileStates[hfKey].status = BT_CONNECTED)) ) devices[nDevicesOnMenu].showConnected = true; else { devices[nDevicesOnMenu].showConnected = false; sprintf(devices[nDevicesOnMenu].connectionState, "disconnected"); } } else if(!strcmp(devices[nDevicesOnMenu].connectionState, "connecting")) { devices[nDevicesOnMenu].showConnected = false; } else { devices[nDevicesOnMenu].showConnected = false; } nDevicesOnMenu++; } } } Q_EMIT signalBluetoothTrustedDevicesUpdate(nDevicesOnMenu, devices); } Done: if (root && !is_error(root)) json_object_put(root); return true; } void StatusBarServicesConnector::requestBluetoothNumProfiles() { bool result; LSError lsError; LSErrorInit(&lsError); result = LSCall(m_service, "palm://com.palm.preferences/appProperties/getAppProperty", "{\"appId\":\"com.palm.bluetooth\",\"key\":\"header\"}", statusBarBluetoothNumProfilesCallback, NULL, NULL, &lsError); if (LSErrorIsSet(&lsError)) { LSErrorPrint(&lsError, stderr); LSErrorFree(&lsError); } } bool StatusBarServicesConnector::statusBarBluetoothNumProfilesCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->bluetoothNumProfilesCallback(handle, message, ctxt); } bool StatusBarServicesConnector::bluetoothNumProfilesCallback(LSHandle* handle, LSMessage* message, void* ctxt) { struct json_object* root = json_tokener_parse(LSMessageGetPayload(message)); struct json_object* header = 0; struct json_object* label = 0; g_message("StatusBar - bluetoothNumProfilesCallback %s", LSMessageGetPayload(message)); label = json_object_object_get(root, "returnValue"); if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) { if(!json_object_get_boolean(label)) { Q_EMIT signalBluetoothParedDevicesAvailable(true); goto Done; } } header = json_object_object_get(root, "header"); if (header && !is_error(header) && json_object_is_type(header, json_type_object)) { label = json_object_object_get(header, "checknum"); if (label && !is_error(label) && json_object_is_type(label, json_type_int)) { int checknum = json_object_get_int(label); if(checknum == 16432047) { label = json_object_object_get(header, "numofprofiles"); if (label && !is_error(label) && json_object_is_type(label, json_type_int)) { int numProfiles = json_object_get_int(label); if(numProfiles > 0) { Q_EMIT signalBluetoothParedDevicesAvailable(true); } else { Q_EMIT signalBluetoothParedDevicesAvailable(false); } } else { Q_EMIT signalBluetoothParedDevicesAvailable(false); } } else { Q_EMIT signalBluetoothParedDevicesAvailable(true); } } else { Q_EMIT signalBluetoothParedDevicesAvailable(true); } } else { Q_EMIT signalBluetoothParedDevicesAvailable(true); } Done: if (root && !is_error(root)) json_object_put(root); return true; } void StatusBarServicesConnector::bluetoothProfileConnect(std::string profile, std::string address) { bool result; LSError lsError; LSErrorInit(&lsError); std::string params = "{\"profile\":\"" + profile + "\",\"address\":\"" + address + "\"}"; result = LSCall(m_service, "palm://com.palm.bluetooth/prof/profconnect", params.c_str(), NULL, NULL, NULL, &lsError); if (LSErrorIsSet(&lsError)) { LSErrorPrint(&lsError, stderr); LSErrorFree(&lsError); } } void StatusBarServicesConnector::bluetoothProfileDisconnect(std::string profile, std::string address) { bool result; LSError lsError; LSErrorInit(&lsError); std::string params = "{\"profile\":\"" + profile + "\",\"address\":\"" + address + "\"}"; result = LSCall(m_service, "palm://com.palm.bluetooth/prof/profdisconnect", params.c_str(), NULL, NULL, NULL, &lsError); if (LSErrorIsSet(&lsError)) { LSErrorPrint(&lsError, stderr); LSErrorFree(&lsError); } } bool StatusBarServicesConnector::isDeviceConnectedOnMenuProfiles(std::string address) { int profIndex = -1; std::string profKey; bool connected = false; std::set<std::string>::iterator it; for(it = m_bluetoothMenuProfiles.begin(); it != m_bluetoothMenuProfiles.end(); it++) { std::string prof = *it; profKey = ""; profKey = prof + address; if(m_bluetoothProfileStates.find(profKey) != m_bluetoothProfileStates.end()) { if ((m_bluetoothProfileStates[profKey].address == address) && ((m_bluetoothProfileStates[profKey].status == BT_CONNECTED) || (m_bluetoothProfileStates[profKey].status == BT_CONNECTING))) { connected = true; break; } } } return connected; } void StatusBarServicesConnector::disconnectAllBtMenuProfiles(std::string address) { std::string profKey; std::set<std::string>::iterator it; for(it = m_bluetoothMenuProfiles.begin(); it != m_bluetoothMenuProfiles.end(); it++) { std::string prof = *it; profKey = ""; profKey = prof + address; if(m_bluetoothProfileStates.find(profKey) != m_bluetoothProfileStates.end()) { if ((m_bluetoothProfileStates[profKey].address == address) && (m_bluetoothProfileStates[profKey].status != BT_DISCONNECTED)) { bluetoothProfileDisconnect(prof, address); } } } } bool StatusBarServicesConnector::isDeviceConnected(std::string address) { int profIndex = -1; std::string profKey; bool connected = false; std::set<std::string>::iterator it; for(unsigned int i = 0; i < m_bluetoothProfiles.size(); i++) { std::string prof = m_bluetoothProfiles[i]; profKey = ""; profKey = prof + address; if(m_bluetoothProfileStates.find(profKey) != m_bluetoothProfileStates.end()) { if ((m_bluetoothProfileStates[profKey].address == address) && (m_bluetoothProfileStates[profKey].status != BT_DISCONNECTED)) { connected = true; break; } } } return connected; } bool StatusBarServicesConnector::statusBarConnMgrServiceUpCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->connMgrServiceUpCallback(handle, message, ctxt); } bool StatusBarServicesConnector::connMgrServiceUpCallback(LSHandle* handle, LSMessage* message, void* ctxt) { g_message("StatusBar - connMgrServiceUpCallback %s", LSMessageGetPayload(message)); struct json_object* json = json_tokener_parse(LSMessageGetPayload(message)); if (json && !is_error(json)) { json_object* label = json_object_object_get(json, "connected"); if (label && json_object_is_type(label, json_type_boolean)) { bool connected = json_object_get_boolean(label); if (connected) { // Bluetooth service up. bool result; LSError lsError; LSErrorInit(&lsError); //Subscribe to Connection Manager Route Status Notifications. result = LSCall(handle, "palm://com.palm.connectionmanager/getstatus", "{\"subscribe\":true}", statusBarConnMgrEventsCallback, NULL, NULL, &lsError); if (!result) goto error; error: if (LSErrorIsSet(&lsError)) { LSErrorPrint(&lsError, stderr); LSErrorFree(&lsError); } } } json_object_put(json); } return true; } bool StatusBarServicesConnector::statusBarConnMgrEventsCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->connMgrEventsCallback(handle, message, ctxt); } bool StatusBarServicesConnector::connMgrEventsCallback(LSHandle* handle, LSMessage* message, void* ctxt) { struct json_object* root = json_tokener_parse(LSMessageGetPayload(message)); struct json_object* label = 0; const char *string = 0; g_message("StatusBar - connMgrEventsCallback %s", LSMessageGetPayload(message)); label = json_object_object_get(root, "isInternetConnectionAvailable"); if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) { m_isInternetConnectionAvailable = json_object_get_boolean(label); if(m_isInternetConnectionAvailable) { struct json_object* wifiObj = 0; wifiObj = json_object_object_get(root, "wifi"); if (wifiObj && !is_error(wifiObj) && json_object_is_type(wifiObj, json_type_object)) { const char* state = 0; const char* onInternet = 0; label = json_object_object_get(wifiObj, "state"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { state = json_object_get_string(label); } label = json_object_object_get(wifiObj, "onInternet"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { onInternet = json_object_get_string(label); } if(!strcmp(state, "connected") && !strcmp(onInternet, "yes")) { //hide the WAN icon now. Q_EMIT signalWanIndexChanged(false, StatusBar::WAN_OFF); m_hideDataIcon = true; } else { m_hideDataIcon = false; } } } } if (root && !is_error(root)) json_object_put(root); return true; } bool StatusBarServicesConnector::statusBarWiFiServiceUpCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->wiFiServiceUpCallback(handle, message, ctxt); } bool StatusBarServicesConnector::wiFiServiceUpCallback(LSHandle* handle, LSMessage* message, void* ctxt) { g_message("StatusBar - wiFiServiceUpCallback %s", LSMessageGetPayload(message)); struct json_object* json = json_tokener_parse(LSMessageGetPayload(message)); if (json && !is_error(json)) { json_object* label = json_object_object_get(json, "connected"); if (label && json_object_is_type(label, json_type_boolean)) { bool connected = json_object_get_boolean(label); if (connected) { // WiFi service up. bool result; LSError lsError; LSErrorInit(&lsError); m_wifiSSID.clear(); m_wifiRadioOn = false; m_wifiConnected = false; Q_EMIT signalWifiStateChanged(m_wifiRadioOn, m_wifiConnected, m_wifiSSID, ""); //Subscribe to Connection Manager Route Status Notifications. result = LSCall(handle, "palm://com.palm.wifi/getstatus", "{\"subscribe\":true}", statusBarWifiEventsCallback, NULL, NULL, &lsError); if (LSErrorIsSet(&lsError)) { LSErrorPrint(&lsError, stderr); LSErrorFree(&lsError); } } else { if(m_wifiRadioOn) { //Simulate WiFi Service Disabled Notification. m_wifiConnected = false; m_wifiSSID.clear(); m_wifiRadioOn = false; Q_EMIT signalWifiIndexChanged(false, StatusBar::WIFI_OFF); Q_EMIT signalWifiStateChanged(m_wifiRadioOn, m_wifiConnected, m_wifiSSID, ""); } } } json_object_put(json); } return true; } bool StatusBarServicesConnector::statusBarWifiEventsCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->wifiEventsCallback(handle, message, ctxt); } bool StatusBarServicesConnector::wifiEventsCallback(LSHandle* handle, LSMessage* message, void* ctxt) { struct json_object* root = json_tokener_parse(LSMessageGetPayload(message)); struct json_object* label = 0; const char *status = 0; g_message("StatusBar - wifiEventsCallback %s", LSMessageGetPayload(message)); label = json_object_object_get(root, "status"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { status = json_object_get_string(label); if(status) { if(!strcmp(status, "connectionStateChanged")) { struct json_object* networkInfo = 0; m_wifiRadioOn = true; networkInfo = json_object_object_get(root, "networkInfo"); if (networkInfo && !is_error(networkInfo) && json_object_is_type(networkInfo, json_type_object)) { const char* connectState = 0; const char* ssid = 0; label = json_object_object_get(networkInfo, "connectState"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { connectState = json_object_get_string(label); } label = json_object_object_get(networkInfo, "ssid"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { ssid = json_object_get_string(label); } if(connectState) { if(!strcmp(connectState, "associating") || !strcmp(connectState, "associated")) { m_wifiSSID = std::string(ssid); Q_EMIT signalWifiIndexChanged(true, StatusBar::WIFI_CONNECTING); Q_EMIT signalWifiStateChanged(m_wifiRadioOn, m_wifiConnected, m_wifiSSID, connectState); } else if(!strcmp(connectState, "ipFailed") || !strcmp(connectState, "notAssociated") || !strcmp(connectState, "associationFailed")) { m_wifiSSID.clear(); m_wifiConnected = false; Q_EMIT signalWifiIndexChanged(true, StatusBar::WIFI_ON); Q_EMIT signalWifiStateChanged(m_wifiRadioOn, m_wifiConnected, m_wifiSSID, connectState); } else if(!strcmp(connectState, "ipConfigured")) { m_wifiConnected = true; m_wifiSSID = std::string(ssid); Q_EMIT signalWifiStateChanged(m_wifiRadioOn, m_wifiConnected, m_wifiSSID, connectState); label = json_object_object_get(networkInfo, "signalBars"); if (label && !is_error(label) && json_object_is_type(label, json_type_int)) { int bars = json_object_get_int(label) - 1; if(bars < 1) bars = 1; if(bars > 3) bars = 3; Q_EMIT signalWifiIndexChanged(true, (StatusBar::IndexWiFi )(StatusBar::WIFI_BAR_1 + bars)); } } } } } else if(!strcmp(status, "signalStrengthChanged")) { if (m_wifiConnected) { label = json_object_object_get(root, "signalBars"); if (label && !is_error(label) && json_object_is_type(label, json_type_int)) { int bars = json_object_get_int(label); if(bars < 1) bars = 1; if(bars > 3) bars = 3; Q_EMIT signalWifiIndexChanged(true, (StatusBar::IndexWiFi )(StatusBar::WIFI_BAR_1 + bars)); } } } else if(!strcmp(status, "serviceEnabled")) { m_wifiConnected = false; m_wifiSSID.clear(); m_wifiRadioOn = true; Q_EMIT signalWifiIndexChanged(true, StatusBar::WIFI_ON); Q_EMIT signalWifiStateChanged(m_wifiRadioOn, m_wifiConnected, m_wifiSSID, ""); updateAirplaneModeProgress(AP_MODE_WIFI); } else if(!strcmp(status, "serviceDisabled")) { m_wifiConnected = false; m_wifiSSID.clear(); m_wifiRadioOn = false; Q_EMIT signalWifiIndexChanged(false, StatusBar::WIFI_OFF); Q_EMIT signalWifiStateChanged(m_wifiRadioOn, m_wifiConnected, m_wifiSSID, ""); updateAirplaneModeProgress(AP_MODE_WIFI); } if (m_wifiConnected && m_hideDataIcon) { signalWanIndexChanged(false, StatusBar::WAN_OFF); } if(!m_cmPayloadBuffer.empty() && !m_wifiConnected) { wanStatusEventsCallback(NULL, m_cmPayloadBuffer.c_str(), NULL); } } } if (root && !is_error(root)) json_object_put(root); return true; } void StatusBarServicesConnector::requestWifiAvailableNetworksList() { bool result; LSError lsError; LSErrorInit(&lsError); if(m_wifiFindNetworksReq) { LSCallCancel(m_service, m_wifiFindNetworksReq, &lsError); m_wifiFindNetworksReq = 0; } result = LSCall(m_service, "palm://com.palm.wifi/findnetworks", "{ }", statusBarWifiAvailableNetworksListCallback, NULL, &m_wifiFindNetworksReq, &lsError); if (LSErrorIsSet(&lsError)) { LSErrorPrint(&lsError, stderr); LSErrorFree(&lsError); } } void StatusBarServicesConnector::cancelWifiNetworksListRequest() { bool result; LSError lsError; LSErrorInit(&lsError); if(m_wifiFindNetworksReq) { LSCallCancel(m_service, m_wifiFindNetworksReq, &lsError); m_wifiFindNetworksReq = 0; } if (LSErrorIsSet(&lsError)) { LSErrorPrint(&lsError, stderr); LSErrorFree(&lsError); } } bool StatusBarServicesConnector::statusBarWifiAvailableNetworksListCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->wifiAvailableNetworksListCallback(handle, message, ctxt); } bool StatusBarServicesConnector::wifiAvailableNetworksListCallback(LSHandle* handle, LSMessage* message, void* ctxt) { struct json_object* root = json_tokener_parse(LSMessageGetPayload(message)); struct json_object* label = 0; const char *status = 0; struct json_object* netArray = 0; struct json_object* networkInfo = 0; g_message("StatusBar - wifiAvailableNetworksListCallback %s", LSMessageGetPayload(message)); label = json_object_object_get(root, "returnValue"); if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) { if(!json_object_get_boolean(label)) { Q_EMIT signalWifiAvailableNetworksListUpdate(0, NULL); goto Done; } } netArray = json_object_object_get(root, "foundNetworks"); if (netArray && !is_error(netArray) && json_object_is_type(netArray, json_type_array)) { int nEntries = json_object_array_length(netArray); t_wifiAccessPoint accessPoints[nEntries]; for(int x = 0; x < json_object_array_length(netArray); x++) { accessPoints[x].profileId = 0; accessPoints[x].signalBars = 0; accessPoints[x].connected = false; sprintf(accessPoints[x].ssid, "%s", ""); sprintf(accessPoints[x].securityType, "%s", ""); sprintf(accessPoints[x].connectionState, "%s", ""); label = json_object_array_get_idx(netArray, x); if (label && !is_error(label) && json_object_is_type(label, json_type_object)) { networkInfo = json_object_object_get(label, "networkInfo"); if (networkInfo && !is_error(networkInfo) && json_object_is_type(networkInfo, json_type_object)) { label = json_object_object_get(networkInfo, "ssid"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { sprintf(accessPoints[x].ssid, "%s", json_object_get_string(label)); } label = json_object_object_get(networkInfo, "profileId"); if (label && !is_error(label) && json_object_is_type(label, json_type_int)) { accessPoints[x].profileId = json_object_get_int(label); } label = json_object_object_get(networkInfo, "signalBars"); if (label && !is_error(label) && json_object_is_type(label, json_type_int)) { accessPoints[x].signalBars = json_object_get_int(label); } label = json_object_object_get(networkInfo, "securityType"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { sprintf(accessPoints[x].securityType, "%s", json_object_get_string(label)); } label = json_object_object_get(networkInfo, "connectState"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { sprintf(accessPoints[x].connectionState, "%s", json_object_get_string(label)); if((!strcmp(accessPoints[x].connectionState, "ipConfigured")) || (!strcmp(accessPoints[x].connectionState, "associated"))) { accessPoints[x].connected = true; } } } } } Q_EMIT signalWifiAvailableNetworksListUpdate(nEntries, accessPoints); } Done: if (root && !is_error(root)) json_object_put(root); return true; } void StatusBarServicesConnector::connectToWifiNetwork(std::string ssid, int profileId, std::string security) { bool result; LSError lsError; LSErrorInit(&lsError); char params[255]; if(profileId) { sprintf(params, "{\"profileId\":%d}", profileId); } else { if(security.empty()) sprintf(params, "{\"ssid\":\"%s\"}", ssid.c_str()); else sprintf(params, "{\"ssid\":\"%s\",\"securityType\":\"%s\"}", ssid.c_str(), security.c_str()); } result = LSCall(m_service, "palm://com.palm.wifi/connect", params, statusBarWifiConnectCallback, NULL, NULL, &lsError); if (LSErrorIsSet(&lsError)) { LSErrorPrint(&lsError, stderr); LSErrorFree(&lsError); } } bool StatusBarServicesConnector::statusBarWifiConnectCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->wifiConnectCallback(handle, message, ctxt); } bool StatusBarServicesConnector::wifiConnectCallback(LSHandle* handle, LSMessage* message, void* ctxt) { struct json_object* root = json_tokener_parse(LSMessageGetPayload(message)); struct json_object* label = 0; g_message("StatusBar - wifiConnectCallback %s", LSMessageGetPayload(message)); if (root && !is_error(root)) json_object_put(root); return true; } void StatusBarServicesConnector::setWifiOnState(bool on) { bool result; LSError lsError; LSErrorInit(&lsError); char params[32]; if(on) { sprintf(params, "{\"state\":\"enabled\"}"); } else { sprintf(params, "{\"state\":\"disabled\"}"); } result = LSCall(m_service, "palm://com.palm.wifi/setstate", params, statusBarWifiPowerStateChangeCallback, NULL, NULL, &lsError); if (LSErrorIsSet(&lsError)) { LSErrorPrint(&lsError, stderr); LSErrorFree(&lsError); } } bool StatusBarServicesConnector::statusBarWifiPowerStateChangeCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->wifiPowerStateChangeCallback(handle, message, ctxt); } bool StatusBarServicesConnector::wifiPowerStateChangeCallback(LSHandle* handle, LSMessage* message, void* ctxt) { struct json_object* root = json_tokener_parse(LSMessageGetPayload(message)); struct json_object* label = 0; g_message("StatusBar - wifiPowerStateChangeCallback %s", LSMessageGetPayload(message)); label = json_object_object_get(root, "returnValue"); if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) { bool success = json_object_get_boolean(label); if(!success) { g_warning("StatusBar - Error Wifi Radio : %s", LSMessageGetPayload(message)); updateAirplaneModeProgress(AP_MODE_WIFI); } } if (root && !is_error(root)) json_object_put(root); return true; } bool StatusBarServicesConnector::statusBarVpnServiceUpCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->vpnServiceUpCallback(handle, message, ctxt); } bool StatusBarServicesConnector::vpnServiceUpCallback(LSHandle* handle, LSMessage* message, void* ctxt) { g_message("StatusBar - vpnServiceUpCallback %s", LSMessageGetPayload(message)); struct json_object* json = json_tokener_parse(LSMessageGetPayload(message)); if (json && !is_error(json)) { json_object* label = json_object_object_get(json, "connected"); if (label && json_object_is_type(label, json_type_boolean)) { bool connected = json_object_get_boolean(label); if (connected) { // VPN service up. bool result; LSError lsError; LSErrorInit(&lsError); result = LSCall(handle, "palm://com.palm.vpn/getProfileList", "{\"subscribe\":true}", statusBarHandleVPNStatusNotification, NULL, NULL, &lsError); if (LSErrorIsSet(&lsError)) { LSErrorPrint(&lsError, stderr); LSErrorFree(&lsError); } } else { Q_EMIT signalVpnStateChanged(false); m_vpnConnected = false; m_connectedVpnInfo.clear(); } } json_object_put(json); } return true; } void StatusBarServicesConnector::requestVpnProfilesList() { bool result; LSError lsError; LSErrorInit(&lsError); result = LSCall(m_service, "palm://com.palm.vpn/getProfileList", "{\"subscribe\":true}", statusBarHandleVPNStatusNotification, NULL, NULL, &lsError); if (LSErrorIsSet(&lsError)) { LSErrorPrint(&lsError, stderr); LSErrorFree(&lsError); } } bool StatusBarServicesConnector::statusBarHandleVPNStatusNotification(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->handleVPNStatusNotification(handle, message, ctxt); } bool StatusBarServicesConnector::handleVPNStatusNotification(LSHandle* handle, LSMessage* message, void* ctxt) { struct json_object* root = json_tokener_parse(LSMessageGetPayload(message)); g_message("StatusBar - handleVPNStatusNotification %s", LSMessageGetPayload(message)); struct json_object* label = 0; json_object* item = NULL; json_object* array = NULL; const char* state = 0; bool vpnConnected = false; array = json_object_object_get(root, "vpnProfiles"); if (array && !is_error(array) && json_object_is_type(array, json_type_array)) { int numProfiles = json_object_array_length(array); int nValidProf = 0; t_vpnProfile profiles[numProfiles]; m_vpnConnected = false; m_connectedVpnInfo.clear(); for(int i = 0; i < numProfiles; i++) { sprintf(profiles[nValidProf].displayName, "%s", ""); sprintf(profiles[nValidProf].connectionState, "%s", ""); sprintf(profiles[nValidProf].profInfo, "%s", ""); state = 0; item = json_object_array_get_idx(array, i); if (item && !is_error(item) && json_object_is_type(item, json_type_object)) { char* infoString = json_object_to_json_string(item); if(infoString) sprintf(profiles[nValidProf].profInfo, "%s", infoString); label = json_object_object_get(item, "vpnProfileName"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { sprintf(profiles[nValidProf].displayName, "%s", json_object_get_string(label)); } label = json_object_object_get(item, "vpnProfileConnectState"); if (label && !is_error(label) && json_object_is_type(label, json_type_string)) { sprintf(profiles[nValidProf].connectionState, "%s", json_object_get_string(label)); if(label && !strcmp(profiles[nValidProf].connectionState, "connected")) { // VPN is connected vpnConnected = true; m_vpnConnected = true; m_connectedVpnInfo = infoString; } } nValidProf++; } } Q_EMIT signalVpnStateChanged(vpnConnected); Q_EMIT signalVpnProfileListUpdate(nValidProf, profiles); } if (root && !is_error(root)) json_object_put(root); return true; } void StatusBarServicesConnector::vpnConnectionRequest(bool connect, std::string profileInfo) { bool result; LSError lsError; LSErrorInit(&lsError); std::string params = profileInfo; if(connect) { if(!m_vpnConnected) { result = LSCall(m_service, "palm://com.palm.vpn/connect", params.c_str(), NULL, NULL, NULL, &lsError); } else { m_pendingVpnProfile = profileInfo; result = LSCall(m_service, "palm://com.palm.vpn/disconnect", params.c_str(), statusBarVpnDisconnectResponse, NULL, NULL, &lsError); } } else { result = LSCall(m_service, "palm://com.palm.vpn/disconnect", params.c_str(), NULL, NULL, NULL, &lsError); } if (LSErrorIsSet(&lsError)) { LSErrorPrint(&lsError, stderr); LSErrorFree(&lsError); } } bool StatusBarServicesConnector::statusBarVpnDisconnectResponse(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->vpnDisconnectResponse(handle, message, ctxt); } bool StatusBarServicesConnector::vpnDisconnectResponse(LSHandle* handle, LSMessage* message, void* ctxt) { struct json_object* root = json_tokener_parse(LSMessageGetPayload(message)); struct json_object* label = 0; g_message("StatusBar - vpnDisconnectResponse %s", LSMessageGetPayload(message)); label = json_object_object_get(root, "returnValue"); if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) { if(json_object_get_boolean(label)) { // disconnected from VPN if(!m_pendingVpnProfile.empty()) { vpnConnectionRequest(true, m_pendingVpnProfile); m_pendingVpnProfile.clear(); } } } return true; } bool StatusBarServicesConnector::statusBarGetSystemTimeCallback(LSHandle* handle, LSMessage* message, void* ctxt) { if(!s_instance) return true; return s_instance->getSystemTimeCallback(handle, message, ctxt); } bool StatusBarServicesConnector::getSystemTimeCallback(LSHandle* handle, LSMessage* message, void* ctxt) { struct json_object* root = json_tokener_parse(LSMessageGetPayload(message)); struct json_object* label = 0; g_message("StatusBar - getSystemTimeCallback %s", LSMessageGetPayload(message)); label = json_object_object_get(root, "returnValue"); if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) { // this is the subscription return value, safe to ignore return true; } // if we get this but it isn't the subscription return value, it is then due to the fact that the // system time was updated Q_EMIT signalSystemTimeChanged(); return true; } void StatusBarServicesConnector::slotEnterBrickMode(bool) { setRadioStatesForMSMMode(false); } void StatusBarServicesConnector::slotExitBrickMode() { setRadioStatesForMSMMode(true); }
31.910548
177
0.715241
[ "vector" ]
c592446b4fb58a60edfaaf2e5b342e45ce2798cb
8,450
cc
C++
chrome/browser/android/download/chrome_download_delegate.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-28T08:09:58.000Z
2021-11-15T15:32:10.000Z
chrome/browser/android/download/chrome_download_delegate.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/android/download/chrome_download_delegate.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.000Z
// Copyright 2015 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 "chrome/browser/android/download/chrome_download_delegate.h" #include <jni.h> #include <string> #include <type_traits> #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "base/android/scoped_java_ref.h" #include "base/bind.h" #include "base/callback.h" #include "base/files/file_path.h" #include "chrome/browser/android/download/android_download_manager_overwrite_infobar_delegate.h" #include "chrome/browser/android/download/download_controller_base.h" #include "chrome/browser/android/tab_android.h" #include "chrome/browser/infobars/infobar_service.h" #include "chrome/browser/permissions/permission_update_infobar_delegate_android.h" #include "chrome/common/safe_browsing/file_type_policies.h" #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" #include "jni/ChromeDownloadDelegate_jni.h" #include "ui/base/l10n/l10n_util.h" using base::android::ConvertUTF8ToJavaString; using base::android::ScopedJavaLocalRef; using content::WebContents; // Gets the download warning text for the given file name. static ScopedJavaLocalRef<jstring> GetDownloadWarningText( JNIEnv* env, const JavaParamRef<jclass>& clazz, const JavaParamRef<jstring>& filename) { return base::android::ConvertUTF8ToJavaString( env, l10n_util::GetStringFUTF8( IDS_PROMPT_DANGEROUS_DOWNLOAD, base::android::ConvertJavaStringToUTF16(env, filename))); } // Returns true if a file name is dangerous, or false otherwise. static jboolean IsDownloadDangerous(JNIEnv* env, const JavaParamRef<jclass>& clazz, const JavaParamRef<jstring>& filename) { base::FilePath path(base::android::ConvertJavaStringToUTF8(env, filename)); return safe_browsing::FileTypePolicies::GetInstance()->GetFileDangerLevel( path) != safe_browsing::DownloadFileType::NOT_DANGEROUS; } // Called when a dangerous download is validated. static void DangerousDownloadValidated( JNIEnv* env, const JavaParamRef<jclass>& clazz, const JavaParamRef<jobject>& tab, const JavaParamRef<jstring>& jdownload_guid, jboolean accept) { std::string download_guid = base::android::ConvertJavaStringToUTF8(env, jdownload_guid); TabAndroid* tab_android = TabAndroid::GetNativeTab(env, tab); DownloadControllerBase::Get()->DangerousDownloadValidated( tab_android->web_contents(), download_guid, accept); } // static bool ChromeDownloadDelegate::EnqueueDownloadManagerRequest( jobject chrome_download_delegate, bool overwrite, jobject download_info) { JNIEnv* env = base::android::AttachCurrentThread(); return Java_ChromeDownloadDelegate_enqueueDownloadManagerRequestFromNative( env, chrome_download_delegate, overwrite, download_info); } // Called when we need to interrupt download and ask users whether to overwrite // an existing file. static void LaunchDownloadOverwriteInfoBar( JNIEnv* env, const JavaParamRef<jclass>& clazz, const JavaParamRef<jobject>& delegate, const JavaParamRef<jobject>& tab, const JavaParamRef<jobject>& download_info, const JavaParamRef<jstring>& jfile_name, const JavaParamRef<jstring>& jdir_name, const JavaParamRef<jstring>& jdir_full_path) { TabAndroid* tab_android = TabAndroid::GetNativeTab(env, tab); std::string file_name = base::android::ConvertJavaStringToUTF8(env, jfile_name); std::string dir_name = base::android::ConvertJavaStringToUTF8(env, jdir_name); std::string dir_full_path = base::android::ConvertJavaStringToUTF8(env, jdir_full_path); chrome::android::AndroidDownloadManagerOverwriteInfoBarDelegate::Create( InfoBarService::FromWebContents(tab_android->web_contents()), file_name, dir_name, dir_full_path, delegate, download_info); } static void LaunchPermissionUpdateInfoBar( JNIEnv* env, const JavaParamRef<jclass>& clazz, const JavaParamRef<jobject>& tab, const JavaParamRef<jstring>& jpermission, jlong callback_id) { TabAndroid* tab_android = TabAndroid::GetNativeTab(env, tab); std::string permission = base::android::ConvertJavaStringToUTF8(env, jpermission); // Convert java long long int to c++ pointer, take ownership. static_assert( std::is_same< DownloadControllerBase::AcquireFileAccessPermissionCallback, base::Callback<void(bool)>>::value, "Callback types don't match!"); std::unique_ptr<base::Callback<void(bool)>> cb( reinterpret_cast<base::Callback<void(bool)>*>(callback_id)); std::vector<std::string> permissions; permissions.push_back(permission); PermissionUpdateInfoBarDelegate::Create( tab_android->web_contents(), permissions, IDS_MISSING_STORAGE_PERMISSION_DOWNLOAD_EDUCATION_TEXT, *cb); } ChromeDownloadDelegate::ChromeDownloadDelegate( WebContents* web_contents) {} ChromeDownloadDelegate::~ChromeDownloadDelegate() { JNIEnv* env = base::android::AttachCurrentThread(); env->DeleteGlobalRef(java_ref_); } void ChromeDownloadDelegate::SetJavaRef(JNIEnv* env, jobject jobj) { java_ref_ = env->NewGlobalRef(jobj); } void ChromeDownloadDelegate::RequestHTTPGetDownload( const std::string& url, const std::string& user_agent, const std::string& content_disposition, const std::string& mime_type, const std::string& cookie, const std::string& referer, const base::string16& file_name, int64_t content_length, bool has_user_gesture, bool must_download) { JNIEnv* env = base::android::AttachCurrentThread(); ScopedJavaLocalRef<jstring> jurl = ConvertUTF8ToJavaString(env, url); ScopedJavaLocalRef<jstring> juser_agent = ConvertUTF8ToJavaString(env, user_agent); ScopedJavaLocalRef<jstring> jcontent_disposition = ConvertUTF8ToJavaString(env, content_disposition); ScopedJavaLocalRef<jstring> jmime_type = ConvertUTF8ToJavaString(env, mime_type); ScopedJavaLocalRef<jstring> jcookie = ConvertUTF8ToJavaString(env, cookie); ScopedJavaLocalRef<jstring> jreferer = ConvertUTF8ToJavaString(env, referer); // net::GetSuggestedFilename will fallback to "download" as filename. ScopedJavaLocalRef<jstring> jfilename = base::android::ConvertUTF16ToJavaString(env, file_name); Java_ChromeDownloadDelegate_requestHttpGetDownload( env, java_ref_, jurl.obj(), juser_agent.obj(), jcontent_disposition.obj(), jmime_type.obj(), jcookie.obj(), jreferer.obj(), has_user_gesture, jfilename.obj(), content_length, must_download); } void ChromeDownloadDelegate::OnDownloadStarted(const std::string& filename, const std::string& mime_type) { JNIEnv* env = base::android::AttachCurrentThread(); ScopedJavaLocalRef<jstring> jfilename = ConvertUTF8ToJavaString( env, filename); ScopedJavaLocalRef<jstring> jmime_type = ConvertUTF8ToJavaString(env, mime_type); Java_ChromeDownloadDelegate_onDownloadStarted( env, java_ref_, jfilename.obj(), jmime_type.obj()); } void ChromeDownloadDelegate::OnDangerousDownload(const std::string& filename, const std::string& guid) { JNIEnv* env = base::android::AttachCurrentThread(); ScopedJavaLocalRef<jstring> jfilename = ConvertUTF8ToJavaString( env, filename); ScopedJavaLocalRef<jstring> jguid = ConvertUTF8ToJavaString(env, guid); Java_ChromeDownloadDelegate_onDangerousDownload( env, java_ref_, jfilename.obj(), jguid.obj()); } void ChromeDownloadDelegate::RequestFileAccess(intptr_t callback_id) { JNIEnv* env = base::android::AttachCurrentThread(); Java_ChromeDownloadDelegate_requestFileAccess( env, java_ref_, callback_id); } void Init(JNIEnv* env, const JavaParamRef<jobject>& obj, const JavaParamRef<jobject>& jweb_contents) { auto web_contents = WebContents::FromJavaWebContents(jweb_contents); ChromeDownloadDelegate::CreateForWebContents(web_contents); ChromeDownloadDelegate::FromWebContents(web_contents)->SetJavaRef(env, obj); } bool RegisterChromeDownloadDelegate(JNIEnv* env) { return RegisterNativesImpl(env); } DEFINE_WEB_CONTENTS_USER_DATA_KEY(ChromeDownloadDelegate);
38.584475
96
0.748757
[ "vector" ]
c59a8faf4a2378888a89c062378932b94a5c7cd0
3,301
cpp
C++
OpenGLParticleSystem/ParticleSystem.cpp
Co3us/OpenGLParticleSystem
65a19510b5e03106cbb78624aeea0e24f9d94200
[ "MIT" ]
2
2020-02-17T20:06:42.000Z
2021-03-31T08:01:38.000Z
OpenGLParticleSystem/ParticleSystem.cpp
Co3us/OpenGLParticleSystem
65a19510b5e03106cbb78624aeea0e24f9d94200
[ "MIT" ]
null
null
null
OpenGLParticleSystem/ParticleSystem.cpp
Co3us/OpenGLParticleSystem
65a19510b5e03106cbb78624aeea0e24f9d94200
[ "MIT" ]
null
null
null
#include "ParticleSystem.h" using namespace std; ParticleSystem::ParticleSystem(int _NMAX, int _numOfParticlesPerSecond) { NMAX = _NMAX; numOfParticlesPerSecond = _numOfParticlesPerSecond; prevTime = glfwGetTime(); fpsTime = glfwGetTime(); partCounter = 0; nbFrames = 0; maxFilledIndex = 0; currentDataSize = 0; squareSize = 0.25; particlesArray = new Particle[NMAX]; flags = new bool[NMAX]; for (size_t i = 0; i < NMAX; i++) flags[i] = false; } ParticleSystem::~ParticleSystem() { delete(particlesArray); delete(flags); } void ParticleSystem::update() { double currentTime = glfwGetTime(); double deltaTime = currentTime - prevTime; prevTime = currentTime; nbFrames++; partCounter += ceil(numOfParticlesPerSecond * deltaTime); initParticles(partCounter); if (currentTime - fpsTime >= 1.0) { cout << "FPS: " << nbFrames << "\n"; fpsTime += 1.0; nbFrames = 0; partCounter = 0; } for (size_t i = 0; i <= maxFilledIndex; i++) { if (flags[i] == true) { particlesArray[i].lifeSpan -= deltaTime; particlesArray[i].position = particlesArray[i].position + particlesArray[i].startVel * deltaTime; if (particlesArray[i].lifeSpan <= 0) { destroyParticle(i); } } } } void ParticleSystem::destroyParticle(int index) { flags[index] = false; if (index == maxFilledIndex) { for (int i = maxFilledIndex; i >= 0; i--) { if (flags[i] == true) { maxFilledIndex = i; break; } } } } void ParticleSystem::initParticles(int n) { for (size_t i = 0; i < n; i++) { Particle particle{}; for (size_t j = 0; j < NMAX; j++) { if (flags[j] == false) { particlesArray[j] = particle; flags[j] = true; if (j >= maxFilledIndex) { maxFilledIndex = j; } break; } } } } vector<glm::vec3> ParticleSystem::getDataSquarePoints() { int squareDim = 1; std::vector<glm::vec3> points; currentDataSize = 0; for (size_t i = 0; i <= maxFilledIndex; i++) { if (flags[i] == true) { getSquareFromCenter(particlesArray[i].position); for (size_t i = 0; i < 4; i++) { points.push_back(squarePoints[i]); currentDataSize++; if (i == 0) { points.push_back(glm::vec3(1, 0, 1)); currentDataSize++; } else if (i == 1) { points.push_back(glm::vec3(0, 0, 1)); currentDataSize++; } else if (i == 2) { points.push_back(glm::vec3(0, 1, 1)); currentDataSize++; } else if (i == 3) { points.push_back(glm::vec3(1, 1, 1)); currentDataSize++; } } } } return points; } std::vector<glm::vec3>ParticleSystem::getDataCenterPoints() { int squareDim = 1; std::vector<glm::vec3> points; currentDataSize = 0; for (size_t i = 0; i <= maxFilledIndex; i++) { if (flags[i] == true) { points.push_back(particlesArray[i].position); currentDataSize++; } } return points; } void ParticleSystem::getSquareFromCenter(glm::vec3 center) { float dist = squareSize; //Point down-left squarePoints[0] = center + glm::vec3(dist, -dist, 0); //Point up-left squarePoints[1] = center + glm::vec3(-dist, -dist, 0); //Point down-right squarePoints[2] = center + glm::vec3(-dist, dist, 0); //Point up_right squarePoints[3] = center + glm::vec3(dist, dist, 0); } int ParticleSystem::getCurrentDataSize() { return currentDataSize; }
21.025478
100
0.632536
[ "vector" ]
c5a10e51cbdffc50e80ac30d42983d0909c7710f
4,095
cpp
C++
qsrc/CQSVGBufferView.cpp
colinw7/CSVG
049419b4114fc6ff7f5b25163398f02c21a64bf6
[ "MIT" ]
5
2015-04-11T14:56:03.000Z
2021-12-14T10:12:36.000Z
qsrc/CQSVGBufferView.cpp
colinw7/CSVG
049419b4114fc6ff7f5b25163398f02c21a64bf6
[ "MIT" ]
3
2015-04-20T19:23:15.000Z
2021-09-03T20:03:30.000Z
qsrc/CQSVGBufferView.cpp
colinw7/CSVG
049419b4114fc6ff7f5b25163398f02c21a64bf6
[ "MIT" ]
3
2015-05-21T08:33:12.000Z
2020-05-13T15:45:11.000Z
#include <CQSVGBufferView.h> #include <CQSVG.h> #include <CQSVGRenderer.h> #include <CSVGBuffer.h> #include <CQSVGUtil.h> #include <CQImage.h> #include <CQUtil.h> #include <QVBoxLayout> #include <QComboBox> #include <QCheckBox> #include <QLabel> #include <QPainter> #include <QMouseEvent> CQSVGBufferView:: CQSVGBufferView(CSVG *svg) : svg_(svg) { setObjectName("bufferView"); setWindowTitle("Buffer View"); auto *layout = CQUtil::makeLayout<QVBoxLayout>(this, 0, 2); //--- auto *controlFrame = CQUtil::makeWidget<QFrame>("control"); controlFrame->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); layout->addWidget(controlFrame); auto *controlLayout = CQUtil::makeLayout<QHBoxLayout>(controlFrame, 0, 2); bgCheck_ = CQUtil::makeLabelWidget<QCheckBox>("Checkerboard", "checkerboard"); connect(bgCheck_, SIGNAL(stateChanged(int)), this, SLOT(updateBuffer())); controlLayout->addWidget(bgCheck_); combo_ = CQUtil::makeWidget<QComboBox>("combo"); connect(combo_, SIGNAL(currentIndexChanged(int)), this, SLOT(updateBuffer())); controlLayout->addWidget(combo_); //--- canvas_ = new CQSVGBufferCanvas(this); layout->addWidget(canvas_); //--- auto *status = new QFrame; status->setObjectName("status"); status->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); layout->addWidget(status); auto *statusLayout = new QHBoxLayout(status); statusLayout->setMargin(0); statusLayout->setSpacing(2); statusLabel_ = new QLabel; statusLabel_->setObjectName("statusLabel"); statusLayout->addWidget(statusLabel_); statusLayout->addStretch(); posLabel_ = new QLabel; posLabel_->setObjectName("posLabel"); statusLayout->addWidget(posLabel_); //--- updateState(); updateBuffer(); } void CQSVGBufferView:: updateState() { combo_->clear(); std::vector<std::string> names; svg_->getBufferNames(names); for (const auto &n : names) combo_->addItem(n.c_str()); } void CQSVGBufferView:: updateBuffer() { QString text; auto *buffer = svg_->getBuffer(bufferName().toStdString()); if (buffer) { text += QString("Opacity: %1").arg(buffer->opacity()); if (buffer->isAlpha()) text += ", Alpha"; if (buffer->isClip()) text += ", Clip"; } statusLabel_->setText(text); canvas_->update(); } QString CQSVGBufferView:: bufferName() const { return combo_->currentText(); } QImage CQSVGBufferView:: bufferImage() const { auto *buffer = svg_->getBuffer(bufferName().toStdString()); auto *renderer = dynamic_cast<CQSVGRenderer *>(buffer->getRenderer()); if (! renderer) return QImage(); return renderer->qimage(); } CBBox2D CQSVGBufferView:: bufferBBox() const { return svg_->getBuffer(bufferName().toStdString())->bbox(); } CPoint2D CQSVGBufferView:: bufferOrigin() const { return svg_->getBuffer(bufferName().toStdString())->origin(); } void CQSVGBufferView:: showPos(const QPoint &ppos) { auto ptext = QString("%1,%2").arg(ppos.x()).arg(ppos.y()); posLabel_->setText(QString("(%1)").arg(ptext)); } bool CQSVGBufferView:: isCheckerboard() const { return bgCheck_->isChecked(); } //--- CQSVGBufferCanvas:: CQSVGBufferCanvas(CQSVGBufferView *view) : view_(view) { setFocusPolicy(Qt::StrongFocus); setMouseTracking(true); } void CQSVGBufferCanvas:: paintEvent(QPaintEvent *) { QPainter painter(this); if (view_->isCheckerboard()) CQSVGUtil::drawCheckerboard(&painter, 32); else painter.fillRect(rect(), Qt::white); auto image = view_->bufferImage (); auto origin = view_->bufferOrigin(); if (! image.isNull()) painter.drawImage(QPointF(origin.x, origin.y), image); auto bbox = view_->bufferBBox(); if (bbox.isSet()) { // TODO: transform painter.setPen(Qt::red); painter.drawRect(CQUtil::toQRect(bbox)); } } void CQSVGBufferCanvas:: mouseMoveEvent(QMouseEvent *e) { view_->showPos(e->pos()); } QSize CQSVGBufferCanvas:: sizeHint() const { QFontMetrics fm(font()); int w = fm.width("X")*20; int h = fm.height() *20; int s = std::max(w, h); return QSize(s, s); }
17.882096
80
0.687912
[ "vector", "transform" ]
c5a3a71175b3c20ebb90f131cda408a8005635c7
2,761
cpp
C++
IMU/VTK-6.2.0/ThirdParty/xdmf3/vtkxdmf3/core/XdmfItem.cpp
timkrentz/SunTracker
9a189cc38f45e5fbc4e4c700d7295a871d022795
[ "MIT" ]
4
2016-03-30T14:31:52.000Z
2019-02-02T05:01:32.000Z
IMU/VTK-6.2.0/ThirdParty/xdmf3/vtkxdmf3/core/XdmfItem.cpp
timkrentz/SunTracker
9a189cc38f45e5fbc4e4c700d7295a871d022795
[ "MIT" ]
null
null
null
IMU/VTK-6.2.0/ThirdParty/xdmf3/vtkxdmf3/core/XdmfItem.cpp
timkrentz/SunTracker
9a189cc38f45e5fbc4e4c700d7295a871d022795
[ "MIT" ]
null
null
null
/*****************************************************************************/ /* XDMF */ /* eXtensible Data Model and Format */ /* */ /* Id : XdmfItem.cpp */ /* */ /* Author: */ /* Kenneth Leiter */ /* kenneth.leiter@arl.army.mil */ /* US Army Research Laboratory */ /* Aberdeen Proving Ground, MD */ /* */ /* Copyright @ 2011 US Army Research Laboratory */ /* All Rights Reserved */ /* See Copyright.txt for details */ /* */ /* This software is distributed WITHOUT ANY WARRANTY; without */ /* even the implied warranty of MERCHANTABILITY or FITNESS */ /* FOR A PARTICULAR PURPOSE. See the above copyright notice */ /* for more information. */ /* */ /*****************************************************************************/ #include "XdmfInformation.hpp" #include "XdmfItem.hpp" XDMF_CHILDREN_IMPLEMENTATION(XdmfItem, XdmfInformation, Information, Key) XdmfItem::XdmfItem() { } XdmfItem::~XdmfItem() { } void XdmfItem::populateItem(const std::map<std::string, std::string> &, const std::vector<shared_ptr<XdmfItem > > & childItems, const XdmfCoreReader * const) { for(std::vector<shared_ptr<XdmfItem> >::const_iterator iter = childItems.begin(); iter != childItems.end(); ++iter) { if(shared_ptr<XdmfInformation> information = shared_dynamic_cast<XdmfInformation>(*iter)) { this->insert(information); } } } void XdmfItem::traverse(const shared_ptr<XdmfBaseVisitor> visitor) { for(std::vector<shared_ptr<XdmfInformation> >::const_iterator iter = mInformations.begin(); iter != mInformations.end(); ++iter) { (*iter)->accept(visitor); } }
43.825397
80
0.357479
[ "vector", "model" ]
c5ae563a10df678942a66e56167dd8337ed0235b
700
hpp
C++
examples/gl-ball/paddle_renderer.hpp
EduRenesto/abcg
4f7ab2d02e20e2a9351af03c34360a7629c219d1
[ "MIT" ]
null
null
null
examples/gl-ball/paddle_renderer.hpp
EduRenesto/abcg
4f7ab2d02e20e2a9351af03c34360a7629c219d1
[ "MIT" ]
null
null
null
examples/gl-ball/paddle_renderer.hpp
EduRenesto/abcg
4f7ab2d02e20e2a9351af03c34360a7629c219d1
[ "MIT" ]
null
null
null
#ifndef __GLBALL_PADDLE_RENDERER_HPP #define __GLBALL_PADDLE_RENDERER_HPP #include <array> #include <GL/glew.h> #include "paddle.hpp" namespace glball { class PaddleRenderer { public: explicit PaddleRenderer(GLuint shader); void render(Paddle& paddle, glm::mat4 &projection_matrix) const; private: GLuint m_paddle_vbo{}; GLuint m_paddle_vao{}; GLuint m_paddle_shader{}; glm::mat3 m_block_scale{}; constexpr static const std::array<glm::vec2, 6> m_paddle_vertices = { glm::vec2(1.0, 1.0), glm::vec2(-1.0, 1.0), glm::vec2(-1.0, -1.0), glm::vec2(-1.0, -1.0), glm::vec2(1.0, -1.0), glm::vec2(1.0, 1.0), }; }; } #endif
18.918919
73
0.632857
[ "render" ]
c5b094a4b45faae0e317ddeadb992429b9c8fa35
97,316
hxx
C++
source/OOSQL/include/OOSQL_StorageManager.hxx
odysseus-oosql/ODYSSEUS-OOSQL
49a5e32b6f73cea611dafdcc0e6767f80d4450ae
[ "BSD-3-Clause" ]
6
2016-08-29T08:03:21.000Z
2022-03-25T09:56:23.000Z
source/OOSQL/include/OOSQL_StorageManager.hxx
odysseus-oosql/ODYSSEUS-OOSQL
49a5e32b6f73cea611dafdcc0e6767f80d4450ae
[ "BSD-3-Clause" ]
null
null
null
source/OOSQL/include/OOSQL_StorageManager.hxx
odysseus-oosql/ODYSSEUS-OOSQL
49a5e32b6f73cea611dafdcc0e6767f80d4450ae
[ "BSD-3-Clause" ]
null
null
null
/******************************************************************************/ /* */ /* Copyright (c) 1990-2016, KAIST */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* */ /* 1. Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* */ /* 2. Redistributions in binary form must reproduce the above copyright */ /* notice, this list of conditions and the following disclaimer in */ /* the documentation and/or other materials provided with the */ /* distribution. */ /* */ /* 3. Neither the name of the copyright holder nor the names of its */ /* contributors may be used to endorse or promote products derived */ /* from this software without specific prior written permission. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */ /* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */ /* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS */ /* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE */ /* COPYRIGHT 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. */ /* */ /******************************************************************************/ /******************************************************************************/ /* */ /* ODYSSEUS/OOSQL DB-IR-Spatial Tightly-Integrated DBMS */ /* Version 5.0 */ /* */ /* Developed by Professor Kyu-Young Whang et al. */ /* */ /* Advanced Information Technology Research Center (AITrc) */ /* Korea Advanced Institute of Science and Technology (KAIST) */ /* */ /* e-mail: odysseus.oosql@gmail.com */ /* */ /* Bibliography: */ /* [1] Whang, K., Lee, J., Lee, M., Han, W., Kim, M., and Kim, J., "DB-IR */ /* Integration Using Tight-Coupling in the Odysseus DBMS," World Wide */ /* Web, Vol. 18, No. 3, pp. 491-520, May 2015. */ /* [2] Whang, K., Lee, M., Lee, J., Kim, M., and Han, W., "Odysseus: a */ /* High-Performance ORDBMS Tightly-Coupled with IR Features," In Proc. */ /* IEEE 21st Int'l Conf. on Data Engineering (ICDE), pp. 1104-1105 */ /* (demo), Tokyo, Japan, April 5-8, 2005. This paper received the Best */ /* Demonstration Award. */ /* [3] Whang, K., Park, B., Han, W., and Lee, Y., "An Inverted Index */ /* Storage Structure Using Subindexes and Large Objects for Tight */ /* Coupling of Information Retrieval with Database Management */ /* Systems," U.S. Patent No.6,349,308 (2002) (Appl. No. 09/250,487 */ /* (1999)). */ /* [4] Whang, K., Lee, J., Kim, M., Lee, M., Lee, K., Han, W., and Kim, */ /* J., "Tightly-Coupled Spatial Database Features in the */ /* Odysseus/OpenGIS DBMS for High-Performance," GeoInformatica, */ /* Vol. 14, No. 4, pp. 425-446, Oct. 2010. */ /* [5] Whang, K., Lee, J., Kim, M., Lee, M., and Lee, K., "Odysseus: a */ /* High-Performance ORDBMS Tightly-Coupled with Spatial Database */ /* Features," In Proc. 23rd IEEE Int'l Conf. on Data Engineering */ /* (ICDE), pp. 1493-1494 (demo), Istanbul, Turkey, Apr. 16-20, 2007. */ /* */ /******************************************************************************/ #ifndef _OOSQL_STORAGEMANAGER_H_ #define _OOSQL_STORAGEMANAGER_H_ #include "OOSQL_StorageSystemHeaders.h" #include "OOSQL_Common.h" #include "OOSQL_MemoryManager.hxx" #include "OOSQL_MemoryManagedObject.hxx" #include "OOSQL_APIs_Internal.hxx" #include "OOSQL_Error.h" // constant definition #ifndef CMP_EQ #define CMP_EQ 0 // equal #endif #ifndef CMP_GT #define CMP_GT 1 // greater than #endif #ifndef CMP_LT #define CMP_LT 2 // less than #endif #ifndef CMP_NE #define CMP_NE 3 // not equal #endif #ifndef CMP_UN #define CMP_UN 4 // unknown #endif #ifndef KEYINFO_COL_ORDER #define KEYINFO_COL_ORDER 3 #endif #ifndef KEYINFO_COL_ASC #define KEYINFO_COL_ASC 2 #endif #ifndef KEYINFO_COL_DESC #define KEYINFO_COL_DESC 1 #endif #ifndef MBR_NUM_PARTS #define MBR_NUM_PARTS 4 #endif #ifndef MAXNUMKEYPARTS #define MAXNUMKEYPARTS 8 #endif #ifndef MAXKEYLEN #define MAXKEYLEN 256 #endif #ifndef MLGF_MAXNUM_KEYS #define MLGF_MAXNUM_KEYS 32 #endif #ifndef MAXATTRNAME #define MAXATTRNAME 250 #endif #ifndef MAXCLASSNAME #define MAXCLASSNAME 250 #endif #ifndef MAXDIRPATH #define MAXDIRPATH 256 #endif #ifndef MAXMETHODNAME #define MAXMETHODNAME 246 #endif #ifndef MAXFUNCTIONNAME #define MAXFUNCTIONNAME 246 #endif #ifndef MAXPROCEDURENAME #define MAXPROCEDURENAME 246 #endif #ifndef MAXNARGUMENT #define MAXNARGUMENT 60 #endif #ifndef MAXINDEXNAME #define MAXINDEXNAME 250 #endif #ifndef MAX_NUM_KEYS #define MAX_NUM_KEYS 32 #endif #ifndef ALL_VALUE #define ALL_VALUE -1 #endif #ifndef NIL #define NIL -1 #endif #ifndef MAXKEYWORDSIZE #define MAXKEYWORDSIZE 128 #endif #ifndef FORWARD #define FORWARD 0 #endif #ifndef BACKWARD #define BACKWARD 1 #endif #ifndef BACKWARD_NOORDERING #define BACKWARD_NOORDERING 2 #endif #ifndef BACKWARD_ORDERING #define BACKWARD_ORDERING 3 #endif #ifndef EOS #define EOS 1 #endif #ifndef SM_COMPLEXTYPE_BASIC #define SM_COMPLEXTYPE_BASIC 0 #endif #ifndef SM_COMPLEXTYPE_SET #define SM_COMPLEXTYPE_SET 1 #endif #ifndef SM_COMPLEXTYPE_COLLECTIONSET #define SM_COMPLEXTYPE_COLLECTIONSET 3 #endif #ifndef SM_COMPLEXTYPE_COLLECTIONBAG #define SM_COMPLEXTYPE_COLLECTIONBAG 4 #endif #ifndef SM_COMPLEXTYPE_COLLECTIONLIST #define SM_COMPLEXTYPE_COLLECTIONLIST 5 #endif #ifndef LOM_COMPLEXTYPE_BASIC #define LOM_COMPLEXTYPE_BASIC 0 #endif #ifndef LOM_COMPLEXTYPE_SET #define LOM_COMPLEXTYPE_SET 1 #endif #ifndef LOM_COMPLEXTYPE_COLLECTIONSET #define LOM_COMPLEXTYPE_COLLECTIONSET 3 #endif #ifndef LOM_COMPLEXTYPE_COLLECTIONBAG #define LOM_COMPLEXTYPE_COLLECTIONBAG 4 #endif #ifndef LOM_COMPLEXTYPE_COLLECTIONLIST #define LOM_COMPLEXTYPE_COLLECTIONLIST 5 #endif #ifndef LOM_COMPLEXTYPE_ODMG_COLLECTIONSET #define LOM_COMPLEXTYPE_ODMG_COLLECTIONSET 6 #endif #ifndef LOM_COMPLEXTYPE_ODMG_COLLECTIONBAG #define LOM_COMPLEXTYPE_ODMG_COLLECTIONBAG 7 #endif #ifndef LOM_COMPLEXTYPE_ODMG_COLLECTIONLIST #define LOM_COMPLEXTYPE_ODMG_COLLECTIONLIST 8 #endif #ifndef LOM_COMPLEXTYPE_ODMG_COLLECTIONARRARY #define LOM_COMPLEXTYPE_ODMG_COLLECTIONARRAY 9 #endif #ifndef OOSQL_COMPLEXTYPE_SET #define OOSQL_COMPLEXTYPE_SET LOM_COMPLEXTYPE_COLLECTIONSET #endif #ifndef OOSQL_COMPLEXTYPE_BAG #define OOSQL_COMPLEXTYPE_BAG LOM_COMPLEXTYPE_COLLECTIONBAG #endif #ifndef OOSQL_COMPLEXTYPE_LIST #define OOSQL_COMPLEXTYPE_LIST LOM_COMPLEXTYPE_COLLECTIONLIST #endif #ifndef OOSQL_COMPLEXTYPE_ODMG_SET #define OOSQL_COMPLEXTYPE_ODMG_SET LOM_COMPLEXTYPE_ODMG_COLLECTIONSET #endif #ifndef OOSQL_COMPLEXTYPE_ODMG_BAG #define OOSQL_COMPLEXTYPE_ODMG_BAG LOM_COMPLEXTYPE_ODMG_COLLECTIONBAG #endif #ifndef OOSQL_COMPLEXTYPE_ODMG_LIST #define OOSQL_COMPLEXTYPE_ODMG_LIST LOM_COMPLEXTYPE_ODMG_COLLECTIONLIST #endif #ifndef OOSQL_COMPLEXTYPE_ODMG_ARRAY #define OOSQL_COMPLEXTYPE_ODMG_ARRAY LOM_COMPLEXTYPE_ODMG_COLLECTIONARRAY #endif #ifndef MAXSUPERCLASSID #define MAXSUPERCLASSID 60 #endif #ifndef MAXNUMOFATTRIBUTE #define MAXNUMOFATTRIBUTE LOM_MAXNUMOFATTRIBUTE #endif #ifndef SM_INDEXTYPE_BTREE #define SM_INDEXTYPE_BTREE 1 #endif #ifndef SM_INDEXTYPE_MLGF #define SM_INDEXTYPE_MLGF 2 #endif #ifndef KEYFLAG_UNIQUE #define KEYFLAG_UNIQUE 1 #endif #ifndef KEYFLAG_CLUSTERING #define KEYFLAG_CLUSTERING 2 #endif #ifndef SORTKEYDESC_ATTR_ORDER #define SORTKEYDESC_ATTR_ORDER 3 // attribute ORDER mask */ #endif #ifndef SORTKEYDESC_ATTR_ASC #define SORTKEYDESC_ATTR_ASC 2 // ascending order */ #endif #ifndef SORTKEYDESC_ATTR_DESC #define SORTKEYDESC_ATTR_DESC 1 // descending order * #endif #ifndef KEYWORD #define KEYWORD 0 #endif #ifndef REVERSEKEYWORD #define REVERSEKEYWORD 1 #endif /* GEOM region query spatial operators */ #ifndef GEO_SPATIAL_INTERSECT #define GEO_SPATIAL_INTERSECT 1 #endif #ifndef GEO_SPATIAL_CONTAIN #define GEO_SPATIAL_CONTAIN 2 #endif #ifndef GEO_SPATIAL_CONTAINED #define GEO_SPATIAL_CONTAINED 4 #endif #ifndef GEO_SPATIAL_EQUAL #define GEO_SPATIAL_EQUAL 8 #endif #ifndef GEO_SPATIAL_DISJOINT #define GEO_SPATIAL_DISJOINT 16 #endif #ifndef GEO_SPATIAL_NORTH #define GEO_SPATIAL_NORTH 32 #endif #ifndef GEO_SPATIAL_SOUTH #define GEO_SPATIAL_SOUTH 64 #endif #ifndef GEO_SPATIAL_EAST #define GEO_SPATIAL_EAST 128 #endif #ifndef GEO_SPATIAL_WEST #define GEO_SPATIAL_WEST 256 #endif #ifndef GEO_SPATIAL_KNN #define GEO_SPATIAL_KNN 512 #endif #ifndef MAX_NUM_EMBEDDEDATTRIBUTES #define MAX_NUM_EMBEDDEDATTRIBUTES 24 #endif #if !defined(SLIMDOWN_OPENGIS) && !defined(_GEO_INTERNAL_H_) typedef LOM_Handle GEO_Handle; #endif class OOSQL_StorageManager : public OOSQL_MemoryManagedObject { public: // Interface Type Definition typedef Four PageNo; typedef Two VolNo; typedef VolNo VolID; typedef UFour Unique; typedef Two SlotNo; typedef UFour_Invariable MLGF_HashValue; typedef One Octet; typedef UFour_Invariable Date; typedef double Interval; typedef Four ClassID; typedef enum {SM_EQ=0x1, SM_LT=0x2, SM_LE=0x3, SM_GT=0x4, SM_GE=0x5, SM_NE=0x6, SM_EOF=0x10, SM_BOF=0x20} CompOp; struct MBR { Four_Invariable values[MBR_NUM_PARTS]; }; struct Time { short _tzHour; short _tzMinute; short _Hour; short _Minute; short _Second; short _100thSec; }; struct Timestamp { Date d; Time t; }; enum TimeZone { GMT = 0, GMT12 = 12, GMT_12 = -12, GMT1 = 1, GMT_1 = -1, GMT2 = 2, GMT_2 = -2, GMT3 = 3, GMT_3 = -3, GMT4 = 4, GMT_4 = -4, GMT5 = 5, GMT_5 = -5, GMT6 = 6, GMT_6 = -6, GMT7 = 7, GMT_7 = -7, GMT8 = 8, GMT_8 = -8, GMT9 = 9, GMT_9 = -9, GMT10 = 10, GMT_10= -10, GMT11 = 11, GMT_11= -11, USeastern = -5, UScentral = -6, USmoutain = -7, USpacific = -8 }; // ID definition struct PageID { PageNo pageNo; // a PageNo VolNo volNo; // a VolNo }; struct ObjectID { // ObjectID is used accross the volumes PageNo pageNo; // specify the page holding the object VolID volNo; // specify the volume in which object is in SlotNo slotNo; // specify the slot within the page Unique unique; // Unique No for checking dangling object }; typedef ObjectID TupleID; struct OID { // OID is used accross the volumes PageNo pageNo; // specify the page holding the object VolID volNo; // specify the volume in which object is in SlotNo slotNo; // specify the slot within the page Unique unique; // Unique No for checking dangling object ClassID classID; // specify the class including the object }; typedef Four Serial; typedef struct { Serial serial; /* a logical serial number */ VolNo volNo; /* a VolNo */ } LogicalID; typedef LogicalID FileID; typedef LogicalID PsyicalIndexID; typedef TupleID LogicalIndexID; struct IndexID { Boolean isLogical; union { PsyicalIndexID physical_iid; LogicalIndexID logical_iid; }index; }; struct XactID { UFour high; UFour low; }; // Key struct BTreeKeyInfo { Two flag; // UNIQUE, ... Two nColumns; // # of key parts struct { Four colNo; Four flag; // ascending/descendig } columns[MAXNUMKEYPARTS]; }; struct MLGF_KeyInfo { Two flag; // CLUSTERING, ... */ Two nColumns; // # of columns on which the index is defined */ Two colNo[MLGF_MAXNUM_KEYS];// column numbers */ Two extraDataLen; // length of the extra data for an object */ }; struct KeyValue { Two len; char val[MAXKEYLEN]; }; // Cursor Type Defineition struct AnyCursor { One opaque; // opaque member TupleID tid; // object pointed by the cursor }; struct DataCursor { One opaque; // opaque member TupleID tid; // object pointed by the cursor }; struct BtreeCursor { One opaque; // opaque member TupleID tid; // object pointed by the cursor KeyValue key; // what key value? }; struct MLGF_Cursor { One opaque; // opaque member TupleID tid; // object pointed by the cursor MLGF_HashValue keys[MLGF_MAXNUM_KEYS]; // what key values? }; union Cursor{ AnyCursor any; // for access of 'flag' and 'oid' DataCursor seq; // sequential scan BtreeCursor btree; // scan using a B+ tree MLGF_Cursor mlgf; // scan using MLGF index }; // Index Desc struct IndexDesc { One indexType; union { BTreeKeyInfo btree; // Key Information for Btree MLGF_KeyInfo mlgf; // Key Information for MLGF } kinfo; }; typedef struct { Two type; /* types supported by COSMOS */ Two offset; /* where ? */ Two length; /* how ? */ } KeyPart; typedef struct { Two flag; /* flag for some more informations */ Two nparts; /* the number of key parts */ KeyPart kpart[MAXNUMKEYPARTS]; /* key parts */ } KeyDesc; typedef struct { One flag; /* flag */ One nKeys; /* number of keys */ Two extraDataLen; /* length of the extra data for an object */ UFour minMaxTypeVector; /* bit vector of flags indicating MIN/MAX of MBR for each attribute */ } MLGF_KeyDesc; typedef struct { Boolean isContainingTupleID; Boolean isContainingSentenceAndWordNum; Boolean isContainingByteOffset; Two nEmbeddedAttributes; Two embeddedAttrNo[MAX_NUM_EMBEDDEDATTRIBUTES]; Two embeddedAttrOffset[MAX_NUM_EMBEDDEDATTRIBUTES]; Two embeddedAttrVarColNo[MAX_NUM_EMBEDDEDATTRIBUTES]; } InMemory_PostingStructureInfo; typedef struct { PsyicalIndexID keywordIndex; /* btree index on keyword attribute of inverted index table */ PsyicalIndexID reverseKeywordIndex; /* SM_TEXT index on reverse-keyword attribtue of inverted index table */ PsyicalIndexID docIdIndex; /* SM_TEXT index on document id of document-id index table */ char invertedIndexName[MAXINDEXNAME]; char docIdIndexTableName[MAXINDEXNAME]; InMemory_PostingStructureInfo postingInfo; } InvertedIndexDesc; // AttrInfo struct AttrInfo { Two complexType; // data type of column Two type; // Attribute type Four length; // Attribute length ,for maximum length of STRING char name[MAXATTRNAME]; // Attribute name Four inheritedFrom; // super class ID Four domain; // domain of this attribute Four offset; // offset of attribute }; // MethodInfo struct MethodInfo { char dirPath[MAXDIRPATH]; // path where this method is implemented char name[MAXMETHODNAME]; // Method name char functionName[MAXFUNCTIONNAME]; // c function name Two nArguments; // # of arguments Four ArgumentsList[MAXNARGUMENT]; // list of arguments Four inheritedFrom; Four returnType; }; // ColListStruct struct ColListStruct { Two colNo; // IN column number Boolean nullFlag; // INOUT is it NULL ? Four start; // IN starting offset within a column, ALL_VALUE: read all data of this column Four length; // IN amount of old data within a column Four dataLength; // IN amount of new data union { Boolean b; Octet o; Two_Invariable s; UTwo_Invariable us; Four_Invariable i; Four_Invariable l; UFour_Invariable ul; Eight_Invariable ll; float f; double d; PageID pid; FileID fid; PsyicalIndexID iid; OID oid; MBR mbr; Date date; Time time; Timestamp timestamp; Interval interval; void* ptr; } data; Four retLength; // OUT return length of Read/Write */ }; struct ColLengthInfoListStruct { Two colNo; Four length; }; struct BoundCond { KeyValue key; // Key Value CompOp op; // The key value is included? }; struct BoolExp { Two op; // operator : EQUAL, LESS, etc Two colNo; // which column ? Two length; // length of the value: used for SM_VARSTRING union { Two s; int i; Four l; float f; double d; PageID pid; FileID fid; PsyicalIndexID iid; OID oid; MBR mbr; /* add date, time, timestamp */ Date date; Time time; Timestamp timestamp; char str[MAXKEYLEN]; } data; // the value to be compared }; struct TextDesc { One isIndexed; One hasBeenIndexed; TupleID contentTid; Four size; }; struct TextColStruct { Four start; // IN starting offset within a column, ALL_VALUE: read all data of this column Four length; // IN amount of old data within a column Four dataLength; // IN amount of new data Four indexMode; void* data; // pointer to data: SM_STRING, SM_VARSTRING Four retLength; // OUT return length of Read/Write }; struct EmbeddedAttrInfo { Four type; Four start; Four length; }; struct EmbeddedAttrTranslationInfo { Four nEmbeddedAttributes; EmbeddedAttrInfo embeddedAttrInfo[MAX_NUM_EMBEDDEDATTRIBUTES]; Two realColNoToEmbeddedColNo[LOM_MAXNUMOFATTRIBUTE]; Two embeddedAttrVarColNo[MAX_NUM_EMBEDDEDATTRIBUTES]; Four embeddedAttributeOffset; Four nVarCols; }; typedef enum { L_NL, L_IS, L_IX, L_S, L_SIX, L_X } LockMode; // lock mode typedef enum { L_INSTANT, L_MANUAL, L_COMMIT } LockDuration; // lock duration struct LockParameter { LockMode mode; LockDuration duration; }; typedef double PostingWeight; struct Point{ float x, y; }; struct Region{ float x1, y1, x2, y2; }; enum {NONSPATIAL_CLASSTYPE, POINT_CLASSTYPE, LINESEG_CLASSTYPE, POLYGON_CLASSTYPE, POLYLINE_CLASSTYPE}; enum {DEFERRED_MODE, IMMEDIATE_MODE}; typedef struct { Boolean isContainingTupleID; Boolean isContainingSentenceAndWordNum; Boolean isContainingByteOffset; Two nEmbeddedAttributes; Two embeddedAttrNo[MAX_NUM_EMBEDDEDATTRIBUTES]; } PostingStructureInfo; typedef TupleID CounterID; typedef struct { Two nparts; /* # of key parts */ Two hdrSize; /* size of header in front of sorted tuple */ struct { Four type; /* part's type */ Four length; /* part's length */ Four flag; /* ascending/descendig = SORTKEYDESC_ATTR_ASC/SORTKEYDESC_ATTR_DESC */ } parts[MAXNUMKEYPARTS]; } SortTupleDesc; typedef struct { Two len; char* data; } SortStreamTuple; public: // Interface OOSQL_StorageManager(OOSQL_SystemHandle* oosqlSystemHandle) { m_oosqlSystemHandle = oosqlSystemHandle; } virtual ~OOSQL_StorageManager() {} // Class Interface virtual Four AlterClass(Four volId, char* className, Four nAddCol, AttrInfo* addColInfo, Four nDropCol, AttrInfo* dropColInfo) { return 0; } virtual Four CreateSequence(Four volId, char* seqName, Four startWith) { return 0; } virtual Four CheckSequence(Four volId, char* seqName) { return 0; } virtual Four DropSequence(Four volId, char* seqName) { return 0; } virtual Four SetSeqVal(Four volId, char* seqName, Four value) { return 0; } virtual Four GetSeqCurrVal(Four volId, char* seqName, Four *currValue) { return 0; } virtual Four GetSeqNextVal(Four volId, char* seqName, Four *nextValue) { return 0; } virtual Four CreateClass(Four volId, char* className, char *indexName, IndexDesc* indexDesc, Four nAttrs, AttrInfo* attrInfo, Four nSuperClasses, char (*superClasses)[MAXCLASSNAME], Four nMethods, MethodInfo* methodInfo, Boolean isTempClass, Four * classId) { return 0; } virtual Four DestroyClass(Four volId,char* className) { return 0; } virtual Four OpenClass(Four volId, char* className) { return 0; } virtual Four OpenClass(Four volId, Four classId) { return 0; } virtual Four CloseClass(Four ocn) { return 0; } virtual Four GetOpenClassNum(Four volId, char* className) { return 0; } virtual Four GetOpenClassNum(Four volId, Four classId) { return 0; } virtual Four GetClassID(Four volId, char* className, Four* classId) { return 0; } // Transaction virtual Four TransBegin(XactID* xctId, ConcurrencyLevel ccLevel) { return 0; } virtual Four TransCommit(XactID* xctId) { return 0; } virtual Four TransAbort(XactID* xctId) { return 0; } // Mount & Dismount virtual Four Mount(Four numDevices, char** deviceNames, Four* volumeId) { return 0; } virtual Four Dismount(Four volumeId) { return 0; } // Object Manipulation virtual Four NextObject(Four scanId, OID* oid, Cursor **cursor) { return 0; } virtual Four DestroyObject(Four ocnOrScanId, Boolean useScanFlag, OID* oid) { return 0; } virtual Four DeferredDestroyObject(Four ocnOrScanId, Boolean useScanFlag, OID* oid) { return 0; } virtual Four CreateObjectByColList(Four ocnOrScanId, Boolean useScanFlag, Four nCols, ColListStruct* clist, OID* oid) { return 0; } virtual Four FetchObjectByColList(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Four nCols, ColListStruct* clist) { return 0; } virtual Four UpdateObjectByColList(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Four nCols, ColListStruct* clist) { return 0; } virtual Four FetchColLength(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Four nCols, ColLengthInfoListStruct* clengthlist) { return 0; } // Relationship virtual Four Relationship_Create(Four volId, char *relationshipName, Four fromClassId, Two fromAttrNum, Four toClassId, Two toAttrNum, One cardinality, One direction, Four* relationshipId) { return 0; } virtual Four Relationship_Destroy(Four volId, char *relationshipName) { return 0; } virtual Four Relationship_CreateInstance(Four fromOcnOrScanId, Boolean fromUseScanFlag, Four toOcnOrScanId, Boolean toUseScanFlag, Four relationshipId, OID* fromOid, OID* toOid) { return 0; } virtual Four Relationship_DestroyInstance(Four fromOcnOrScanId, Boolean fromUseScanFlag, Four toOcnOrScanId, Boolean toUseScanFlag, Four relationshipId, OID* fromOid, OID* toOid) { return 0; } virtual Four Relationship_OpenScan(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Four relationshipId) { return 0; } virtual Four Relationship_CloseScan(Four relationshipScanId) { return 0; } virtual Four Relationship_NextInstance(Four relationshipScanId, Four nOIDs, OID* oids) { return 0; } virtual Four Relationship_GetId(Four volId, char* relationshipName, Four* relationshipId) { return 0; } // Error Message virtual char *Err(Four errorCode) { return 0; } // Scan virtual Four CloseScan(Four scanId) { return 0; } virtual Four OpenIndexScan(Four ocn, IndexID* iid, BoundCond* startBound, BoundCond* stopBound, Four nBools, BoolExp* bools, LockParameter* lockup) { return 0; } virtual Four OpenSeqScan(Four ocn, Four scanDirection, Four nBools, BoolExp* bools, LockParameter* lockup) { return 0; } virtual Four OpenNearestObjQueryScan(Four ocn, IndexID *iid, Point queryPoint, Four nBools, BoolExp* bools, LockParameter *lockup) { return 0; } virtual Four OpenPointQueryScan(Four ocn, IndexID *iid, Point queryPoint, Four nBools, BoolExp* bools, LockParameter *lockup) { return 0; } virtual Four OpenRegionQueryScan(Four ocn, IndexID *iid, Region queryRegion, Four spatialOp, Four nBools, BoolExp* bools, LockParameter *lockup) { return 0; } virtual Four OpenMBRqueryScan(Four ocn, IndexID *iid, Region queryRegion, Four spatialOp, Four nBools, BoolExp* bools, LockParameter *lockup, IndexID* tidJoinIndexID = 0, BoundCond* tidJoinIndexStartBound = 0, BoundCond* tidJoinIndexStopBound = 0) { return 0; } virtual Four OpenMlgfIndexScan(Four ocn, IndexID* iid, MLGF_HashValue lowerBounds[], MLGF_HashValue upperBounds[], Four nBools, BoolExp* bools, LockParameter* lockup) { return 0; } // Index virtual Four AddIndex(Four volId, char *className, char *indexName, IndexDesc *indexDesc, IndexID *indexID) { return 0; } virtual Four DropIndex(Four volId, char *indexName) { return 0; } // Text Interface virtual Four Text_CreateContent(Four ocnOrScanId, Boolean useScanFlag, OID *oid, Two colNum, TextColStruct *text, TextDesc *textDesc) { return 0; } virtual Four Text_GetDescriptor(Four ocnOrScanId, Boolean useScanFlag, OID *oid, Two colNo, TextDesc *textDesc) { return 0; } virtual Four Text_DestroyContent(Four ocnOrScanId, Boolean useScanFlag, OID *oid, Two colNo, TextDesc *textDesc) { return 0; } virtual Four Text_FetchContent(Four ocnOrScanId, Boolean useScanFlag, OID *oid, Two colNo, TextColStruct *text, TextDesc *textDesc) { return 0; } virtual Four Text_UpdateContent(Four ocnOrScanId, Boolean useScanFlag, OID *oid, Two colNo, TextColStruct *text, TextDesc *textDesc) { return 0; } virtual Four Text_GetNPostingsOfCurrentKeyword(Four textScan, Four *nPostings) { return 0; } virtual Four Text_OpenIndexScan(Four ocn, IndexID *indexId, Four keywordKind, BoundCond *keywordStartBound, BoundCond *keywordStopBound, LockParameter *lockup) { return 0; } virtual Four Text_OpenIndexScan_GivenInvertedEntryTupleID(Four ocn, Two colNo, TupleID* invertedTableEntryTupleID, LockParameter* lockup) { return 0; } virtual Four Text_Scan_Open(Four ocn, OID *oid, Two colNo, Four keywordKind, BoundCond *keywordStartBound, BoundCond *keywordStopBound, LockParameter *lockup) { return 0; } virtual Four Text_Scan_Close(Four osn) { return 0; } virtual Four Text_GetNPostings(Four ocn, IndexID *indexId, Four keywordKind, BoundCond *keywordStartBound, BoundCond *keywordStopBound, LockParameter *lockup, Four *nPostings) { return 0; } virtual Four Text_Scan_NextPosting(Four textScan, Four bufferLength, char *postingBuffer, Four *requiredSize, PostingWeight *weight) { return 0; } #ifndef COMPRESSION virtual Four Text_NextPostings(Four textScan, Four postingLengthBufferSize, char *postingLengthBuffer, Four postingBufferSize, char *postingBuffer, Four scanDirection, Four logicalIdHints, Four *nReturnedPosting, Four *requiredSize) { return 0; } #else virtual Four Text_NextPostings(Four textScan, Four postingLengthBufferSize, char *postingLengthBuffer, Four postingBufferSize, char *postingBuffer, Four scanDirection, Four logicalIdHints, Four *nReturnedPosting, Four *requiredSize, VolNo *volNoOfPostingTupleID, Four *lastDocId) { return 0; } #endif virtual Four Text_GetCursorKeyword(Four textScan, char *keyword) { return 0; } virtual Four Text_MakeIndex(Four volId, Four temporaryVolId, char *className) { return 0; } virtual Four Text_BatchInvertedIndexBuild(Four volId, Four temporaryVolId, char *className) { return 0; } virtual Four Text_DefinePostingStructure(Four volId, char *className, char *attrName, PostingStructureInfo *postingInfo) { return 0; } virtual Four Text_GetLogicalId(Four ocnOrScanId, Boolean useScanFlag, OID* oid) { return 0; } virtual Four Text_GetStemizerFPtr(Four ocn, Two colNo, void** stemizerFPtr) { return 0; } virtual Four Text_GetOIDFromLogicalDocId(Four ocn, Four logicalId, OID* oid) { return 0; } virtual Four Text_GetNumOfTextObjectsInClass(Four ocn, Four* nObjects) { return 0; } // Misc Text Interface virtual Four GetEmbeddedAttrTranslationInfo(Four textScanId, EmbeddedAttrTranslationInfo* embeddedAttrTranslationInfo) { return 0; } virtual Four GetEmbeddedAttrsVal(Four textScanId, char *ptrToEmbeddedAttrsBuf, Four embeddedAttrSize, Four nCols, ColListStruct *clist) { return 0; } // Time Related virtual TimeZone GetLocalTimeZone() { return GMT; } virtual void SetCurTime(Time *_time, TimeZone tz) {} virtual unsigned short GetHour(Time *time) { return 0; } virtual unsigned short GetMinute(Time *time) { return 0; } virtual unsigned short GetSecond(Time *time) { return 0; } virtual long GetJulDay(unsigned short m, unsigned short d, unsigned short y) { return 0; } virtual void GetGregorianDate(Date *date, unsigned short *mm, unsigned short *dd, unsigned short *yy) {} virtual void SetCurDate(Date *date) {} virtual void SetDate(unsigned short year, unsigned short month, unsigned short day, Date *date) {} virtual int CompareDate(Date *date1, Date *date2) { return 0; } virtual int CompareTime(Time *time1, Time *time2) { return 0; } virtual int CompareTimestamp(Timestamp* timestamp1, Timestamp* timestamp2) { return 0; } virtual unsigned short GetYear(Date *date) { return 0; } virtual unsigned short GetMonth(Date *date) { return 0; } virtual unsigned short GetDay(Date *date) { return 0; } // Sort Interface virtual Four SortRelation(Four volId, Four temporaryVolId, char *inRelName, BTreeKeyInfo *kinfo, Boolean newRelFlag, char *outRelName, Boolean tmpRelFlag, LockParameter *lockup) { return 0; } // Collection Interface virtual Four CollectionSet_Create(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four keySize) { return 0; } virtual Four CollectionSet_Destroy(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo) { return 0; } virtual Four CollectionSet_AssignElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four nElements, Four* elementSizes, void* elements) { return 0; } virtual Four CollectionSet_Assign(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four assignedOrnOrScanId, Boolean assignedUseScanFlag, OID* assignedOid, Four assignedColNo) { return 0; } virtual Four CollectionSet_GetN_Elements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four* nElements) { return 0; } virtual Four CollectionSet_InsertElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four nElements, Four* elementSizes, void* elements) { return 0; } virtual Four CollectionSet_DeleteElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four nElements, Four* elementSizes, void* elements) { return 0; } virtual Four CollectionSet_DeleteAll(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo) { return 0; } virtual Four CollectionSet_IsMember(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four elementSize, void* element) { return 0; } virtual Four CollectionSet_IsNull(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo) { return 0; } virtual Four CollectionSet_IsEqual(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four comparedOrnOrScanId, Boolean comparedUseScanFlag, OID* comparedOid, Four comparedColNo) { return 0; } virtual Four CollectionSet_IsSubset(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four comparedOrnOrScanId, Boolean comparedUseScanFlag, OID* comparedOid, Four comparedColNo) { return 0; } virtual Four CollectionSet_GetSizeOfElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four ith, Four nElements, Four* elementsSize) { return 0; } virtual Four CollectionSet_RetrieveElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four ith, Four nElements, Four* elementSizes, Four sizeOfElements, void* elements) { return 0; } virtual Four CollectionSet_Union(Four ornOrScanIdA, Boolean useScanFlagA, OID* oidA, Four colNoA, Four ornOrScanIdB, Boolean useScanFlagB, OID* oidB, Four colNoB, Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo) { return 0; } virtual Four CollectionSet_Intersect(Four ornOrScanIdA, Boolean useScanFlagA, OID* oidA, Four colNoA, Four ornOrScanIdB, Boolean useScanFlagB, OID* oidB, Four colNoB, Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo) { return 0; } virtual Four CollectionSet_Difference(Four ornOrScanIdA, Boolean useScanFlagA, OID* oidA, Four colNoA, Four ornOrScanIdB, Boolean useScanFlagB, OID* oidB, Four colNoB, Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo) { return 0; } virtual Four CollectionSet_UnionWith(Four ornOrScanIdA, Boolean useScanFlagA, OID* oidA, Four colNoA, Four ornOrScanIdB, Boolean useScanFlagB, OID* oidB, Four colNoB) { return 0; } virtual Four CollectionSet_IntersectWith(Four ornOrScanIdA, Boolean useScanFlagA, OID* oidA, Four colNoA, Four ornOrScanIdB, Boolean useScanFlagB, OID* oidB, Four colNoB) { return 0; } virtual Four CollectionSet_DifferenceWith(Four ornOrScanIdA, Boolean useScanFlagA, OID* oidA, Four colNoA, Four ornOrScanIdB, Boolean useScanFlagB, OID* oidB, Four colNoB) { return 0; } virtual Four CollectionSet_Scan_Open(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo) { return 0; } virtual Four CollectionSet_Scan_Close(Four CollectionScanId) { return 0; } virtual Four CollectionSet_Scan_NextElements(Four CollectionScanId, Four nElements, Four* elementSizes, Four sizeOfElements, void* elements) { return 0; } virtual Four CollectionSet_Scan_GetSizeOfNextElements(Four CollectionScanId, Four nElements, Four* elementsSize) { return 0; } virtual Four CollectionSet_Scan_InsertElements(Four CollectionScanId, Four nElements, Four* elementSizes, void* elements) { return 0; } virtual Four CollectionSet_Scan_DeleteElements(Four CollectionScanId) { return 0; } virtual Four CollectionBag_Create(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four keySize) { return 0; } virtual Four CollectionBag_Destroy(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo) { return 0; } virtual Four CollectionBag_AssignElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four nElements, Four* elementSizes, void* elements) { return 0; } virtual Four CollectionBag_Assign(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four assignedOrnOrScanId, Boolean assignedUseScanFlag, OID* assignedOid, Four assignedColNo) { return 0; } virtual Four CollectionBag_GetN_Elements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four* nElements) { return 0; } virtual Four CollectionBag_InsertElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four nElements, Four* elementSizes, void* elements) { return 0; } virtual Four CollectionBag_DeleteElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four nElements, Four* elementSizes, void* elements) { return 0; } virtual Four CollectionBag_DeleteAll(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo) { return 0; } virtual Four CollectionBag_IsMember(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four elementSize, void* element) { return 0; } virtual Four CollectionBag_IsNull(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo) { return 0; } virtual Four CollectionBag_IsEqual(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four comparedOrnOrScanId, Boolean comparedUseScanFlag, OID* comparedOid, Four comparedColNo) { return 0; } virtual Four CollectionBag_IsSubset(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four comparedOrnOrScanId, Boolean comparedUseScanFlag, OID* comparedOid, Four comparedColNo) { return 0; } virtual Four CollectionBag_GetSizeOfElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four ith, Four nElements, Four* elementsSize) { return 0; } virtual Four CollectionBag_RetrieveElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four ith, Four nElements, Four* elementSizes, Four sizeOfElements, void* elements) { return 0; } virtual Four CollectionBag_Union(Four ornOrScanIdA, Boolean useScanFlagA, OID* oidA, Four colNoA, Four ornOrScanIdB, Boolean useScanFlagB, OID* oidB, Four colNoB, Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo) { return 0; } virtual Four CollectionBag_Intersect(Four ornOrScanIdA, Boolean useScanFlagA, OID* oidA, Four colNoA, Four ornOrScanIdB, Boolean useScanFlagB, OID* oidB, Four colNoB, Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo) { return 0; } virtual Four CollectionBag_Difference(Four ornOrScanIdA, Boolean useScanFlagA, OID* oidA, Four colNoA, Four ornOrScanIdB, Boolean useScanFlagB, OID* oidB, Four colNoB, Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo) { return 0; } virtual Four CollectionBag_UnionWith(Four ornOrScanIdA, Boolean useScanFlagA, OID* oidA, Four colNoA, Four ornOrScanIdB, Boolean useScanFlagB, OID* oidB, Four colNoB) { return 0; } virtual Four CollectionBag_IntersectWith(Four ornOrScanIdA, Boolean useScanFlagA, OID* oidA, Four colNoA, Four ornOrScanIdB, Boolean useScanFlagB, OID* oidB, Four colNoB) { return 0; } virtual Four CollectionBag_DifferenceWith(Four ornOrScanIdA, Boolean useScanFlagA, OID* oidA, Four colNoA, Four ornOrScanIdB, Boolean useScanFlagB, OID* oidB, Four colNoB) { return 0; } virtual Four CollectionBag_Scan_Open(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo) { return 0; } virtual Four CollectionBag_Scan_Close(Four CollectionScanId) { return 0; } virtual Four CollectionBag_Scan_NextElements(Four CollectionScanId, Four nElements, Four* elementSizes, Four sizeOfElements, void* elements) { return 0; } virtual Four CollectionBag_Scan_GetSizeOfNextElements(Four CollectionScanId, Four nElements, Four* elementsSize) { return 0; } virtual Four CollectionBag_Scan_InsertElements(Four CollectionScanId, Four nElements, Four* elementSizes, void* elements) { return 0; } virtual Four CollectionBag_Scan_DeleteElements(Four CollectionScanId) { return 0; } virtual Four CollectionList_Create(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo) { return 0; } virtual Four CollectionList_Destroy(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo) { return 0; } virtual Four CollectionList_GetN_Elements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four* nElements) { return 0; } virtual Four CollectionList_AssignElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four nElements, Four* elementSizes, void* elements) { return 0; } virtual Four CollectionList_Assign(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four assignedOrnOrScanId, Boolean assignedUseScanFlag, OID* assignedOid, Four assignedColNo) { return 0; } virtual Four CollectionList_InsertElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four ith, Four nElements, Four* elementSizes, void* elements) { return 0; } virtual Four CollectionList_DeleteElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four ith, Four nElements) { return 0; } virtual Four CollectionList_DeleteAll(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo) { return 0; } virtual Four CollectionList_AppendElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four nElements, Four* elementSizes, void* elements) { return 0; } virtual Four CollectionList_GetSizeOfElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four ith, Four nElements, Four* elementsSize) { return 0; } virtual Four CollectionList_RetrieveElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four ith, Four nElements, Four* elementSizes, Four sizeOfElements, void* elements) { return 0; } virtual Four CollectionList_UpdateElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four ith, Four nElements, Four* elementSizes, void* elements) { return 0; } virtual Four CollectionList_Concatenate(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four concatnatedOrnOrScanId, Boolean concatnatedUseScanFlag, OID* concatnatedOid, Four concatnatedColNo) { return 0; } virtual Four CollectionList_Resize(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four size) { return 0; } virtual Four CollectionList_IsMember(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four elementSize, void* element, Four* pos) { return 0; } virtual Four CollectionList_IsNull(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo) { return 0; } virtual Four CollectionList_IsEqual(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four comparedOrnOrScanId, Boolean comparedUseScanFlag, OID* comparedOid, Four comparedColNo) { return 0; } virtual Four CollectionList_Scan_Open(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo) { return 0; } virtual Four CollectionList_Scan_Close(Four CollectionScanId) { return 0; } virtual Four CollectionList_Scan_NextElements(Four CollectionScanId, Four nElements, Four* elementSizes, Four sizeOfElements, void* elements) { return 0; } virtual Four CollectionList_Scan_GetSizeOfNextElements(Four CollectionScanId, Four nElements, Four* elementsSize) { return 0; } virtual Four CollectionList_Scan_InsertElements(Four CollectionScanId, Four nElements, Four* elementSizes, void* elements) { return 0; } virtual Four CollectionList_Scan_DeleteElements(Four CollectionScanId) { return 0; } virtual Four Geometry_GetMBR(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Four colNo, float* xmin, float* ymin, float* xmax, float* ymax) { return 0; } virtual Four Geometry_GetMBR(char* data, Four length, float* xmin, float* ymin, float* xmax, float* ymax) { return 0; } // Member Functions of Predefined Class virtual Four PDC_Contain(Four ocnOrScanIdA, Boolean useScanFlagA, OID* oidA, Four ocnOrScanIdB, Boolean useScanFlagB, OID* oidB) { return 0; } virtual Four PDC_Contained(Four ocnOrScanIdA, Boolean useScanFlagA, OID* oidA, Four ocnOrScanIdB, Boolean useScanFlagB, OID* oidB) { return 0; } virtual Four PDC_Cover(Four ocnOrScanIdA, Boolean useScanFlagA, OID* oidA, Four ocnOrScanIdB, Boolean useScanFlagB, OID* oidB) { return 0; } virtual Four PDC_Covered(Four ocnOrScanIdA, Boolean useScanFlagA, OID* oidA, Four ocnOrScanIdB, Boolean useScanFlagB, OID* oidB) { return 0; } virtual Four PDC_Intersect(Four ocnOrScanIdA, Boolean useScanFlagA, OID* oidA, Four ocnOrScanIdB, Boolean useScanFlagB, OID* oidB) { return 0; } virtual Four PDC_Meet(Four ocnOrScanIdA, Boolean useScanFlagA, OID* oidA, Four ocnOrScanIdB, Boolean useScanFlagB, OID* oidB) { return 0; } virtual Four PDC_Equal(Four ocnOrScanIdA, Boolean useScanFlagA, OID* oidA, Four ocnOrScanIdB, Boolean useScanFlagB, OID* oidB) { return 0; } virtual Four PDC_Disjoint(Four ocnOrScanIdA, Boolean useScanFlagA, OID* oidA, Four ocnOrScanIdB, Boolean useScanFlagB, OID* oidB) { return 0; } virtual Four PDC_East(Four ocnOrScanIdA, Boolean useScanFlagA, OID* oidA, Four ocnOrScanIdB, Boolean useScanFlagB, OID* oidB) { return 0; } virtual Four PDC_West(Four ocnOrScanIdA, Boolean useScanFlagA, OID* oidA, Four ocnOrScanIdB, Boolean useScanFlagB, OID* oidB) { return 0; } virtual Four PDC_North(Four ocnOrScanIdA, Boolean useScanFlagA, OID* oidA, Four ocnOrScanIdB, Boolean useScanFlagB, OID* oidB) { return 0; } virtual Four PDC_South(Four ocnOrScanIdA, Boolean useScanFlagA, OID* oidA, Four ocnOrScanIdB, Boolean useScanFlagB, OID* oidB) { return 0; } virtual Four PDC_Contain(Four classTypeA, Four nPointsA, Point* pointsA, Four classTypeB, Four nPointsB, Point* pointsB) { return 0; } virtual Four PDC_Contained(Four classTypeA, Four nPointsA, Point* pointsA, Four classTypeB, Four nPointsB, Point* pointsB) { return 0; } virtual Four PDC_Cover(Four classTypeA, Four nPointsA, Point* pointsA, Four classTypeB, Four nPointsB, Point* pointsB) { return 0; } virtual Four PDC_Covered(Four classTypeA, Four nPointsA, Point* pointsA, Four classTypeB, Four nPointsB, Point* pointsB) { return 0; } virtual Four PDC_Intersect(Four classTypeA, Four nPointsA, Point* pointsA, Four classTypeB, Four nPointsB, Point* pointsB) { return 0; } virtual Four PDC_Meet(Four classTypeA, Four nPointsA, Point* pointsA, Four classTypeB, Four nPointsB, Point* pointsB) { return 0; } virtual Four PDC_Equal(Four classTypeA, Four nPointsA, Point* pointsA, Four classTypeB, Four nPointsB, Point* pointsB) { return 0; } virtual Four PDC_Disjoint(Four classTypeA, Four nPointsA, Point* pointsA, Four classTypeB, Four nPointsB, Point* pointsB) { return 0; } virtual Four PDC_East(Four classTypeA, Four nPointsA, Point* pointsA, Four classTypeB, Four nPointsB, Point* pointsB) { return 0; } virtual Four PDC_West(Four classTypeA, Four nPointsA, Point* pointsA, Four classTypeB, Four nPointsB, Point* pointsB) { return 0; } virtual Four PDC_North(Four classTypeA, Four nPointsA, Point* pointsA, Four classTypeB, Four nPointsB, Point* pointsB) { return 0; } virtual Four PDC_South(Four classTypeA, Four nPointsA, Point* pointsA, Four classTypeB, Four nPointsB, Point* pointsB) { return 0; } virtual Four PDC_ContainRegion(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Region queryRegion) { return 0; } virtual Four PDC_ContainedInRegion(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Region queryRegion) { return 0; } virtual Four PDC_CoverRegion(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Region queryRegion) { return 0; } virtual Four PDC_CoveredInRegion(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Region queryRegion) { return 0; } virtual Four PDC_IntersectWithRegion(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Region queryRegion) { return 0; } virtual Four PDC_EqualWithRegion(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Region queryRegion) { return 0; } virtual Four PDC_MeetWithRegion(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Region queryRegion) { return 0; } virtual Four PDC_DisjointWithRegion(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Region queryRegion) { return 0; } virtual Four PDC_EastOfRegion(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Region queryRegion) { return 0; } virtual Four PDC_WestOfRegion(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Region queryRegion) { return 0; } virtual Four PDC_NorthOfRegion(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Region queryRegion) { return 0; } virtual Four PDC_SouthOfRegion(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Region queryRegion) { return 0; } virtual Four PDC_ContainPoint(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Point queryPoint) { return 0; } virtual Four PDC_CoverPoint(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Point queryPoint) { return 0; } virtual Four PDC_IntersectWithPoint(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Point queryPoint) { return 0; } virtual Four PDC_MeetWithPoint(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Point queryPoint) { return 0; } virtual Four PDC_DisjointWithPoint(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Point queryPoint) { return 0; } virtual Four PDC_EastOfPoint(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Point queryPoint) { return 0; } virtual Four PDC_WestOfPoint(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Point queryPoint) { return 0; } virtual Four PDC_NorthOfPoint(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Point queryPoint) { return 0; } virtual Four PDC_SouthOfPoint(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Point queryPoint) { return 0; } virtual Four PDC_GetPoints(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Four startPoint, Four nPoints, Point* points) { return 0; } virtual Four PDC_GetMBR(Four ocnOrScanId, Boolean useScanFlag, OID* oid, MBR* mbr) { return 0; } virtual Four PDC_Point_SetPoint(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Four x, Four y) { return 0; } virtual Four PDC_LineSeg_SetPoints(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Four x1, Four y1, Four x2, Four y2) { return 0; } virtual Four PDC_LineSeg_AddToPoly(Four lineOcnOrScanId, Boolean lineUseScanFlag, OID *line, Four polyOcnOrScanId, Boolean polyUseScanFlag, OID *poly) { return 0; } virtual Four PDC_LineSeg_DeleteFromPoly(Four lineOcnOrScanId, Boolean lineUseScanFlag, OID *line, Four polyOcnOrScanId, Boolean polyUseScanFlag, OID *poly) { return 0; } virtual Four PDC_Poly_AddLineSegs(Four polyOcnOrScanId, Boolean polyUseScanFlag, OID *poly, Four lineOcnOrScanId, Boolean lineUseScanFlag, Four nOIDs, OID *lineSeg) { return 0; } virtual Four PDC_Poly_DeleteLineSegs(Four polyOcnOrScanId, Boolean polyUseScanFlag, OID *poly, Four lineOcnOrScanId, Boolean lineUseScanFlag, Four nOIDs, OID *lineSeg) { return 0; } virtual Four PDC_GetDistance(Four classTypeA, Four nPointsA, Point* pointsA, Four classTypeB, Four nPointsB, Point* pointsB, double* distance) { return 0; } virtual Four PDC_GetDistance(Four ocnOrScanIdA, Boolean useScanFlagA, OID* oidA, Four ocnOrScanIdB, Boolean useScanFlagB, OID* oidB, double* distance) { return 0; } virtual Four PDC_GetDistanceWithPoint(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Point queryPoint, double* distance) { return 0; } virtual Four PDC_GetArea(Four classType, Four nPoints, Point* points, double* area) { return 0; } virtual Four PDC_GetArea(Four ocnOrScanId, Boolean useScanFlag, OID* oid, double* area) { return 0; } virtual Four PDC_GetLength(Four classType, Four nPoints, Point* points, double* area) { return 0; } virtual Four PDC_GetLength(Four ocnOrScanId, Boolean useScanFlag, OID* oid, double* area) { return 0; } // Utility Function static char* TYPE_TO_DOMAIN_NAME(Four typeId); static void OIDCLEAR(OID& a) { a.pageNo = 0, a.volNo = 0, a.slotNo = 0, a.classID = 0; } static int TESTOIDCLEARPTR(OID& a) { return a.pageNo == 0 && a.volNo == 0 && a.slotNo == 0 && a.classID == 0; } static void SetNilTupleID(TupleID& tid) { tid.pageNo = NIL; } static int DoesNoContentExistTextDesc(TextDesc &textDesc) { return textDesc.size == NIL; } static void MakeNullTextDesc(TextDesc& textDesc) { SetNilTupleID(textDesc.contentTid), textDesc.size = NIL, textDesc.isIndexed = SM_FALSE, textDesc.hasBeenIndexed = SM_FALSE; } static int OIDGT(OID& a, OID& b) { return (a.volNo > b.volNo || (a.volNo == b.volNo && a.pageNo > b.pageNo) || (a.volNo == b.volNo && a.pageNo == b.pageNo && a.slotNo > b.slotNo)); } static int OIDLT(OID& a, OID& b) { return (a.volNo < b.volNo || (a.volNo == b.volNo && a.pageNo < b.pageNo) || (a.volNo == b.volNo && a.pageNo == b.pageNo && a.slotNo < b.slotNo)); } static int OIDEQ(OID& a, OID& b) { return (a.unique == b.unique && a.classID == b.classID && a.pageNo == b.pageNo && a.volNo == b.volNo && a.slotNo == b.slotNo); } #if defined (EXTENDED_BOOLEAN_MODEL) static double CalculateWeight(double nPositions, double nPostings) { return nPositions / nPostings; } #elif defined (HEURISTIC_MODEL) static double CalculateWeight(double nPositions, double nPostingsPerObject) { return nPositions / nPostingsPerObject; } #endif OOSQL_SystemHandle* GetOOSQL_SystemHandle() { return m_oosqlSystemHandle; } virtual Four CreateCounter(Four volId, char *cntrName, Four initialValue, CounterID *cntrId) { return 0; } virtual Four DestroyCounter(Four volId, char *cntrName) { return 0; } virtual Four GetCounterId(Four volId, char *cntrName, CounterID *cntrId) { return 0; } virtual Four SetCounter(Four volId, CounterID *cntrId, Four value) { return 0; } virtual Four ReadCounter(Four volId, CounterID *cntrId, Four *value) { return 0; } virtual Four GetCounterValues(Four volId, CounterID *cntrId, Four nValues, Four *startValue) { return 0; } /* Sort stream functions */ virtual Four OpenSortStream(VolID, SortTupleDesc*) { return 0; } virtual Four CloseSortStream(Four) { return 0; } virtual Four SortingSortStream(Four) { return 0; } virtual Four PutTuplesIntoSortStream(Four, Four, SortStreamTuple*) { return 0; } virtual Four GetTuplesFromSortStream(Four, Four*, SortStreamTuple*, Boolean*) { return 0; } virtual Four OpenStream(VolID) { return 0; } virtual Four CloseStream(Four) { return 0; } virtual Four ChangePhaseStream(Four) { return 0; } virtual Four PutTuplesIntoStream(Four, Four, SortStreamTuple*) { return 0; } virtual Four GetTuplesFromStream(Four, Four*, SortStreamTuple*, Boolean*) { return 0; } protected: OOSQL_SystemHandle* m_oosqlSystemHandle; }; #undef OOSQL_TYPE_SHORT #undef OOSQL_TYPE_INT #undef OOSQL_TYPE_LONG #undef OOSQL_TYPE_LONG_LONG #undef OOSQL_TYPE_LONG_VAR #undef OOSQL_TYPE_FLOAT #undef OOSQL_TYPE_DOUBLE #undef OOSQL_TYPE_STRING #undef OOSQL_TYPE_VARSTRING #undef OOSQL_TYPE_PAGEID #undef OOSQL_TYPE_FILEID #undef OOSQL_TYPE_INDEXID #undef OOSQL_TYPE_OID #undef OOSQL_TYPE_MBR #undef OOSQL_TYPE_TEXT #undef OOSQL_TYPE_DATE #undef OOSQL_TYPE_TIME #undef OOSQL_TYPE_TIMESTAMP #undef OOSQL_TYPE_INTERVAL #define OOSQL_TYPE_SHORT 0 #define OOSQL_TYPE_INT 1 #define OOSQL_TYPE_LONG 2 #define OOSQL_TYPE_LONG_LONG 14 #define OOSQL_TYPE_FLOAT 3 #define OOSQL_TYPE_DOUBLE 4 #define OOSQL_TYPE_STRING 5 #define OOSQL_TYPE_VARSTRING 6 #define OOSQL_TYPE_PAGEID 7 #define OOSQL_TYPE_FILEID 8 #define OOSQL_TYPE_INDEXID 9 #define OOSQL_TYPE_OID 10 #define OOSQL_TYPE_MBR 12 #define OOSQL_TYPE_TEXT 39 #define OOSQL_TYPE_DATE 50 #define OOSQL_TYPE_TIME 51 #define OOSQL_TYPE_TIMESTAMP 52 #define OOSQL_TYPE_INTERVAL 53 #define OOSQL_TYPE_BOOL 100 #undef OOSQL_TYPE_SHORT_SIZE #undef OOSQL_TYPE_INT_SIZE #undef OOSQL_TYPE_LONG_SIZE #undef OOSQL_TYPE_LONG_SIZE_VAR #undef OOSQL_TYPE_LONG_LONG_SIZE #undef OOSQL_TYPE_FLOAT_SIZE #undef OOSQL_TYPE_DOUBLE_SIZE #undef OOSQL_TYPE_STRING_SIZE #undef OOSQL_TYPE_VARSTRING_SIZE #undef OOSQL_TYPE_PAGEID_SIZE #undef OOSQL_TYPE_FILEID_SIZE #undef OOSQL_TYPE_INDEXID_SIZE #undef OOSQL_TYPE_OID_SIZE #undef OOSQL_TYPE_MBR_SIZE #undef OOSQL_TYPE_TEXT_SIZE #undef OOSQL_TYPE_DATE_SIZE #undef OOSQL_TYPE_TIME_SIZE #undef OOSQL_TYPE_TIMESTAMP_SIZE #undef OOSQL_TYPE_INTERVAL_SIZE #define OOSQL_TYPE_SHORT_SIZE sizeof(Two_Invariable) #define OOSQL_TYPE_INT_SIZE sizeof(Four_Invariable) #define OOSQL_TYPE_LONG_SIZE sizeof(Four_Invariable) #define OOSQL_TYPE_LONG_LONG_SIZE sizeof(Eight_Invariable) #ifndef SUPPORT_LARGE_DATABASE2 #define OOSQL_TYPE_LONG_VAR OOSQL_TYPE_LONG #define OOSQL_TYPE_LONG_SIZE_VAR OOSQL_TYPE_LONG_SIZE #else #define OOSQL_TYPE_LONG_VAR OOSQL_TYPE_LONG_LONG #define OOSQL_TYPE_LONG_SIZE_VAR OOSQL_TYPE_LONG_LONG_SIZE #endif #define OOSQL_TYPE_FLOAT_SIZE sizeof(float) #define OOSQL_TYPE_DOUBLE_SIZE sizeof(double) #define OOSQL_TYPE_STRING_SIZE 0 #define OOSQL_TYPE_VARSTRING_SIZE 0 #define OOSQL_TYPE_PAGEID_SIZE sizeof(OOSQL_StorageManager::PageID) #define OOSQL_TYPE_FILEID_SIZE sizeof(OOSQL_StorageManager::FileID) #define OOSQL_TYPE_INDEXID_SIZE sizeof(OOSQL_StorageManager::FileID) #define OOSQL_TYPE_OID_SIZE sizeof(OOSQL_StorageManager::OID) #define OOSQL_TYPE_MBR_SIZE sizeof(OOSQL_StorageManager::MBR) #define OOSQL_TYPE_TEXT_SIZE 0 #define OOSQL_TYPE_DATE_SIZE sizeof(OOSQL_StorageManager::Date) #define OOSQL_TYPE_TIME_SIZE sizeof(OOSQL_StorageManager::Time) #define OOSQL_TYPE_TIMESTAMP_SIZE sizeof(OOSQL_StorageManager::Timestamp) #define OOSQL_TYPE_INTERVAL_SIZE sizeof(OOSQL_StorageManager::Interval) #define OOSQL_TYPE_BOOL_SIZE sizeof(Boolean) enum ComplexTypeID { COMPLEXTYPEID_BASIC = OOSQL_COMPLEXTYPE_BASIC, COMPLEXTYPEID_SET = OOSQL_COMPLEXTYPE_SET, COMPLEXTYPEID_BAG = OOSQL_COMPLEXTYPE_BAG, COMPLEXTYPEID_LIST = OOSQL_COMPLEXTYPE_LIST, COMPLEXTYPEID_ODMG_SET = OOSQL_COMPLEXTYPE_ODMG_SET, COMPLEXTYPEID_ODMG_BAG = OOSQL_COMPLEXTYPE_ODMG_BAG, COMPLEXTYPEID_ODMG_LIST = OOSQL_COMPLEXTYPE_ODMG_LIST, COMPLEXTYPEID_ODMG_ARRAY = OOSQL_COMPLEXTYPE_ODMG_ARRAY }; enum TypeID { TYPEID_SHORT = 0, TYPEID_INT = 1, TYPEID_LONG = 2, TYPEID_LONG_LONG = 14, TYPEID_FLOAT = 3, TYPEID_DOUBLE = 4, TYPEID_STRING = 5, TYPEID_VARSTRING = 6, TYPEID_PAGEID = 7, TYPEID_FILEID = 8, TYPEID_INDEXID = 9, TYPEID_OID = 10, TYPEID_MBR = 12, TYPEID_STRUCTURE = 15, TYPEID_NIL, TYPEID_BOOL, TYPEID_ID, TYPEID_DOMAIN, TYPEID_NONE, TYPEID_NULL, TYPEID_COMPLEX, TYPEID_SET, TYPEID_BAG, TYPEID_LIST, TYPEID_ARRAY, TYPEID_TEXT = 39, TYPEID_DATE = 50, TYPEID_TIME = 51, TYPEID_TIMESTAMP = 52, TYPEID_INTERVAL = 53, TYPEID_OGIS_GEOMETRY = 128, TYPEID_OGIS_POINT = 129, TYPEID_OGIS_LINESTRING = 130, TYPEID_OGIS_POLYGON = 131, TYPEID_OGIS_GEOMETRYCOLLECTION = 132, TYPEID_OGIS_MULTIPOINT = 133, TYPEID_OGIS_MULTILINESTRING = 134, TYPEID_OGIS_MULTIPOLYGON = 135, TYPEID_SET_SHORT = (COMPLEXTYPEID_SET << 16) | TYPEID_SHORT, TYPEID_SET_INT = (COMPLEXTYPEID_SET << 16) | TYPEID_INT, TYPEID_SET_LONG = (COMPLEXTYPEID_SET << 16) | TYPEID_LONG, TYPEID_SET_LONG_LONG = (COMPLEXTYPEID_SET << 16) | TYPEID_LONG_LONG, TYPEID_SET_FLOAT = (COMPLEXTYPEID_SET << 16) | TYPEID_FLOAT, TYPEID_SET_DOUBLE = (COMPLEXTYPEID_SET << 16) | TYPEID_DOUBLE, TYPEID_SET_STRING = (COMPLEXTYPEID_SET << 16) | TYPEID_STRING, TYPEID_SET_VARSTRING = (COMPLEXTYPEID_SET << 16) | TYPEID_VARSTRING, TYPEID_SET_PAGEID = (COMPLEXTYPEID_SET << 16) | TYPEID_PAGEID, TYPEID_SET_FILEID = (COMPLEXTYPEID_SET << 16) | TYPEID_FILEID, TYPEID_SET_INDEXID = (COMPLEXTYPEID_SET << 16) | TYPEID_INDEXID, TYPEID_SET_OID = (COMPLEXTYPEID_SET << 16) | TYPEID_OID, TYPEID_SET_MBR = (COMPLEXTYPEID_SET << 16) | TYPEID_MBR, TYPEID_BAG_SHORT = (COMPLEXTYPEID_BAG << 16) | TYPEID_SHORT, TYPEID_BAG_INT = (COMPLEXTYPEID_BAG << 16) | TYPEID_INT, TYPEID_BAG_LONG = (COMPLEXTYPEID_BAG << 16) | TYPEID_LONG, TYPEID_BAG_LONG_LONG = (COMPLEXTYPEID_BAG << 16) | TYPEID_LONG_LONG, TYPEID_BAG_FLOAT = (COMPLEXTYPEID_BAG << 16) | TYPEID_FLOAT, TYPEID_BAG_DOUBLE = (COMPLEXTYPEID_BAG << 16) | TYPEID_DOUBLE, TYPEID_BAG_STRING = (COMPLEXTYPEID_BAG << 16) | TYPEID_STRING, TYPEID_BAG_VARSTRING = (COMPLEXTYPEID_BAG << 16) | TYPEID_VARSTRING, TYPEID_BAG_PAGEID = (COMPLEXTYPEID_BAG << 16) | TYPEID_PAGEID, TYPEID_BAG_FILEID = (COMPLEXTYPEID_BAG << 16) | TYPEID_FILEID, TYPEID_BAG_INDEXID = (COMPLEXTYPEID_BAG << 16) | TYPEID_INDEXID, TYPEID_BAG_OID = (COMPLEXTYPEID_BAG << 16) | TYPEID_OID, TYPEID_BAG_MBR = (COMPLEXTYPEID_BAG << 16) | TYPEID_MBR, TYPEID_LIST_SHORT = (COMPLEXTYPEID_LIST << 16) | TYPEID_SHORT, TYPEID_LIST_INT = (COMPLEXTYPEID_LIST << 16) | TYPEID_INT, TYPEID_LIST_LONG = (COMPLEXTYPEID_LIST << 16) | TYPEID_LONG, TYPEID_LIST_LONG_LONG = (COMPLEXTYPEID_LIST << 16) | TYPEID_LONG_LONG, TYPEID_LIST_FLOAT = (COMPLEXTYPEID_LIST << 16) | TYPEID_FLOAT, TYPEID_LIST_DOUBLE = (COMPLEXTYPEID_LIST << 16) | TYPEID_DOUBLE, TYPEID_LIST_STRING = (COMPLEXTYPEID_LIST << 16) | TYPEID_STRING, TYPEID_LIST_VARSTRING = (COMPLEXTYPEID_LIST << 16) | TYPEID_VARSTRING, TYPEID_LIST_PAGEID = (COMPLEXTYPEID_LIST << 16) | TYPEID_PAGEID, TYPEID_LIST_FILEID = (COMPLEXTYPEID_LIST << 16) | TYPEID_FILEID, TYPEID_LIST_INDEXID = (COMPLEXTYPEID_LIST << 16) | TYPEID_INDEXID, TYPEID_LIST_OID = (COMPLEXTYPEID_LIST << 16) | TYPEID_OID, TYPEID_LIST_MBR = (COMPLEXTYPEID_LIST << 16) | TYPEID_MBR, TYPEID_ODMG_SET_SHORT = (COMPLEXTYPEID_ODMG_SET << 16) | TYPEID_SHORT, TYPEID_ODMG_SET_INT = (COMPLEXTYPEID_ODMG_SET << 16) | TYPEID_INT, TYPEID_ODMG_SET_LONG = (COMPLEXTYPEID_ODMG_SET << 16) | TYPEID_LONG, TYPEID_ODMG_SET_LONG_LONG = (COMPLEXTYPEID_ODMG_SET << 16) | TYPEID_LONG_LONG, TYPEID_ODMG_SET_FLOAT = (COMPLEXTYPEID_ODMG_SET << 16) | TYPEID_FLOAT, TYPEID_ODMG_SET_DOUBLE = (COMPLEXTYPEID_ODMG_SET << 16) | TYPEID_DOUBLE, TYPEID_ODMG_SET_STRING = (COMPLEXTYPEID_ODMG_SET << 16) | TYPEID_STRING, TYPEID_ODMG_SET_VARSTRING = (COMPLEXTYPEID_ODMG_SET << 16) | TYPEID_VARSTRING, TYPEID_ODMG_SET_PAGEID = (COMPLEXTYPEID_ODMG_SET << 16) | TYPEID_PAGEID, TYPEID_ODMG_SET_FILEID = (COMPLEXTYPEID_ODMG_SET << 16) | TYPEID_FILEID, TYPEID_ODMG_SET_INDEXID = (COMPLEXTYPEID_ODMG_SET << 16) | TYPEID_INDEXID, TYPEID_ODMG_SET_OID = (COMPLEXTYPEID_ODMG_SET << 16) | TYPEID_OID, TYPEID_ODMG_SET_MBR = (COMPLEXTYPEID_ODMG_SET << 16) | TYPEID_MBR, TYPEID_ODMG_BAG_SHORT = (COMPLEXTYPEID_ODMG_BAG << 16) | TYPEID_SHORT, TYPEID_ODMG_BAG_INT = (COMPLEXTYPEID_ODMG_BAG << 16) | TYPEID_INT, TYPEID_ODMG_BAG_LONG = (COMPLEXTYPEID_ODMG_BAG << 16) | TYPEID_LONG, TYPEID_ODMG_BAG_LONG_LONG = (COMPLEXTYPEID_ODMG_BAG << 16) | TYPEID_LONG_LONG, TYPEID_ODMG_BAG_FLOAT = (COMPLEXTYPEID_ODMG_BAG << 16) | TYPEID_FLOAT, TYPEID_ODMG_BAG_DOUBLE = (COMPLEXTYPEID_ODMG_BAG << 16) | TYPEID_DOUBLE, TYPEID_ODMG_BAG_STRING = (COMPLEXTYPEID_ODMG_BAG << 16) | TYPEID_STRING, TYPEID_ODMG_BAG_VARSTRING = (COMPLEXTYPEID_ODMG_BAG << 16) | TYPEID_VARSTRING, TYPEID_ODMG_BAG_PAGEID = (COMPLEXTYPEID_ODMG_BAG << 16) | TYPEID_PAGEID, TYPEID_ODMG_BAG_FILEID = (COMPLEXTYPEID_ODMG_BAG << 16) | TYPEID_FILEID, TYPEID_ODMG_BAG_INDEXID = (COMPLEXTYPEID_ODMG_BAG << 16) | TYPEID_INDEXID, TYPEID_ODMG_BAG_OID = (COMPLEXTYPEID_ODMG_BAG << 16) | TYPEID_OID, TYPEID_ODMG_BAG_MBR = (COMPLEXTYPEID_ODMG_BAG << 16) | TYPEID_MBR, TYPEID_ODMG_LIST_SHORT = (COMPLEXTYPEID_ODMG_LIST << 16) | TYPEID_SHORT, TYPEID_ODMG_LIST_INT = (COMPLEXTYPEID_ODMG_LIST << 16) | TYPEID_INT, TYPEID_ODMG_LIST_LONG = (COMPLEXTYPEID_ODMG_LIST << 16) | TYPEID_LONG, TYPEID_ODMG_LIST_LONG_LONG = (COMPLEXTYPEID_ODMG_LIST << 16) | TYPEID_LONG_LONG, TYPEID_ODMG_LIST_FLOAT = (COMPLEXTYPEID_ODMG_LIST << 16) | TYPEID_FLOAT, TYPEID_ODMG_LIST_DOUBLE = (COMPLEXTYPEID_ODMG_LIST << 16) | TYPEID_DOUBLE, TYPEID_ODMG_LIST_STRING = (COMPLEXTYPEID_ODMG_LIST << 16) | TYPEID_STRING, TYPEID_ODMG_LIST_VARSTRING = (COMPLEXTYPEID_ODMG_LIST << 16) | TYPEID_VARSTRING, TYPEID_ODMG_LIST_PAGEID = (COMPLEXTYPEID_ODMG_LIST << 16) | TYPEID_PAGEID, TYPEID_ODMG_LIST_FILEID = (COMPLEXTYPEID_ODMG_LIST << 16) | TYPEID_FILEID, TYPEID_ODMG_LIST_INDEXID = (COMPLEXTYPEID_ODMG_LIST << 16) | TYPEID_INDEXID, TYPEID_ODMG_LIST_OID = (COMPLEXTYPEID_ODMG_LIST << 16) | TYPEID_OID, TYPEID_ODMG_LIST_MBR = (COMPLEXTYPEID_ODMG_LIST << 16) | TYPEID_MBR, TYPEID_ODMG_ARRAY_SHORT = (COMPLEXTYPEID_ODMG_ARRAY << 16) | TYPEID_SHORT, TYPEID_ODMG_ARRAY_INT = (COMPLEXTYPEID_ODMG_ARRAY << 16) | TYPEID_INT, TYPEID_ODMG_ARRAY_LONG = (COMPLEXTYPEID_ODMG_ARRAY << 16) | TYPEID_LONG, TYPEID_ODMG_ARRAY_LONG_LONG = (COMPLEXTYPEID_ODMG_ARRAY << 16) | TYPEID_LONG_LONG, TYPEID_ODMG_ARRAY_FLOAT = (COMPLEXTYPEID_ODMG_ARRAY << 16) | TYPEID_FLOAT, TYPEID_ODMG_ARRAY_DOUBLE = (COMPLEXTYPEID_ODMG_ARRAY << 16) | TYPEID_DOUBLE, TYPEID_ODMG_ARRAY_STRING = (COMPLEXTYPEID_ODMG_ARRAY << 16) | TYPEID_STRING, TYPEID_ODMG_ARRAY_VARSTRING = (COMPLEXTYPEID_ODMG_ARRAY << 16) | TYPEID_VARSTRING, TYPEID_ODMG_ARRAY_PAGEID = (COMPLEXTYPEID_ODMG_ARRAY << 16) | TYPEID_PAGEID, TYPEID_ODMG_ARRAY_FILEID = (COMPLEXTYPEID_ODMG_ARRAY << 16) | TYPEID_FILEID, TYPEID_ODMG_ARRAY_INDEXID = (COMPLEXTYPEID_ODMG_ARRAY << 16) | TYPEID_INDEXID, TYPEID_ODMG_ARRAY_OID = (COMPLEXTYPEID_ODMG_ARRAY << 16) | TYPEID_OID, TYPEID_ODMG_ARRAY_MBR = (COMPLEXTYPEID_ODMG_ARRAY << 16) | TYPEID_MBR }; #define TYPEID_NONE_SIZE 0 #define TYPEID_NULL_SIZE 0 #define TYPEID_SHORT_SIZE sizeof(Two_Invariable) #define TYPEID_INT_SIZE sizeof(Four_Invariable) #define TYPEID_LONG_SIZE sizeof(Four_Invariable) #define TYPEID_LONG_LONG_SIZE sizeof(Eight_Invariable) #define TYPEID_FLOAT_SIZE sizeof(float) #define TYPEID_DOUBLE_SIZE sizeof(double) #define TYPEID_STRING_SIZE 0 // variable #define TYPEID_VARSTRING_SIZE 0 // variable #define TYPEID_SET_SIZE 0 // variable #define TYPEID_BAG_SIZE 0 // variable #define TYPEID_LIST_SIZE 0 // variable #define TYPEID_ARRAY_SIZE 0 // variable #define TYPEID_DATE_SIZE sizeof(OOSQL_StorageManager::Date) #define TYPEID_TIME_SIZE sizeof(OOSQL_StorageManager::Time) #define TYPEID_TIMESTAMP_SIZE sizeof(OOSQL_StorageManager::Timestamp) #define TYPEID_INTERVAL_SIZE sizeof(OOSQL_StorageManager::Interval) #define TYPEID_STRUCTURE_SIZE 0 // variable #define TYPEID_OID_SIZE sizeof(OOSQL_StorageManager::OID) #define TYPEID_NIL_SIZE 0 #define TYPEID_BOOL_SIZE 4 #define TYPEID_MBR_SIZE sizeof(OOSQL_StorageManager::MBR); #define TYPEID_ID_SIZE 0 #define TYPEID_DOMAIN_SIZE 0 #define TYPEID_TEXT_SIZE 0 // variable #define TYPEID_PAGEID_SIZE sizeof(OOSQL_StorageManager::PageID) #define TYPEID_FILEID_SIZE sizeof(OOSQL_StorageManager::FileID) #define TYPEID_INDEXID_SIZE sizeof(OOSQL_StorageManager::FileID) #define TYPEID_OGIS_GEOMETRY_SIZE 0 #define TYPEID_OGIS_POINT_SIZE 0 #define TYPEID_OGIS_LINESTRING_SIZE 0 #define TYPEID_OGIS_POLYGON_SIZE 0 #define TYPEID_OGIS_GEOMETRYCOLLECTION_SIZE 0 #define TYPEID_OGIS_MULTIPOINT_SIZE 0 #define TYPEID_OGIS_MULTILINESTRING_SIZE 0 #define TYPEID_OGIS_MULTIPOLYGON_SIZE 0 #define OOSQL_COMPOSE_TYPE(x, y) (TypeID)(((UFour_Invariable)(x) << 16) | (y)) #define OOSQL_MASK_COMPLEXTYPE(x) (ComplexTypeID)(0xffff & ((UFour_Invariable)(x) >> 16)) #define OOSQL_MASK_TYPE(x) (TypeID)(0xffff & (UFour_Invariable)(x)) #ifndef SUPPORT_LARGE_DATABASE2 #define TYPEID_SHORT_VAR TYPEID_SHORT #define TYPEID_SHORT_SIZE_VAR TYPEID_SHORT_SIZE #define TYPEID_LONG_VAR TYPEID_LONG #define TYPEID_LONG_SIZE_VAR TYPEID_LONG_SIZE #else #define TYPEID_SHORT_VAR TYPEID_LONG #define TYPEID_SHORT_SIZE_VAR TYPEID_LONG_SIZE #define TYPEID_LONG_VAR TYPEID_LONG_LONG #define TYPEID_LONG_SIZE_VAR TYPEID_LONG_LONG_SIZE #endif class OOSQL_StorageManagerLOM : public OOSQL_StorageManager { public: OOSQL_StorageManagerLOM(OOSQL_SystemHandle* oosqlSystemHandle, LOM_Handle* systemHandle); ~OOSQL_StorageManagerLOM(); // Class Interface Four AlterClass(Four volId, char* className, Four nAddCol, AttrInfo* addColInfo, Four nDropCol, AttrInfo* dropColInfo); Four CreateSequence(Four volId, char* seqName, Four startWith); Four CheckSequence(Four volId, char* seqName); Four DropSequence(Four volId, char* seqName); Four SetSeqVal(Four volId, char* seqName, Four value); Four GetSeqCurrVal(Four volId, char* seqName, Four *currValue); Four GetSeqNextVal(Four volId, char* seqName, Four *nextValue); Four CreateClass(Four volId, char* className, char *indexName, IndexDesc* indexDesc, Four nAttrs, AttrInfo* attrInfo, Four nSuperClasses, char (*superClasses)[MAXCLASSNAME], Four nMethods, MethodInfo* methodInfo, Boolean isTempClass, Four * classId); Four DestroyClass(Four volId,char* className); Four OpenClass(Four volId, char* className); Four OpenClass(Four volId, Four classId); Four GetOpenClassNum(Four volId, char* className); Four GetOpenClassNum(Four volId, Four classId); Four CloseClass(Four ocn); Four GetClassID(Four volId, char* className, Four* classId); // Transaction Four TransBegin(XactID* xctId, ConcurrencyLevel ccLevel); Four TransCommit(XactID* xctId); Four TransAbort(XactID* xctId); // Mount & Dismount Four Mount(Four numDevices, char** deviceNames, Four* volumeId); Four Dismount(Four volumeId); // Object Manipulation Four NextObject(Four scanId, OID* oid, Cursor **cursor); Four DestroyObject(Four ocnOrScanId, Boolean useScanFlag, OID* oid); Four DeferredDestroyObject(Four ocnOrScanId, Boolean useScanFlag, OID* oid); Four CreateObjectByColList(Four ocnOrScanId, Boolean useScanFlag, Four nCols, ColListStruct* clist, OID* oid); Four FetchObjectByColList(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Four nCols, ColListStruct* clist); Four UpdateObjectByColList(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Four nCols, ColListStruct* clist); Four FetchColLength(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Four nCols, ColLengthInfoListStruct* clengthlist); // Relationship Four Relationship_Create(Four volId, char *relationshipName, Four fromClassId, Two fromAttrNum, Four toClassId, Two toAttrNum, One cardinality, One direction, Four* relationshipId); Four Relationship_Destroy(Four volId, char *relationshipName); Four Relationship_CreateInstance(Four fromOcnOrScanId, Boolean fromUseScanFlag, Four toOcnOrScanId, Boolean toUseScanFlag, Four relationshipId, OID* fromOid, OID* toOid); Four Relationship_DestroyInstance(Four fromOcnOrScanId, Boolean fromUseScanFlag, Four toOcnOrScanId, Boolean toUseScanFlag, Four relationshipId, OID* fromOid, OID* toOid); Four Relationship_OpenScan(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Four relationshipId); Four Relationship_CloseScan(Four relationshipScanId); Four Relationship_NextInstance(Four relationshipScanId, Four nOIDs, OID* oids); Four Relationship_GetId(Four volId, char* relationshipName, Four* relationshipId); // Error Message char *Err(Four errorCode); // Scan Four CloseScan(Four scanId); Four OpenIndexScan(Four ocn, IndexID* iid, BoundCond* startBound, BoundCond* stopBound, Four nBools, BoolExp* bools, LockParameter* lockup); Four OpenSeqScan(Four ocn, Four scanDirection, Four nBools, BoolExp* bools, LockParameter* lockup); Four OpenMlgfIndexScan(Four ocn, IndexID* iid, MLGF_HashValue lowerBounds[], MLGF_HashValue upperBounds[], Four nBools, BoolExp* bools, LockParameter* lockup); // Index Four AddIndex(Four volId, char *className, char *indexName, IndexDesc *indexDesc, IndexID *indexID); Four DropIndex(Four volId, char *indexName); // Text Interface Four Text_CreateContent(Four ocnOrScanId, Boolean useScanFlag, OID *oid, Two colNum, TextColStruct *text, TextDesc *textDesc); Four Text_GetDescriptor(Four ocnOrScanId, Boolean useScanFlag, OID *oid, Two colNo, TextDesc *textDesc); Four Text_DestroyContent(Four ocnOrScanId, Boolean useScanFlag, OID *oid, Two colNo, TextDesc *textDesc); Four Text_FetchContent(Four ocnOrScanId, Boolean useScanFlag, OID *oid, Two colNo, TextColStruct *text, TextDesc *textDesc); Four Text_UpdateContent(Four ocnOrScanId, Boolean useScanFlag, OID *oid, Two colNo, TextColStruct *text, TextDesc *textDesc); Four Text_GetNPostingsOfCurrentKeyword(Four textScan, Four *nPostings); Four Text_OpenIndexScan(Four ocn, IndexID *indexId, Four keywordKind, BoundCond *keywordStartBound, BoundCond *keywordStopBound, LockParameter *lockup); Four Text_OpenIndexScan_GivenInvertedEntryTupleID(Four ocn, Two colNo, TupleID* invertedTableEntryTupleID, LockParameter* lockup); Four Text_Scan_Open(Four ocn, OID *oid, Two colNo, Four keywordKind, BoundCond *keywordStartBound, BoundCond *keywordStopBound, LockParameter *lockup); Four Text_Scan_Close(Four osn); Four Text_GetNPostings(Four ocn, IndexID *indexId, Four keywordKind, BoundCond *keywordStartBound, BoundCond *keywordStopBound, LockParameter *lockup, Four *nPostings); Four Text_Scan_NextPosting(Four textScan, Four bufferLength, char *postingBuffer, Four *requiredSize, PostingWeight *weight); #ifndef COMPRESSION Four Text_NextPostings(Four textScan, Four postingLengthBufferSize, char *postingLengthBuffer, Four postingBufferSize, char *postingBuffer, Four scanDirection, Four logicalIdHints, Four *nReturnedPosting, Four *requiredSize); #else Four Text_NextPostings(Four textScan, Four postingLengthBufferSize, char *postingLengthBuffer, Four postingBufferSize, char *postingBuffer, Four scanDirection, Four logicalIdHints, Four *nReturnedPosting, Four *requiredSize, VolNo *volNoOfPostingTupleID, Four* lastDocId); #endif Four Text_GetCursorKeyword(Four textScan, char *keyword); Four Text_MakeIndex(Four volId, Four temporaryVolId, char *className); Four Text_BatchInvertedIndexBuild(Four volId, Four temporaryVolId, char *className); Four Text_DefinePostingStructure(Four volId, char *className, char *attrName, PostingStructureInfo *postingInfo); Four Text_GetLogicalId(Four ocnOrScanId, Boolean useScanFlag, OID* oid); Four Text_GetStemizerFPtr(Four ocn, Two colNo, void** stemizerFPtr); Four Text_GetOIDFromLogicalDocId(Four ocn, Four logicalId, OID* oid); Four Text_GetNumOfTextObjectsInClass(Four ocn, Four* nObjects); // Misc Text Interface Four GetEmbeddedAttrTranslationInfo(Four textScanId, EmbeddedAttrTranslationInfo* embeddedAttrTranslationInfo); Four GetEmbeddedAttrsVal(Four textScanId, char *ptrToEmbeddedAttrsBuf, Four embeddedAttrSize, Four nCols, ColListStruct *clist); // Sort Interface Four SortRelation(Four volId, Four temporaryVolId, char *inRelName, BTreeKeyInfo *kinfo, Boolean newRelFlag, char *outRelName, Boolean tmpRelFlag, LockParameter *lockup); // Collection Interface Four CollectionSet_Create(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four keySize); Four CollectionSet_Destroy(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo); Four CollectionSet_AssignElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four nElements, Four* elementSizes, void* elements); Four CollectionSet_Assign(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four assignedOrnOrScanId, Boolean assignedUseScanFlag, OID* assignedOid, Four assignedColNo); Four CollectionSet_GetN_Elements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four* nElements); Four CollectionSet_InsertElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four nElements, Four* elementSizes, void* elements); Four CollectionSet_DeleteElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four nElements, Four* elementSizes, void* elements); Four CollectionSet_DeleteAll(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo); Four CollectionSet_IsMember(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four elementSize, void* element); Four CollectionSet_IsNull(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo); Four CollectionSet_IsEqual(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four comparedOrnOrScanId, Boolean comparedUseScanFlag, OID* comparedOid, Four comparedColNo); Four CollectionSet_IsSubset(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four comparedOrnOrScanId, Boolean comparedUseScanFlag, OID* comparedOid, Four comparedColNo); Four CollectionSet_GetSizeOfElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four ith, Four nElements, Four* elementsSize); Four CollectionSet_RetrieveElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four ith, Four nElements, Four* elementSizes, Four sizeOfElements, void* elements); Four CollectionSet_Union(Four ornOrScanIdA, Boolean useScanFlagA, OID* oidA, Four colNoA, Four ornOrScanIdB, Boolean useScanFlagB, OID* oidB, Four colNoB, Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo); Four CollectionSet_Intersect(Four ornOrScanIdA, Boolean useScanFlagA, OID* oidA, Four colNoA, Four ornOrScanIdB, Boolean useScanFlagB, OID* oidB, Four colNoB, Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo); Four CollectionSet_Difference(Four ornOrScanIdA, Boolean useScanFlagA, OID* oidA, Four colNoA, Four ornOrScanIdB, Boolean useScanFlagB, OID* oidB, Four colNoB, Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo); Four CollectionSet_UnionWith(Four ornOrScanIdA, Boolean useScanFlagA, OID* oidA, Four colNoA, Four ornOrScanIdB, Boolean useScanFlagB, OID* oidB, Four colNoB); Four CollectionSet_IntersectWith(Four ornOrScanIdA, Boolean useScanFlagA, OID* oidA, Four colNoA, Four ornOrScanIdB, Boolean useScanFlagB, OID* oidB, Four colNoB); Four CollectionSet_DifferenceWith(Four ornOrScanIdA, Boolean useScanFlagA, OID* oidA, Four colNoA, Four ornOrScanIdB, Boolean useScanFlagB, OID* oidB, Four colNoB); Four CollectionSet_Scan_Open(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo); Four CollectionSet_Scan_Close(Four CollectionScanId); Four CollectionSet_Scan_NextElements(Four CollectionScanId, Four nElements, Four* elementSizes, Four sizeOfElements, void* elements); Four CollectionSet_Scan_GetSizeOfNextElements(Four CollectionScanId, Four nElements, Four* elementsSize); Four CollectionSet_Scan_InsertElements(Four CollectionScanId, Four nElements, Four* elementSizes, void* elements); Four CollectionSet_Scan_DeleteElements(Four CollectionScanId); Four CollectionBag_Create(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four keySize); Four CollectionBag_Destroy(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo); Four CollectionBag_AssignElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four nElements, Four* elementSizes, void* elements); Four CollectionBag_Assign(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four assignedOrnOrScanId, Boolean assignedUseScanFlag, OID* assignedOid, Four assignedColNo); Four CollectionBag_GetN_Elements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four* nElements); Four CollectionBag_InsertElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four nElements, Four* elementSizes, void* elements); Four CollectionBag_DeleteElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four nElements, Four* elementSizes, void* elements); Four CollectionBag_DeleteAll(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo); Four CollectionBag_IsMember(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four elementSize, void* element); Four CollectionBag_IsNull(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo); Four CollectionBag_IsEqual(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four comparedOrnOrScanId, Boolean comparedUseScanFlag, OID* comparedOid, Four comparedColNo); Four CollectionBag_IsSubset(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four comparedOrnOrScanId, Boolean comparedUseScanFlag, OID* comparedOid, Four comparedColNo); Four CollectionBag_GetSizeOfElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four ith, Four nElements, Four* elementsSize); Four CollectionBag_RetrieveElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four ith, Four nElements, Four* elementSizes, Four sizeOfElements, void* elements); Four CollectionBag_Union(Four ornOrScanIdA, Boolean useScanFlagA, OID* oidA, Four colNoA, Four ornOrScanIdB, Boolean useScanFlagB, OID* oidB, Four colNoB, Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo); Four CollectionBag_Intersect(Four ornOrScanIdA, Boolean useScanFlagA, OID* oidA, Four colNoA, Four ornOrScanIdB, Boolean useScanFlagB, OID* oidB, Four colNoB, Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo); Four CollectionBag_Difference(Four ornOrScanIdA, Boolean useScanFlagA, OID* oidA, Four colNoA, Four ornOrScanIdB, Boolean useScanFlagB, OID* oidB, Four colNoB, Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo); Four CollectionBag_UnionWith(Four ornOrScanIdA, Boolean useScanFlagA, OID* oidA, Four colNoA, Four ornOrScanIdB, Boolean useScanFlagB, OID* oidB, Four colNoB); Four CollectionBag_IntersectWith(Four ornOrScanIdA, Boolean useScanFlagA, OID* oidA, Four colNoA, Four ornOrScanIdB, Boolean useScanFlagB, OID* oidB, Four colNoB); Four CollectionBag_DifferenceWith(Four ornOrScanIdA, Boolean useScanFlagA, OID* oidA, Four colNoA, Four ornOrScanIdB, Boolean useScanFlagB, OID* oidB, Four colNoB); Four CollectionBag_Scan_Open(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo); Four CollectionBag_Scan_Close(Four CollectionScanId); Four CollectionBag_Scan_NextElements(Four CollectionScanId, Four nElements, Four* elementSizes, Four sizeOfElements, void* elements); Four CollectionBag_Scan_GetSizeOfNextElements(Four CollectionScanId, Four nElements, Four* elementsSize); Four CollectionBag_Scan_InsertElements(Four CollectionScanId, Four nElements, Four* elementSizes, void* elements); Four CollectionBag_Scan_DeleteElements(Four CollectionScanId); Four CollectionList_Create(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo); Four CollectionList_Destroy(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo); Four CollectionList_GetN_Elements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four* nElements); Four CollectionList_AssignElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four nElements, Four* elementSizes, void* elements); Four CollectionList_Assign(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four assignedOrnOrScanId, Boolean assignedUseScanFlag, OID* assignedOid, Four assignedColNo); Four CollectionList_InsertElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four ith, Four nElements, Four* elementSizes, void* elements); Four CollectionList_DeleteElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four ith, Four nElements); Four CollectionList_DeleteAll(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo); Four CollectionList_AppendElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four nElements, Four* elementSizes, void* elements); Four CollectionList_GetSizeOfElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four ith, Four nElements, Four* elementsSize); Four CollectionList_RetrieveElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four ith, Four nElements, Four* elementSizes, Four sizeOfElements, void* elements); Four CollectionList_UpdateElements(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four ith, Four nElements, Four* elementSizes, void* elements); Four CollectionList_Concatenate(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four concatnatedOrnOrScanId, Boolean concatnatedUseScanFlag, OID* concatnatedOid, Four concatnatedColNo); Four CollectionList_Resize(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four size); Four CollectionList_IsMember(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four elementSize, void* element, Four* pos); Four CollectionList_IsNull(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo); Four CollectionList_IsEqual(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo, Four comparedOrnOrScanId, Boolean comparedUseScanFlag, OID* comparedOid, Four comparedColNo); Four CollectionList_Scan_Open(Four ornOrScanId, Boolean useScanFlag, OID* oid, Four colNo); Four CollectionList_Scan_Close(Four CollectionScanId); Four CollectionList_Scan_NextElements(Four CollectionScanId, Four nElements, Four* elementSizes, Four sizeOfElements, void* elements); Four CollectionList_Scan_GetSizeOfNextElements(Four CollectionScanId, Four nElements, Four* elementsSize); Four CollectionList_Scan_InsertElements(Four CollectionScanId, Four nElements, Four* elementSizes, void* elements); Four CollectionList_Scan_DeleteElements(Four CollectionScanId); // Time Related TimeZone GetLocalTimeZone(); void SetCurTime(Time *_time, TimeZone tz); unsigned short GetHour(Time *time); unsigned short GetMinute(Time *time); unsigned short GetSecond(Time *time); long GetJulDay(unsigned short m, unsigned short d, unsigned short y); void GetGregorianDate(Date *date, unsigned short *mm, unsigned short *dd, unsigned short *yy); void SetCurDate(Date *date); void SetDate(unsigned short year, unsigned short month, unsigned short day, Date *date); int CompareDate(Date *date1, Date *date2); int CompareTime(Time *time1, Time *time2); int CompareTimestamp(Timestamp* timestamp1, Timestamp* timestamp2); unsigned short GetYear(Date *date); unsigned short GetMonth(Date *date); unsigned short GetDay(Date *date); Four CreateCounter(Four volId, char *cntrName, Four initialValue, CounterID *cntrId); Four DestroyCounter(Four volId, char *cntrName); Four GetCounterId(Four volId, char *cntrName, CounterID *cntrId); Four SetCounter(Four volId, CounterID *cntrId, Four value); Four ReadCounter(Four volId, CounterID *cntrId, Four *value); Four GetCounterValues(Four volId, CounterID *cntrId, Four nValues, Four *startValue); /* Sort stream functions */ Four OpenSortStream(VolID, SortTupleDesc*); Four CloseSortStream(Four); Four SortingSortStream(Four); Four PutTuplesIntoSortStream(Four, Four, SortStreamTuple*); Four GetTuplesFromSortStream(Four, Four*, SortStreamTuple*, Boolean*); Four OpenStream(VolID); Four CloseStream(Four); Four ChangePhaseStream(Four); Four PutTuplesIntoStream(Four, Four, SortStreamTuple*); Four GetTuplesFromStream(Four, Four*, SortStreamTuple*, Boolean*); private: LOM_Handle* m_systemHandle; }; inline void ConvertToUserLevelColNoInColListStruct(Four nCols, OOSQL_StorageManager::ColListStruct* clist) { int i; for(i = 0; i < nCols; i++) clist[i].colNo --; } inline void ConvertToSystemLevelColNoInColListStruct(Four nCols, OOSQL_StorageManager::ColListStruct* clist) { int i; for(i = 0; i < nCols; i++) clist[i].colNo ++; } inline void ConvertToUserLevelColNoInColLengthInfoListStruct(Four nCols, OOSQL_StorageManager::ColLengthInfoListStruct* clengthlist) { int i; for(i = 0; i < nCols; i++) clengthlist[i].colNo --; } inline void ConvertToSystemLevelColNoInColLengthInfoListStruct(Four nCols, OOSQL_StorageManager::ColLengthInfoListStruct* clengthlist) { int i; for(i = 0; i < nCols; i++) clengthlist[i].colNo ++; } inline void ConvertToUserLevelColNoInBoolExp(Four nBools, OOSQL_StorageManager::BoolExp* bools) { for(int i = 0; i < nBools; i++) bools[i].colNo --; } inline void ConvertToSystemLevelColNoInBoolExp(Four nBools, OOSQL_StorageManager::BoolExp* bools) { for(int i = 0; i < nBools; i++) bools[i].colNo ++; } inline void ConvertToUserLevelColNoInIndexDesc(OOSQL_StorageManager::IndexDesc* indexDesc) { int i; if(indexDesc) { if(indexDesc->indexType == SM_INDEXTYPE_BTREE) for(i = 0; i < indexDesc->kinfo.btree.nColumns; i++) indexDesc->kinfo.btree.columns[i].colNo --; else // SM_INDEXTYPE_MLGF for(i = 0; i < indexDesc->kinfo.mlgf.nColumns; i++) indexDesc->kinfo.mlgf.colNo[i] --; } } inline void ConvertToSystemLevelColNoInIndexDesc(OOSQL_StorageManager::IndexDesc* indexDesc) { int i; if(indexDesc) { if(indexDesc->indexType == SM_INDEXTYPE_BTREE) for(i = 0; i < indexDesc->kinfo.btree.nColumns; i++) indexDesc->kinfo.btree.columns[i].colNo ++; else // SM_INDEXTYPE_MLGF for(i = 0; i < indexDesc->kinfo.mlgf.nColumns; i++) indexDesc->kinfo.mlgf.colNo[i] ++; } } inline void ConvertToUserLevelColNoInEmbeddedAttrTranslationInfo(OOSQL_StorageManager::EmbeddedAttrTranslationInfo* embeddedAttrTranslationInfo) { Two newRealColNoToEmbeddedColNo[LOM_MAXNUMOFATTRIBUTE]; memcpy(&newRealColNoToEmbeddedColNo[0], &embeddedAttrTranslationInfo->realColNoToEmbeddedColNo[1], (LOM_MAXNUMOFATTRIBUTE - 1) * sizeof(Two)); memcpy(&newRealColNoToEmbeddedColNo[LOM_MAXNUMOFATTRIBUTE - 1], &embeddedAttrTranslationInfo->realColNoToEmbeddedColNo[0], sizeof(Two)); memcpy(embeddedAttrTranslationInfo->realColNoToEmbeddedColNo, newRealColNoToEmbeddedColNo, sizeof(newRealColNoToEmbeddedColNo)); } inline void ConvertToSystemLevelColNoInEmbeddedAttrTranslationInfo(OOSQL_StorageManager::EmbeddedAttrTranslationInfo* embeddedAttrTranslationInfo) { Two newRealColNoToEmbeddedColNo[LOM_MAXNUMOFATTRIBUTE]; memcpy(&newRealColNoToEmbeddedColNo[1], &embeddedAttrTranslationInfo->realColNoToEmbeddedColNo[0], (LOM_MAXNUMOFATTRIBUTE - 1) * sizeof(Two)); memcpy(&newRealColNoToEmbeddedColNo[0], &embeddedAttrTranslationInfo->realColNoToEmbeddedColNo[LOM_MAXNUMOFATTRIBUTE - 1], sizeof(Two)); memcpy(embeddedAttrTranslationInfo->realColNoToEmbeddedColNo, newRealColNoToEmbeddedColNo, sizeof(newRealColNoToEmbeddedColNo)); } inline Four OOSQL_StorageManagerLOM::FetchObjectByColList(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Four nCols, ColListStruct* clist) { Four i, j; Four e; ColListStruct clistToUse[MAXNUMOFATTRIBUTE]; Four nColsToUse; for(i = 0, j = 0; i < nCols; i++) { if(clist[i].dataLength > 0) { clistToUse[j] = clist[i]; j++; } } nColsToUse = j; if(nColsToUse > 0) { ConvertToUserLevelColNoInColListStruct(nColsToUse, clistToUse); e = LOM_FetchObjectByColList(m_systemHandle, ocnOrScanId, useScanFlag, (::OID*)oid, nColsToUse, (::LOM_ColListStruct*)clistToUse); ConvertToSystemLevelColNoInColListStruct(nColsToUse, clistToUse); OOSQL_CHECK_ERR(e); } for(i = 0, j = 0; i < nCols; i++) { if(clist[i].dataLength > 0) { clist[i] = clistToUse[j]; j++; } else clist[i].retLength = 0; } return eNOERROR; } inline Four OOSQL_StorageManagerLOM::GetEmbeddedAttrTranslationInfo(Four textScanId, EmbeddedAttrTranslationInfo* embeddedAttrTranslationInfo) { Four e = LOM_GetEmbeddedAttrTranslationInfo(m_systemHandle, textScanId, (::LOM_EmbeddedAttrTranslationInfo*)embeddedAttrTranslationInfo); ConvertToSystemLevelColNoInEmbeddedAttrTranslationInfo(embeddedAttrTranslationInfo); return e; } inline Four OOSQL_StorageManagerLOM::GetEmbeddedAttrsVal(Four textScanId, char *ptrToEmbeddedAttrsBuf, Four embeddedAttrSize, Four nCols, ColListStruct *clist) { ConvertToUserLevelColNoInColListStruct(nCols, clist); Four e = LOM_GetEmbeddedAttrsVal(m_systemHandle, textScanId, ptrToEmbeddedAttrsBuf, embeddedAttrSize, nCols, (::LOM_ColListStruct*)clist); ConvertToSystemLevelColNoInColListStruct(nCols, clist); return e; } inline Four OOSQL_StorageManagerLOM::Text_GetNPostings(Four ocn, IndexID *indexId, Four keywordKind, BoundCond *keywordStartBound, BoundCond *keywordStopBound, LockParameter *lockup, Four *nPostings) { return LOM_Text_GetNPostings(m_systemHandle, ocn, (::LOM_IndexID*)indexId, keywordKind, (::BoundCond*)keywordStartBound, (::BoundCond*)keywordStopBound, (::LockParameter*)lockup, nPostings); } inline Four OOSQL_StorageManagerLOM::Text_Scan_NextPosting(Four textScan, Four bufferLength, char *postingBuffer, Four *requiredSize, PostingWeight *weight) { Four e; e = LOM_Text_Scan_NextPosting(m_systemHandle, textScan, bufferLength, postingBuffer, requiredSize, (::PostingWeight*)weight); if(e == eBIGGERPOSTINGBUFFERNEEDED_LOM) return eBIGGERPOSTINGBUFFERNEEDED_OOSQL; else OOSQL_CHECK_ERR(e); return e; } // Argument postingLengthBufferSize, postingLengthBuffer, scanDirection are added. inline Four OOSQL_StorageManagerLOM::Text_NextPostings( Four textScan, // IN: text scan Id Four postingLengthBufferSize, // IN: size of buffer to hold postings' length char* postingLengthBuffer, // IN: buffer to hold postings' length Four postingBufferSize, // IN: size of buffer to hold postings char* postingBuffer, // IN: buffer to hold postings Four scanDirection, // IN: scan direction to read postings (FORWARD | BACKWARD) Four logicalIdHints, // IN: logical Id hints to skip postings Four* nReturnedPosting, // OUT: number of read postings #ifndef COMPRESSION Four* requiredSize // OUT: sufficient size of buffer to hold postings #else Four* requiredSize, // OUT: sufficient size of buffer to hold postings VolNo* volNoOfPostingTupleID, Four* lastDocId #endif ) { Four e; #if defined (ORDEREDSET_BACKWARD_SCAN) #ifndef COMPRESSION e = LOM_Text_NextPostings(m_systemHandle, textScan, postingLengthBufferSize, postingLengthBuffer, postingBufferSize, postingBuffer, scanDirection, logicalIdHints, nReturnedPosting, requiredSize); #else e = LOM_Text_NextPostings(m_systemHandle, textScan, postingLengthBufferSize, postingLengthBuffer, postingBufferSize, postingBuffer, scanDirection, logicalIdHints, nReturnedPosting, requiredSize, volNoOfPostingTupleID, lastDocId); #endif #else e = LOM_Text_NextPostings(m_systemHandle, textScan, 0, NULL, postingBufferSize, postingBuffer, FORWARD, logicalIdHints, nReturnedPosting, requiredSize); #endif /* #if defined (ORDEREDSET_BACKWARD_SCAN) */ if(e == eBIGGERPOSTINGBUFFERNEEDED_LOM) return eBIGGERPOSTINGBUFFERNEEDED_OOSQL; else OOSQL_CHECK_ERR(e); return e; } inline Four OOSQL_StorageManagerLOM::Text_GetCursorKeyword(Four textScan, char *keyword) { return LOM_Text_GetCursorKeyword(m_systemHandle, textScan, keyword); } inline Four OOSQL_StorageManagerLOM::Text_GetLogicalId(Four ocnOrScanId, Boolean useScanFlag, OID* oid) { return lom_Text_GetLogicalId(m_systemHandle, ocnOrScanId, useScanFlag, (::OID*)oid); } inline Four OOSQL_StorageManagerLOM::Text_GetNumOfTextObjectsInClass(Four ocn, Four* nObjects) { return LOM_Text_GetNumOfTextObjectsInClass(m_systemHandle, ocn, nObjects); } #ifndef SLIMDOWN_OPENGIS class OOSQL_StorageManagerGEO : public OOSQL_StorageManagerLOM { public: OOSQL_StorageManagerGEO(OOSQL_SystemHandle* oosqlSystemHandle, GEO_Handle* systemHandle); ~OOSQL_StorageManagerGEO(); Four AddIndex(Four volId, char *className, char *indexName, IndexDesc *indexDesc, IndexID *indexID); Four AddIndex(Four volId, Four schemaId, char *tableName, char *indexName, IndexDesc *indexDesc, IndexID *indexID); Four DropIndex(Four volId, char *indexName); Four OpenClass(Four volId, char* className); Four OpenClass(Four volId, Four classId); Four GetOpenClassNum(Four volId, Four classId); Four CloseClass(Four ocn); // Object Manipulation Four NextObject(Four scanId, OID* oid, Cursor **cursor); Four DestroyObject(Four ocnOrScanId, Boolean useScanFlag, OID* oid); Four CreateObjectByColList(Four ocnOrScanId, Boolean useScanFlag, Four nCols, ColListStruct* clist, OID* oid); Four UpdateObjectByColList(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Four nCols, ColListStruct* clist); Four Geometry_GetMBR(Four ocnOrScanId, Boolean useScanFlag, OID* oid, Four colNo, float* xmin, float* ymin, float* xmax, float* ymax); Four Geometry_GetMBR(char* data, Four length, float* xmin, float* ymin, float* xmax, float* ymax); Four OpenMBRqueryScan(Four ocn, IndexID *iid, Region queryRegion, Four spatialOp, Four nBools, BoolExp* bools, LockParameter *lockup, IndexID* tidJoinIndexID = 0, BoundCond* tidJoinIndexStartBound = 0, BoundCond* tidJoinIndexStopBound = 0 ); Four CloseScan(Four scanId); private: GEO_Handle* m_systemHandle; }; #endif // SLIMDOWN_OPENGIS #endif //_OOSQL_STORAGEMANAGER_H_
55.993096
294
0.740032
[ "object", "vector" ]
c5b1e8f3dd36b5ed3eac63d96db3e512d74eb7a0
23,720
cpp
C++
src/graphics/GraphicsSystem.cpp
Faaux/DingoEngine
05c8ae59816befaaa203e8d5310c4e17da89bb7b
[ "MIT" ]
null
null
null
src/graphics/GraphicsSystem.cpp
Faaux/DingoEngine
05c8ae59816befaaa203e8d5310c4e17da89bb7b
[ "MIT" ]
null
null
null
src/graphics/GraphicsSystem.cpp
Faaux/DingoEngine
05c8ae59816befaaa203e8d5310c4e17da89bb7b
[ "MIT" ]
null
null
null
/** * @file GraphicsSystem.cpp * @author Faaux (github.com/Faaux) * @date 11 February 2018 */ #include "GraphicsSystem.h" #include "Font.h" #include "Shader.h" #include "imgui/DG_Imgui.h" #include "imgui/imgui_impl_sdl_gl3.h" #include "main.h" #include "math/BoundingBox.h" namespace DG::graphics { DebugRenderContext* g_DebugRenderContext = nullptr; inline const char* ErrorToString(const GLenum errorCode) { switch (errorCode) { case GL_NO_ERROR: return "GL_NO_ERROR"; case GL_INVALID_ENUM: return "GL_INVALID_ENUM"; case GL_INVALID_VALUE: return "GL_INVALID_VALUE"; case GL_INVALID_OPERATION: return "GL_INVALID_OPERATION"; case GL_OUT_OF_MEMORY: return "GL_OUT_OF_MEMORY"; default: return "Unknown GL error"; } // switch (errorCode) } GraphicsSystem::GraphicsSystem() { // Enable Depthtesting glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glDepthFunc(GL_LESS); } void GraphicsSystem::Render(ImDrawData* imOverlayDrawData, WorldRenderData** renderData, s32 count) { static vec4 clearColor(0.1f, 0.1f, 0.1f, 1.f); TWEAKER_CAT("OpenGL", Color3Small, "Clear Color", &clearColor); glClearColor(clearColor.r, clearColor.g, clearColor.b, clearColor.a); for (int i = 0; i < count; ++i) { RenderWorldInternal(renderData[i]); } // Imgui glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); ImGui_ImplSdlGL3_RenderDrawLists(imOverlayDrawData); } void GraphicsSystem::RenderWorldInternal(WorldRenderData* worldData) { static vec3 lightColor(1); static vec3 lightDirection(0.1, -1, 0); static float bias = 0.001f; TWEAKER_CAT("OpenGL", F1, "Shadow Bias", &bias); TWEAKER(Color3Small, "Light Color", &lightColor); TWEAKER(F3, "Light Direction", &lightDirection); glPolygonMode(GL_FRONT_AND_BACK, worldData->RenderCTX->IsWireframe ? GL_LINE : GL_FILL); if (worldData->RenderCTX->IsWireframe) { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glDisable(GL_CULL_FACE); } else { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_CULL_FACE); } glEnable(GL_DEPTH_TEST); // Dir Light Shadowmap static bool wasFBInit = false; static Framebuffer shadowFramebuffer; static Shader* shadowShader = g_Managers->ShaderManager->LoadOrGet(StringId("shadow_map"), "shadow_map"); static mat4 lightProjection; static mat4 lightViewMatrix; if (!wasFBInit) { wasFBInit = true; shadowFramebuffer.Initialize(2048, 2048, false, true, true); } AABB aabb; // Shadow Map Orthographic View Calculation { lightViewMatrix = glm::lookAt(-lightDirection, vec3(0.f), vec3(0.f, 1.f, 0.f)); // Calculate projection for light { auto renderQueues = worldData->RenderCTX->GetRenderQueues(); AABB aabb; for (u32 queueIndex = 0; queueIndex < worldData->RenderCTX->GetRenderQueueCount(); ++queueIndex) { // Setup Shader auto renderQueue = renderQueues[queueIndex]; // Render Models for (u32 renderableIndex = 0; renderableIndex < renderQueue->Count; ++renderableIndex) { auto& renderable = renderQueue->Renderables[renderableIndex]; auto& model = renderable.Model; if (model) { AABB modelSpaceAABB = TransformAABB(model->aabb, renderable.ModelMatrix); if (queueIndex == 0 && renderableIndex == 0) { aabb = modelSpaceAABB; } aabb = CombineAABB(aabb, modelSpaceAABB); } } } // We got our AABB transform it to light space AABB lightaabb = TransformAABB(aabb, Transform(lightViewMatrix)); lightProjection = glm::ortho(lightaabb.Min.x, lightaabb.Max.x, lightaabb.Min.y, lightaabb.Max.y, -10.f, 100.f); } shadowFramebuffer.Bind(); glClear(GL_DEPTH_BUFFER_BIT); // Render Shadowmap auto renderQueues = worldData->RenderCTX->GetRenderQueues(); for (u32 queueIndex = 0; queueIndex < worldData->RenderCTX->GetRenderQueueCount(); ++queueIndex) { // Setup Shader auto renderQueue = renderQueues[queueIndex]; shadowShader->Use(); shadowShader->SetUniform("vp", lightProjection * lightViewMatrix); // Render Models for (u32 renderableIndex = 0; renderableIndex < renderQueue->Count; ++renderableIndex) { auto& renderable = renderQueue->Renderables[renderableIndex]; auto& model = renderable.Model; if (model) { for (auto& mesh : model->meshes) { shadowShader->SetUniform("m", renderable.ModelMatrix * mesh.localTransform); glBindVertexArray(mesh.vao); glDrawElements(mesh.drawMode, (s32)mesh.count, mesh.type, (void*)mesh.byteOffset); } CheckOpenGLError(__FILE__, __LINE__); } } } shadowFramebuffer.UnBind(); // Unbind after we are done rendering glBindVertexArray(0); } // End ShadowMap auto activeFramebuffer = worldData->Window->GetFramebuffer(); activeFramebuffer->Bind(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); const Camera* camera = worldData->Window->GetCamera(); auto renderQueues = worldData->RenderCTX->GetRenderQueues(); for (u32 queueIndex = 0; queueIndex < worldData->RenderCTX->GetRenderQueueCount(); ++queueIndex) { // Setup Shader auto renderQueue = renderQueues[queueIndex]; renderQueue->Shader->Use(); renderQueue->Shader->SetUniform("proj", camera->GetProjectionMatrix()); renderQueue->Shader->SetUniform("view", camera->GetViewMatrix()); renderQueue->Shader->SetUniform("lightMVP", lightProjection * lightViewMatrix); renderQueue->Shader->SetUniform("lightDirection", lightDirection); renderQueue->Shader->SetUniform("lightColor", lightColor); renderQueue->Shader->SetUniform("bias", bias); renderQueue->Shader->SetUniform("resolution", activeFramebuffer->GetSize()); glActiveTexture(GL_TEXTURE0); shadowFramebuffer.DepthTexture.Bind(); // Render Models for (u32 renderableIndex = 0; renderableIndex < renderQueue->Count; ++renderableIndex) { auto& renderable = renderQueue->Renderables[renderableIndex]; auto& model = renderable.Model; if (model) { for (auto& mesh : model->meshes) { renderQueue->Shader->SetUniform("model", renderable.ModelMatrix * mesh.localTransform); glBindVertexArray(mesh.vao); glDrawElements(mesh.drawMode, (s32)(mesh.count), mesh.type, (void*)(mesh.byteOffset)); } CheckOpenGLError(__FILE__, __LINE__); } } } // Unbind after we are done rendering glBindVertexArray(0); _debugRenderSystem.Render(worldData); activeFramebuffer->UnBind(); } void RenderContext::AddRenderQueue(RenderQueue* queue) { Assert(_currentIndexRenderQueue < COUNT_OF(_renderQueues)); _renderQueues[_currentIndexRenderQueue++] = queue; } void DebugRenderContext::AddLine(const vec3& vertex0, const vec3& vertex1, const Color& color, bool depthEnabled) { if (depthEnabled) { _depthEnabledDebugLines.emplace_back(vertex0, vertex1, color); } else { _depthDisabledDebugLines.emplace_back(vertex0, vertex1, color); } } void DebugRenderContext::AddTextScreen(const vec2& position, const std::string& text, Color color, bool depthEnabled) { auto& vectorToAdd = depthEnabled ? _depthEnabledDebugTextScreen : _depthDisabledDebugTextScreen; vectorToAdd.emplace_back(color, position, text); } void DebugRenderContext::AddTextWorld(const vec3& position, const std::string& text, Color color, bool depthEnabled) { auto& vectorToAdd = depthEnabled ? _depthEnabledDebugTextWorld : _depthDisabledDebugTextWorld; vectorToAdd.emplace_back(color, position, text); } void DebugRenderContext::Reset() { _depthEnabledDebugLines.clear(); _depthDisabledDebugLines.clear(); _depthEnabledDebugTextWorld.clear(); _depthDisabledDebugTextWorld.clear(); _depthEnabledDebugTextScreen.clear(); _depthDisabledDebugTextScreen.clear(); } const std::vector<DebugLine>& DebugRenderContext::GetDebugLines(bool depthEnabled) const { if (depthEnabled) return _depthEnabledDebugLines; return _depthDisabledDebugLines; } const std::vector<DebugTextScreen>& DebugRenderContext::GetDebugTextScreen(bool depthEnabled) const { return depthEnabled ? _depthEnabledDebugTextScreen : _depthDisabledDebugTextScreen; } const std::vector<DebugTextWorld>& DebugRenderContext::GetDebugTextWorld(bool depthEnabled) const { return depthEnabled ? _depthEnabledDebugTextWorld : _depthDisabledDebugTextWorld; } DebugRenderSystem::DebugRenderSystem() : _shader("debug_lines") { SetupVertexBuffers(); } void DebugRenderSystem::SetupVertexBuffers() { glGenVertexArrays(1, &linePointVAO); glGenBuffers(1, &linePointVBO); glGenBuffers(1, &linePointEBO); glBindVertexArray(linePointVAO); // Index Buffer u32 indices[DebugDrawBufferSize * 6]; u32 index = 0; for (u32 i = 0; i < DebugDrawBufferSize; ++i) { // First Quad Triangle indices[index++] = i * 4 + 0; indices[index++] = i * 4 + 1; indices[index++] = i * 4 + 2; // Second Quad Triangle indices[index++] = i * 4 + 2; indices[index++] = i * 4 + 3; indices[index++] = i * 4 + 0; } glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, linePointEBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); // Data Buffer glBindBuffer(GL_ARRAY_BUFFER, linePointVBO); // RenderInterface will never be called with a batch larger than // DEBUG_DRAW_VERTEX_BUFFER_SIZE vertexes, so we can allocate the same amount here. glBufferData(GL_ARRAY_BUFFER, DebugDrawBufferSize * sizeof(DebugLine), nullptr, GL_STREAM_DRAW); size_t offset = 0; glEnableVertexAttribArray(0); // in_first (vec3) glVertexAttribPointer( /* index = */ 0, /* size = */ 3, /* type = */ GL_FLOAT, /* normalize = */ GL_FALSE, /* stride = */ sizeof(DebugPoint), /* offset = */ (void*)offset); offset += sizeof(vec3); glEnableVertexAttribArray(1); // in_second (vec3) glVertexAttribPointer( /* index = */ 1, /* size = */ 3, /* type = */ GL_FLOAT, /* normalize = */ GL_FALSE, /* stride = */ sizeof(DebugPoint), /* offset = */ (void*)offset); offset += sizeof(vec3); glEnableVertexAttribArray(2); // in_ColorPointSize (vec4) glVertexAttribPointer( /* index = */ 2, /* size = */ 4, /* type = */ GL_FLOAT, /* normalize = */ GL_FALSE, /* stride = */ sizeof(DebugPoint), /* offset = */ (void*)offset); offset += sizeof(vec4); glEnableVertexAttribArray(3); // direction (float) glVertexAttribPointer( /* index = */ 3, /* size = */ 1, /* type = */ GL_FLOAT, /* normalize = */ GL_FALSE, /* stride = */ sizeof(DebugPoint), /* offset = */ (void*)offset); CheckOpenGLError(__FILE__, __LINE__); // VAOs can be a pain in the neck if left enabled... glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); } void DebugRenderSystem::Render(WorldRenderData* worldData) { static bool isFontInit = false; static Font font; auto activeFramebuffer = worldData->Window->GetFramebuffer(); auto activeCamera = worldData->Window->GetCamera(); if (!isFontInit) { vec2 currentSize = activeFramebuffer->GetSize(); font.Init("Roboto-Regular.ttf", 16); isFontInit = true; } RenderDebugLines(activeCamera, true, worldData->DebugRenderCTX->GetDebugLines(true)); RenderDebugLines(activeCamera, false, worldData->DebugRenderCTX->GetDebugLines(false)); glDisable(GL_DEPTH_TEST); for (auto& text : worldData->DebugRenderCTX->GetDebugTextScreen(false)) { font.RenderTextScreen(text.text, text.position, text.color); } for (auto& text : worldData->DebugRenderCTX->GetDebugTextWorld(false)) { font.RenderTextWorldBillboard(text.text, activeCamera, activeFramebuffer->GetSize(), text.position, text.color); } glEnable(GL_DEPTH_TEST); for (auto& text : worldData->DebugRenderCTX->GetDebugTextScreen(true)) { font.RenderTextScreen(text.text, text.position, text.color); } for (auto& text : worldData->DebugRenderCTX->GetDebugTextWorld(true)) { font.RenderTextWorldBillboard(text.text, activeCamera, activeFramebuffer->GetSize(), text.position, text.color); } } void DebugRenderSystem::RenderDebugLines(Camera* camera, bool depthEnabled, const std::vector<DebugLine>& lines) { if (lines.empty()) return; glBindVertexArray(linePointVAO); _shader.Use(); _shader.SetUniform("mv_Matrix", camera->GetViewMatrix()); _shader.SetUniform("p_Matrix", camera->GetProjectionMatrix()); if (depthEnabled) { glEnable(GL_DEPTH_TEST); } else { glDisable(GL_DEPTH_TEST); } glBindBuffer(GL_ARRAY_BUFFER, linePointVBO); s32 size_left = (s32)lines.size(); s32 size_drawn = 0; while (size_left != 0) { const s32 size_to_draw = size_left > DebugDrawBufferSize ? DebugDrawBufferSize : size_left; glBufferSubData(GL_ARRAY_BUFFER, 0, size_to_draw * sizeof(DebugLine), lines.data() + size_drawn); glDrawElements(GL_TRIANGLES, size_to_draw * 6, GL_UNSIGNED_INT, 0); size_drawn += size_to_draw; size_left -= size_to_draw; } glUseProgram(0); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); } void AddDebugLine(const vec3& fromPosition, const vec3& toPosition, Color color, f32 lineWidth, f32 durationSeconds, bool depthEnabled) { Assert(g_DebugRenderContext); color.w = lineWidth; g_DebugRenderContext->AddLine(fromPosition, toPosition, color, depthEnabled); } void AddDebugCross(const vec3& position, Color color, f32 size, f32 lineWidth, f32 durationSeconds, bool depthEnabled) { color.w = lineWidth; const f32 halfSize = size / 2.0f; AddDebugLine(position - vec3(halfSize, 0, 0), position + vec3(halfSize, 0, 0), color, lineWidth, durationSeconds, depthEnabled); AddDebugLine(position - vec3(0, halfSize, 0), position + vec3(0, halfSize, 0), color, lineWidth, durationSeconds, depthEnabled); AddDebugLine(position - vec3(0, 0, halfSize), position + vec3(0, 0, halfSize), color, lineWidth, durationSeconds, depthEnabled); } void AddDebugSphere(const vec3& centerPosition, Color color, f32 radius, f32 durationSeconds, bool depthEnabled) { // ToDo: Export these lines and just scale and move them appropriately, no need to calculate // each time static const int stepSize = 30; vec3 cache[360 / stepSize]; vec3 radiusVec(0.0f, 0.0f, radius); cache[0] = centerPosition + radiusVec; for (size_t n = 1; n < COUNT_OF(cache); ++n) { cache[n] = cache[0]; } vec3 lastPoint, temp; for (int i = stepSize; i <= 180; i += stepSize) { const float rad = glm::radians((f32)i); const float s = glm::sin(rad); const float c = glm::cos(rad); lastPoint.x = centerPosition.x; lastPoint.y = centerPosition.y + radius * s; lastPoint.z = centerPosition.z + radius * c; for (int n = 0, j = stepSize; j <= 360; j += stepSize, ++n) { const float radTemp = glm::radians((f32)j); temp.x = centerPosition.x + glm::sin(radTemp) * radius * s; temp.y = centerPosition.y + glm::cos(radTemp) * radius * s; temp.z = lastPoint.z; AddDebugLine(lastPoint, temp, color, 1, durationSeconds, depthEnabled); AddDebugLine(lastPoint, cache[n], color, 1, durationSeconds, depthEnabled); cache[n] = lastPoint; lastPoint = temp; } } } void AddDebugCircle(const vec3& centerPosition, const vec3& planeNormal, Color color, f32 radius, f32 durationSeconds, bool depthEnabled) { // Find 2 orthogonal vectors (Orthogonal --> DotProduct is Zero) vec3 vecX(1.0f, -planeNormal.x / planeNormal.y, 0.0f); vec3 vecZ = cross(planeNormal, vecX) * radius; vecX *= radius; vecZ *= radius; static const int stepSize = 15; vec3 lastPoint = centerPosition + vecZ; for (int i = stepSize; i <= 360; i += stepSize) { const float rad = glm::radians((f32)i); const float s = glm::sin(rad); const float c = glm::cos(rad); const vec3 point = centerPosition + vecX * s + vecZ * c; AddDebugLine(lastPoint, point, color, 1, durationSeconds, depthEnabled); AddDebugLine(lastPoint, centerPosition, color, 1, durationSeconds, depthEnabled); lastPoint = point; } } void AddDebugAxes(const Transform& transform, f32 size, f32 lineWidth, f32 durationSeconds, bool depthEnabled) { auto modelMatrix = transform.GetModelMatrix(); const vec3 right(modelMatrix[0]); const vec3 up(modelMatrix[1]); const vec3 forward(modelMatrix[2]); AddDebugLine(transform.GetPosition(), transform.GetPosition() + normalize(right) * size, Color(1, 0, 0, lineWidth), lineWidth, durationSeconds, depthEnabled); AddDebugLine(transform.GetPosition(), transform.GetPosition() + normalize(up) * size, Color(0, 1, 0, lineWidth), lineWidth, durationSeconds, depthEnabled); AddDebugLine(transform.GetPosition(), transform.GetPosition() + normalize(forward) * size, Color(0, 0, 1, lineWidth), lineWidth, durationSeconds, depthEnabled); } void AddDebugTriangle(const vec3& vertex0, const vec3& vertex1, const vec3& vertex2, Color color, f32 lineWidth, f32 durationSeconds, bool depthEnabled) { color.w = lineWidth; AddDebugLine(vertex0, vertex1, color, lineWidth, durationSeconds, depthEnabled); AddDebugLine(vertex1, vertex2, color, lineWidth, durationSeconds, depthEnabled); AddDebugLine(vertex2, vertex0, color, lineWidth, durationSeconds, depthEnabled); } void AddDebugAABB(const vec3& minCoords, const vec3& maxCoords, Color color, f32 lineWidth, f32 durationSeconds, bool depthEnabled) { vec3 p1 = minCoords; vec3 p2 = maxCoords; vec3 p3 = vec3(maxCoords.x, minCoords.y, minCoords.z); vec3 p4 = vec3(minCoords.x, maxCoords.y, minCoords.z); vec3 p5 = vec3(minCoords.x, minCoords.y, maxCoords.z); vec3 p6 = vec3(minCoords.x, maxCoords.y, maxCoords.z); vec3 p7 = vec3(maxCoords.x, minCoords.y, maxCoords.z); vec3 p8 = vec3(maxCoords.x, maxCoords.y, minCoords.z); AddDebugLine(p1, p3, color, lineWidth, durationSeconds, depthEnabled); AddDebugLine(p1, p4, color, lineWidth, durationSeconds, depthEnabled); AddDebugLine(p1, p5, color, lineWidth, durationSeconds, depthEnabled); AddDebugLine(p3, p7, color, lineWidth, durationSeconds, depthEnabled); AddDebugLine(p3, p8, color, lineWidth, durationSeconds, depthEnabled); AddDebugLine(p6, p4, color, lineWidth, durationSeconds, depthEnabled); AddDebugLine(p6, p5, color, lineWidth, durationSeconds, depthEnabled); AddDebugLine(p8, p4, color, lineWidth, durationSeconds, depthEnabled); AddDebugLine(p5, p7, color, lineWidth, durationSeconds, depthEnabled); AddDebugLine(p2, p6, color, lineWidth, durationSeconds, depthEnabled); AddDebugLine(p2, p7, color, lineWidth, durationSeconds, depthEnabled); AddDebugLine(p2, p8, color, lineWidth, durationSeconds, depthEnabled); } void AddDebugTextWorld(const vec3& position, const std::string& text, Color color, f32 durationSeconds, bool depthEnabled) { Assert(g_DebugRenderContext); g_DebugRenderContext->AddTextWorld(position, text, color, depthEnabled); } void AddDebugTextScreen(const vec2& position, const std::string& text, Color color, f32 durationSeconds, bool depthEnabled) { Assert(g_DebugRenderContext); g_DebugRenderContext->AddTextScreen(position, text, color, depthEnabled); } void AddDebugXZGrid(const vec2& center, const f32 min, const f32 max, const f32 height, f32 step, Color color, f32 lineWidth, f32 durationSeconds, bool depthEnabled) { // Line at min { // Horizontal Line const vec3 from(center.x + min, height, center.y + min); const vec3 to(center.x + max, height, center.y + min); AddDebugLine(from, to, color, lineWidth, durationSeconds, depthEnabled); } { // Vertical Line const vec3 from(center.x + min, height, center.y + min); const vec3 to(center.x + min, height, center.y + max); AddDebugLine(from, to, color, lineWidth, durationSeconds, depthEnabled); } for (f32 i = min + step; i < max; i += step) { { // Horizontal Line const vec3 from(center.x + min, height, center.y + i); const vec3 to(center.x + max, height, center.y + i); AddDebugLine(from, to, color, lineWidth, durationSeconds, depthEnabled); } { // Vertical Line const vec3 from(center.x + i, height, center.y + min); const vec3 to(center.x + i, height, center.y + max); AddDebugLine(from, to, color, lineWidth, durationSeconds, depthEnabled); } } // Line at max { // Horizontal Line const vec3 from(center.x + min, height, center.y + max); const vec3 to(center.x + max, height, center.y + max); AddDebugLine(from, to, color, lineWidth, durationSeconds, depthEnabled); } { // Vertical Line const vec3 from(center.x + max, height, center.y + min); const vec3 to(center.x + max, height, center.y + max); AddDebugLine(from, to, color, lineWidth, durationSeconds, depthEnabled); } } void CheckOpenGLError(const char* file, const int line) { GLenum err; while ((err = glad_glGetError()) != GL_NO_ERROR) { SDL_LogError(0, "%s(%d) : GL_Error=0x%X - %s", file, line, err, ErrorToString(err)); } } } // namespace DG::graphics
36.158537
100
0.62715
[ "mesh", "render", "vector", "model", "transform" ]
c5b2fd67760f64c8b82005e0bb4c91d6d3a042be
443
cpp
C++
atcoder/abc/abc_142/b.cpp
hsmtknj/programming-contest
b0d7f8a2d12fb031d3a802e6a4769cd6d2defcab
[ "MIT" ]
null
null
null
atcoder/abc/abc_142/b.cpp
hsmtknj/programming-contest
b0d7f8a2d12fb031d3a802e6a4769cd6d2defcab
[ "MIT" ]
null
null
null
atcoder/abc/abc_142/b.cpp
hsmtknj/programming-contest
b0d7f8a2d12fb031d3a802e6a4769cd6d2defcab
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> int main() { int N; int K; // input std::cin >> N >> K; std::vector<int> v(N); for (int i = 0; i < v.size(); i++) { int h; std::cin >> h; v[i] = h; } // solve int cnt = 0; for (int i = 0; i < v.size(); i++) { if (v[i] >= K) { cnt++; } } // answer std::cout << cnt << std::endl; }
13.424242
38
0.354402
[ "vector" ]
c5b3fe52c0d1a84a0bda6ee8e5cb6ce2f20dc1f9
13,688
cxx
C++
src/medVtkInria/vtkDataManagement/vtkMetaVolumeMesh.cxx
nebatmusic/medInria-public
09000bd2f129692e42314a8eb1313d238603252e
[ "BSD-1-Clause" ]
1
2020-11-16T13:55:45.000Z
2020-11-16T13:55:45.000Z
src/medVtkInria/vtkDataManagement/vtkMetaVolumeMesh.cxx
nebatmusic/medInria-public
09000bd2f129692e42314a8eb1313d238603252e
[ "BSD-1-Clause" ]
null
null
null
src/medVtkInria/vtkDataManagement/vtkMetaVolumeMesh.cxx
nebatmusic/medInria-public
09000bd2f129692e42314a8eb1313d238603252e
[ "BSD-1-Clause" ]
null
null
null
/*========================================================================= medInria Copyright (c) INRIA 2013 - 2014. All rights reserved. See LICENSE.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. =========================================================================*/ #include <vtkMetaVolumeMesh.h> #include "vtkObjectFactory.h" #include <vtkUnstructuredGrid.h> #include <vtkUnstructuredGridReader.h> #include <vtkUnstructuredGridWriter.h> #include <vtksys/SystemTools.hxx> #include <vtkProperty.h> #include <vtkDataSetSurfaceFilter.h> #include <vtkPolyDataMapper.h> #include <vtkPolyDataNormals.h> // #include <vtkActor.h> #include <vtkPoints.h> #include <vtkPointData.h> #include <vtkCellData.h> #include <vtkIdList.h> #include <vtkUnsignedShortArray.h> #include <vtkSmartPointer.h> #include <vtkErrorCode.h> //---------------------------------------------------------------------------- vtkStandardNewMacro( vtkMetaVolumeMesh ); vtkCxxRevisionMacro(vtkMetaVolumeMesh, "$Revision: 838 $"); //---------------------------------------------------------------------------- vtkMetaVolumeMesh::vtkMetaVolumeMesh() { this->Type = vtkMetaDataSet::VTK_META_VOLUME_MESH; } vtkMetaVolumeMesh::vtkMetaVolumeMesh(const vtkMetaVolumeMesh& other) : vtkMetaDataSet(other) { } //---------------------------------------------------------------------------- vtkMetaVolumeMesh::~vtkMetaVolumeMesh() { } vtkMetaVolumeMesh* vtkMetaVolumeMesh::Clone() { return new vtkMetaVolumeMesh(*this); } //---------------------------------------------------------------------------- void vtkMetaVolumeMesh::Initialize() { this->Superclass::Initialize(); if (!this->DataSet) return; vtkProperty* property = vtkProperty::SafeDownCast(this->GetProperty()); if (!property) { property = vtkProperty::New(); this->SetProperty (property); property->Delete(); } } //---------------------------------------------------------------------------- vtkUnstructuredGrid* vtkMetaVolumeMesh::GetUnstructuredGrid() const { if (!this->DataSet) return nullptr; return vtkUnstructuredGrid::SafeDownCast (this->DataSet); } //---------------------------------------------------------------------------- void vtkMetaVolumeMesh::ReadVtkFile (const char* filename) { vtkUnstructuredGridReader* reader = vtkUnstructuredGridReader::New(); reader->SetFileName (filename); try { reader->Update(); this->SetDataSet (reader->GetOutput()); } catch (vtkErrorCode::ErrorIds error) { reader->Delete(); throw error; } reader->Delete(); } //---------------------------------------------------------------------------- void vtkMetaVolumeMesh::Read (const char* filename) { unsigned long format = vtkMetaVolumeMesh::CanReadFile (filename); try { std::cout << "Reading " << filename << "... "; switch (format) { case vtkMetaVolumeMesh::FILE_IS_VTK : this->ReadVtkFile (filename); break; case vtkMetaVolumeMesh::FILE_IS_MESH : this->ReadMeshFile (filename); break; case vtkMetaVolumeMesh::FILE_IS_GMESH : this->ReadGMeshFile (filename); break; default : vtkErrorMacro(<<"unknown dataset type : "<<filename<<endl); throw vtkErrorCode::UnrecognizedFileTypeError; } std::cout << "done." << std::endl; } catch (vtkErrorCode::ErrorIds error) { throw error; } this->SetFilePath (filename); } //---------------------------------------------------------------------------- void vtkMetaVolumeMesh::WriteVtkFile (const char* filename) { if (!this->DataSet) { vtkErrorMacro(<<"No DataSet to write"<<endl); throw vtkErrorCode::UserError; } vtkUnstructuredGrid* c_mesh = vtkUnstructuredGrid::SafeDownCast (this->DataSet); if (!c_mesh) { vtkErrorMacro(<<"DataSet is not a polydata object"<<endl); throw vtkErrorCode::UserError; } vtkUnstructuredGridWriter* writer = vtkUnstructuredGridWriter::New(); writer->SetFileName (filename); try { writer->SetInput (c_mesh); writer->Write(); writer->Delete(); } catch (vtkErrorCode::ErrorIds error) { writer->Delete(); throw error; } this->SetFilePath (filename); } //---------------------------------------------------------------------------- void vtkMetaVolumeMesh::Write (const char* filename) { try { std::cout << "writing " << filename << "... "; this->WriteVtkFile (filename); std::cout << "done." << std::endl; } catch (vtkErrorCode::ErrorIds error) { throw error; } } //---------------------------------------------------------------------------- bool vtkMetaVolumeMesh::IsVtkExtension (const char* ext) { if (strcmp (ext, ".vtk") == 0 || strcmp (ext, ".vtu") == 0) return true; return false; } //---------------------------------------------------------------------------- bool vtkMetaVolumeMesh::IsMeshExtension (const char* ext) { if (strcmp (ext, ".mesh") == 0) return true; return false; } //---------------------------------------------------------------------------- bool vtkMetaVolumeMesh::IsGMeshExtension (const char* ext) { if (strcmp (ext, ".msh") == 0) return true; return false; } //---------------------------------------------------------------------------- unsigned int vtkMetaVolumeMesh::CanReadFile (const char* filename) { if (vtkMetaVolumeMesh::IsMeshExtension(vtksys::SystemTools::GetFilenameLastExtension(filename).c_str())) { // medit .mesh format must have 'MeshVersionFormatted' // as a header if (vtkMetaDataSet::IsMeditFormat(filename)) { // Additionally, check if there are any tetrahedra std::ifstream file(filename); if (vtkMetaDataSet::PlaceStreamCursor(file, "Tetrahedra")) { return vtkMetaVolumeMesh::FILE_IS_MESH; } } return 0; } if (vtkMetaVolumeMesh::IsGMeshExtension(vtksys::SystemTools::GetFilenameLastExtension(filename).c_str())) { // check if there is any tetrahedron... std::ifstream file (filename ); char str[256]; file >> str; if(file.fail()) { return 0; } while( (!file.fail()) && (strcmp (str, "$ELM") != 0) && (strcmp (str, "$ENDELM") != 0) ) { file >> str; } if (strcmp (str, "$ELM") == 0) return vtkMetaVolumeMesh::FILE_IS_GMESH; else return 0; } if (!vtkMetaVolumeMesh::IsVtkExtension(vtksys::SystemTools::GetFilenameLastExtension(filename).c_str())) return 0; vtkUnstructuredGridReader* reader = vtkUnstructuredGridReader::New(); reader->SetFileName (filename); if (reader->IsFileUnstructuredGrid ()) { reader->Delete(); return vtkMetaVolumeMesh::FILE_IS_VTK; } reader->Delete(); return 0; } void vtkMetaVolumeMesh::ReadMeshFile (const char* filename) { std::ifstream file (filename ); if(file.fail()) { vtkErrorMacro("File not found\n"); throw vtkErrorCode::FileNotFoundError; } vtkPoints* points = vtkPoints::New(); vtkUnsignedShortArray* pointarray = vtkUnsignedShortArray::New(); vtkUnsignedShortArray* cellarray = vtkUnsignedShortArray::New(); pointarray->SetName("Point array"); cellarray->SetName ("Zones"); vtkUnstructuredGrid* outputmesh = vtkUnstructuredGrid::New(); unsigned short ref = 0; // Find vertices in file if (vtkMetaDataSet::PlaceStreamCursor(file, "Vertices")) { // read all vertices unsigned int NVertices = 0; file >> NVertices; points->SetNumberOfPoints (NVertices); pointarray->Allocate(NVertices); // read vertex position for(unsigned int i = 0; i < NVertices; i++) { double pos[3]; file >> pos[0] >> pos[1] >> pos[2] >> ref; points->SetPoint(i, pos[0], pos[1], pos[2]); pointarray->InsertNextValue(ref); } vtkMetaDataSet::ClearInputStream(file); } else { // no vertices found, abort points->Delete(); pointarray->Delete(); cellarray->Delete(); outputmesh->Delete(); vtkErrorMacro("No point in file\n"); throw vtkErrorCode::CannotOpenFileError; } outputmesh->SetPoints (points); points->Delete(); if (outputmesh->GetPointData()) { outputmesh->GetPointData()->AddArray (pointarray); } pointarray->Delete(); // vtk automatically reallocates memory outputmesh->Allocate(1000); cellarray->Allocate(1000); // in medit format, "Corners" and "Required vertices" are // the vertices if (vtkMetaDataSet::PlaceStreamCursor(file, "Corners")) { // read vertices this->ReadMeditCells(file, outputmesh, 1, cellarray); } vtkMetaDataSet::ClearInputStream(file); if (vtkMetaDataSet::PlaceStreamCursor(file, "RequiredVertices")) { // read another kind of vertices this->ReadMeditCells(file, outputmesh, 1, cellarray); } vtkMetaDataSet::ClearInputStream(file); // find all edges if (vtkMetaDataSet::PlaceStreamCursor(file, "Edges")) { // read all edges this->ReadMeditCells(file, outputmesh, 2, cellarray); } vtkMetaDataSet::ClearInputStream(file); // read all triangles if (vtkMetaDataSet::PlaceStreamCursor(file, "Triangles")) { this->ReadMeditCells(file, outputmesh, 3, cellarray); } vtkMetaDataSet::ClearInputStream(file); // find all tetra if (vtkMetaDataSet::PlaceStreamCursor(file, "Tetrahedra")) { this->ReadMeditCells(file, outputmesh, 4, cellarray); } else { // no tetra found, the mesh file is incomplete cellarray->Delete(); outputmesh->Delete(); vtkErrorMacro("No triangle in file\n"); throw vtkErrorCode::CannotOpenFileError; } // finished reading cells if (outputmesh->GetCellData()) { outputmesh->GetCellData()->AddArray (cellarray); } this->SetDataSet (outputmesh); cellarray->Delete(); outputmesh->Delete(); } void vtkMetaVolumeMesh::ReadGMeshFile (const char* filename) { std::ifstream file (filename ); char str[256]; if(file.fail()) { vtkErrorMacro("File not found\n"); throw vtkErrorCode::FileNotFoundError; } vtkPoints* points = vtkPoints::New(); vtkUnsignedShortArray* pointarray = vtkUnsignedShortArray::New(); vtkUnsignedShortArray* cellarray = vtkUnsignedShortArray::New(); vtkUnstructuredGrid* outputmesh = vtkUnstructuredGrid::New(); unsigned short ref = 0; file >> str; while( (strcmp (str, "$NOD") != 0) ) { if (file.fail()) { points->Delete(); pointarray->Delete(); cellarray->Delete(); outputmesh->Delete(); vtkErrorMacro("No point in file\n"); throw vtkErrorCode::CannotOpenFileError; } file >> str; } unsigned int NVertices = 0; file >> NVertices; points->SetNumberOfPoints( NVertices ); pointarray->SetName ("Point array"); pointarray->Allocate(NVertices); // read vertex position for( unsigned int i = 0; i < NVertices; i++ ) { double pos[3]; file >> ref >> pos[0] >> pos[1] >> pos[2]; points->SetPoint(i, pos[0], pos[1], pos[2]); pointarray->InsertNextValue( ref - 1 ); } outputmesh->SetPoints (points); // if (outputmesh->GetPointData()) // { // outputmesh->GetPointData()->AddArray (pointarray); // } file >> str; while( (strcmp (str, "$ELM") != 0) ) { if (file.fail()) { points->Delete(); pointarray->Delete(); cellarray->Delete(); outputmesh->Delete(); vtkErrorMacro("No tetrahedron in file\n"); throw vtkErrorCode::CannotOpenFileError; } file >> str; } unsigned int NTetrahedra; file >> NTetrahedra; outputmesh->Allocate (NTetrahedra); cellarray->SetName ("Zones"); cellarray->Allocate(NTetrahedra); for( unsigned int i = 0; i < NTetrahedra; i++ ) { unsigned int ids[4]; unsigned int b1, b2, b3, b4; file >> ref >> b1 >> b2 >> b3 >> b4 >> ids[0] >> ids[1] >> ids[2] >> ids[3]; vtkIdList* idlist = vtkIdList::New(); idlist->InsertNextId(ids[0] - 1); idlist->InsertNextId(ids[1] - 1); idlist->InsertNextId(ids[2] - 1); idlist->InsertNextId(ids[3] - 1); outputmesh->InsertNextCell (VTK_TETRA, idlist); idlist->Delete(); cellarray->InsertNextValue(ref); } // if (outputmesh->GetCellData()) // { // outputmesh->GetCellData()->AddArray (cellarray); // } this->SetDataSet (outputmesh); points->Delete(); pointarray->Delete(); cellarray->Delete(); outputmesh->Delete(); } void vtkMetaVolumeMesh::ReadMeditCells(std::ifstream& file, vtkUnstructuredGrid* mesh, int nbCellPoints, vtkDataArray* attrArray) { int cellType = -1; switch (nbCellPoints) { case 4: cellType = VTK_TETRA; break; case 3: cellType = VTK_TRIANGLE; break; case 2: cellType = VTK_LINE; break; case 1: cellType = VTK_VERTEX; break; default: vtkErrorMacro("Invalid cell type for medit format"); return; } // read stream int i, nbCells; int ref; vtkSmartPointer<vtkIdList> idlist = vtkSmartPointer<vtkIdList>::New(); vtkIdType id; file >> nbCells; for (i = 0; i < nbCells && file.good(); ++i) { idlist->Initialize(); for (int j = 0; j < nbCellPoints; ++j) { file >> id; idlist->InsertNextId(id-1); } if (cellType == VTK_VERTEX) { ref = 0; } else { file >> ref; } mesh->InsertNextCell(cellType, idlist); attrArray->InsertNextTuple1(ref); } if (i != nbCells) { vtkErrorMacro("Unexpected end of file."); throw vtkErrorCode::PrematureEndOfFileError; } }
23.64076
129
0.597385
[ "mesh", "object" ]
c5b5d896bf1dfad429bb39987013ead891ebf8f7
26,782
cpp
C++
ref.neo/d3xp/gamesys/Class.cpp
Grimace1975/bclcontrib-scriptsharp
8c1b05024404e9115be96a328c79a8555eca2e4a
[ "MIT" ]
null
null
null
ref.neo/d3xp/gamesys/Class.cpp
Grimace1975/bclcontrib-scriptsharp
8c1b05024404e9115be96a328c79a8555eca2e4a
[ "MIT" ]
null
null
null
ref.neo/d3xp/gamesys/Class.cpp
Grimace1975/bclcontrib-scriptsharp
8c1b05024404e9115be96a328c79a8555eca2e4a
[ "MIT" ]
null
null
null
/* =========================================================================== Doom 3 GPL Source Code Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company. This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?). Doom 3 Source Code 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. Doom 3 Source Code 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 Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ /* Base class for all C++ objects. Provides fast run-time type checking and run-time instancing of objects. */ #include "../../idlib/precompiled.h" #pragma hdrstop #include "../Game_local.h" #include "TypeInfo.h" /*********************************************************************** idTypeInfo ***********************************************************************/ // this is the head of a singly linked list of all the idTypes static idTypeInfo *typelist = NULL; static idHierarchy<idTypeInfo> classHierarchy; static int eventCallbackMemory = 0; /* ================ idTypeInfo::idClassType() Constructor for class. Should only be called from CLASS_DECLARATION macro. Handles linking class definition into class hierarchy. This should only happen at startup as idTypeInfos are statically defined. Since static variables can be initialized in any order, the constructor must handle the case that subclasses are initialized before superclasses. ================ */ idTypeInfo::idTypeInfo( const char *classname, const char *superclass, idEventFunc<idClass> *eventCallbacks, idClass *( *CreateInstance )( void ), void ( idClass::*Spawn )( void ), void ( idClass::*Save )( idSaveGame *savefile ) const, void ( idClass::*Restore )( idRestoreGame *savefile ) ) { idTypeInfo *type; idTypeInfo **insert; this->classname = classname; this->superclass = superclass; this->eventCallbacks = eventCallbacks; this->eventMap = NULL; this->Spawn = Spawn; this->Save = Save; this->Restore = Restore; this->CreateInstance = CreateInstance; this->super = idClass::GetClass( superclass ); this->freeEventMap = false; typeNum = 0; lastChild = 0; // Check if any subclasses were initialized before their superclass for( type = typelist; type != NULL; type = type->next ) { if ( ( type->super == NULL ) && !idStr::Cmp( type->superclass, this->classname ) && idStr::Cmp( type->classname, "idClass" ) ) { type->super = this; } } // Insert sorted for ( insert = &typelist; *insert; insert = &(*insert)->next ) { assert( idStr::Cmp( classname, (*insert)->classname ) ); if ( idStr::Cmp( classname, (*insert)->classname ) < 0 ) { next = *insert; *insert = this; break; } } if ( !*insert ) { *insert = this; next = NULL; } } /* ================ idTypeInfo::~idTypeInfo ================ */ idTypeInfo::~idTypeInfo() { Shutdown(); } /* ================ idTypeInfo::Init Initializes the event callback table for the class. Creates a table for fast lookups of event functions. Should only be called once. ================ */ void idTypeInfo::Init( void ) { idTypeInfo *c; idEventFunc<idClass> *def; int ev; int i; bool *set; int num; if ( eventMap ) { // we've already been initialized by a subclass return; } // make sure our superclass is initialized first if ( super && !super->eventMap ) { super->Init(); } // add to our node hierarchy if ( super ) { node.ParentTo( super->node ); } else { node.ParentTo( classHierarchy ); } node.SetOwner( this ); // keep track of the number of children below each class for( c = super; c != NULL; c = c->super ) { c->lastChild++; } // if we're not adding any new event callbacks, we can just use our superclass's table if ( ( !eventCallbacks || !eventCallbacks->event ) && super ) { eventMap = super->eventMap; return; } // set a flag so we know to delete the eventMap table freeEventMap = true; // Allocate our new table. It has to have as many entries as there // are events. NOTE: could save some space by keeping track of the maximum // event that the class responds to and doing range checking. num = idEventDef::NumEventCommands(); eventMap = new eventCallback_t[ num ]; memset( eventMap, 0, sizeof( eventCallback_t ) * num ); eventCallbackMemory += sizeof( eventCallback_t ) * num; // allocate temporary memory for flags so that the subclass's event callbacks // override the superclass's event callback set = new bool[ num ]; memset( set, 0, sizeof( bool ) * num ); // go through the inheritence order and copies the event callback function into // a list indexed by the event number. This allows fast lookups of // event functions. for( c = this; c != NULL; c = c->super ) { def = c->eventCallbacks; if ( !def ) { continue; } // go through each entry until we hit the NULL terminator for( i = 0; def[ i ].event != NULL; i++ ) { ev = def[ i ].event->GetEventNum(); if ( set[ ev ] ) { continue; } set[ ev ] = true; eventMap[ ev ] = def[ i ].function; } } delete[] set; } /* ================ idTypeInfo::Shutdown Should only be called when DLL or EXE is being shutdown. Although it cleans up any allocated memory, it doesn't bother to remove itself from the class list since the program is shutting down. ================ */ void idTypeInfo::Shutdown() { // free up the memory used for event lookups if ( eventMap ) { if ( freeEventMap ) { delete[] eventMap; } eventMap = NULL; } typeNum = 0; lastChild = 0; } /*********************************************************************** idClass ***********************************************************************/ const idEventDef EV_Remove( "<immediateremove>", NULL ); const idEventDef EV_SafeRemove( "remove", NULL ); ABSTRACT_DECLARATION( NULL, idClass ) EVENT( EV_Remove, idClass::Event_Remove ) EVENT( EV_SafeRemove, idClass::Event_SafeRemove ) END_CLASS // alphabetical order idList<idTypeInfo *> idClass::types; // typenum order idList<idTypeInfo *> idClass::typenums; bool idClass::initialized = false; int idClass::typeNumBits = 0; int idClass::memused = 0; int idClass::numobjects = 0; /* ================ idClass::CallSpawn ================ */ void idClass::CallSpawn( void ) { idTypeInfo *type; type = GetType(); CallSpawnFunc( type ); } /* ================ idClass::CallSpawnFunc ================ */ classSpawnFunc_t idClass::CallSpawnFunc( idTypeInfo *cls ) { classSpawnFunc_t func; if ( cls->super ) { func = CallSpawnFunc( cls->super ); if ( func == cls->Spawn ) { // don't call the same function twice in a row. // this can happen when subclasses don't have their own spawn function. return func; } } ( this->*cls->Spawn )(); return cls->Spawn; } /* ================ idClass::FindUninitializedMemory ================ */ void idClass::FindUninitializedMemory( void ) { #ifdef ID_DEBUG_UNINITIALIZED_MEMORY unsigned long *ptr = ( ( unsigned long * )this ) - 1; int size = *ptr; assert( ( size & 3 ) == 0 ); size >>= 2; for ( int i = 0; i < size; i++ ) { if ( ptr[i] == 0xcdcdcdcd ) { const char *varName = GetTypeVariableName( GetClassname(), i << 2 ); gameLocal.Warning( "type '%s' has uninitialized variable %s (offset %d)", GetClassname(), varName, i << 2 ); } } #endif } /* ================ idClass::Spawn ================ */ void idClass::Spawn( void ) { } /* ================ idClass::~idClass Destructor for object. Cancels any events that depend on this object. ================ */ idClass::~idClass() { idEvent::CancelEvents( this ); } /* ================ idClass::DisplayInfo_f ================ */ void idClass::DisplayInfo_f( const idCmdArgs &args ) { gameLocal.Printf( "Class memory status: %i bytes allocated in %i objects\n", memused, numobjects ); } /* ================ idClass::ListClasses_f ================ */ void idClass::ListClasses_f( const idCmdArgs &args ) { int i; idTypeInfo *type; gameLocal.Printf( "%-24s %-24s %-6s %-6s\n", "Classname", "Superclass", "Type", "Subclasses" ); gameLocal.Printf( "----------------------------------------------------------------------\n" ); for( i = 0; i < types.Num(); i++ ) { type = types[ i ]; gameLocal.Printf( "%-24s %-24s %6d %6d\n", type->classname, type->superclass, type->typeNum, type->lastChild - type->typeNum ); } gameLocal.Printf( "...%d classes", types.Num() ); } /* ================ idClass::CreateInstance ================ */ idClass *idClass::CreateInstance( const char *name ) { const idTypeInfo *type; idClass *obj; type = idClass::GetClass( name ); if ( !type ) { return NULL; } obj = type->CreateInstance(); return obj; } /* ================ idClass::Init Should be called after all idTypeInfos are initialized, so must be called manually upon game code initialization. Tells all the idTypeInfos to initialize their event callback table for the associated class. This should only be called once during the execution of the program or DLL. ================ */ void idClass::Init( void ) { idTypeInfo *c; int num; gameLocal.Printf( "Initializing class hierarchy\n" ); if ( initialized ) { gameLocal.Printf( "...already initialized\n" ); return; } // init the event callback tables for all the classes for( c = typelist; c != NULL; c = c->next ) { c->Init(); } // number the types according to the class hierarchy so we can quickly determine if a class // is a subclass of another num = 0; for( c = classHierarchy.GetNext(); c != NULL; c = c->node.GetNext(), num++ ) { c->typeNum = num; c->lastChild += num; } // number of bits needed to send types over network typeNumBits = idMath::BitsForInteger( num ); // create a list of the types so we can do quick lookups // one list in alphabetical order, one in typenum order types.SetGranularity( 1 ); types.SetNum( num ); typenums.SetGranularity( 1 ); typenums.SetNum( num ); num = 0; for( c = typelist; c != NULL; c = c->next, num++ ) { types[ num ] = c; typenums[ c->typeNum ] = c; } initialized = true; gameLocal.Printf( "...%i classes, %i bytes for event callbacks\n", types.Num(), eventCallbackMemory ); } /* ================ idClass::Shutdown ================ */ void idClass::Shutdown( void ) { idTypeInfo *c; for( c = typelist; c != NULL; c = c->next ) { c->Shutdown(); } types.Clear(); typenums.Clear(); initialized = false; } /* ================ idClass::new ================ */ #ifdef ID_DEBUG_MEMORY #undef new #endif void * idClass::operator new( size_t s ) { int *p; s += sizeof( int ); p = (int *)Mem_Alloc( s ); *p = s; memused += s; numobjects++; #ifdef ID_DEBUG_UNINITIALIZED_MEMORY unsigned long *ptr = (unsigned long *)p; int size = s; assert( ( size & 3 ) == 0 ); size >>= 3; for ( int i = 1; i < size; i++ ) { ptr[i] = 0xcdcdcdcd; } #endif return p + 1; } void * idClass::operator new( size_t s, int, int, char *, int ) { int *p; s += sizeof( int ); p = (int *)Mem_Alloc( s ); *p = s; memused += s; numobjects++; #ifdef ID_DEBUG_UNINITIALIZED_MEMORY unsigned long *ptr = (unsigned long *)p; int size = s; assert( ( size & 3 ) == 0 ); size >>= 3; for ( int i = 1; i < size; i++ ) { ptr[i] = 0xcdcdcdcd; } #endif return p + 1; } #ifdef ID_DEBUG_MEMORY #define new ID_DEBUG_NEW #endif /* ================ idClass::delete ================ */ void idClass::operator delete( void *ptr ) { int *p; if ( ptr ) { p = ( ( int * )ptr ) - 1; memused -= *p; numobjects--; Mem_Free( p ); } } void idClass::operator delete( void *ptr, int, int, char *, int ) { int *p; if ( ptr ) { p = ( ( int * )ptr ) - 1; memused -= *p; numobjects--; Mem_Free( p ); } } /* ================ idClass::GetClass Returns the idTypeInfo for the name of the class passed in. This is a static function so it must be called as idClass::GetClass( classname ) ================ */ idTypeInfo *idClass::GetClass( const char *name ) { idTypeInfo *c; int order; int mid; int min; int max; if ( !initialized ) { // idClass::Init hasn't been called yet, so do a slow lookup for( c = typelist; c != NULL; c = c->next ) { if ( !idStr::Cmp( c->classname, name ) ) { return c; } } } else { // do a binary search through the list of types min = 0; max = types.Num() - 1; while( min <= max ) { mid = ( min + max ) / 2; c = types[ mid ]; order = idStr::Cmp( c->classname, name ); if ( !order ) { return c; } else if ( order > 0 ) { max = mid - 1; } else { min = mid + 1; } } } return NULL; } /* ================ idClass::GetType ================ */ idTypeInfo *idClass::GetType( const int typeNum ) { idTypeInfo *c; if ( !initialized ) { for( c = typelist; c != NULL; c = c->next ) { if ( c->typeNum == typeNum ) { return c; } } } else if ( ( typeNum >= 0 ) && ( typeNum < types.Num() ) ) { return typenums[ typeNum ]; } return NULL; } /* ================ idClass::GetClassname Returns the text classname of the object. ================ */ const char *idClass::GetClassname( void ) const { idTypeInfo *type; type = GetType(); return type->classname; } /* ================ idClass::GetSuperclass Returns the text classname of the superclass. ================ */ const char *idClass::GetSuperclass( void ) const { idTypeInfo *cls; cls = GetType(); return cls->superclass; } /* ================ idClass::CancelEvents ================ */ void idClass::CancelEvents( const idEventDef *ev ) { idEvent::CancelEvents( this, ev ); } /* ================ idClass::PostEventArgs ================ */ bool idClass::PostEventArgs( const idEventDef *ev, int time, int numargs, ... ) { idTypeInfo *c; idEvent *event; va_list args; assert( ev ); if ( !idEvent::initialized ) { return false; } c = GetType(); if ( !c->eventMap[ ev->GetEventNum() ] ) { // we don't respond to this event, so ignore it return false; } // we service events on the client to avoid any bad code filling up the event pool // we don't want them processed usually, unless when the map is (re)loading. // we allow threads to run fine, though. if ( gameLocal.isClient && ( gameLocal.GameState() != GAMESTATE_STARTUP ) && !IsType( idThread::Type ) ) { return true; } va_start( args, numargs ); event = idEvent::Alloc( ev, numargs, args ); va_end( args ); event->Schedule( this, c, time ); return true; } /* ================ idClass::PostEventMS ================ */ bool idClass::PostEventMS( const idEventDef *ev, int time ) { return PostEventArgs( ev, time, 0 ); } /* ================ idClass::PostEventMS ================ */ bool idClass::PostEventMS( const idEventDef *ev, int time, idEventArg arg1 ) { return PostEventArgs( ev, time, 1, &arg1 ); } /* ================ idClass::PostEventMS ================ */ bool idClass::PostEventMS( const idEventDef *ev, int time, idEventArg arg1, idEventArg arg2 ) { return PostEventArgs( ev, time, 2, &arg1, &arg2 ); } /* ================ idClass::PostEventMS ================ */ bool idClass::PostEventMS( const idEventDef *ev, int time, idEventArg arg1, idEventArg arg2, idEventArg arg3 ) { return PostEventArgs( ev, time, 3, &arg1, &arg2, &arg3 ); } /* ================ idClass::PostEventMS ================ */ bool idClass::PostEventMS( const idEventDef *ev, int time, idEventArg arg1, idEventArg arg2, idEventArg arg3, idEventArg arg4 ) { return PostEventArgs( ev, time, 4, &arg1, &arg2, &arg3, &arg4 ); } /* ================ idClass::PostEventMS ================ */ bool idClass::PostEventMS( const idEventDef *ev, int time, idEventArg arg1, idEventArg arg2, idEventArg arg3, idEventArg arg4, idEventArg arg5 ) { return PostEventArgs( ev, time, 5, &arg1, &arg2, &arg3, &arg4, &arg5 ); } /* ================ idClass::PostEventMS ================ */ bool idClass::PostEventMS( const idEventDef *ev, int time, idEventArg arg1, idEventArg arg2, idEventArg arg3, idEventArg arg4, idEventArg arg5, idEventArg arg6 ) { return PostEventArgs( ev, time, 6, &arg1, &arg2, &arg3, &arg4, &arg5, &arg6 ); } /* ================ idClass::PostEventMS ================ */ bool idClass::PostEventMS( const idEventDef *ev, int time, idEventArg arg1, idEventArg arg2, idEventArg arg3, idEventArg arg4, idEventArg arg5, idEventArg arg6, idEventArg arg7 ) { return PostEventArgs( ev, time, 7, &arg1, &arg2, &arg3, &arg4, &arg5, &arg6, &arg7 ); } /* ================ idClass::PostEventMS ================ */ bool idClass::PostEventMS( const idEventDef *ev, int time, idEventArg arg1, idEventArg arg2, idEventArg arg3, idEventArg arg4, idEventArg arg5, idEventArg arg6, idEventArg arg7, idEventArg arg8 ) { return PostEventArgs( ev, time, 8, &arg1, &arg2, &arg3, &arg4, &arg5, &arg6, &arg7, &arg8 ); } /* ================ idClass::PostEventSec ================ */ bool idClass::PostEventSec( const idEventDef *ev, float time ) { return PostEventArgs( ev, SEC2MS( time ), 0 ); } /* ================ idClass::PostEventSec ================ */ bool idClass::PostEventSec( const idEventDef *ev, float time, idEventArg arg1 ) { return PostEventArgs( ev, SEC2MS( time ), 1, &arg1 ); } /* ================ idClass::PostEventSec ================ */ bool idClass::PostEventSec( const idEventDef *ev, float time, idEventArg arg1, idEventArg arg2 ) { return PostEventArgs( ev, SEC2MS( time ), 2, &arg1, &arg2 ); } /* ================ idClass::PostEventSec ================ */ bool idClass::PostEventSec( const idEventDef *ev, float time, idEventArg arg1, idEventArg arg2, idEventArg arg3 ) { return PostEventArgs( ev, SEC2MS( time ), 3, &arg1, &arg2, &arg3 ); } /* ================ idClass::PostEventSec ================ */ bool idClass::PostEventSec( const idEventDef *ev, float time, idEventArg arg1, idEventArg arg2, idEventArg arg3, idEventArg arg4 ) { return PostEventArgs( ev, SEC2MS( time ), 4, &arg1, &arg2, &arg3, &arg4 ); } /* ================ idClass::PostEventSec ================ */ bool idClass::PostEventSec( const idEventDef *ev, float time, idEventArg arg1, idEventArg arg2, idEventArg arg3, idEventArg arg4, idEventArg arg5 ) { return PostEventArgs( ev, SEC2MS( time ), 5, &arg1, &arg2, &arg3, &arg4, &arg5 ); } /* ================ idClass::PostEventSec ================ */ bool idClass::PostEventSec( const idEventDef *ev, float time, idEventArg arg1, idEventArg arg2, idEventArg arg3, idEventArg arg4, idEventArg arg5, idEventArg arg6 ) { return PostEventArgs( ev, SEC2MS( time ), 6, &arg1, &arg2, &arg3, &arg4, &arg5, &arg6 ); } /* ================ idClass::PostEventSec ================ */ bool idClass::PostEventSec( const idEventDef *ev, float time, idEventArg arg1, idEventArg arg2, idEventArg arg3, idEventArg arg4, idEventArg arg5, idEventArg arg6, idEventArg arg7 ) { return PostEventArgs( ev, SEC2MS( time ), 7, &arg1, &arg2, &arg3, &arg4, &arg5, &arg6, &arg7 ); } /* ================ idClass::PostEventSec ================ */ bool idClass::PostEventSec( const idEventDef *ev, float time, idEventArg arg1, idEventArg arg2, idEventArg arg3, idEventArg arg4, idEventArg arg5, idEventArg arg6, idEventArg arg7, idEventArg arg8 ) { return PostEventArgs( ev, SEC2MS( time ), 8, &arg1, &arg2, &arg3, &arg4, &arg5, &arg6, &arg7, &arg8 ); } /* ================ idClass::ProcessEventArgs ================ */ bool idClass::ProcessEventArgs( const idEventDef *ev, int numargs, ... ) { idTypeInfo *c; int num; int data[ D_EVENT_MAXARGS ]; va_list args; assert( ev ); assert( idEvent::initialized ); c = GetType(); num = ev->GetEventNum(); if ( !c->eventMap[ num ] ) { // we don't respond to this event, so ignore it return false; } va_start( args, numargs ); idEvent::CopyArgs( ev, numargs, args, data ); va_end( args ); ProcessEventArgPtr( ev, data ); return true; } /* ================ idClass::ProcessEvent ================ */ bool idClass::ProcessEvent( const idEventDef *ev ) { return ProcessEventArgs( ev, 0 ); } /* ================ idClass::ProcessEvent ================ */ bool idClass::ProcessEvent( const idEventDef *ev, idEventArg arg1 ) { return ProcessEventArgs( ev, 1, &arg1 ); } /* ================ idClass::ProcessEvent ================ */ bool idClass::ProcessEvent( const idEventDef *ev, idEventArg arg1, idEventArg arg2 ) { return ProcessEventArgs( ev, 2, &arg1, &arg2 ); } /* ================ idClass::ProcessEvent ================ */ bool idClass::ProcessEvent( const idEventDef *ev, idEventArg arg1, idEventArg arg2, idEventArg arg3 ) { return ProcessEventArgs( ev, 3, &arg1, &arg2, &arg3 ); } /* ================ idClass::ProcessEvent ================ */ bool idClass::ProcessEvent( const idEventDef *ev, idEventArg arg1, idEventArg arg2, idEventArg arg3, idEventArg arg4 ) { return ProcessEventArgs( ev, 4, &arg1, &arg2, &arg3, &arg4 ); } /* ================ idClass::ProcessEvent ================ */ bool idClass::ProcessEvent( const idEventDef *ev, idEventArg arg1, idEventArg arg2, idEventArg arg3, idEventArg arg4, idEventArg arg5 ) { return ProcessEventArgs( ev, 5, &arg1, &arg2, &arg3, &arg4, &arg5 ); } /* ================ idClass::ProcessEvent ================ */ bool idClass::ProcessEvent( const idEventDef *ev, idEventArg arg1, idEventArg arg2, idEventArg arg3, idEventArg arg4, idEventArg arg5, idEventArg arg6 ) { return ProcessEventArgs( ev, 6, &arg1, &arg2, &arg3, &arg4, &arg5, &arg6 ); } /* ================ idClass::ProcessEvent ================ */ bool idClass::ProcessEvent( const idEventDef *ev, idEventArg arg1, idEventArg arg2, idEventArg arg3, idEventArg arg4, idEventArg arg5, idEventArg arg6, idEventArg arg7 ) { return ProcessEventArgs( ev, 7, &arg1, &arg2, &arg3, &arg4, &arg5, &arg6, &arg7 ); } /* ================ idClass::ProcessEvent ================ */ bool idClass::ProcessEvent( const idEventDef *ev, idEventArg arg1, idEventArg arg2, idEventArg arg3, idEventArg arg4, idEventArg arg5, idEventArg arg6, idEventArg arg7, idEventArg arg8 ) { return ProcessEventArgs( ev, 8, &arg1, &arg2, &arg3, &arg4, &arg5, &arg6, &arg7, &arg8 ); } /* ================ idClass::ProcessEventArgPtr ================ */ bool idClass::ProcessEventArgPtr( const idEventDef *ev, int *data ) { idTypeInfo *c; int num; eventCallback_t callback; assert( ev ); assert( idEvent::initialized ); #ifdef _D3XP SetTimeState ts; if ( IsType( idEntity::Type ) ) { idEntity *ent = (idEntity*)this; ts.PushState( ent->timeGroup ); } #endif if ( g_debugTriggers.GetBool() && ( ev == &EV_Activate ) && IsType( idEntity::Type ) ) { const idEntity *ent = *reinterpret_cast<idEntity **>( data ); gameLocal.Printf( "%d: '%s' activated by '%s'\n", gameLocal.framenum, static_cast<idEntity *>( this )->GetName(), ent ? ent->GetName() : "NULL" ); } c = GetType(); num = ev->GetEventNum(); if ( !c->eventMap[ num ] ) { // we don't respond to this event, so ignore it return false; } callback = c->eventMap[ num ]; #if !CPU_EASYARGS /* on ppc architecture, floats are passed in a seperate set of registers the function prototypes must have matching float declaration http://developer.apple.com/documentation/DeveloperTools/Conceptual/MachORuntime/2rt_powerpc_abi/chapter_9_section_5.html */ switch( ev->GetFormatspecIndex() ) { case 1 << D_EVENT_MAXARGS : ( this->*callback )(); break; // generated file - see CREATE_EVENT_CODE #include "Callbacks.cpp" default: gameLocal.Warning( "Invalid formatspec on event '%s'", ev->GetName() ); break; } #else assert( D_EVENT_MAXARGS == 8 ); switch( ev->GetNumArgs() ) { case 0 : ( this->*callback )(); break; case 1 : typedef void ( idClass::*eventCallback_1_t )( const int ); ( this->*( eventCallback_1_t )callback )( data[ 0 ] ); break; case 2 : typedef void ( idClass::*eventCallback_2_t )( const int, const int ); ( this->*( eventCallback_2_t )callback )( data[ 0 ], data[ 1 ] ); break; case 3 : typedef void ( idClass::*eventCallback_3_t )( const int, const int, const int ); ( this->*( eventCallback_3_t )callback )( data[ 0 ], data[ 1 ], data[ 2 ] ); break; case 4 : typedef void ( idClass::*eventCallback_4_t )( const int, const int, const int, const int ); ( this->*( eventCallback_4_t )callback )( data[ 0 ], data[ 1 ], data[ 2 ], data[ 3 ] ); break; case 5 : typedef void ( idClass::*eventCallback_5_t )( const int, const int, const int, const int, const int ); ( this->*( eventCallback_5_t )callback )( data[ 0 ], data[ 1 ], data[ 2 ], data[ 3 ], data[ 4 ] ); break; case 6 : typedef void ( idClass::*eventCallback_6_t )( const int, const int, const int, const int, const int, const int ); ( this->*( eventCallback_6_t )callback )( data[ 0 ], data[ 1 ], data[ 2 ], data[ 3 ], data[ 4 ], data[ 5 ] ); break; case 7 : typedef void ( idClass::*eventCallback_7_t )( const int, const int, const int, const int, const int, const int, const int ); ( this->*( eventCallback_7_t )callback )( data[ 0 ], data[ 1 ], data[ 2 ], data[ 3 ], data[ 4 ], data[ 5 ], data[ 6 ] ); break; case 8 : typedef void ( idClass::*eventCallback_8_t )( const int, const int, const int, const int, const int, const int, const int, const int ); ( this->*( eventCallback_8_t )callback )( data[ 0 ], data[ 1 ], data[ 2 ], data[ 3 ], data[ 4 ], data[ 5 ], data[ 6 ], data[ 7 ] ); break; default: gameLocal.Warning( "Invalid formatspec on event '%s'", ev->GetName() ); break; } #endif return true; } /* ================ idClass::Event_Remove ================ */ void idClass::Event_Remove( void ) { delete this; } /* ================ idClass::Event_SafeRemove ================ */ void idClass::Event_SafeRemove( void ) { // Forces the remove to be done at a safe time PostEventMS( &EV_Remove, 0 ); }
25.053321
342
0.616309
[ "object" ]
c5bfb355392f6579073d7fe28f5982f93c21556b
37,897
cc
C++
src/vendor/mariadb-10.6.7/storage/innobase/mtr/mtr0mtr.cc
zettadb/zettalib
3d5f96dc9e3e4aa255f4e6105489758944d37cc4
[ "Apache-2.0" ]
null
null
null
src/vendor/mariadb-10.6.7/storage/innobase/mtr/mtr0mtr.cc
zettadb/zettalib
3d5f96dc9e3e4aa255f4e6105489758944d37cc4
[ "Apache-2.0" ]
null
null
null
src/vendor/mariadb-10.6.7/storage/innobase/mtr/mtr0mtr.cc
zettadb/zettalib
3d5f96dc9e3e4aa255f4e6105489758944d37cc4
[ "Apache-2.0" ]
2
2022-02-27T14:00:01.000Z
2022-03-31T06:24:22.000Z
/***************************************************************************** Copyright (c) 1995, 2017, Oracle and/or its affiliates. All Rights Reserved. Copyright (c) 2017, 2022, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA *****************************************************************************/ /**************************************************//** @file mtr/mtr0mtr.cc Mini-transaction buffer Created 11/26/1995 Heikki Tuuri *******************************************************/ #include "mtr0mtr.h" #include "buf0buf.h" #include "buf0flu.h" #include "fsp0sysspace.h" #include "page0types.h" #include "mtr0log.h" #include "log0recv.h" #include "my_cpu.h" #ifdef BTR_CUR_HASH_ADAPT # include "btr0sea.h" #endif /** Iterate over a memo block in reverse. */ template <typename Functor> struct CIterate { CIterate() : functor() {} CIterate(const Functor& functor) : functor(functor) {} /** @return false if the functor returns false. */ bool operator()(mtr_buf_t::block_t* block) const { const mtr_memo_slot_t* start = reinterpret_cast<const mtr_memo_slot_t*>( block->begin()); mtr_memo_slot_t* slot = reinterpret_cast<mtr_memo_slot_t*>( block->end()); ut_ad(!(block->used() % sizeof(*slot))); while (slot-- != start) { if (!functor(slot)) { return(false); } } return(true); } Functor functor; }; template <typename Functor> struct Iterate { Iterate() : functor() {} Iterate(const Functor& functor) : functor(functor) {} /** @return false if the functor returns false. */ bool operator()(mtr_buf_t::block_t* block) { const mtr_memo_slot_t* start = reinterpret_cast<const mtr_memo_slot_t*>( block->begin()); mtr_memo_slot_t* slot = reinterpret_cast<mtr_memo_slot_t*>( block->end()); ut_ad(!(block->used() % sizeof(*slot))); while (slot-- != start) { if (!functor(slot)) { return(false); } } return(true); } Functor functor; }; /** Find specific object */ struct Find { /** Constructor */ Find(const void* object, ulint type) : m_slot(), m_type(type), m_object(object) { ut_a(object != NULL); } /** @return false if the object was found. */ bool operator()(mtr_memo_slot_t* slot) { if (m_object == slot->object && m_type == slot->type) { m_slot = slot; return(false); } return(true); } /** Slot if found */ mtr_memo_slot_t*m_slot; /** Type of the object to look for */ const ulint m_type; /** The object instance to look for */ const void* m_object; }; /** Find a page frame */ struct FindPage { /** Constructor @param[in] ptr pointer to within a page frame @param[in] flags MTR_MEMO flags to look for */ FindPage(const void* ptr, ulint flags) : m_ptr(ptr), m_flags(flags), m_slot(NULL) { /* There must be some flags to look for. */ ut_ad(flags); /* We can only look for page-related flags. */ ut_ad(!(flags & ulint(~(MTR_MEMO_PAGE_S_FIX | MTR_MEMO_PAGE_X_FIX | MTR_MEMO_PAGE_SX_FIX | MTR_MEMO_BUF_FIX | MTR_MEMO_MODIFY)))); } /** Visit a memo entry. @param[in] slot memo entry to visit @retval false if a page was found @retval true if the iteration should continue */ bool operator()(mtr_memo_slot_t* slot) { ut_ad(m_slot == NULL); if (!(m_flags & slot->type) || slot->object == NULL) { return(true); } buf_page_t* bpage = static_cast<buf_page_t*>(slot->object); if (m_ptr < bpage->frame || m_ptr >= bpage->frame + srv_page_size) { return(true); } ut_ad(!(slot->type & MTR_MEMO_PAGE_S_FIX) || bpage->lock.have_s()); ut_ad(!(slot->type & MTR_MEMO_PAGE_SX_FIX) || bpage->lock.have_u_or_x()); ut_ad(!(slot->type & MTR_MEMO_PAGE_X_FIX) || bpage->lock.have_x()); m_slot = slot; return(false); } /** @return the slot that was found */ mtr_memo_slot_t* get_slot() const { ut_ad(m_slot != NULL); return(m_slot); } /** @return the block that was found */ buf_block_t* get_block() const { return(reinterpret_cast<buf_block_t*>(get_slot()->object)); } private: /** Pointer inside a page frame to look for */ const void*const m_ptr; /** MTR_MEMO flags to look for */ const ulint m_flags; /** The slot corresponding to m_ptr */ mtr_memo_slot_t* m_slot; }; /** Release latches and decrement the buffer fix count. @param slot memo slot */ static void memo_slot_release(mtr_memo_slot_t *slot) { void *object= slot->object; slot->object= nullptr; switch (const auto type= slot->type) { case MTR_MEMO_S_LOCK: static_cast<index_lock*>(object)->s_unlock(); break; case MTR_MEMO_X_LOCK: case MTR_MEMO_SX_LOCK: static_cast<index_lock*>(object)-> u_or_x_unlock(type == MTR_MEMO_SX_LOCK); break; case MTR_MEMO_SPACE_X_LOCK: static_cast<fil_space_t*>(object)->set_committed_size(); static_cast<fil_space_t*>(object)->x_unlock(); break; case MTR_MEMO_SPACE_S_LOCK: static_cast<fil_space_t*>(object)->s_unlock(); break; default: buf_page_t *bpage= static_cast<buf_page_t*>(object); bpage->unfix(); switch (auto latch= slot->type & ~MTR_MEMO_MODIFY) { case MTR_MEMO_PAGE_S_FIX: bpage->lock.s_unlock(); return; case MTR_MEMO_PAGE_SX_FIX: case MTR_MEMO_PAGE_X_FIX: bpage->lock.u_or_x_unlock(latch == MTR_MEMO_PAGE_SX_FIX); /* fall through */ case MTR_MEMO_BUF_FIX: return; } ut_ad("invalid type" == 0); } } /** Release the latches acquired by the mini-transaction. */ struct ReleaseLatches { /** @return true always. */ bool operator()(mtr_memo_slot_t *slot) const { void *object= slot->object; if (!object) return true; slot->object= nullptr; switch (const auto type= slot->type) { case MTR_MEMO_S_LOCK: static_cast<index_lock*>(object)->s_unlock(); break; case MTR_MEMO_SPACE_X_LOCK: static_cast<fil_space_t*>(object)->set_committed_size(); static_cast<fil_space_t*>(object)->x_unlock(); break; case MTR_MEMO_SPACE_S_LOCK: static_cast<fil_space_t*>(object)->s_unlock(); break; case MTR_MEMO_X_LOCK: case MTR_MEMO_SX_LOCK: static_cast<index_lock*>(object)-> u_or_x_unlock(type == MTR_MEMO_SX_LOCK); break; default: buf_page_t *bpage= static_cast<buf_page_t*>(object); bpage->unfix(); switch (auto latch= slot->type & ~MTR_MEMO_MODIFY) { case MTR_MEMO_PAGE_S_FIX: bpage->lock.s_unlock(); return true; case MTR_MEMO_PAGE_SX_FIX: case MTR_MEMO_PAGE_X_FIX: bpage->lock.u_or_x_unlock(latch == MTR_MEMO_PAGE_SX_FIX); /* fall through */ case MTR_MEMO_BUF_FIX: return true; } ut_ad("invalid type" == 0); } return true; } }; /** Release the latches and blocks acquired by the mini-transaction. */ struct ReleaseAll { /** @return true always. */ bool operator()(mtr_memo_slot_t *slot) const { if (slot->object) memo_slot_release(slot); return true; } }; #ifdef UNIV_DEBUG /** Check that all slots have been handled. */ struct DebugCheck { /** @return true always. */ bool operator()(const mtr_memo_slot_t* slot) const { ut_ad(!slot->object); return(true); } }; #endif /** Release page latches held by the mini-transaction. */ struct ReleaseBlocks { const lsn_t start, end; #ifdef UNIV_DEBUG const mtr_buf_t &memo; ReleaseBlocks(lsn_t start, lsn_t end, const mtr_buf_t &memo) : start(start), end(end), memo(memo) #else /* UNIV_DEBUG */ ReleaseBlocks(lsn_t start, lsn_t end, const mtr_buf_t&) : start(start), end(end) #endif /* UNIV_DEBUG */ { ut_ad(start); ut_ad(end); } /** @return true always */ bool operator()(mtr_memo_slot_t* slot) const { if (!slot->object) return true; switch (slot->type) { case MTR_MEMO_PAGE_X_MODIFY: case MTR_MEMO_PAGE_SX_MODIFY: break; default: ut_ad(!(slot->type & MTR_MEMO_MODIFY)); return true; } buf_flush_note_modification(static_cast<buf_block_t*>(slot->object), start, end); return true; } }; /** Start a mini-transaction. */ void mtr_t::start() { ut_ad(!m_freed_pages); ut_ad(!m_freed_space); MEM_UNDEFINED(this, sizeof *this); MEM_MAKE_DEFINED(&m_freed_space, sizeof m_freed_space); MEM_MAKE_DEFINED(&m_freed_pages, sizeof m_freed_pages); ut_d(m_start= true); ut_d(m_commit= false); ut_d(m_freeing_tree= false); m_last= nullptr; m_last_offset= 0; new(&m_memo) mtr_buf_t(); new(&m_log) mtr_buf_t(); m_made_dirty= false; m_inside_ibuf= false; m_modifications= false; m_log_mode= MTR_LOG_ALL; ut_d(m_user_space_id= TRX_SYS_SPACE); m_user_space= nullptr; m_commit_lsn= 0; m_trim_pages= false; } /** Release the resources */ inline void mtr_t::release_resources() { ut_ad(is_active()); ut_d(m_memo.for_each_block_in_reverse(CIterate<DebugCheck>())); m_log.erase(); m_memo.erase(); ut_d(m_commit= true); } /** Commit a mini-transaction. */ void mtr_t::commit() { ut_ad(is_active()); ut_ad(!is_inside_ibuf()); /* This is a dirty read, for debugging. */ ut_ad(!m_modifications || !recv_no_log_write); ut_ad(!m_modifications || m_log_mode != MTR_LOG_NONE); if (m_modifications && (m_log_mode == MTR_LOG_NO_REDO || !m_log.empty())) { ut_ad(!srv_read_only_mode || m_log_mode == MTR_LOG_NO_REDO); std::pair<lsn_t,page_flush_ahead> lsns; if (UNIV_LIKELY(m_log_mode == MTR_LOG_ALL)) { lsns= do_write(); if (m_made_dirty) mysql_mutex_lock(&log_sys.flush_order_mutex); /* It is now safe to release log_sys.mutex because the buf_pool.flush_order_mutex will ensure that we are the first one to insert into buf_pool.flush_list. */ mysql_mutex_unlock(&log_sys.mutex); } else { ut_ad(m_log_mode == MTR_LOG_NO_REDO); ut_ad(m_log.size() == 0); m_commit_lsn= log_sys.get_lsn(); lsns= { m_commit_lsn, PAGE_FLUSH_NO }; if (UNIV_UNLIKELY(m_made_dirty)) /* This should be IMPORT TABLESPACE */ mysql_mutex_lock(&log_sys.flush_order_mutex); } if (m_freed_pages) { ut_ad(!m_freed_pages->empty()); ut_ad(m_freed_space); ut_ad(m_freed_space->is_owner()); ut_ad(is_named_space(m_freed_space)); /* Update the last freed lsn */ m_freed_space->update_last_freed_lsn(m_commit_lsn); if (!is_trim_pages()) for (const auto &range : *m_freed_pages) m_freed_space->add_free_range(range); else m_freed_space->clear_freed_ranges(); delete m_freed_pages; m_freed_pages= nullptr; m_freed_space= nullptr; /* mtr_t::start() will reset m_trim_pages */ } else ut_ad(!m_freed_space); m_memo.for_each_block_in_reverse(CIterate<const ReleaseBlocks> (ReleaseBlocks(lsns.first, m_commit_lsn, m_memo))); if (m_made_dirty) mysql_mutex_unlock(&log_sys.flush_order_mutex); m_memo.for_each_block_in_reverse(CIterate<ReleaseLatches>()); if (UNIV_UNLIKELY(lsns.second != PAGE_FLUSH_NO)) buf_flush_ahead(m_commit_lsn, lsns.second == PAGE_FLUSH_SYNC); if (m_made_dirty) srv_stats.log_write_requests.inc(); } else m_memo.for_each_block_in_reverse(CIterate<ReleaseAll>()); release_resources(); } /** Shrink a tablespace. */ struct Shrink { /** the first non-existing page in the tablespace */ const page_id_t high; Shrink(const fil_space_t &space) : high({space.id, space.size}) {} bool operator()(mtr_memo_slot_t *slot) const { if (!slot->object) return true; switch (slot->type) { default: ut_ad("invalid type" == 0); return false; case MTR_MEMO_SPACE_X_LOCK: ut_ad(high.space() == static_cast<fil_space_t*>(slot->object)->id); return true; case MTR_MEMO_PAGE_X_MODIFY: case MTR_MEMO_PAGE_SX_MODIFY: case MTR_MEMO_PAGE_X_FIX: case MTR_MEMO_PAGE_SX_FIX: auto &bpage= static_cast<buf_block_t*>(slot->object)->page; const auto s= bpage.state(); ut_ad(s >= buf_page_t::FREED); ut_ad(s < buf_page_t::READ_FIX); ut_ad(bpage.frame); const page_id_t id{bpage.id()}; if (id < high) { ut_ad(id.space() == high.space() || (id == page_id_t{0, TRX_SYS_PAGE_NO} && srv_is_undo_tablespace(high.space()))); break; } if (s >= buf_page_t::UNFIXED) bpage.set_freed(s); ut_ad(id.space() == high.space()); if (bpage.oldest_modification() > 1) bpage.reset_oldest_modification(); slot->type= static_cast<mtr_memo_type_t>(slot->type & ~MTR_MEMO_MODIFY); } return true; } }; /** Commit a mini-transaction that is shrinking a tablespace. @param space tablespace that is being shrunk */ void mtr_t::commit_shrink(fil_space_t &space) { ut_ad(is_active()); ut_ad(!is_inside_ibuf()); ut_ad(!high_level_read_only); ut_ad(m_modifications); ut_ad(m_made_dirty); ut_ad(!recv_recovery_is_on()); ut_ad(m_log_mode == MTR_LOG_ALL); ut_ad(UT_LIST_GET_LEN(space.chain) == 1); log_write_and_flush_prepare(); const lsn_t start_lsn= do_write().first; mysql_mutex_lock(&log_sys.flush_order_mutex); /* Durably write the reduced FSP_SIZE before truncating the data file. */ log_write_and_flush(); os_file_truncate(space.chain.start->name, space.chain.start->handle, os_offset_t{space.size} << srv_page_size_shift, true); if (m_freed_pages) { ut_ad(!m_freed_pages->empty()); ut_ad(m_freed_space == &space); ut_ad(memo_contains(*m_freed_space)); ut_ad(is_named_space(m_freed_space)); m_freed_space->update_last_freed_lsn(m_commit_lsn); if (!is_trim_pages()) for (const auto &range : *m_freed_pages) m_freed_space->add_free_range(range); else m_freed_space->clear_freed_ranges(); delete m_freed_pages; m_freed_pages= nullptr; m_freed_space= nullptr; /* mtr_t::start() will reset m_trim_pages */ } else ut_ad(!m_freed_space); m_memo.for_each_block_in_reverse(CIterate<Shrink>{space}); m_memo.for_each_block_in_reverse(CIterate<const ReleaseBlocks> (ReleaseBlocks(start_lsn, m_commit_lsn, m_memo))); mysql_mutex_unlock(&log_sys.flush_order_mutex); mysql_mutex_lock(&fil_system.mutex); ut_ad(space.is_being_truncated); ut_ad(space.is_stopping()); space.clear_stopping(); space.is_being_truncated= false; mysql_mutex_unlock(&fil_system.mutex); m_memo.for_each_block_in_reverse(CIterate<ReleaseLatches>()); srv_stats.log_write_requests.inc(); release_resources(); } /** Commit a mini-transaction that did not modify any pages, but generated some redo log on a higher level, such as FILE_MODIFY records and an optional FILE_CHECKPOINT marker. The caller must hold log_sys.mutex. This is to be used at log_checkpoint(). @param[in] checkpoint_lsn log checkpoint LSN, or 0 */ void mtr_t::commit_files(lsn_t checkpoint_lsn) { mysql_mutex_assert_owner(&log_sys.mutex); ut_ad(is_active()); ut_ad(!is_inside_ibuf()); ut_ad(m_log_mode == MTR_LOG_ALL); ut_ad(!m_made_dirty); ut_ad(m_memo.size() == 0); ut_ad(!srv_read_only_mode); ut_ad(!m_freed_space); ut_ad(!m_freed_pages); if (checkpoint_lsn) { byte* ptr = m_log.push<byte*>(SIZE_OF_FILE_CHECKPOINT); compile_time_assert(SIZE_OF_FILE_CHECKPOINT == 3 + 8 + 1); *ptr = FILE_CHECKPOINT | (SIZE_OF_FILE_CHECKPOINT - 2); ::memset(ptr + 1, 0, 2); mach_write_to_8(ptr + 3, checkpoint_lsn); ptr[3 + 8] = 0; } else { *m_log.push<byte*>(1) = 0; } finish_write(m_log.size()); srv_stats.log_write_requests.inc(); release_resources(); if (checkpoint_lsn) { DBUG_PRINT("ib_log", ("FILE_CHECKPOINT(" LSN_PF ") written at " LSN_PF, checkpoint_lsn, log_sys.get_lsn())); } } #ifdef UNIV_DEBUG /** Check if a tablespace is associated with the mini-transaction (needed for generating a FILE_MODIFY record) @param[in] space tablespace @return whether the mini-transaction is associated with the space */ bool mtr_t::is_named_space(ulint space) const { ut_ad(!m_user_space || m_user_space->id != TRX_SYS_SPACE); switch (m_log_mode) { case MTR_LOG_NONE: case MTR_LOG_NO_REDO: return(true); case MTR_LOG_ALL: return(m_user_space_id == space || is_predefined_tablespace(space)); } ut_error; return(false); } /** Check if a tablespace is associated with the mini-transaction (needed for generating a FILE_MODIFY record) @param[in] space tablespace @return whether the mini-transaction is associated with the space */ bool mtr_t::is_named_space(const fil_space_t* space) const { ut_ad(!m_user_space || m_user_space->id != TRX_SYS_SPACE); switch (m_log_mode) { case MTR_LOG_NONE: case MTR_LOG_NO_REDO: return true; case MTR_LOG_ALL: return m_user_space == space || is_predefined_tablespace(space->id); } ut_error; return false; } #endif /* UNIV_DEBUG */ /** Acquire a tablespace X-latch. @param[in] space_id tablespace ID @return the tablespace object (never NULL) */ fil_space_t* mtr_t::x_lock_space(ulint space_id) { fil_space_t* space; ut_ad(is_active()); if (space_id == TRX_SYS_SPACE) { space = fil_system.sys_space; } else if ((space = m_user_space) && space_id == space->id) { } else { space = fil_space_get(space_id); ut_ad(m_log_mode != MTR_LOG_NO_REDO || space->purpose == FIL_TYPE_TEMPORARY || space->purpose == FIL_TYPE_IMPORT); } ut_ad(space); ut_ad(space->id == space_id); x_lock_space(space); return(space); } /** Acquire an exclusive tablespace latch. @param space tablespace */ void mtr_t::x_lock_space(fil_space_t *space) { ut_ad(space->purpose == FIL_TYPE_TEMPORARY || space->purpose == FIL_TYPE_IMPORT || space->purpose == FIL_TYPE_TABLESPACE); if (!memo_contains(*space)) { memo_push(space, MTR_MEMO_SPACE_X_LOCK); space->x_lock(); } } /** Release an object in the memo stack. @return true if released */ bool mtr_t::memo_release(const void* object, ulint type) { ut_ad(is_active()); /* We cannot release a page that has been written to in the middle of a mini-transaction. */ ut_ad(!m_modifications || type != MTR_MEMO_PAGE_X_FIX); Iterate<Find> iteration(Find(object, type)); if (!m_memo.for_each_block_in_reverse(iteration)) { memo_slot_release(iteration.functor.m_slot); return(true); } return(false); } /** Release a page latch. @param[in] ptr pointer to within a page frame @param[in] type object type: MTR_MEMO_PAGE_X_FIX, ... */ void mtr_t::release_page(const void* ptr, mtr_memo_type_t type) { ut_ad(is_active()); /* We cannot release a page that has been written to in the middle of a mini-transaction. */ ut_ad(!m_modifications || type != MTR_MEMO_PAGE_X_FIX); Iterate<FindPage> iteration(FindPage(ptr, type)); if (!m_memo.for_each_block_in_reverse(iteration)) { memo_slot_release(iteration.functor.get_slot()); return; } /* The page was not found! */ ut_ad(0); } static bool log_margin_warned; static time_t log_margin_warn_time; static bool log_close_warned; static time_t log_close_warn_time; /** Check margin not to overwrite transaction log from the last checkpoint. If would estimate the log write to exceed the log_capacity, waits for the checkpoint is done enough. @param len length of the data to be written */ static void log_margin_checkpoint_age(ulint len) { const ulint framing_size= log_sys.framing_size(); /* actual length stored per block */ const ulint len_per_blk= OS_FILE_LOG_BLOCK_SIZE - framing_size; /* actual data length in last block already written */ ulint extra_len= log_sys.buf_free % OS_FILE_LOG_BLOCK_SIZE; ut_ad(extra_len >= LOG_BLOCK_HDR_SIZE); extra_len-= LOG_BLOCK_HDR_SIZE; /* total extra length for block header and trailer */ extra_len= ((len + extra_len) / len_per_blk) * framing_size; const ulint margin= len + extra_len; mysql_mutex_assert_owner(&log_sys.mutex); const lsn_t lsn= log_sys.get_lsn(); if (UNIV_UNLIKELY(margin > log_sys.log_capacity)) { time_t t= time(nullptr); /* return with warning output to avoid deadlock */ if (!log_margin_warned || difftime(t, log_margin_warn_time) > 15) { log_margin_warned= true; log_margin_warn_time= t; ib::error() << "innodb_log_file_size is too small " "for mini-transaction size " << len; } } else if (UNIV_LIKELY(lsn + margin <= log_sys.last_checkpoint_lsn + log_sys.log_capacity)) return; log_sys.set_check_flush_or_checkpoint(); } /** Open the log for log_write_low(). The log must be closed with log_close(). @param len length of the data to be written @return start lsn of the log record */ static lsn_t log_reserve_and_open(size_t len) { for (ut_d(ulint count= 0);;) { mysql_mutex_assert_owner(&log_sys.mutex); /* Calculate an upper limit for the space the string may take in the log buffer */ size_t len_upper_limit= (4 * OS_FILE_LOG_BLOCK_SIZE) + srv_log_write_ahead_size + (5 * len) / 4; if (log_sys.buf_free + len_upper_limit <= srv_log_buffer_size) break; mysql_mutex_unlock(&log_sys.mutex); DEBUG_SYNC_C("log_buf_size_exceeded"); /* Not enough free space, do a write of the log buffer */ log_write_up_to(log_sys.get_lsn(), false); srv_stats.log_waits.inc(); ut_ad(++count < 50); mysql_mutex_lock(&log_sys.mutex); } return log_sys.get_lsn(); } /** Append data to the log buffer. */ static void log_write_low(const void *str, size_t size) { mysql_mutex_assert_owner(&log_sys.mutex); const ulint trailer_offset= log_sys.trailer_offset(); do { /* Calculate a part length */ size_t len= size; size_t data_len= (log_sys.buf_free % OS_FILE_LOG_BLOCK_SIZE) + size; if (data_len > trailer_offset) { data_len= trailer_offset; len= trailer_offset - log_sys.buf_free % OS_FILE_LOG_BLOCK_SIZE; } memcpy(log_sys.buf + log_sys.buf_free, str, len); size-= len; str= static_cast<const char*>(str) + len; byte *log_block= static_cast<byte*>(ut_align_down(log_sys.buf + log_sys.buf_free, OS_FILE_LOG_BLOCK_SIZE)); log_block_set_data_len(log_block, data_len); lsn_t lsn= log_sys.get_lsn(); if (data_len == trailer_offset) { /* This block became full */ log_block_set_data_len(log_block, OS_FILE_LOG_BLOCK_SIZE); log_block_set_checkpoint_no(log_block, log_sys.next_checkpoint_no); len+= log_sys.framing_size(); lsn+= len; /* Initialize the next block header */ log_block_init(log_block + OS_FILE_LOG_BLOCK_SIZE, lsn); } else lsn+= len; log_sys.set_lsn(lsn); log_sys.buf_free+= len; ut_ad(log_sys.buf_free <= size_t{srv_log_buffer_size}); } while (size); } /** Close the log at mini-transaction commit. @return whether buffer pool flushing is needed */ static mtr_t::page_flush_ahead log_close(lsn_t lsn) { mysql_mutex_assert_owner(&log_sys.mutex); ut_ad(lsn == log_sys.get_lsn()); byte *log_block= static_cast<byte*>(ut_align_down(log_sys.buf + log_sys.buf_free, OS_FILE_LOG_BLOCK_SIZE)); if (!log_block_get_first_rec_group(log_block)) { /* We initialized a new log block which was not written full by the current mtr: the next mtr log record group will start within this block at the offset data_len */ log_block_set_first_rec_group(log_block, log_block_get_data_len(log_block)); } if (log_sys.buf_free > log_sys.max_buf_free) log_sys.set_check_flush_or_checkpoint(); const lsn_t checkpoint_age= lsn - log_sys.last_checkpoint_lsn; if (UNIV_UNLIKELY(checkpoint_age >= log_sys.log_capacity) && /* silence message on create_log_file() after the log had been deleted */ checkpoint_age != lsn) { time_t t= time(nullptr); if (!log_close_warned || difftime(t, log_close_warn_time) > 15) { log_close_warned= true; log_close_warn_time= t; ib::error() << "The age of the last checkpoint is " << checkpoint_age << ", which exceeds the log capacity " << log_sys.log_capacity << "."; } } else if (UNIV_LIKELY(checkpoint_age <= log_sys.max_modified_age_async)) return mtr_t::PAGE_FLUSH_NO; else if (UNIV_LIKELY(checkpoint_age <= log_sys.max_checkpoint_age)) return mtr_t::PAGE_FLUSH_ASYNC; log_sys.set_check_flush_or_checkpoint(); return mtr_t::PAGE_FLUSH_SYNC; } /** Write the block contents to the REDO log */ struct mtr_write_log { /** Append a block to the redo log buffer. @return whether the appending should continue */ bool operator()(const mtr_buf_t::block_t *block) const { log_write_low(block->begin(), block->used()); return true; } }; std::pair<lsn_t,mtr_t::page_flush_ahead> mtr_t::do_write() { ut_ad(!recv_no_log_write); ut_ad(m_log_mode == MTR_LOG_ALL); ulint len = m_log.size(); ut_ad(len > 0); if (len > srv_log_buffer_size / 2) { log_buffer_extend(ulong((len + 1) * 2)); } fil_space_t* space = m_user_space; if (space != NULL && is_predefined_tablespace(space->id)) { /* Omit FILE_MODIFY for predefined tablespaces. */ space = NULL; } mysql_mutex_lock(&log_sys.mutex); if (fil_names_write_if_was_clean(space)) { len = m_log.size(); } else { /* This was not the first time of dirtying a tablespace since the latest checkpoint. */ ut_ad(len == m_log.size()); } *m_log.push<byte*>(1) = 0; len++; /* check and attempt a checkpoint if exceeding capacity */ log_margin_checkpoint_age(len); return finish_write(len); } /** Append the redo log records to the redo log buffer. @param len number of bytes to write @return {start_lsn,flush_ahead} */ inline std::pair<lsn_t,mtr_t::page_flush_ahead> mtr_t::finish_write(ulint len) { ut_ad(m_log_mode == MTR_LOG_ALL); mysql_mutex_assert_owner(&log_sys.mutex); ut_ad(m_log.size() == len); ut_ad(len > 0); lsn_t start_lsn; if (m_log.is_small()) { const mtr_buf_t::block_t* front = m_log.front(); ut_ad(len <= front->used()); m_commit_lsn = log_reserve_and_write_fast(front->begin(), len, &start_lsn); if (!m_commit_lsn) { goto piecewise; } } else { piecewise: /* Open the database log for log_write_low */ start_lsn = log_reserve_and_open(len); mtr_write_log write_log; m_log.for_each_block(write_log); m_commit_lsn = log_sys.get_lsn(); } page_flush_ahead flush= log_close(m_commit_lsn); DBUG_EXECUTE_IF("ib_log_flush_ahead", flush = PAGE_FLUSH_SYNC;); return std::make_pair(start_lsn, flush); } /** Find out whether a block was not X-latched by the mini-transaction */ struct FindBlockX { const buf_block_t &block; FindBlockX(const buf_block_t &block): block(block) {} /** @return whether the block was not found x-latched */ bool operator()(const mtr_memo_slot_t *slot) const { return slot->object != &block || slot->type != MTR_MEMO_PAGE_X_FIX; } }; #ifdef UNIV_DEBUG /** Assert that the block is not present in the mini-transaction */ struct FindNoBlock { const buf_block_t &block; FindNoBlock(const buf_block_t &block): block(block) {} /** @return whether the block was not found */ bool operator()(const mtr_memo_slot_t *slot) const { return slot->object != &block; } }; #endif /* UNIV_DEBUG */ bool mtr_t::have_x_latch(const buf_block_t &block) const { if (m_memo.for_each_block(CIterate<FindBlockX>(FindBlockX(block)))) { ut_ad(m_memo.for_each_block(CIterate<FindNoBlock>(FindNoBlock(block)))); ut_ad(!memo_contains_flagged(&block, MTR_MEMO_PAGE_S_FIX | MTR_MEMO_PAGE_SX_FIX | MTR_MEMO_BUF_FIX | MTR_MEMO_MODIFY)); return false; } ut_ad(block.page.lock.have_x()); return true; } /** Check if we are holding exclusive tablespace latch @param space tablespace to search for @param shared whether to look for shared latch, instead of exclusive @return whether space.latch is being held */ bool mtr_t::memo_contains(const fil_space_t& space, bool shared) { Iterate<Find> iteration(Find(&space, shared ? MTR_MEMO_SPACE_S_LOCK : MTR_MEMO_SPACE_X_LOCK)); if (m_memo.for_each_block_in_reverse(iteration)) return false; ut_ad(shared || space.is_owner()); return true; } #ifdef BTR_CUR_HASH_ADAPT /** If a stale adaptive hash index exists on the block, drop it. Multiple executions of btr_search_drop_page_hash_index() on the same block must be prevented by exclusive page latch. */ ATTRIBUTE_COLD static void mtr_defer_drop_ahi(buf_block_t *block, mtr_memo_type_t fix_type) { switch (fix_type) { case MTR_MEMO_BUF_FIX: /* We do not drop the adaptive hash index, because safely doing so would require acquiring block->lock, and that is not safe to acquire in some RW_NO_LATCH access paths. Those code paths should have no business accessing the adaptive hash index anyway. */ break; case MTR_MEMO_PAGE_S_FIX: /* Temporarily release our S-latch. */ block->page.lock.s_unlock(); block->page.lock.x_lock(); if (dict_index_t *index= block->index) if (index->freed()) btr_search_drop_page_hash_index(block); block->page.lock.x_unlock(); block->page.lock.s_lock(); ut_ad(!block->page.is_read_fixed()); break; case MTR_MEMO_PAGE_SX_FIX: block->page.lock.u_x_upgrade(); if (dict_index_t *index= block->index) if (index->freed()) btr_search_drop_page_hash_index(block); block->page.lock.x_u_downgrade(); break; default: ut_ad(fix_type == MTR_MEMO_PAGE_X_FIX); btr_search_drop_page_hash_index(block); } } #endif /* BTR_CUR_HASH_ADAPT */ /** Upgrade U-latched pages to X */ struct UpgradeX { const buf_block_t &block; UpgradeX(const buf_block_t &block) : block(block) {} bool operator()(mtr_memo_slot_t *slot) const { if (slot->object == &block && (MTR_MEMO_PAGE_SX_FIX & slot->type)) slot->type= static_cast<mtr_memo_type_t> (slot->type ^ (MTR_MEMO_PAGE_SX_FIX | MTR_MEMO_PAGE_X_FIX)); return true; } }; /** Upgrade U locks on a block to X */ void mtr_t::page_lock_upgrade(const buf_block_t &block) { ut_ad(block.page.lock.have_x()); m_memo.for_each_block(CIterate<UpgradeX>((UpgradeX(block)))); #ifdef BTR_CUR_HASH_ADAPT ut_ad(!block.index || !block.index->freed()); #endif /* BTR_CUR_HASH_ADAPT */ } /** Upgrade U locks to X */ struct UpgradeLockX { const index_lock &lock; UpgradeLockX(const index_lock &lock) : lock(lock) {} bool operator()(mtr_memo_slot_t *slot) const { if (slot->object == &lock && (MTR_MEMO_SX_LOCK & slot->type)) slot->type= static_cast<mtr_memo_type_t> (slot->type ^ (MTR_MEMO_SX_LOCK | MTR_MEMO_X_LOCK)); return true; } }; /** Upgrade U locks on a block to X */ void mtr_t::lock_upgrade(const index_lock &lock) { ut_ad(lock.have_x()); m_memo.for_each_block(CIterate<UpgradeLockX>((UpgradeLockX(lock)))); } /** Latch a buffer pool block. @param block block to be latched @param rw_latch RW_S_LATCH, RW_SX_LATCH, RW_X_LATCH, RW_NO_LATCH */ void mtr_t::page_lock(buf_block_t *block, ulint rw_latch) { mtr_memo_type_t fix_type; ut_d(const auto state= block->page.state()); ut_ad(state > buf_page_t::FREED); ut_ad(state > buf_page_t::WRITE_FIX || state < buf_page_t::READ_FIX); switch (rw_latch) { case RW_NO_LATCH: fix_type= MTR_MEMO_BUF_FIX; goto done; case RW_S_LATCH: fix_type= MTR_MEMO_PAGE_S_FIX; block->page.lock.s_lock(); break; case RW_SX_LATCH: fix_type= MTR_MEMO_PAGE_SX_FIX; block->page.lock.u_lock(); ut_ad(!block->page.is_io_fixed()); break; default: ut_ad(rw_latch == RW_X_LATCH); fix_type= MTR_MEMO_PAGE_X_FIX; if (block->page.lock.x_lock_upgraded()) { block->unfix(); page_lock_upgrade(*block); return; } ut_ad(!block->page.is_io_fixed()); } #ifdef BTR_CUR_HASH_ADAPT if (dict_index_t *index= block->index) if (index->freed()) mtr_defer_drop_ahi(block, fix_type); #endif /* BTR_CUR_HASH_ADAPT */ done: ut_ad(state < buf_page_t::UNFIXED || page_id_t(page_get_space_id(block->page.frame), page_get_page_no(block->page.frame)) == block->page.id()); memo_push(block, fix_type); } #ifdef UNIV_DEBUG /** Check if we are holding an rw-latch in this mini-transaction @param lock latch to search for @param type held latch type @return whether (lock,type) is contained */ bool mtr_t::memo_contains(const index_lock &lock, mtr_memo_type_t type) { Iterate<Find> iteration(Find(&lock, type)); if (m_memo.for_each_block_in_reverse(iteration)) return false; switch (type) { case MTR_MEMO_X_LOCK: ut_ad(lock.have_x()); break; case MTR_MEMO_SX_LOCK: ut_ad(lock.have_u_or_x()); break; case MTR_MEMO_S_LOCK: ut_ad(lock.have_s()); break; default: break; } return true; } /** Debug check for flags */ struct FlaggedCheck { FlaggedCheck(const void* ptr, ulint flags) : m_ptr(ptr), m_flags(flags) { /* There must be some flags to look for. */ ut_ad(flags); /* Look for rw-lock-related and page-related flags. */ ut_ad(!(flags & ulint(~(MTR_MEMO_PAGE_S_FIX | MTR_MEMO_PAGE_X_FIX | MTR_MEMO_PAGE_SX_FIX | MTR_MEMO_BUF_FIX | MTR_MEMO_MODIFY | MTR_MEMO_X_LOCK | MTR_MEMO_SX_LOCK | MTR_MEMO_S_LOCK)))); /* Either some rw-lock-related or page-related flags must be specified, but not both at the same time. */ ut_ad(!(flags & (MTR_MEMO_PAGE_S_FIX | MTR_MEMO_PAGE_X_FIX | MTR_MEMO_PAGE_SX_FIX | MTR_MEMO_BUF_FIX | MTR_MEMO_MODIFY)) == !!(flags & (MTR_MEMO_X_LOCK | MTR_MEMO_SX_LOCK | MTR_MEMO_S_LOCK))); } /** Visit a memo entry. @param[in] slot memo entry to visit @retval false if m_ptr was found @retval true if the iteration should continue */ bool operator()(const mtr_memo_slot_t* slot) const { if (m_ptr != slot->object) { return(true); } auto f = m_flags & slot->type; if (!f) { return true; } if (f & (MTR_MEMO_PAGE_S_FIX | MTR_MEMO_PAGE_SX_FIX | MTR_MEMO_PAGE_X_FIX)) { block_lock* lock = &static_cast<buf_block_t*>( const_cast<void*>(m_ptr))->page.lock; ut_ad(!(f & MTR_MEMO_PAGE_S_FIX) || lock->have_s()); ut_ad(!(f & MTR_MEMO_PAGE_SX_FIX) || lock->have_u_or_x()); ut_ad(!(f & MTR_MEMO_PAGE_X_FIX) || lock->have_x()); } else { index_lock* lock = static_cast<index_lock*>( const_cast<void*>(m_ptr)); ut_ad(!(f & MTR_MEMO_S_LOCK) || lock->have_s()); ut_ad(!(f & MTR_MEMO_SX_LOCK) || lock->have_u_or_x()); ut_ad(!(f & MTR_MEMO_X_LOCK) || lock->have_x()); } return(false); } const void*const m_ptr; const ulint m_flags; }; /** Check if memo contains the given item. @param object object to search @param flags specify types of object (can be ORred) of MTR_MEMO_PAGE_S_FIX ... values @return true if contains */ bool mtr_t::memo_contains_flagged(const void* ptr, ulint flags) const { ut_ad(is_active()); return !m_memo.for_each_block_in_reverse( CIterate<FlaggedCheck>(FlaggedCheck(ptr, flags))); } /** Check if memo contains the given page. @param[in] ptr pointer to within buffer frame @param[in] flags specify types of object with OR of MTR_MEMO_PAGE_S_FIX... values @return the block @retval NULL if not found */ buf_block_t* mtr_t::memo_contains_page_flagged( const byte* ptr, ulint flags) const { Iterate<FindPage> iteration(FindPage(ptr, flags)); return m_memo.for_each_block_in_reverse(iteration) ? NULL : iteration.functor.get_block(); } /** Print info of an mtr handle. */ void mtr_t::print() const { ib::info() << "Mini-transaction handle: memo size " << m_memo.size() << " bytes log size " << get_log()->size() << " bytes"; } #endif /* UNIV_DEBUG */ /** Find a block, preferrably in MTR_MEMO_MODIFY state */ struct FindModified { mtr_memo_slot_t *found= nullptr; const buf_block_t& block; FindModified(const buf_block_t &block) : block(block) {} bool operator()(mtr_memo_slot_t *slot) { if (slot->object != &block) return true; found= slot; return !(slot->type & (MTR_MEMO_MODIFY | MTR_MEMO_PAGE_X_FIX | MTR_MEMO_PAGE_SX_FIX)); } }; /** Mark the given latched page as modified. @param block page that will be modified */ void mtr_t::modify(const buf_block_t &block) { if (UNIV_UNLIKELY(m_memo.empty())) { /* This must be PageConverter::update_page() in IMPORT TABLESPACE. */ ut_ad(!block.page.in_LRU_list); return; } Iterate<FindModified> iteration((FindModified(block))); if (UNIV_UNLIKELY(m_memo.for_each_block(iteration))) { ut_ad("modifying an unlatched page" == 0); return; } iteration.functor.found->type= static_cast<mtr_memo_type_t> (iteration.functor.found->type | MTR_MEMO_MODIFY); }
27.303314
79
0.676412
[ "object" ]
c5c7c7597e84154f57acd4d47d8af497725748fa
9,981
cpp
C++
src/core/separatetabbar.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
src/core/separatetabbar.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
src/core/separatetabbar.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2010-2011 Oleg Linkin * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. **********************************************************************/ #include "separatetabbar.h" #include <QMouseEvent> #include <QStyle> #include <QStylePainter> #include <QStyleOption> #include <QApplication> #include <QMimeData> #include <QDrag> #include <QtDebug> #include <interfaces/ihavetabs.h> #include <interfaces/idndtab.h> #include "coreproxy.h" #include "separatetabwidget.h" #include "core.h" #include "tabmanager.h" #include "rootwindowsmanager.h" namespace LeechCraft { SeparateTabBar::SeparateTabBar (QWidget *parent) : QTabBar (parent) , Window_ (0) , Id_ (0) , InMove_ (false) , AddTabButton_ (nullptr) { setObjectName ("org_LeechCraft_MainWindow_CentralTabBar"); setExpanding (false); setIconSize (QSize (15, 15)); setContextMenuPolicy (Qt::CustomContextMenu); setElideMode (Qt::ElideRight); setDocumentMode (true); setAcceptDrops (true); setMovable (true); setUsesScrollButtons (true); addTab (QString ()); connect (this, SIGNAL (currentChanged (int)), this, SLOT (toggleCloseButtons ())); } void SeparateTabBar::SetWindow (MainWindow *win) { Window_ = win; } void SeparateTabBar::SetTabData (int index) { if (index < 0 || index >= count () - 1) { qWarning () << Q_FUNC_INFO << "invalid index " << index; return; } setTabData (index, ++Id_); } void SeparateTabBar::SetTabClosable (int index, bool closable, QWidget *closeButton) { if (index < 0 || index >= count ()) { qWarning () << Q_FUNC_INFO << "invalid index " << index; return; } setTabButton (index, GetCloseButtonPosition (), closable ? closeButton : 0); } void SeparateTabBar::SetTabWidget (SeparateTabWidget *widget) { TabWidget_ = widget; } void SeparateTabBar::SetAddTabButton (QWidget *w) { AddTabButton_ = w; setTabButton (count () - 1, GetAntiCloseButtonPosition (), w); } QTabBar::ButtonPosition SeparateTabBar::GetCloseButtonPosition () const { return static_cast<QTabBar::ButtonPosition> (style ()-> styleHint (QStyle::SH_TabBar_CloseButtonPosition)); } void SeparateTabBar::SetInMove (bool inMove) { InMove_ = inMove; } QTabBar::ButtonPosition SeparateTabBar::GetAntiCloseButtonPosition () const { return GetCloseButtonPosition () == QTabBar::LeftSide ? QTabBar::RightSide : QTabBar::LeftSide; } struct TabInfo { int Idx_; int WidthHint_; }; QVector<TabInfo> SeparateTabBar::GetTabInfos () const { const auto maxTabWidth = width () / 4; const auto cnt = count (); QVector<TabInfo> infos; for (int i = 0; i < cnt - 1; ++i) { auto hintedWidth = QTabBar::tabSizeHint (i).width (); if (const auto button = tabButton (i, GetCloseButtonPosition ())) if (!button->isVisible ()) hintedWidth -= button->width (); infos.push_back ({ i, std::min (hintedWidth, maxTabWidth) }); } std::sort (infos.begin (), infos.end (), [] (const TabInfo& l, const TabInfo& r) { return l.WidthHint_ < r.WidthHint_; }); return infos; } void SeparateTabBar::UpdateComputedWidths () const { auto infos = GetTabInfos (); ComputedWidths_.resize (infos.size ()); const auto btnWidth = QTabBar::tabSizeHint (count () - 1).width (); auto remainder = width () - btnWidth; while (!infos.isEmpty ()) { auto currentMax = remainder / infos.size (); if (infos.front ().WidthHint_ > currentMax) break; const auto& info = infos.front (); remainder -= info.WidthHint_; ComputedWidths_ [info.Idx_] = info.WidthHint_; infos.pop_front (); } if (infos.isEmpty ()) return; const auto uniform = remainder / infos.size (); for (const auto& info : infos) ComputedWidths_ [info.Idx_] = uniform; } void SeparateTabBar::toggleCloseButtons () const { const bool widthsEmpty = ComputedWidths_.isEmpty (); if (widthsEmpty) UpdateComputedWidths (); const auto current = currentIndex (); for (int i = 0, cnt = count () - 1; i < cnt; ++i) { const auto button = tabButton (i, GetCloseButtonPosition ()); if (!button) continue; const auto visible = i == current || button->width () * 2.5 < ComputedWidths_.value (i); button->setVisible (visible); } if (widthsEmpty) ComputedWidths_.clear (); } void SeparateTabBar::tabLayoutChange () { ComputedWidths_.clear (); QTabBar::tabLayoutChange (); } QSize SeparateTabBar::tabSizeHint (int index) const { auto result = QTabBar::tabSizeHint (index); if (index == count () - 1) return result; if (ComputedWidths_.isEmpty ()) { UpdateComputedWidths (); toggleCloseButtons (); } result.setWidth (ComputedWidths_.value (index)); return result; } void SeparateTabBar::mouseReleaseEvent (QMouseEvent *event) { int index = tabAt (event->pos ()); if (index == count () - 1 && event->button () == Qt::LeftButton) { emit addDefaultTab (); return; } if (InMove_) { emit releasedMouseAfterMove (currentIndex ()); InMove_ = false; emit currentChanged (currentIndex ()); } else if (index != -1 && event->button () == Qt::MidButton && index != count () - 1) { auto rootWM = Core::Instance ().GetRootWindowsManager (); auto tm = rootWM->GetTabManager (Window_); tm->remove (index); } QTabBar::mouseReleaseEvent (event); } void SeparateTabBar::mousePressEvent (QMouseEvent *event) { if (event->button () == Qt::LeftButton && tabAt (event->pos ()) == count () - 1) return; setMovable (QApplication::keyboardModifiers () == Qt::NoModifier); if (event->button () == Qt::LeftButton) DragStartPos_ = event->pos (); QTabBar::mousePressEvent (event); } void SeparateTabBar::mouseMoveEvent (QMouseEvent *event) { if (isMovable ()) { QTabBar::mouseMoveEvent (event); return; } if (!(event->buttons () & Qt::LeftButton)) return; if ((event->pos () - DragStartPos_).manhattanLength () < QApplication::startDragDistance ()) return; const int dragIdx = tabAt (DragStartPos_); auto widget = TabWidget_->Widget (dragIdx); auto itw = qobject_cast<ITabWidget*> (widget); if (!itw) { qWarning () << Q_FUNC_INFO << "widget at" << dragIdx << "doesn't implement ITabWidget"; return; } auto px = QPixmap::grabWidget (widget); px = px.scaledToWidth (px.width () / 2, Qt::SmoothTransformation); auto idt = qobject_cast<IDNDTab*> (widget); auto data = new QMimeData (); if (!idt || QApplication::keyboardModifiers () == Qt::ControlModifier) { data->setData ("x-leechcraft/tab-drag-action", "reordering"); data->setData ("x-leechcraft/tab-tabclass", itw->GetTabClassInfo ().TabClass_); } else if (idt) idt->FillMimeData (data); auto drag = new QDrag (this); drag->setMimeData (data); drag->setPixmap (px); drag->exec (); } void SeparateTabBar::dragEnterEvent (QDragEnterEvent *event) { dragMoveEvent (event); } void SeparateTabBar::dragMoveEvent (QDragMoveEvent *event) { const auto tabIdx = tabAt (event->pos ()); if (tabIdx == count () - 1) return; auto data = event->mimeData (); const auto& formats = data->formats (); if (formats.contains ("x-leechcraft/tab-drag-action") && data->data ("x-leechcraft/tab-drag-action") == "reordering") event->acceptProposedAction (); else if (tabIdx >= 0) TabWidget_->setCurrentIndex (tabIdx); if (auto idt = qobject_cast<IDNDTab*> (TabWidget_->Widget (tabIdx))) idt->HandleDragEnter (event); } void SeparateTabBar::dropEvent (QDropEvent *event) { auto data = event->mimeData (); const int to = tabAt (event->pos ()); auto widget = TabWidget_->Widget (to); if (data->data ("x-leechcraft/tab-drag-action") == "reordering") { const int from = tabAt (DragStartPos_); if (from == to || to == count () - 1) return; moveTab (from, to); emit releasedMouseAfterMove (to); event->acceptProposedAction (); } else if (auto idt = qobject_cast<IDNDTab*> (widget)) idt->HandleDrop (event); } void SeparateTabBar::mouseDoubleClickEvent (QMouseEvent *event) { QWidget::mouseDoubleClickEvent (event); if (tabAt (event->pos ()) == -1) emit addDefaultTab (); } void SeparateTabBar::tabInserted (int index) { QTabBar::tabInserted (index); emit tabWasInserted (index); } void SeparateTabBar::tabRemoved (int index) { QTabBar::tabRemoved (index); emit tabWasRemoved (index); } }
25.526854
94
0.665965
[ "object" ]
c5cb4f05e17bf828bf708463c1938f372fef96b1
301
cpp
C++
Src/Graph/TransformUpdateVisitor.cpp
patrickuhlmann/OpenGL-Scenegraph
92c8a6fcadc48b185cf27db00474693916bc4802
[ "MIT" ]
1
2018-12-19T04:34:05.000Z
2018-12-19T04:34:05.000Z
Src/Graph/TransformUpdateVisitor.cpp
patrickuhlmann/OpenGL-Scenegraph
92c8a6fcadc48b185cf27db00474693916bc4802
[ "MIT" ]
null
null
null
Src/Graph/TransformUpdateVisitor.cpp
patrickuhlmann/OpenGL-Scenegraph
92c8a6fcadc48b185cf27db00474693916bc4802
[ "MIT" ]
null
null
null
#include "TransformUpdateVisitor.hpp" TransformUpdateVisitor::TransformUpdateVisitor( TransformStrategy* s ) : _strategy(s) {} TransformUpdateVisitor::~TransformUpdateVisitor() { delete _strategy; } void TransformUpdateVisitor::VisitTransform( Transform* node ) { _strategy->Apply( node ); }
27.363636
88
0.777409
[ "transform" ]
c5cc0871de814a536226e8eb11024fa4d3404966
1,310
cpp
C++
cpp/until20/usability_variables/main.cpp
lonelyhentai/workspace
2a996af58d6b9be5d608ed040267398bcf72403b
[ "MIT" ]
2
2021-04-26T16:37:38.000Z
2022-03-15T01:26:19.000Z
cpp/until20/usability_variables/main.cpp
lonelyhentai/workspace
2a996af58d6b9be5d608ed040267398bcf72403b
[ "MIT" ]
null
null
null
cpp/until20/usability_variables/main.cpp
lonelyhentai/workspace
2a996af58d6b9be5d608ed040267398bcf72403b
[ "MIT" ]
1
2022-03-15T01:26:23.000Z
2022-03-15T01:26:23.000Z
#include <iostream> #include <vector> #include <algorithm> #include <initializer_list> #include <tuple> class Foo { public: int value_a; int value_b; Foo(int a, int b): value_a(a), value_b(b) {} }; class MagicFoo { public: std::vector<int> vec; MagicFoo(std::initializer_list<int> list) { for(std::initializer_list<int>::iterator it = list.begin(); it != list.end(); ++it) { vec.push_back(*it); } } }; std::tuple<int, double, std::string> f() { return std::make_tuple(1, 2.3, "456"); } int main() { std::vector<int> vec = { 1, 2, 3, 4 }; if (const std::vector<int>::iterator itr = std::find(vec.begin(), vec.end(), 3); itr != vec.end()) { *itr = 4; } // before c++ 11 int arr[3] = { 1, 2, 3 }; Foo foo(1, 2); vec = { 1, 2, 3, 4, 5 }; std::cout << "arr[0]: " << arr[0] << std::endl; std::cout << "foo: " << foo.value_a << ", " << foo.value_b << std::endl; for(std::vector<int>::const_iterator it = vec.begin(); it != vec.end(); ++ it) { std::cout << *it << std::endl; } MagicFoo magic_foo = { 1, 2, 3, 4, 5 }; std::cout << "magicFoo: "; for(std::vector<int>::const_iterator it = magic_foo.vec.begin(); it != magic_foo.vec.end(); ++it) { std::cout << *it << std::endl; } auto [x, y, z] = f(); std::cout << x << ", " << y << ", " << z << std::endl; return 0; }
20.46875
99
0.558015
[ "vector" ]
c5cd07a72596886a9846e8a42b72eb9ef35274ad
1,743
cpp
C++
subset_sum_dp.cpp
kshitijanand36/Important-programs
6b5867896d64ab16453248e0f8c1ca0ba54036e3
[ "MIT" ]
null
null
null
subset_sum_dp.cpp
kshitijanand36/Important-programs
6b5867896d64ab16453248e0f8c1ca0ba54036e3
[ "MIT" ]
null
null
null
subset_sum_dp.cpp
kshitijanand36/Important-programs
6b5867896d64ab16453248e0f8c1ca0ba54036e3
[ "MIT" ]
null
null
null
// Created by Kshitij Anand NSIT #include <bits/stdc++.h> //#include <ext/numeric> //using namespace __gnu_cxx; using namespace std; #define int long long #define pb push_back #define P pair<int,int> #define F first #define S second #define vi vector<int> #define vc vector<char> #define vb vector<bool> #define all(x) x.begin(),x.end() #define sz(x) (int)x.size() #define mp(a, b) make_pair(a, b) #define min3(a, b, c) min(min(a, b), c) #define min4(a, b, c, d) min(min(a, b), min(c, d)) #define max3(a, b, c) max(max(a, b), c) #define max4(a, b, c, d) max(max(a, b), max(c, d)) #define fill(arr,val) memset(arr,val,sizeof(arr)) #define inf 1e18 #define ps(x,y) fixed<<setprecision(y)<<x #define db(x) cout<<#x<<" : "<<x<<endl const int N = 1000000007; int dp[100001][101]; bool func(int arr[] ,int n , int curr , int sum){ if(sum == 0) return true; if(sum <0 or curr == n) return false; if(dp[sum][curr] !=-1) return dp[sum][curr]; bool ans = func(arr , n , curr + 1 , sum) | func(arr , n ,curr + 1 , sum - arr[curr]); dp[sum][curr] = ans; return ans; } void solve(){ int n,a,b,c, ans=0, count=0, sum=0; cin>>n; int arr[n]; for(int i=0;i<n;i++){ cin>>arr[i]; sum += arr[i]; } if(sum%2){ cout<<"NO\n"; return; } fill(dp , -1); sum/=2; bool check = func(arr , n, 0 ,sum); if(check){ cout<<"YES\n"; } else cout<<"NO\n"; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int t; cin>>t; while(t--) { solve(); } return 0; }
19.153846
91
0.520941
[ "vector" ]
c5ce19f7ef28fe2781ec5a8a8afe3520501d7be9
1,478
cpp
C++
GoonRenderer/Sources/Context.cpp
Snowapril/GoonRenderer
dce6c0cc5d89384d6ec29e98e63d0813bd138572
[ "MIT" ]
1
2019-09-14T11:07:16.000Z
2019-09-14T11:07:16.000Z
GoonRenderer/Sources/Context.cpp
Snowapril/GoonRenderer
dce6c0cc5d89384d6ec29e98e63d0813bd138572
[ "MIT" ]
null
null
null
GoonRenderer/Sources/Context.cpp
Snowapril/GoonRenderer
dce6c0cc5d89384d6ec29e98e63d0813bd138572
[ "MIT" ]
2
2021-03-21T02:53:48.000Z
2021-04-02T08:25:03.000Z
#include "Context.h" #include "Object/VBO.h" #include "Buffer.h" #include <cassert> namespace gr { Context::~Context() noexcept { for (int i = 0; i < staticVBOs.size(); ++i) if ( staticVBOs[i]) delete staticVBOs[i]; for (int i = 0; i < dynamicVBOs.size(); ++i) if (dynamicVBOs[i]) delete dynamicVBOs[i]; staticVBOs.clear(); dynamicVBOs.clear(); } GoonID Context::generateVBO(void *_data, std::vector< VertexStrideInfo >&& _vStrideInfos, GoonEnum _usage) noexcept { GoonID objectID = -1; switch(_usage) { case GOON_STATIC_DRAW : staticVBOs.push_back(new VBO(_data, std::move(_vStrideInfos))); objectID = static_cast<GoonID>(staticVBOs.size() - 1); break; case GOON_DYNAMIC_DRAW : dynamicVBOs.push_back(new VBO(_data, std::move(_vStrideInfos))); objectID = static_cast<GoonID>(dynamicVBOs.size() - 1); break; default: assert(false); break; } return objectID; } GoonID Context::generateBuffer(int _width, int _height, int _numChannels, unsigned char *_data) { buffers.push_back(new Buffer(_width, _height, _numChannels, _data)); return static_cast<GoonID>(buffers.size()); } Buffer* Context::getBufferByIndex(int _id) noexcept { return buffers[_id]; } };
28.980392
119
0.575778
[ "object", "vector" ]
c5dcb03544631f049c9e4f3bc7bb57b9707b1c70
391
cpp
C++
Basic/1049.cpp
GodLovesJonny/PAT-Solutions
b32d7de549c6b0ad8dc2e48d8a0e5cbf2241ed77
[ "MIT" ]
6
2019-03-13T10:07:25.000Z
2019-09-29T14:10:11.000Z
Basic/1049.cpp
GodLovesJonny/PAT-Solutions
b32d7de549c6b0ad8dc2e48d8a0e5cbf2241ed77
[ "MIT" ]
null
null
null
Basic/1049.cpp
GodLovesJonny/PAT-Solutions
b32d7de549c6b0ad8dc2e48d8a0e5cbf2241ed77
[ "MIT" ]
null
null
null
#include <algorithm> #include <cmath> #include <cstdio> #include <cstring> #include <iostream> #include <queue> #include <string> #include <vector> using namespace std; int N; int main() { ios::sync_with_stdio(false); int i; double sum; double pivot; cin >> N; for (i = 0; i < N; i++) { cin >> pivot; sum += pivot * (N - i) * (i + 1); } printf("%.2lf\n", sum); return 0; }
13.964286
35
0.601023
[ "vector" ]
c5e231f6eb1f58980dd9519158317617333d035c
91,130
cpp
C++
libvast/src/type.cpp
krionbsd/vast
c9fbc7230cac21886cf9d032e57b752276ba7ff7
[ "BSD-3-Clause" ]
null
null
null
libvast/src/type.cpp
krionbsd/vast
c9fbc7230cac21886cf9d032e57b752276ba7ff7
[ "BSD-3-Clause" ]
null
null
null
libvast/src/type.cpp
krionbsd/vast
c9fbc7230cac21886cf9d032e57b752276ba7ff7
[ "BSD-3-Clause" ]
null
null
null
// _ _____ __________ // | | / / _ | / __/_ __/ Visibility // | |/ / __ |_\ \ / / Across // |___/_/ |_/___/ /_/ Space and Time // // SPDX-FileCopyrightText: (c) 2021 The VAST Contributors // SPDX-License-Identifier: BSD-3-Clause #include "vast/type.hpp" #include "vast/data.hpp" #include "vast/detail/assert.hpp" #include "vast/detail/overload.hpp" #include "vast/die.hpp" #include "vast/error.hpp" #include "vast/fbs/type.hpp" #include "vast/legacy_type.hpp" #include "vast/schema.hpp" #include <caf/sum_type.hpp> #include <fmt/format.h> // -- utility functions ------------------------------------------------------- namespace vast { namespace { std::span<const std::byte> none_type_representation() { // This helper function solely exists because ADL will not find the as_bytes // overload for none_type from within the as_bytes overload for type. return as_bytes(none_type{}); } constexpr size_t reserved_string_size(std::string_view str) { // This helper function calculates the length of a string in a FlatBuffers // table. It adds an extra byte because strings in FlatBuffers tables are // always zero-terminated, and then rounds up to a full four bytes because of // the included padding. return str.empty() ? 0 : (((str.size() + 1 + 3) / 4) * 4); } const fbs::Type* resolve_transparent(const fbs::Type* root, enum type::transparent transparent = type::transparent::yes) { VAST_ASSERT(root); while (transparent == type::transparent::yes) { switch (root->type_type()) { case fbs::type::Type::NONE: case fbs::type::Type::bool_type: case fbs::type::Type::integer_type: case fbs::type::Type::count_type: case fbs::type::Type::real_type: case fbs::type::Type::duration_type: case fbs::type::Type::time_type: case fbs::type::Type::string_type: case fbs::type::Type::pattern_type: case fbs::type::Type::address_type: case fbs::type::Type::subnet_type: case fbs::type::Type::enumeration_type: case fbs::type::Type::list_type: case fbs::type::Type::map_type: case fbs::type::Type::record_type: transparent = type::transparent::no; break; case fbs::type::Type::enriched_type: root = root->type_as_enriched_type()->type_nested_root(); VAST_ASSERT(root); break; } } return root; } template <complex_type T> std::span<const std::byte> as_bytes_complex(const T& ct) { const auto& t = static_cast<const type&>(static_cast<const stateful_type_base&>(ct)); const auto* root = &t.table(type::transparent::no); auto result = as_bytes(t); while (true) { switch (root->type_type()) { case fbs::type::Type::NONE: case fbs::type::Type::bool_type: case fbs::type::Type::integer_type: case fbs::type::Type::count_type: case fbs::type::Type::real_type: case fbs::type::Type::duration_type: case fbs::type::Type::time_type: case fbs::type::Type::string_type: case fbs::type::Type::pattern_type: case fbs::type::Type::address_type: case fbs::type::Type::subnet_type: case fbs::type::Type::enumeration_type: case fbs::type::Type::list_type: case fbs::type::Type::map_type: case fbs::type::Type::record_type: return result; case fbs::type::Type::enriched_type: { const auto* enriched = root->type_as_enriched_type(); VAST_ASSERT(enriched); root = enriched->type_nested_root(); VAST_ASSERT(root); result = as_bytes(*enriched->type()); break; } } } __builtin_unreachable(); } template <class T> requires(std::is_same_v<T, struct enumeration_type::field> // || std::is_same_v<T, enumeration_type::field_view>) void construct_enumeration_type(stateful_type_base& self, const T* begin, const T* end) { VAST_ASSERT(begin != end, "An enumeration type must not have zero " "fields"); // Unlike for other concrete types, we do not calculate the exact amount of // bytes we need to allocate beforehand. This is because the individual // fields are stored in a flat hash map, whose size cannot trivially be // determined. auto builder = flatbuffers::FlatBufferBuilder{}; auto field_offsets = std::vector<flatbuffers::Offset<fbs::type::detail::EnumerationField>>{}; field_offsets.reserve(end - begin); uint32_t next_key = 0; for (const auto* it = begin; it != end; ++it) { const auto key = it->key != std::numeric_limits<uint32_t>::max() ? it->key : next_key; next_key = key + 1; const auto name_offset = builder.CreateString(it->name); field_offsets.emplace_back( fbs::type::detail::CreateEnumerationField(builder, key, name_offset)); } const auto fields_offset = builder.CreateVectorOfSortedTables(&field_offsets); const auto enumeration_type_offset = fbs::type::CreateEnumerationType(builder, fields_offset); const auto type_offset = fbs::CreateType(builder, fbs::type::Type::enumeration_type, enumeration_type_offset.Union()); builder.Finish(type_offset); auto result = builder.Release(); auto chunk = chunk::make(std::move(result)); self = type{std::move(chunk)}; } template <class T> void construct_record_type(stateful_type_base& self, const T& begin, const T& end) { VAST_ASSERT(begin != end, "A record type must not have zero fields."); const auto reserved_size = [&]() noexcept { // By default the builder allocates 1024 bytes, which is much more than // what we require, and since we can easily calculate the exact amount we // should do that. The total length is made up from the following terms: // - 52 bytes FlatBuffers table framing // - 24 bytes for each contained field. // - All contained string lengths, rounded up to four each. // - All contained nested type FlatBuffers. size_t size = 52; for (auto it = begin; it != end; ++it) { const auto& type_bytes = as_bytes(it->type); size += 24; VAST_ASSERT(!it->name.empty(), "Record field names must not be empty."); size += reserved_string_size(it->name); size += type_bytes.size(); } return size; }(); auto builder = flatbuffers::FlatBufferBuilder{reserved_size}; auto field_offsets = std::vector<flatbuffers::Offset<fbs::type::detail::RecordField>>{}; field_offsets.reserve(end - begin); for (auto it = begin; it != end; ++it) { const auto type_bytes = as_bytes(it->type); const auto name_offset = builder.CreateString(it->name); const auto type_offset = builder.CreateVector( reinterpret_cast<const uint8_t*>(type_bytes.data()), type_bytes.size()); field_offsets.emplace_back( fbs::type::detail::CreateRecordField(builder, name_offset, type_offset)); } const auto fields_offset = builder.CreateVector(field_offsets); const auto record_type_offset = fbs::type::CreateRecordType(builder, fields_offset); const auto type_offset = fbs::CreateType( builder, fbs::type::Type::record_type, record_type_offset.Union()); builder.Finish(type_offset); auto result = builder.Release(); VAST_ASSERT(result.size() == reserved_size); auto chunk = chunk::make(std::move(result)); self = type{std::move(chunk)}; } } // namespace // -- type -------------------------------------------------------------------- type::type() noexcept = default; type::type(const type& other) noexcept = default; type& type::operator=(const type& rhs) noexcept = default; type::type(type&& other) noexcept = default; type& type::operator=(type&& other) noexcept = default; type::~type() noexcept = default; type::type(chunk_ptr&& table) noexcept { #if VAST_ENABLE_ASSERTIONS VAST_ASSERT(table); VAST_ASSERT(table->size() > 0); const auto* const data = reinterpret_cast<const uint8_t*>(table->data()); auto verifier = flatbuffers::Verifier{data, table->size()}; VAST_ASSERT(fbs::GetType(data)->Verify(verifier), "Encountered invalid vast.fbs.Type FlatBuffers table."); # if defined(FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE) VAST_ASSERT(verifier.GetComputedSize() == table->size(), "Encountered unexpected excess bytes in vast.fbs.Type " "FlatBuffers table."); # endif // defined(FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE) #endif // VAST_ENABLE_ASSERTIONS table_ = std::move(table); } type::type(std::string_view name, const type& nested, const std::vector<struct attribute>& attributes) noexcept { if (name.empty() && attributes.empty()) { // This special case fbs::type::Type::exists for easier conversion of legacy // types, which did not require an legacy alias type wrapping to have a name. *this = nested; } else { const auto nested_bytes = as_bytes(nested); const auto reserved_size = [&]() noexcept { // The total length is made up from the following terms: // - 52 bytes FlatBuffers table framing // - Nested type FlatBuffers table size // - All contained string lengths, rounded up to four each // Note that this cannot account for attributes, since they are stored in // hash map which makes calculating the space requirements non-trivial. size_t size = 52; size += nested_bytes.size(); size += reserved_string_size(name); return size; }; auto builder = attributes.empty() ? flatbuffers::FlatBufferBuilder{reserved_size()} : flatbuffers::FlatBufferBuilder{}; const auto nested_type_offset = builder.CreateVector( reinterpret_cast<const uint8_t*>(nested_bytes.data()), nested_bytes.size()); const auto name_offset = name.empty() ? 0 : builder.CreateString(name); const auto attributes_offset = [&]() noexcept -> flatbuffers::Offset< flatbuffers::Vector<flatbuffers::Offset<fbs::type::detail::Attribute>>> { if (attributes.empty()) return 0; auto attributes_offsets = std::vector<flatbuffers::Offset<fbs::type::detail::Attribute>>{}; attributes_offsets.reserve(attributes.size()); for (const auto& attribute : attributes) { const auto key_offset = builder.CreateString(attribute.key); const auto value_offset = attribute.value ? builder.CreateString(*attribute.value) : 0; attributes_offsets.emplace_back(fbs::type::detail::CreateAttribute( builder, key_offset, value_offset)); } return builder.CreateVectorOfSortedTables(&attributes_offsets); }(); const auto enriched_type_offset = fbs::type::detail::CreateEnrichedType( builder, nested_type_offset, name_offset, attributes_offset); const auto type_offset = fbs::CreateType( builder, fbs::type::Type::enriched_type, enriched_type_offset.Union()); builder.Finish(type_offset); auto result = builder.Release(); table_ = chunk::make(std::move(result)); } } type::type(std::string_view name, const type& nested) noexcept : type(name, nested, {}) { // nop } type::type(const type& nested, const std::vector<struct attribute>& attributes) noexcept : type("", nested, attributes) { // nop } type type::infer(const data& value) noexcept { auto f = detail::overload{ [](caf::none_t) noexcept -> type { return {}; }, [](const bool&) noexcept -> type { return type{bool_type{}}; }, [](const integer&) noexcept -> type { return type{integer_type{}}; }, [](const count&) noexcept -> type { return type{count_type{}}; }, [](const real&) noexcept -> type { return type{real_type{}}; }, [](const duration&) noexcept -> type { return type{duration_type{}}; }, [](const time&) noexcept -> type { return type{time_type{}}; }, [](const std::string&) noexcept -> type { return type{string_type{}}; }, [](const pattern&) noexcept -> type { return type{pattern_type{}}; }, [](const address&) noexcept -> type { return type{address_type{}}; }, [](const subnet&) noexcept -> type { return type{subnet_type{}}; }, [](const enumeration&) noexcept -> type { // Enumeration types cannot be inferred. return {}; }, [](const list& list) noexcept -> type { // List types cannot be inferred from empty lists. if (list.empty()) return type{list_type{none_type{}}}; // Technically lists can contain heterogenous data, but for optimization // purposes we only check the first element when assertions are disabled. auto value_type = infer(*list.begin()); VAST_ASSERT(std::all_of(list.begin() + 1, list.end(), [&](const auto& elem) noexcept { return value_type.type_index() == infer(elem).type_index(); }), "expected a homogenous list"); return type{list_type{value_type}}; }, [](const map& map) noexcept -> type { // Map types cannot be inferred from empty maps. if (map.empty()) return type{map_type{none_type{}, none_type{}}}; // Technically maps can contain heterogenous data, but for optimization // purposes we only check the first element when assertions are disabled. auto key_type = infer(map.begin()->first); auto value_type = infer(map.begin()->second); VAST_ASSERT(std::all_of(map.begin() + 1, map.end(), [&](const auto& elem) noexcept { return key_type.type_index() == infer(elem.first).type_index() && value_type.type_index() == infer(elem.second).type_index(); }), "expected a homogenous map"); return type{map_type{key_type, value_type}}; }, [](const record& record) noexcept -> type { // Record types cannot be inferred from empty records. if (record.empty()) return {}; auto fields = std::vector<record_type::field_view>{}; fields.reserve(record.size()); for (const auto& field : record) fields.push_back({ field.first, infer(field.second), }); return type{record_type{fields}}; }, }; return caf::visit(f, value); } type type::from_legacy_type(const legacy_type& other) noexcept { const auto attributes = [&] { auto result = std::vector<struct attribute>{}; const auto& attributes = other.attributes(); result.reserve(attributes.size()); for (const auto& attribute : other.attributes()) result.push_back({ attribute.key, attribute.value ? *attribute.value : std::optional<std::string>{}, }); return result; }(); auto f = detail::overload{ [&](const legacy_none_type&) { return type{other.name(), none_type{}, attributes}; }, [&](const legacy_bool_type&) { return type{other.name(), bool_type{}, attributes}; }, [&](const legacy_integer_type&) { return type{other.name(), integer_type{}, attributes}; }, [&](const legacy_count_type&) { return type{other.name(), count_type{}, attributes}; }, [&](const legacy_real_type&) { return type{other.name(), real_type{}, attributes}; }, [&](const legacy_duration_type&) { return type{other.name(), duration_type{}, attributes}; }, [&](const legacy_time_type&) { return type{other.name(), time_type{}, attributes}; }, [&](const legacy_string_type&) { return type{other.name(), string_type{}, attributes}; }, [&](const legacy_pattern_type&) { return type{other.name(), pattern_type{}, attributes}; }, [&](const legacy_address_type&) { return type{other.name(), address_type{}, attributes}; }, [&](const legacy_subnet_type&) { return type{other.name(), subnet_type{}, attributes}; }, [&](const legacy_enumeration_type& enumeration) { auto fields = std::vector<struct enumeration_type::field>{}; fields.reserve(enumeration.fields.size()); for (const auto& field : enumeration.fields) fields.push_back({field}); return type{other.name(), enumeration_type{fields}, attributes}; }, [&](const legacy_list_type& list) { return type{other.name(), list_type{from_legacy_type(list.value_type)}, attributes}; }, [&](const legacy_map_type& map) { return type{other.name(), map_type{from_legacy_type(map.key_type), from_legacy_type(map.value_type)}, attributes}; }, [&](const legacy_alias_type& alias) { return type{other.name(), from_legacy_type(alias.value_type), attributes}; }, [&](const legacy_record_type& record) { auto fields = std::vector<struct record_type::field_view>{}; fields.reserve(record.fields.size()); for (const auto& field : record.fields) fields.push_back({field.name, from_legacy_type(field.type)}); return type{other.name(), record_type{fields}, attributes}; }, }; return caf::visit(f, other); } legacy_type type::to_legacy_type() const noexcept { auto f = detail::overload{ [&](const none_type&) -> legacy_type { return legacy_none_type{}; }, [&](const bool_type&) -> legacy_type { return legacy_bool_type{}; }, [&](const integer_type&) -> legacy_type { return legacy_integer_type{}; }, [&](const count_type&) -> legacy_type { return legacy_count_type{}; }, [&](const real_type&) -> legacy_type { return legacy_real_type{}; }, [&](const duration_type&) -> legacy_type { return legacy_duration_type{}; }, [&](const time_type&) -> legacy_type { return legacy_time_type{}; }, [&](const string_type&) -> legacy_type { return legacy_string_type{}; }, [&](const pattern_type&) -> legacy_type { return legacy_pattern_type{}; }, [&](const address_type&) -> legacy_type { return legacy_address_type{}; }, [&](const subnet_type&) -> legacy_type { return legacy_subnet_type{}; }, [&](const enumeration_type& enumeration) -> legacy_type { auto result = legacy_enumeration_type{}; for (uint32_t i = 0; const auto& field : enumeration.fields()) { VAST_ASSERT(i++ == field.key, "failed to convert enumeration type to " "legacy enumeration type"); result.fields.emplace_back(std::string{field.name}); } return result; }, [&](const list_type& list) -> legacy_type { return legacy_list_type{list.value_type().to_legacy_type()}; }, [&](const map_type& map) -> legacy_type { return legacy_map_type{ map.key_type().to_legacy_type(), map.value_type().to_legacy_type(), }; }, [&](const record_type& record) -> legacy_type { auto result = legacy_record_type{}; for (const auto& field : record.fields()) result.fields.push_back({ std::string{field.name}, field.type.to_legacy_type(), }); return result; }, }; auto result = caf::visit(f, *this); if (!name().empty()) result = legacy_alias_type{std::move(result)}.name(std::string{name()}); for (const auto& attribute : attributes()) { if (attribute.value.empty()) result.update_attributes({{std::string{attribute.key}}}); else result.update_attributes({{ std::string{attribute.key}, std::string{attribute.value}, }}); } return result; } const fbs::Type& type::table(enum transparent transparent) const noexcept { const auto repr = as_bytes(*this); const auto* table = fbs::GetType(repr.data()); VAST_ASSERT(table); const auto* resolved = resolve_transparent(table, transparent); VAST_ASSERT(resolved); return *resolved; } type::operator bool() const noexcept { return table(transparent::yes).type_type() != fbs::type::Type::NONE; } bool operator==(const type& lhs, const type& rhs) noexcept { const auto lhs_bytes = as_bytes(lhs); const auto rhs_bytes = as_bytes(rhs); return std::equal(lhs_bytes.begin(), lhs_bytes.end(), rhs_bytes.begin(), rhs_bytes.end()); } std::strong_ordering operator<=>(const type& lhs, const type& rhs) noexcept { auto lhs_bytes = as_bytes(lhs); auto rhs_bytes = as_bytes(rhs); // TODO: Replace implementation with `std::lexicographical_compare_three_way` // once that is implemented for all compilers we need to support. This does // the same thing essentially, just a lot less generic. if (lhs_bytes.data() == rhs_bytes.data() && lhs_bytes.size() == rhs_bytes.size()) return std::strong_ordering::equal; while (!lhs_bytes.empty() && !rhs_bytes.empty()) { if (lhs_bytes[0] < rhs_bytes[0]) return std::strong_ordering::less; if (lhs_bytes[0] > rhs_bytes[0]) return std::strong_ordering::greater; lhs_bytes = lhs_bytes.subspan(1); rhs_bytes = rhs_bytes.subspan(1); } return !lhs_bytes.empty() ? std::strong_ordering::greater : !rhs_bytes.empty() ? std::strong_ordering::less : std::strong_ordering::equivalent; } uint8_t type::type_index() const noexcept { static_assert( std::is_same_v<uint8_t, std::underlying_type_t<vast::fbs::type::Type>>); return static_cast<uint8_t>(table(transparent::yes).type_type()); } std::span<const std::byte> as_bytes(const type& x) noexcept { return x.table_ ? as_bytes(*x.table_) : none_type_representation(); } data type::construct() const noexcept { auto f = []<concrete_type T>(const T& x) noexcept -> data { return x.construct(); }; return caf::visit(f, *this); } void inspect(caf::detail::stringification_inspector& f, type& x) { static_assert( std::is_same_v<caf::detail::stringification_inspector::result_type, void>); static_assert(caf::detail::stringification_inspector::reads_state); auto str = fmt::to_string(x); f(str); } void type::assign_metadata(const type& other) noexcept { const auto name = other.name(); if (name.empty() && !other.has_attributes()) return; const auto nested_bytes = as_bytes(table_); const auto reserved_size = [&]() noexcept { // The total length is made up from the following terms: // - 52 bytes FlatBuffers table framing // - Nested type FlatBuffers table size // - All contained string lengths, rounded up to four each // Note that this cannot account for attributes, since they are stored in // hash map which makes calculating the space requirements non-trivial. size_t size = 52; size += nested_bytes.size(); size += reserved_string_size(name); return size; }; auto builder = other.has_attributes() ? flatbuffers::FlatBufferBuilder{reserved_size()} : flatbuffers::FlatBufferBuilder{}; const auto nested_type_offset = builder.CreateVector( reinterpret_cast<const uint8_t*>(nested_bytes.data()), nested_bytes.size()); const auto name_offset = name.empty() ? 0 : builder.CreateString(name); const auto attributes_offset = [&]() noexcept -> flatbuffers::Offset< flatbuffers::Vector<flatbuffers::Offset<fbs::type::detail::Attribute>>> { if (!other.has_attributes()) return 0; auto attributes_offsets = std::vector<flatbuffers::Offset<fbs::type::detail::Attribute>>{}; for (const auto& attribute : other.attributes()) { const auto key_offset = builder.CreateString(attribute.key); const auto value_offset = attribute.value.empty() ? 0 : builder.CreateString(attribute.value); attributes_offsets.emplace_back( fbs::type::detail::CreateAttribute(builder, key_offset, value_offset)); } return builder.CreateVectorOfSortedTables(&attributes_offsets); }(); const auto enriched_type_offset = fbs::type::detail::CreateEnrichedType( builder, nested_type_offset, name_offset, attributes_offset); const auto type_offset = fbs::CreateType( builder, fbs::type::Type::enriched_type, enriched_type_offset.Union()); builder.Finish(type_offset); auto result = builder.Release(); table_ = chunk::make(std::move(result)); } std::string_view type::name() const& noexcept { const auto* root = &table(transparent::no); while (true) { switch (root->type_type()) { case fbs::type::Type::NONE: case fbs::type::Type::bool_type: case fbs::type::Type::integer_type: case fbs::type::Type::count_type: case fbs::type::Type::real_type: case fbs::type::Type::duration_type: case fbs::type::Type::time_type: case fbs::type::Type::string_type: case fbs::type::Type::pattern_type: case fbs::type::Type::address_type: case fbs::type::Type::subnet_type: case fbs::type::Type::enumeration_type: case fbs::type::Type::list_type: case fbs::type::Type::map_type: case fbs::type::Type::record_type: return ""; case fbs::type::Type::enriched_type: { const auto* enriched_type = root->type_as_enriched_type(); if (const auto* name = enriched_type->name()) return name->string_view(); root = enriched_type->type_nested_root(); VAST_ASSERT(root); break; } } } __builtin_unreachable(); } detail::generator<std::string_view> type::names() const& noexcept { const auto* root = &table(transparent::no); while (true) { switch (root->type_type()) { case fbs::type::Type::NONE: case fbs::type::Type::bool_type: case fbs::type::Type::integer_type: case fbs::type::Type::count_type: case fbs::type::Type::real_type: case fbs::type::Type::duration_type: case fbs::type::Type::time_type: case fbs::type::Type::string_type: case fbs::type::Type::pattern_type: case fbs::type::Type::address_type: case fbs::type::Type::subnet_type: case fbs::type::Type::enumeration_type: case fbs::type::Type::list_type: case fbs::type::Type::map_type: case fbs::type::Type::record_type: co_return; case fbs::type::Type::enriched_type: { const auto* enriched_type = root->type_as_enriched_type(); if (const auto* name = enriched_type->name()) co_yield name->string_view(); root = enriched_type->type_nested_root(); VAST_ASSERT(root); break; } } } __builtin_unreachable(); } std::optional<std::string_view> type::attribute(const char* key) const& noexcept { const auto* root = &table(transparent::no); while (true) { switch (root->type_type()) { case fbs::type::Type::NONE: case fbs::type::Type::bool_type: case fbs::type::Type::integer_type: case fbs::type::Type::count_type: case fbs::type::Type::real_type: case fbs::type::Type::duration_type: case fbs::type::Type::time_type: case fbs::type::Type::string_type: case fbs::type::Type::pattern_type: case fbs::type::Type::address_type: case fbs::type::Type::subnet_type: case fbs::type::Type::enumeration_type: case fbs::type::Type::list_type: case fbs::type::Type::map_type: case fbs::type::Type::record_type: return std::nullopt; case fbs::type::Type::enriched_type: { const auto* enriched_type = root->type_as_enriched_type(); if (const auto* attributes = enriched_type->attributes()) { if (const auto* attribute = attributes->LookupByKey(key)) { if (const auto* value = attribute->value()) return value->string_view(); return ""; } } root = enriched_type->type_nested_root(); VAST_ASSERT(root); break; } } } __builtin_unreachable(); } bool type::has_attributes() const noexcept { const auto* root = &table(transparent::no); while (true) { switch (root->type_type()) { case fbs::type::Type::NONE: case fbs::type::Type::bool_type: case fbs::type::Type::integer_type: case fbs::type::Type::count_type: case fbs::type::Type::real_type: case fbs::type::Type::duration_type: case fbs::type::Type::time_type: case fbs::type::Type::string_type: case fbs::type::Type::pattern_type: case fbs::type::Type::address_type: case fbs::type::Type::subnet_type: case fbs::type::Type::enumeration_type: case fbs::type::Type::list_type: case fbs::type::Type::map_type: case fbs::type::Type::record_type: return false; case fbs::type::Type::enriched_type: { const auto* enriched_type = root->type_as_enriched_type(); if (const auto* attributes = enriched_type->attributes()) { if (attributes->begin() != attributes->end()) return true; } root = enriched_type->type_nested_root(); VAST_ASSERT(root); break; } } } __builtin_unreachable(); } detail::generator<type::attribute_view> type::attributes() const& noexcept { const auto* root = &table(transparent::no); while (true) { switch (root->type_type()) { case fbs::type::Type::NONE: case fbs::type::Type::bool_type: case fbs::type::Type::integer_type: case fbs::type::Type::count_type: case fbs::type::Type::real_type: case fbs::type::Type::duration_type: case fbs::type::Type::time_type: case fbs::type::Type::string_type: case fbs::type::Type::pattern_type: case fbs::type::Type::address_type: case fbs::type::Type::subnet_type: case fbs::type::Type::enumeration_type: case fbs::type::Type::list_type: case fbs::type::Type::map_type: case fbs::type::Type::record_type: co_return; case fbs::type::Type::enriched_type: { const auto* enriched_type = root->type_as_enriched_type(); if (const auto* attributes = enriched_type->attributes()) { for (const auto& attribute : *attributes) { if (attribute->value() != nullptr && attribute->value()->begin() != attribute->value()->end()) co_yield {attribute->key()->string_view(), attribute->value()->string_view()}; else co_yield {attribute->key()->string_view(), ""}; } } root = enriched_type->type_nested_root(); VAST_ASSERT(root); break; } } } __builtin_unreachable(); } bool is_container(const type& type) noexcept { const auto& root = type.table(type::transparent::yes); switch (root.type_type()) { case fbs::type::Type::NONE: case fbs::type::Type::bool_type: case fbs::type::Type::integer_type: case fbs::type::Type::count_type: case fbs::type::Type::real_type: case fbs::type::Type::duration_type: case fbs::type::Type::time_type: case fbs::type::Type::string_type: case fbs::type::Type::pattern_type: case fbs::type::Type::address_type: case fbs::type::Type::subnet_type: case fbs::type::Type::enumeration_type: return false; case fbs::type::Type::list_type: case fbs::type::Type::map_type: case fbs::type::Type::record_type: return true; case fbs::type::Type::enriched_type: __builtin_unreachable(); } __builtin_unreachable(); } type flatten(const type& t) noexcept { if (const auto* rt = caf::get_if<record_type>(&t)) { auto result = type{flatten(*rt)}; result.assign_metadata(t); return result; } return t; } bool congruent(const type& x, const type& y) noexcept { auto f = detail::overload{ [](const enumeration_type& x, const enumeration_type& y) noexcept { const auto xf = x.fields(); const auto yf = y.fields(); if (xf.size() != yf.size()) return false; for (size_t i = 0; i < xf.size(); ++i) if (xf[i].key != yf[i].key) return false; return true; }, [](const list_type& x, const list_type& y) noexcept { return congruent(x.value_type(), y.value_type()); }, [](const map_type& x, const map_type& y) noexcept { return congruent(x.key_type(), y.key_type()) && congruent(x.value_type(), y.value_type()); }, [](const record_type& x, const record_type& y) noexcept { if (x.num_fields() != y.num_fields()) return false; for (size_t i = 0; i < x.num_fields(); ++i) if (!congruent(x.field(i).type, y.field(i).type)) return false; return true; }, []<complex_type T>(const T&, const T&) noexcept { static_assert(detail::always_false_v<T>, "missing congruency check for " "complex type"); }, []<concrete_type T, concrete_type U>(const T&, const U&) noexcept { return std::is_same_v<T, U>; }, }; return caf::visit(f, x, y); } bool congruent(const type& x, const data& y) noexcept { auto f = detail::overload{ [](const auto&, const auto&) noexcept { return false; }, [](const none_type&, caf::none_t) noexcept { return true; }, [](const bool_type&, bool) noexcept { return true; }, [](const integer_type&, integer) noexcept { return true; }, [](const count_type&, count) noexcept { return true; }, [](const real_type&, real) noexcept { return true; }, [](const duration_type&, duration) noexcept { return true; }, [](const time_type&, time) noexcept { return true; }, [](const string_type&, const std::string&) noexcept { return true; }, [](const pattern_type&, const pattern&) noexcept { return true; }, [](const address_type&, const address&) noexcept { return true; }, [](const subnet_type&, const subnet&) noexcept { return true; }, [](const enumeration_type& x, const std::string& y) noexcept { return x.resolve(y).has_value(); }, [](const list_type&, const list&) noexcept { return true; }, [](const map_type&, const map&) noexcept { return true; }, [](const record_type& x, const list& y) noexcept { if (x.num_fields() != y.size()) return false; for (size_t i = 0; i < x.num_fields(); ++i) if (!congruent(x.field(i).type, y[i])) return false; return true; }, [](const record_type& x, const record& y) noexcept { if (x.num_fields() != y.size()) return false; for (const auto& field : x.fields()) { if (auto it = y.find(field.name); it != y.end()) { if (!congruent(field.type, it->second)) return false; } else { return false; } } return true; }, }; return caf::visit(f, x, y); } bool congruent(const data& x, const type& y) noexcept { return congruent(y, x); } bool compatible(const type& lhs, relational_operator op, const type& rhs) noexcept { auto string_and_pattern = [](auto& x, auto& y) { return (caf::holds_alternative<string_type>(x) && caf::holds_alternative<pattern_type>(y)) || (caf::holds_alternative<pattern_type>(x) && caf::holds_alternative<string_type>(y)); }; switch (op) { case relational_operator::match: case relational_operator::not_match: return string_and_pattern(lhs, rhs); case relational_operator::equal: case relational_operator::not_equal: return !lhs || !rhs || string_and_pattern(lhs, rhs) || congruent(lhs, rhs); case relational_operator::less: case relational_operator::less_equal: case relational_operator::greater: case relational_operator::greater_equal: return congruent(lhs, rhs); case relational_operator::in: case relational_operator::not_in: if (caf::holds_alternative<string_type>(lhs)) return caf::holds_alternative<string_type>(rhs) || is_container(rhs); else if (caf::holds_alternative<address_type>(lhs) || caf::holds_alternative<subnet_type>(lhs)) return caf::holds_alternative<subnet_type>(rhs) || is_container(rhs); else return is_container(rhs); case relational_operator::ni: return compatible(rhs, relational_operator::in, lhs); case relational_operator::not_ni: return compatible(rhs, relational_operator::not_in, lhs); } __builtin_unreachable(); } bool compatible(const type& lhs, relational_operator op, const data& rhs) noexcept { auto string_and_pattern = [](auto& x, auto& y) { return (caf::holds_alternative<string_type>(x) && caf::holds_alternative<pattern>(y)) || (caf::holds_alternative<pattern_type>(x) && caf::holds_alternative<std::string>(y)); }; switch (op) { case relational_operator::match: case relational_operator::not_match: return string_and_pattern(lhs, rhs); case relational_operator::equal: case relational_operator::not_equal: return !lhs || caf::holds_alternative<caf::none_t>(rhs) || string_and_pattern(lhs, rhs) || congruent(lhs, rhs); case relational_operator::less: case relational_operator::less_equal: case relational_operator::greater: case relational_operator::greater_equal: return congruent(lhs, rhs); case relational_operator::in: case relational_operator::not_in: if (caf::holds_alternative<string_type>(lhs)) return caf::holds_alternative<std::string>(rhs) || is_container(rhs); else if (caf::holds_alternative<address_type>(lhs) || caf::holds_alternative<subnet_type>(lhs)) return caf::holds_alternative<subnet>(rhs) || is_container(rhs); else return is_container(rhs); case relational_operator::ni: case relational_operator::not_ni: if (caf::holds_alternative<std::string>(rhs)) return caf::holds_alternative<string_type>(lhs) || is_container(lhs); else if (caf::holds_alternative<address>(rhs) || caf::holds_alternative<subnet>(rhs)) return caf::holds_alternative<subnet_type>(lhs) || is_container(lhs); else return is_container(lhs); } __builtin_unreachable(); } bool compatible(const data& lhs, relational_operator op, const type& rhs) noexcept { return compatible(rhs, flip(op), lhs); } bool is_subset(const type& x, const type& y) noexcept { const auto* sub = caf::get_if<record_type>(&x); const auto* super = caf::get_if<record_type>(&y); // If either of the types is not a record type, check if they are // congruent instead. if (!sub || !super) return congruent(x, y); // Check whether all fields of the subset exist in the superset. for (const auto& sub_field : sub->fields()) { bool exists_in_superset = false; for (const auto& super_field : super->fields()) { if (sub_field.name == super_field.name) { // Perform the check recursively to support nested record types. if (!is_subset(sub_field.type, super_field.type)) return false; exists_in_superset = true; } } // Not all fields of the subset exist in the superset; exit early. if (!exists_in_superset) return false; } return true; } // WARNING: making changes to the logic of this function requires adapting the // companion overload in view.cpp. bool type_check(const type& x, const data& y) noexcept { auto f = detail::overload{ [&](const none_type&, const auto&) { // Cannot determine data type since data may always be // null. return true; }, [&](const auto&, const caf::none_t&) { // Every type can be assigned nil. return true; }, [&](const none_type&, const caf::none_t&) { return true; }, [&](const enumeration_type& t, const enumeration& u) { return !t.field(u).empty(); }, [&](const list_type& t, const list& u) { if (u.empty()) return true; const auto vt = t.value_type(); auto it = u.begin(); const auto check = [&](const auto& d) noexcept { return type_check(vt, d); }; if (check(*it)) { // Technically lists can contain heterogenous data, // but for optimization purposes we only check the // first element when assertions are disabled. VAST_ASSERT(std::all_of(it + 1, u.end(), check), // "expected a homogenous list"); return true; } return false; }, [&](const map_type& t, const map& u) { if (u.empty()) return true; const auto kt = t.key_type(); const auto vt = t.value_type(); auto it = u.begin(); const auto check = [&](const auto& d) noexcept { return type_check(kt, d.first) && type_check(vt, d.second); }; if (check(*it)) { // Technically maps can contain heterogenous data, // but for optimization purposes we only check the // first element when assertions are disabled. VAST_ASSERT(std::all_of(it + 1, u.end(), check), // "expected a homogenous map"); return true; } return false; }, [&](const record_type& t, const record& u) { if (u.size() != t.num_fields()) return false; for (size_t i = 0; i < u.size(); ++i) { const auto field = t.field(i); const auto& [k, v] = as_vector(u)[i]; if (field.name != k || type_check(field.type, v)) return false; } return true; }, [&]<basic_type T, class U>(const T&, const U&) { // For basic types we can solely rely on the result of // construct. return std::is_same_v<type_to_data_t<T>, U>; }, [&]<complex_type T, class U>(const T&, const U&) { // We don't have a matching overload. static_assert(!std::is_same_v<type_to_data_t<T>, U>, // "missing type check overload"); return false; }, }; return caf::visit(f, x, y); } caf::error replace_if_congruent(std::initializer_list<type*> xs, const schema& with) { for (auto* x : xs) if (const auto* t = with.find(x->name())) { if (!congruent(*x, *t)) return caf::make_error(ec::type_clash, fmt::format("incongruent type {}", x->name())); *x = *t; } return caf::none; } // -- none_type --------------------------------------------------------------- static_assert(none_type::type_index == static_cast<uint8_t>(fbs::type::Type::NONE)); std::span<const std::byte> as_bytes(const none_type&) noexcept { static const auto buffer = []() noexcept { constexpr auto reserved_size = 12; auto builder = flatbuffers::FlatBufferBuilder{reserved_size}; const auto type = fbs::CreateType(builder); builder.Finish(type); auto result = builder.Release(); VAST_ASSERT(result.size() == reserved_size); return result; }(); return as_bytes(buffer); } caf::none_t none_type::construct() noexcept { return {}; } // -- bool_type --------------------------------------------------------------- static_assert(bool_type::type_index == static_cast<uint8_t>(fbs::type::Type::bool_type)); std::span<const std::byte> as_bytes(const bool_type&) noexcept { static const auto buffer = []() noexcept { constexpr auto reserved_size = 32; auto builder = flatbuffers::FlatBufferBuilder{reserved_size}; const auto bool_type = fbs::type::CreateBoolType(builder); const auto type = fbs::CreateType(builder, fbs::type::Type::bool_type, bool_type.Union()); builder.Finish(type); auto result = builder.Release(); VAST_ASSERT(result.size() == reserved_size); return result; }(); return as_bytes(buffer); } bool bool_type::construct() noexcept { return {}; } // -- integer_type ------------------------------------------------------------ static_assert(integer_type::type_index == static_cast<uint8_t>(fbs::type::Type::integer_type)); std::span<const std::byte> as_bytes(const integer_type&) noexcept { static const auto buffer = []() noexcept { constexpr auto reserved_size = 32; auto builder = flatbuffers::FlatBufferBuilder{reserved_size}; const auto integer_type = fbs::type::CreateIntegerType(builder); const auto type = fbs::CreateType(builder, fbs::type::Type::integer_type, integer_type.Union()); builder.Finish(type); auto result = builder.Release(); VAST_ASSERT(result.size() == reserved_size); return result; }(); return as_bytes(buffer); } integer integer_type::construct() noexcept { return {}; } // -- count_type -------------------------------------------------------------- static_assert(count_type::type_index == static_cast<uint8_t>(fbs::type::Type::count_type)); std::span<const std::byte> as_bytes(const count_type&) noexcept { static const auto buffer = []() noexcept { constexpr auto reserved_size = 32; auto builder = flatbuffers::FlatBufferBuilder{reserved_size}; const auto count_type = fbs::type::CreateCountType(builder); const auto type = fbs::CreateType(builder, fbs::type::Type::count_type, count_type.Union()); builder.Finish(type); auto result = builder.Release(); VAST_ASSERT(result.size() == reserved_size); return result; }(); return as_bytes(buffer); } count count_type::construct() noexcept { return {}; } // -- real_type --------------------------------------------------------------- static_assert(real_type::type_index == static_cast<uint8_t>(fbs::type::Type::real_type)); std::span<const std::byte> as_bytes(const real_type&) noexcept { static const auto buffer = []() noexcept { constexpr auto reserved_size = 32; auto builder = flatbuffers::FlatBufferBuilder{reserved_size}; const auto real_type = fbs::type::CreateRealType(builder); const auto type = fbs::CreateType(builder, fbs::type::Type::real_type, real_type.Union()); builder.Finish(type); auto result = builder.Release(); VAST_ASSERT(result.size() == reserved_size); return result; }(); return as_bytes(buffer); } real real_type::construct() noexcept { return {}; } // -- duration_type ----------------------------------------------------------- static_assert(duration_type::type_index == static_cast<uint8_t>(fbs::type::Type::duration_type)); std::span<const std::byte> as_bytes(const duration_type&) noexcept { static const auto buffer = []() noexcept { constexpr auto reserved_size = 32; auto builder = flatbuffers::FlatBufferBuilder{reserved_size}; const auto duration_type = fbs::type::CreateDurationType(builder); const auto type = fbs::CreateType(builder, fbs::type::Type::duration_type, duration_type.Union()); builder.Finish(type); auto result = builder.Release(); VAST_ASSERT(result.size() == reserved_size); return result; }(); return as_bytes(buffer); } duration duration_type::construct() noexcept { return {}; } // -- time_type --------------------------------------------------------------- static_assert(time_type::type_index == static_cast<uint8_t>(fbs::type::Type::time_type)); std::span<const std::byte> as_bytes(const time_type&) noexcept { static const auto buffer = []() noexcept { constexpr auto reserved_size = 32; auto builder = flatbuffers::FlatBufferBuilder{reserved_size}; const auto time_type = fbs::type::CreateDurationType(builder); const auto type = fbs::CreateType(builder, fbs::type::Type::time_type, time_type.Union()); builder.Finish(type); auto result = builder.Release(); VAST_ASSERT(result.size() == reserved_size); return result; }(); return as_bytes(buffer); } time time_type::construct() noexcept { return {}; } // -- string_type -------------------------------------------------------------- static_assert(string_type::type_index == static_cast<uint8_t>(fbs::type::Type::string_type)); std::span<const std::byte> as_bytes(const string_type&) noexcept { static const auto buffer = []() noexcept { constexpr auto reserved_size = 32; auto builder = flatbuffers::FlatBufferBuilder{reserved_size}; const auto string_type = fbs::type::CreateStringType(builder); const auto type = fbs::CreateType(builder, fbs::type::Type::string_type, string_type.Union()); builder.Finish(type); auto result = builder.Release(); VAST_ASSERT(result.size() == reserved_size); return result; }(); return as_bytes(buffer); } std::string string_type::construct() noexcept { return {}; } // -- pattern_type ------------------------------------------------------------ static_assert(pattern_type::type_index == static_cast<uint8_t>(fbs::type::Type::pattern_type)); std::span<const std::byte> as_bytes(const pattern_type&) noexcept { static const auto buffer = []() noexcept { constexpr auto reserved_size = 32; auto builder = flatbuffers::FlatBufferBuilder{reserved_size}; const auto pattern_type = fbs::type::CreatePatternType(builder); const auto type = fbs::CreateType(builder, fbs::type::Type::pattern_type, pattern_type.Union()); builder.Finish(type); auto result = builder.Release(); VAST_ASSERT(result.size() == reserved_size); return result; }(); return as_bytes(buffer); } pattern pattern_type::construct() noexcept { return {}; } // -- address_type ------------------------------------------------------------ static_assert(address_type::type_index == static_cast<uint8_t>(fbs::type::Type::address_type)); std::span<const std::byte> as_bytes(const address_type&) noexcept { static const auto buffer = []() noexcept { constexpr auto reserved_size = 32; auto builder = flatbuffers::FlatBufferBuilder{reserved_size}; const auto address_type = fbs::type::CreateAddressType(builder); const auto type = fbs::CreateType(builder, fbs::type::Type::address_type, address_type.Union()); builder.Finish(type); auto result = builder.Release(); VAST_ASSERT(result.size() == reserved_size); return result; }(); return as_bytes(buffer); } address address_type::construct() noexcept { return {}; } // -- subnet_type ------------------------------------------------------------- static_assert(subnet_type::type_index == static_cast<uint8_t>(fbs::type::Type::subnet_type)); std::span<const std::byte> as_bytes(const subnet_type&) noexcept { static const auto buffer = []() noexcept { constexpr auto reserved_size = 32; auto builder = flatbuffers::FlatBufferBuilder{reserved_size}; const auto subnet_type = fbs::type::CreateSubnetType(builder); const auto type = fbs::CreateType(builder, fbs::type::Type::subnet_type, subnet_type.Union()); builder.Finish(type); auto result = builder.Release(); VAST_ASSERT(result.size() == reserved_size); return result; }(); return as_bytes(buffer); } subnet subnet_type::construct() noexcept { return {}; } // -- enumeration_type -------------------------------------------------------- enumeration_type::enumeration_type( const enumeration_type& other) noexcept = default; enumeration_type& enumeration_type::operator=(const enumeration_type& rhs) noexcept = default; enumeration_type::enumeration_type(enumeration_type&& other) noexcept = default; enumeration_type& enumeration_type::operator=(enumeration_type&& other) noexcept = default; enumeration_type::~enumeration_type() noexcept = default; enumeration_type::enumeration_type( const std::vector<field_view>& fields) noexcept { construct_enumeration_type(*this, fields.data(), fields.data() + fields.size()); } enumeration_type::enumeration_type( std::initializer_list<field_view> fields) noexcept : enumeration_type{std::vector<field_view>{fields}} { // nop } enumeration_type::enumeration_type( const std::vector<struct field>& fields) noexcept { construct_enumeration_type(*this, fields.data(), fields.data() + fields.size()); } const fbs::Type& enumeration_type::table() const noexcept { const auto repr = as_bytes(*this); const auto* table = fbs::GetType(repr.data()); VAST_ASSERT(table); VAST_ASSERT(table == resolve_transparent(table)); VAST_ASSERT(table->type_type() == fbs::type::Type::enumeration_type); return *table; } static_assert(enumeration_type::type_index == static_cast<uint8_t>(fbs::type::Type::enumeration_type)); std::span<const std::byte> as_bytes(const enumeration_type& x) noexcept { return as_bytes_complex(x); } enumeration enumeration_type::construct() const noexcept { const auto* fields = table().type_as_enumeration_type()->fields(); VAST_ASSERT(fields); VAST_ASSERT(fields->size() > 0); const auto value = fields->Get(0)->key(); // TODO: Currently, enumeration can not holds keys that don't fit a uint8_t; // when switching to a strong typedef for enumeration we should change that. // An example use case fbs::type::Type::is NetFlow, where many enumeration // values require usage of a uint16_t, which for now we would need to model as // strings in schemas. VAST_ASSERT(value <= std::numeric_limits<enumeration>::max()); return static_cast<enumeration>(value); } std::string_view enumeration_type::field(uint32_t key) const& noexcept { const auto* fields = table().type_as_enumeration_type()->fields(); VAST_ASSERT(fields); if (const auto* field = fields->LookupByKey(key)) return field->name()->string_view(); return ""; } std::vector<enumeration_type::field_view> enumeration_type::fields() const& noexcept { const auto* fields = table().type_as_enumeration_type()->fields(); VAST_ASSERT(fields); auto result = std::vector<field_view>{}; result.reserve(fields->size()); for (const auto& field : *fields) result.push_back({field->name()->string_view(), field->key()}); return result; } std::optional<uint32_t> enumeration_type::resolve(std::string_view key) const noexcept { const auto* fields = table().type_as_enumeration_type()->fields(); VAST_ASSERT(fields); for (const auto& field : *fields) if (field->name()->string_view() == key) return field->key(); return std::nullopt; } // -- list_type --------------------------------------------------------------- list_type::list_type(const list_type& other) noexcept = default; list_type& list_type::operator=(const list_type& rhs) noexcept = default; list_type::list_type(list_type&& other) noexcept = default; list_type& list_type::operator=(list_type&& other) noexcept = default; list_type::~list_type() noexcept = default; list_type::list_type(const type& value_type) noexcept { const auto value_type_bytes = as_bytes(value_type); const auto reserved_size = 44 + value_type_bytes.size(); auto builder = flatbuffers::FlatBufferBuilder{reserved_size}; const auto list_type_offset = fbs::type::CreateListType( builder, builder.CreateVector( reinterpret_cast<const uint8_t*>(value_type_bytes.data()), value_type_bytes.size())); const auto type_offset = fbs::CreateType(builder, fbs::type::Type::list_type, list_type_offset.Union()); builder.Finish(type_offset); auto result = builder.Release(); VAST_ASSERT(result.size() == reserved_size); table_ = chunk::make(std::move(result)); } const fbs::Type& list_type::table() const noexcept { const auto repr = as_bytes(*this); const auto* table = fbs::GetType(repr.data()); VAST_ASSERT(table); VAST_ASSERT(table == resolve_transparent(table)); VAST_ASSERT(table->type_type() == fbs::type::Type::list_type); return *table; } static_assert(list_type::type_index == static_cast<uint8_t>(fbs::type::Type::list_type)); std::span<const std::byte> as_bytes(const list_type& x) noexcept { return as_bytes_complex(x); } list list_type::construct() noexcept { return {}; } type list_type::value_type() const noexcept { const auto* view = table().type_as_list_type()->type(); VAST_ASSERT(view); return type{table_->slice(as_bytes(*view))}; } // -- map_type ---------------------------------------------------------------- map_type::map_type(const map_type& other) noexcept = default; map_type& map_type::operator=(const map_type& rhs) noexcept = default; map_type::map_type(map_type&& other) noexcept = default; map_type& map_type::operator=(map_type&& other) noexcept = default; map_type::~map_type() noexcept = default; map_type::map_type(const type& key_type, const type& value_type) noexcept { const auto key_type_bytes = as_bytes(key_type); const auto value_type_bytes = as_bytes(value_type); const auto reserved_size = 52 + key_type_bytes.size() + value_type_bytes.size(); auto builder = flatbuffers::FlatBufferBuilder{reserved_size}; const auto key_type_offset = builder.CreateVector( reinterpret_cast<const uint8_t*>(key_type_bytes.data()), key_type_bytes.size()); const auto value_type_offset = builder.CreateVector( reinterpret_cast<const uint8_t*>(value_type_bytes.data()), value_type_bytes.size()); const auto map_type_offset = fbs::type::CreateMapType(builder, key_type_offset, value_type_offset); const auto type_offset = fbs::CreateType(builder, fbs::type::Type::map_type, map_type_offset.Union()); builder.Finish(type_offset); auto result = builder.Release(); VAST_ASSERT(result.size() == reserved_size); table_ = chunk::make(std::move(result)); } const fbs::Type& map_type::table() const noexcept { const auto repr = as_bytes(*this); const auto* table = fbs::GetType(repr.data()); VAST_ASSERT(table); VAST_ASSERT(table == resolve_transparent(table)); VAST_ASSERT(table->type_type() == fbs::type::Type::map_type); return *table; } static_assert(map_type::type_index == static_cast<uint8_t>(fbs::type::Type::map_type)); std::span<const std::byte> as_bytes(const map_type& x) noexcept { return as_bytes_complex(x); } map map_type::construct() noexcept { return {}; } type map_type::key_type() const noexcept { const auto* view = table().type_as_map_type()->key_type(); VAST_ASSERT(view); return type{table_->slice(as_bytes(*view))}; } type map_type::value_type() const noexcept { const auto* view = table().type_as_map_type()->value_type(); VAST_ASSERT(view); return type{table_->slice(as_bytes(*view))}; } // -- record_type ------------------------------------------------------------- record_type::record_type(const record_type& other) noexcept = default; record_type& record_type::operator=(const record_type& rhs) noexcept = default; record_type::record_type(record_type&& other) noexcept = default; record_type& record_type::operator=(record_type&& other) noexcept = default; record_type::~record_type() noexcept = default; record_type::record_type(const std::vector<field_view>& fields) noexcept { construct_record_type(*this, fields.data(), fields.data() + fields.size()); } record_type::record_type(std::initializer_list<field_view> fields) noexcept : record_type{std::vector<field_view>{fields}} { // nop } record_type::record_type(const std::vector<struct field>& fields) noexcept { construct_record_type(*this, fields.data(), fields.data() + fields.size()); } const fbs::Type& record_type::table() const noexcept { const auto repr = as_bytes(*this); const auto* table = fbs::GetType(repr.data()); VAST_ASSERT(table); VAST_ASSERT(table == resolve_transparent(table)); VAST_ASSERT(table->type_type() == fbs::type::Type::record_type); return *table; } static_assert(record_type::type_index == static_cast<uint8_t>(fbs::type::Type::record_type)); std::span<const std::byte> as_bytes(const record_type& x) noexcept { return as_bytes_complex(x); } record record_type::construct() const noexcept { // A record is a stable map under the hood, and we construct its underlying // vector directly here as that is slightly more efficient, and as an added // benefit(?) allows for creating records with duplicate fields, so if this // record type happens to break its contract we can still create a fitting // record from it. Known occurences of such record types are: // - test.full blueprint record type for the test generator. // - Combined layout of the partition v0. // We should consider getting rid of vector_map::make_unsafe in the future. auto result = record::vector_type{}; result.reserve(num_fields()); for (const auto& field : fields()) result.emplace_back(field.name, field.type.construct()); return record::make_unsafe(std::move(result)); } detail::generator<record_type::field_view> record_type::fields() const noexcept { const auto* record = table().type_as_record_type(); VAST_ASSERT(record); const auto* fields = record->fields(); VAST_ASSERT(fields); for (const auto* field : *fields) { co_yield { field->name()->string_view(), type{table_->slice(as_bytes(*field->type()))}, }; } co_return; } detail::generator<record_type::leaf_view> record_type::leaves() const noexcept { auto index = offset{0}; auto history = detail::stack_vector<const fbs::type::RecordType*, 64>{ table().type_as_record_type()}; while (!index.empty()) { const auto* record = history.back(); VAST_ASSERT(record); const auto* fields = record->fields(); VAST_ASSERT(fields); // This is our exit condition: If we arrived at the end of a record, we need // to step out one layer. We must also reset the target key at this point. if (index.back() >= fields->size()) { history.pop_back(); index.pop_back(); if (!index.empty()) ++index.back(); continue; } const auto* field = record->fields()->Get(index.back()); VAST_ASSERT(field); const auto* field_type = resolve_transparent(field->type_nested_root()); VAST_ASSERT(field_type); switch (field_type->type_type()) { case fbs::type::Type::NONE: case fbs::type::Type::bool_type: case fbs::type::Type::integer_type: case fbs::type::Type::count_type: case fbs::type::Type::real_type: case fbs::type::Type::duration_type: case fbs::type::Type::time_type: case fbs::type::Type::string_type: case fbs::type::Type::pattern_type: case fbs::type::Type::address_type: case fbs::type::Type::subnet_type: case fbs::type::Type::enumeration_type: case fbs::type::Type::list_type: case fbs::type::Type::map_type: { auto leaf = leaf_view{ { field->name()->string_view(), type{table_->slice(as_bytes(*field->type()))}, }, index, }; co_yield std::move(leaf); ++index.back(); break; } case fbs::type::Type::record_type: { history.emplace_back(field_type->type_as_record_type()); index.push_back(0); break; } case fbs::type::Type::enriched_type: __builtin_unreachable(); break; } } co_return; } size_t record_type::num_fields() const noexcept { const auto* record = table().type_as_record_type(); VAST_ASSERT(record); return record->fields()->size(); } size_t record_type::num_leaves() const noexcept { auto num_leaves = size_t{0}; auto index = offset{0}; auto history = detail::stack_vector<const fbs::type::RecordType*, 64>{ table().type_as_record_type()}; while (!index.empty()) { const auto* record = history.back(); VAST_ASSERT(record); const auto* fields = record->fields(); VAST_ASSERT(fields); // This is our exit condition: If we arrived at the end of a record, we need // to step out one layer. We must also reset the target key at this point. if (index.back() >= fields->size()) { history.pop_back(); index.pop_back(); if (!index.empty()) ++index.back(); continue; } const auto* field = record->fields()->Get(index.back()); VAST_ASSERT(field); const auto* field_type = resolve_transparent(field->type_nested_root()); VAST_ASSERT(field_type); switch (field_type->type_type()) { case fbs::type::Type::NONE: case fbs::type::Type::bool_type: case fbs::type::Type::integer_type: case fbs::type::Type::count_type: case fbs::type::Type::real_type: case fbs::type::Type::duration_type: case fbs::type::Type::time_type: case fbs::type::Type::string_type: case fbs::type::Type::pattern_type: case fbs::type::Type::address_type: case fbs::type::Type::subnet_type: case fbs::type::Type::enumeration_type: case fbs::type::Type::list_type: case fbs::type::Type::map_type: { ++index.back(); ++num_leaves; break; } case fbs::type::Type::record_type: { history.emplace_back(field_type->type_as_record_type()); index.push_back(0); break; } case fbs::type::Type::enriched_type: __builtin_unreachable(); break; } } return num_leaves; } offset record_type::resolve_flat_index(size_t flat_index) const noexcept { size_t current_flat_index = 0; auto index = offset{0}; auto history = detail::stack_vector<const fbs::type::RecordType*, 64>{ table().type_as_record_type()}; while (!index.empty()) { const auto* record = history.back(); VAST_ASSERT(record); const auto* fields = record->fields(); VAST_ASSERT(fields); // This is our exit condition: If we arrived at the end of a record, we need // to step out one layer. We must also reset the target key at this point. if (index.back() >= fields->size()) { history.pop_back(); index.pop_back(); if (!index.empty()) ++index.back(); continue; } const auto* field = record->fields()->Get(index.back()); VAST_ASSERT(field); const auto* field_type = resolve_transparent(field->type_nested_root()); VAST_ASSERT(field_type); switch (field_type->type_type()) { case fbs::type::Type::NONE: case fbs::type::Type::bool_type: case fbs::type::Type::integer_type: case fbs::type::Type::count_type: case fbs::type::Type::real_type: case fbs::type::Type::duration_type: case fbs::type::Type::time_type: case fbs::type::Type::string_type: case fbs::type::Type::pattern_type: case fbs::type::Type::address_type: case fbs::type::Type::subnet_type: case fbs::type::Type::enumeration_type: case fbs::type::Type::list_type: case fbs::type::Type::map_type: { if (current_flat_index == flat_index) return index; ++current_flat_index; ++index.back(); break; } case fbs::type::Type::record_type: { history.emplace_back(field_type->type_as_record_type()); index.push_back(0); break; } case fbs::type::Type::enriched_type: __builtin_unreachable(); break; } } die("index out of bounds"); } std::optional<offset> record_type::resolve_key(std::string_view key) const noexcept { auto index = offset{0}; auto history = std::vector{std::pair{ table().type_as_record_type(), key, }}; while (!index.empty()) { const auto& [record, remaining_key] = history.back(); VAST_ASSERT(record); const auto* fields = record->fields(); VAST_ASSERT(fields); // This is our exit condition: If we arrived at the end of a record, we need // to step out one layer. We must also reset the target key at this point. if (index.back() >= fields->size() || remaining_key.empty()) { history.pop_back(); index.pop_back(); if (!index.empty()) ++index.back(); continue; } const auto* field = record->fields()->Get(index.back()); VAST_ASSERT(field); const auto* field_name = field->name(); VAST_ASSERT(field_name); const auto* field_type = resolve_transparent(field->type_nested_root()); VAST_ASSERT(field_type); switch (field_type->type_type()) { case fbs::type::Type::NONE: case fbs::type::Type::bool_type: case fbs::type::Type::integer_type: case fbs::type::Type::count_type: case fbs::type::Type::real_type: case fbs::type::Type::duration_type: case fbs::type::Type::time_type: case fbs::type::Type::string_type: case fbs::type::Type::pattern_type: case fbs::type::Type::address_type: case fbs::type::Type::subnet_type: case fbs::type::Type::enumeration_type: case fbs::type::Type::list_type: case fbs::type::Type::map_type: { if (remaining_key == field_name->string_view()) return index; ++index.back(); break; } case fbs::type::Type::record_type: { auto [remaining_key_mismatch, field_name_mismatch] = std::mismatch(remaining_key.begin(), remaining_key.end(), field_name->begin(), field_name->end()); if (field_name_mismatch == field_name->end() && remaining_key_mismatch == remaining_key.end()) return index; if (field_name_mismatch == field_name->end() && remaining_key_mismatch != remaining_key.end() && *remaining_key_mismatch == '.') { history.emplace_back(field_type->type_as_record_type(), remaining_key.substr(1 + remaining_key_mismatch - remaining_key.begin())); index.push_back(0); } else { ++index.back(); } break; } case fbs::type::Type::enriched_type: __builtin_unreachable(); break; } } return {}; } detail::generator<offset> record_type::resolve_key_suffix(std::string_view key, std::string_view prefix) const noexcept { if (key.empty()) co_return; auto index = offset{0}; auto history = std::vector{ std::pair{ table().type_as_record_type(), std::vector{key}, }, }; const auto* prefix_begin = prefix.begin(); while (prefix_begin != prefix.end()) { const auto [prefix_mismatch, key_mismatch] = std::mismatch(prefix_begin, prefix.end(), key.begin(), key.end()); if (prefix_mismatch == prefix.end() && key_mismatch != key.end() && *key_mismatch == '.') history[0].second.push_back(key.substr(1 + key_mismatch - key.begin())); prefix_begin = std::find(prefix_begin, prefix.end(), '.'); if (prefix_begin == prefix.end()) break; ++prefix_begin; } while (!index.empty()) { auto& [record, remaining_keys] = history.back(); VAST_ASSERT(record); const auto* fields = record->fields(); VAST_ASSERT(fields); // This is our exit condition: If we arrived at the end of a record, we // need to step out one layer. We must also reset the target key at this // point. if (index.back() >= fields->size()) { history.pop_back(); index.pop_back(); if (!index.empty()) ++index.back(); continue; } const auto* field = record->fields()->Get(index.back()); VAST_ASSERT(field); const auto* field_name = field->name(); VAST_ASSERT(field_name); const auto* field_type = resolve_transparent(field->type_nested_root()); VAST_ASSERT(field_type); switch (field_type->type_type()) { case fbs::type::Type::NONE: case fbs::type::Type::bool_type: case fbs::type::Type::integer_type: case fbs::type::Type::count_type: case fbs::type::Type::real_type: case fbs::type::Type::duration_type: case fbs::type::Type::time_type: case fbs::type::Type::string_type: case fbs::type::Type::pattern_type: case fbs::type::Type::address_type: case fbs::type::Type::subnet_type: case fbs::type::Type::enumeration_type: case fbs::type::Type::list_type: case fbs::type::Type::map_type: { for (const auto& remaining_key : remaining_keys) { // TODO: Once we no longer support flattening types, we can switch to // an equality comparison between field_name and remaining_key here. const auto [field_name_mismatch, remaining_key_mismatch] = std::mismatch(field_name->rbegin(), field_name->rend(), remaining_key.rbegin(), remaining_key.rend()); if (remaining_key_mismatch == remaining_key.rend() && (field_name_mismatch == field_name->rend() || *field_name_mismatch == '.')) { co_yield index; break; } } ++index.back(); break; } case fbs::type::Type::record_type: { using history_entry = decltype(history)::value_type; auto next = history_entry{ field_type->type_as_record_type(), history[0].second, }; for (const auto& remaining_key : remaining_keys) { auto [remaining_key_mismatch, field_name_mismatch] = std::mismatch(remaining_key.begin(), remaining_key.end(), field_name->begin(), field_name->end()); if (field_name_mismatch == field_name->end() && remaining_key_mismatch != remaining_key.end() && *remaining_key_mismatch == '.') { next.second.emplace_back(remaining_key.substr( 1 + remaining_key_mismatch - remaining_key.begin())); } } history.push_back(std::move(next)); index.push_back(0); break; } case fbs::type::Type::enriched_type: __builtin_unreachable(); break; } } co_return; } std::string_view record_type::key(size_t index) const& noexcept { const auto* record = table().type_as_record_type(); VAST_ASSERT(record); VAST_ASSERT(index < record->fields()->size(), "index out of bounds"); const auto* field = record->fields()->Get(index); VAST_ASSERT(field); return field->name()->string_view(); } std::string record_type::key(const offset& index) const noexcept { auto result = std::string{}; const auto* record = table().type_as_record_type(); VAST_ASSERT(record); for (size_t i = 0; i < index.size() - 1; ++i) { VAST_ASSERT(index[i] < record->fields()->size()); const auto* field = record->fields()->Get(index[i]); VAST_ASSERT(field); fmt::format_to(std::back_inserter(result), "{}.", field->name()->string_view()); record = resolve_transparent(field->type_nested_root())->type_as_record_type(); VAST_ASSERT(record); } VAST_ASSERT(index.back() < record->fields()->size()); const auto* field = record->fields()->Get(index.back()); VAST_ASSERT(field); fmt::format_to(std::back_inserter(result), "{}", field->name()->string_view()); return result; } record_type::field_view record_type::field(size_t index) const noexcept { const auto* record = table().type_as_record_type(); VAST_ASSERT(record); VAST_ASSERT(index < record->fields()->size(), "index out of bounds"); const auto* field = record->fields()->Get(index); VAST_ASSERT(field); VAST_ASSERT(field->type()); return { field->name()->string_view(), type{table_->slice(as_bytes(*field->type()))}, }; } record_type::field_view record_type::field(const offset& index) const noexcept { VAST_ASSERT(!index.empty(), "offset must not be empty"); const auto* record = table().type_as_record_type(); VAST_ASSERT(record); for (size_t i = 0; i < index.size() - 1; ++i) { VAST_ASSERT(index[i] < record->fields()->size(), "index out of bounds"); record = resolve_transparent(record->fields()->Get(index[i])->type_nested_root()) ->type_as_record_type(); VAST_ASSERT(record, "offset contains excess indices"); } VAST_ASSERT(index.back() < record->fields()->size(), "index out of bounds"); const auto* field = record->fields()->Get(index.back()); VAST_ASSERT(field); return { field->name()->string_view(), type{table_->slice(as_bytes(*field->type()))}, }; } size_t record_type::flat_index(const offset& index) const noexcept { VAST_ASSERT(!index.empty(), "index must not be empty"); auto flat_index = size_t{0}; auto current_index = offset{0}; auto history = detail::stack_vector<const fbs::type::RecordType*, 64>{ table().type_as_record_type()}; while (true) { VAST_ASSERT(current_index <= index, "index out of bounds"); const auto* record = history.back(); VAST_ASSERT(record); const auto* fields = record->fields(); VAST_ASSERT(fields); // This is our exit condition: If we arrived at the end of a record, we need // to step out one layer. if (current_index.back() >= fields->size()) { history.pop_back(); current_index.pop_back(); VAST_ASSERT(!current_index.empty()); ++current_index.back(); continue; } const auto* field = record->fields()->Get(current_index.back()); VAST_ASSERT(field); const auto* field_type = resolve_transparent(field->type_nested_root()); VAST_ASSERT(field_type); switch (field_type->type_type()) { case fbs::type::Type::NONE: case fbs::type::Type::bool_type: case fbs::type::Type::integer_type: case fbs::type::Type::count_type: case fbs::type::Type::real_type: case fbs::type::Type::duration_type: case fbs::type::Type::time_type: case fbs::type::Type::string_type: case fbs::type::Type::pattern_type: case fbs::type::Type::address_type: case fbs::type::Type::subnet_type: case fbs::type::Type::enumeration_type: case fbs::type::Type::list_type: case fbs::type::Type::map_type: { if (index == current_index) return flat_index; ++current_index.back(); ++flat_index; break; } case fbs::type::Type::record_type: { VAST_ASSERT(index != current_index); history.emplace_back(field_type->type_as_record_type()); current_index.push_back(0); break; } case fbs::type::Type::enriched_type: __builtin_unreachable(); break; } } } record_type::transformation::function_type record_type::drop() noexcept { return [](const field_view&) noexcept -> std::vector<struct field> { return {}; }; } record_type::transformation::function_type record_type::assign(std::vector<struct field> fields) noexcept { return [fields = std::move(fields)]( const field_view&) noexcept -> std::vector<struct field> { return fields; }; } record_type::transformation::function_type record_type::insert_before(std::vector<struct field> fields) noexcept { return [fields = std::move(fields)](const field_view& field) mutable noexcept -> std::vector<struct field> { fields.reserve(fields.size() + 1); fields.push_back({std::string{field.name}, field.type}); return fields; }; } record_type::transformation::function_type record_type::insert_after(std::vector<struct field> fields) noexcept { return [fields = std::move(fields)](const field_view& field) mutable noexcept -> std::vector<struct field> { fields.reserve(fields.size() + 1); fields.insert(fields.begin(), {std::string{field.name}, field.type}); return fields; }; } std::optional<record_type> record_type::transform( std::vector<transformation> transformations) const noexcept { // This function recursively calls do_transform while iterating over all the // leaves of the record type backwards. // // Given this record type: // // type x = record { // a: record { // b: integer, // c: integer, // }, // d: record { // e: record { // f: integer, // }, // }, // } // // A transformation of `d.e` will cause `f` and `a` to be untouched and // simply copied to the new record type, while all the other fields need to // be re-created. This is essentially an optimization over the naive approach // that recursively converts the record type into a list of record fields, // and then modifies that. As an additional benefit this function allows for // applying multiple transformations at the same time. // // This algorithm works by walking over the transformations in reverse order // (by offset), and unwrapping the record type into fields for all fields // whose offset is a prefix of the transformations target offset. // Transformations are applied when unwrapping if the target offset matches // the field offset exactly. After having walked over a record type, the // fields are joined back together at the end of the recursive lambda call. const auto do_transform = [](const auto& do_transform, const record_type& self, offset index, auto& current, const auto end) noexcept -> std::optional<record_type> { if (current == end) return self; auto new_fields = std::vector<struct field>{}; new_fields.reserve(self.num_fields()); index.emplace_back(self.num_fields()); while (index.back() > 0 && current != end) { const auto& old_field = self.field(--index.back()); // Compare the offsets of the next target with our current offset. const auto [index_mismatch, current_index_mismatch] = std::mismatch(index.begin(), index.end(), current->index.begin(), current->index.end()); if (index_mismatch == index.end() && current_index_mismatch == current->index.end()) { // The offset matches exactly, so we apply the transformation. do { auto replacements = std::invoke(std::move(current->fun), old_field); std::move(replacements.rbegin(), replacements.rend(), std::back_inserter(new_fields)); ++current; } while (current != end && current->index == index); } else if (index_mismatch == index.end()) { // The index is a prefix of the target offset for the next // transformation, so we recurse one level deeper. VAST_ASSERT(caf::holds_alternative<record_type>(old_field.type)); if (auto sub_result = do_transform(do_transform, caf::get<record_type>(old_field.type), index, current, end)) new_fields.push_back({ std::string{old_field.name}, std::move(*sub_result), }); // Check for invalid arguments on the way in. VAST_ASSERT(current == end || index != current->index, "cannot apply transformations to both a nested record type " "and its children at the same time."); } else { // Check for invalid arguments on the way out. VAST_ASSERT(current_index_mismatch != current->index.end(), "cannot apply transformations to both a nested record type " "and its children at the same time."); // We don't have a match and we also don't have a transformation, so // we just leave the field untouched. new_fields.push_back({ std::string{old_field.name}, old_field.type, }); } } // In case fbs::type::Type::we exited the loop earlier, we still have to add // all the remaining fields back to the modified record (untouched). while (index.back() > 0) { const auto& old_field = self.field(--index.back()); new_fields.push_back({ std::string{old_field.name}, old_field.type, }); } if (new_fields.empty()) return std::nullopt; type result{}; construct_record_type(result, new_fields.rbegin(), new_fields.rend()); return caf::get<record_type>(result); }; // Verify that transformations are sorted in order. VAST_ASSERT(std::is_sorted(transformations.begin(), transformations.end(), [](const auto& lhs, const auto& rhs) noexcept { return lhs.index <= rhs.index; })); auto current = transformations.rbegin(); auto result = do_transform(do_transform, *this, {}, current, transformations.rend()); VAST_ASSERT(current == transformations.rend(), "index out of bounds"); return result; } caf::expected<record_type> merge(const record_type& lhs, const record_type& rhs, enum record_type::merge_conflict merge_conflict) noexcept { auto do_merge = [&](const record_type::field_view& lfield, const record_type::field_view& rfield) noexcept { return detail::overload{ [&](const record_type& lhs, const record_type& rhs) noexcept -> caf::expected<type> { if (auto result = merge(lhs, rhs, merge_conflict)) return type{*result}; else return result.error(); }, [&]<concrete_type T, concrete_type U>( const T& lhs, const U& rhs) noexcept -> caf::expected<type> { switch (merge_conflict) { case record_type::merge_conflict::fail: { if (congruent(type{lhs}, type{rhs})) { if (lfield.type.name() != rfield.type.name()) return caf::make_error( ec::logic_error, fmt::format("conflicting alias types {} and {} for " "field {}; failed to merge {} and {}", lfield.type.name(), rfield.type.name(), rfield.name, lhs, rhs)); auto to_vector = [](detail::generator<type::attribute_view>&& rng) { auto result = std::vector<type::attribute_view>{}; for (auto&& elem : std::move(rng)) result.push_back(std::move(elem)); return result; }; const auto lhs_attributes = to_vector(lfield.type.attributes()); const auto rhs_attributes = to_vector(rfield.type.attributes()); const auto conflicting_attribute = std::any_of( lhs_attributes.begin(), lhs_attributes.end(), [&](const auto& lhs_attribute) noexcept { return rfield.type.attribute(lhs_attribute.key.data()) != lhs_attribute.value; }); if (conflicting_attribute) return caf::make_error(ec::logic_error, fmt::format("conflicting attributes for " "field {}; failed to " "merge {} and {}", rfield.name, lhs, rhs)); auto attributes = std::vector<struct type::attribute>{}; for (const auto& attribute : lhs_attributes) attributes.push_back( {std::string{attribute.key}, std::optional{std::string{attribute.value}}}); for (const auto& attribute : rhs_attributes) attributes.push_back( {std::string{attribute.key}, std::optional{std::string{attribute.value}}}); return type{lfield.type.name(), lfield.type, attributes}; } return caf::make_error(ec::logic_error, fmt::format("conflicting field {}; " "failed to " "merge {} and {}", rfield.name, lhs, rhs)); } case record_type::merge_conflict::prefer_left: return lfield.type; case record_type::merge_conflict::prefer_right: return rfield.type; } __builtin_unreachable(); }, }; }; auto transformations = std::vector<record_type::transformation>{}; auto additions = std::vector<struct record_type::field>{}; transformations.reserve(rhs.num_fields()); auto err = caf::error{}; for (auto rfield : rhs.fields()) { if (const auto& lindex = lhs.resolve_key(rfield.name)) { transformations.push_back({ *lindex, ([&, rfield = std::move(rfield)]( const record_type::field_view& lfield) mutable noexcept -> std::vector<struct record_type::field> { if (auto result = caf::visit(do_merge(lfield, rfield), lfield.type, rfield.type)) { return {{ std::string{rfield.name}, *result, }}; } else { err = std::move(result.error()); return {}; } }), }); } else { additions.push_back({std::string{rfield.name}, rfield.type}); } } auto result = lhs.transform(std::move(transformations)); if (err) return err; VAST_ASSERT(result); result = result->transform({{ {result->num_fields() - 1}, record_type::insert_after(std::move(additions)), }}); VAST_ASSERT(result); return std::move(*result); } record_type flatten(const record_type& type) noexcept { auto fields = std::vector<struct record_type::field>{}; for (const auto& [field, offset] : type.leaves()) fields.push_back({ type.key(offset), field.type, }); return record_type{fields}; } } // namespace vast // -- sum_type_access --------------------------------------------------------- namespace caf { uint8_t sum_type_access<vast::type>::index_from_type(const vast::type& x) noexcept { static const auto table = []<vast::concrete_type... Ts, uint8_t... Indices>( caf::detail::type_list<Ts...>, std::integer_sequence<uint8_t, Indices...>) noexcept { std::array<uint8_t, std::numeric_limits<uint8_t>::max()> tbl{}; tbl.fill(std::numeric_limits<uint8_t>::max()); (static_cast<void>(tbl[Ts::type_index] = Indices), ...); return tbl; } (types{}, std::make_integer_sequence<uint8_t, caf::detail::tl_size<types>::value>()); // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index) auto result = table[x.type_index()]; VAST_ASSERT(result != std::numeric_limits<uint8_t>::max()); return result; } } // namespace caf
36.306773
81
0.624536
[ "vector", "model", "transform" ]
c5e5b6cf94c3d193390161c953f2a6afa56bdfec
11,301
hxx
C++
main/svx/source/inc/sdbdatacolumn.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/svx/source/inc/sdbdatacolumn.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/svx/source/inc/sdbdatacolumn.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 SVX_FORM_SDBDATACOLUMN_HXX #define SVX_FORM_SDBDATACOLUMN_HXX #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/sdb/XColumn.hpp> #include <com/sun/star/sdb/XColumnUpdate.hpp> #include <osl/diagnose.h> //.............................................................................. namespace svxform { //.............................................................................. //========================================================================== //= DataColumn - a class wrapping an object implementing a sdb::DataColumn service //========================================================================== class DataColumn { // interfaces needed for sddb::Column ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> m_xPropertySet; // interfaces needed for sdb::DataColumn ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XColumn> m_xColumn; ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XColumnUpdate> m_xColumnUpdate; public: DataColumn() { }; DataColumn(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxIFace); // if the object behind _rxIFace doesn't fully support the DataColumn service, // (which is checked via the supported interfaces) _all_ members will be set to // void !, even if the object has some of the needed interfaces. sal_Bool is() const { return m_xColumn.is(); } sal_Bool Is() const { return m_xColumn.is(); } sal_Bool supportsUpdate() const { return m_xColumnUpdate.is(); } DataColumn* operator ->() { return this; } operator ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface> () const{ return m_xColumn.get(); } // 'conversions' inline const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& getPropertySet() const { return m_xPropertySet; } inline const ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XColumn>& getColumn() const { return m_xColumn; } inline const ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XColumnUpdate>& getColumnUpdate() const { OSL_ENSURE(m_xColumnUpdate.is() , "DataColumn::getColumnUpdate: NULL!"); return m_xColumnUpdate; } // das normale queryInterface ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& type) throw ( ::com::sun::star::uno::RuntimeException ) { return m_xColumn->queryInterface(type); } // ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> inline ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo> getPropertySetInfo() const throw( ::com::sun::star::uno::RuntimeException ); inline void setPropertyValue(const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue) throw( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException ); inline ::com::sun::star::uno::Any getPropertyValue(const ::rtl::OUString& PropertyName) const throw( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException ); inline void addPropertyChangeListener(const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener>& xListener) throw( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException ); inline void removePropertyChangeListener(const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener>& aListener) throw( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException ); inline void addVetoableChangeListener(const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener>& aListener) throw( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException ); inline void removeVetoableChangeListener(const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener>& aListener) throw( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException ); // ::com::sun::star::sdb::XColumn inline sal_Bool wasNull() throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline ::rtl::OUString getString() throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline sal_Bool getBoolean() throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline sal_Int8 getByte() throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline sal_Int16 getShort() throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline sal_Int32 getInt() throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline sal_Int64 getLong() throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline float getFloat() throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline double getDouble() throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline ::com::sun::star::uno::Sequence< sal_Int8 > getBytes() throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline ::com::sun::star::util::Date getDate() throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline ::com::sun::star::util::Time getTime() throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline ::com::sun::star::util::DateTime getTimestamp() throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream> getBinaryStream() throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream> getCharacterStream() throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline ::com::sun::star::uno::Any getObject(const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess>& typeMap) throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRef> getRef() throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XBlob> getBlob() throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XClob> getClob() throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XArray> getArray() throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); // XColumnUpdate inline void updateNull(void) throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline void updateBoolean(sal_Bool x) throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline void updateByte(sal_Int8 x) throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline void updateShort(sal_Int16 x) throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline void updateInt(sal_Int32 x) throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline void updateLong(sal_Int64 x) throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline void updateFloat(float x) throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline void updateDouble(double x) throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline void updateString(const ::rtl::OUString& x) throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline void updateBytes(const ::com::sun::star::uno::Sequence< sal_Int8 >& x) throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline void updateDate(const com::sun::star::util::Date& x) throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline void updateTime(const ::com::sun::star::util::Time& x) throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline void updateTimestamp(const ::com::sun::star::util::DateTime& x) throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline void updateBinaryStream(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream>& x, sal_Int32 length) throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline void updateCharacterStream(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream>& x, sal_Int32 length) throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline void updateObject(const ::com::sun::star::uno::Any& x) throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); inline void updateNumericObject(const ::com::sun::star::uno::Any& x, sal_Int32 scale) throw( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException ); }; #endif // SVX_FORM_SDBDATACOLUMN_HXX //.............................................................................. } // namespace svxform //..............................................................................
82.489051
357
0.669852
[ "object" ]
c5e71f0f71c6dedc1332cdcddf7d0947c64c0a8f
21,285
cpp
C++
part_2_stdlib/chapter_10_genericalg.cpp
lsqyling/PrimerAdvanced
f6831e73b04fcaf590f1dd99271b3ac0c8660117
[ "CC0-1.0" ]
1
2019-05-18T05:22:20.000Z
2019-05-18T05:22:20.000Z
part_2_stdlib/chapter_10_genericalg.cpp
lsqyling/PrimerAdvanced
f6831e73b04fcaf590f1dd99271b3ac0c8660117
[ "CC0-1.0" ]
null
null
null
part_2_stdlib/chapter_10_genericalg.cpp
lsqyling/PrimerAdvanced
f6831e73b04fcaf590f1dd99271b3ac0c8660117
[ "CC0-1.0" ]
null
null
null
// // Created by shiqing on 19-4-27. // #include <algorithm> #include <fstream> #include <sstream> #include "../common/CommonHeaders.h" #include "../part_1_foundation/SalesData.h" /* * Exercise 10.1: * The algorithm header defines a function named count * that, like find, takes a pair of iterators and a value. count returns a count * of how often that value appears. Read a sequence of ints into a vector * and print the count of how many elements have a given value. * @see testingFindCounts(); * * Exercise 10.2: * Repeat the previous program, but read values into a list of strings. * @see testingFindCounts(); * */ const string text_file_path = "../../part_2_stdlib/5.Harry Potter and the Order of the Phoenix.txt"; const string mark_file_path = "../../part_2_stdlib/mark.data"; const string numbs_file_path = "../../part_2_stdlib/numbers.txt"; void testingFindCounts() { vector<int> vi = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 3, 3, 3}; auto cnt = std::count(vi.begin(), vi.end(), 3); cout << "The number of times the number 3 appears is: " << cnt << endl; vector<string> vs = {"hello", "how", "now", "world", "word", "what", "how"}; cnt = std::count(vs.begin(), vs.end(), "how"); cout << "the string of 'how' appears is: " << cnt << endl; } /* * Exercise 10.3: Use accumulate to sum the elements in a vector<int>. * @see accumulateInts(); * * * Exercise 10.4: Assuming v is a vector<double>, what, if anything, is * wrong with calling accumulate(v.cbegin(), v.cend(), 0)? * @see accumulateInts(); * * Exercise 10.5: In the call to equal on rosters, what would happen if both * rosters held C-style strings, rather than library strings? * @see accumulateInts(); */ void accumulateInts() { vector<int> vi = {0, 1, 3, 4, 5, 6, 7, 8, 9}; int sum = std::accumulate(vi.cbegin(), vi.cend(), 0); cout << "sum = " << sum << endl; vector<double> vd = {0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9}; auto sumD = std::accumulate(vd.cbegin(), vd.cend(), 0); cout << "sumD = " << sumD << '\n'; sumD = std::accumulate(vd.cbegin(), vd.cend(), 0.0); cout << "sumD = " << sumD << endl; vector<const char *> roster = {"hello", "world", "!!", "oh", "my", "dear!!"}; list<string> roster1 = {"hello", "world", "!!", "oh", "my", "dear!!"}; bool flag = std::equal(roster.cbegin(), roster.cend(), roster1.cbegin()); cout << "flag = " << flag << endl; } /* * Exercise 10.6: Using fill_n, write a program to set a sequence of int values to 0. * @see changeableContains(); * * Exercise 10.7: Determine if there are any errors in the following programs * and, if so, correct the error(s): * vector<int> vec; list<int> lst; int i; * while (cin >> i) * lst.push_back(i); * copy(lst.cbegin(), lst.cend(), vec.begin()); //std::back_inserter(vec); * (b) * vector<int> vec; * vec.reserve(10); // reserve is covered in § 9.4 (p. 356) //wrong: vec.resize(10); * fill_n(vec.begin(), 10, 0); * * * Exercise 10.8: We said that algorithms do not change the size of the * containers over which they operate.Why doesn't the use of back_inserter invalidate this claim? * * Answer: * Inserters like back_inserter is part of <iterator> rather than <algorithm>. */ void changeableContains() { vector<int> vi{0, 2, 3, 5, 5, 6, 8, 9}; std::fill_n(vi.begin(), vi.size(), 0); for (const auto &item : vi) { cout << item << " "; } cout << '\n'; } /* * Exercise 10.9: Implement your own version of elimDups. Test your * program by printing the vector after you read the input, after the call to * unique, and after the call to erase. * @see elimDups(); * * Exercise 10.10: Why do you think the algorithms don’t change the size of containers? * Answer: * The library algorithms operate on iterators, not containers. Therefore, an * algorithm cannot (directly) add or remove elements. */ bool isShorter(const string &s1, const string &s2) { return s1.size() < s2.size(); } void elimDups(vector<string> &vs) { std::sort(vs.begin(), vs.end()); auto it = std::unique(vs.begin(), vs.end()); vs.erase(it, vs.end()); } /* * Exercise 10.11: Write a program that uses stable_sort and isShorter * to sort a vector passed to your version of elimDups. Print the vector to * verify that your program is correct. * @see elimDups(); * * * Exercise 10.12: Write a function named compareIsbn that compares the * isbn() members of two Sales_data objects. Use that function to sort a * vector that holds Sales_data objects. * * * * Exercise 10.13: * The library defines an algorithm named partition that * takes a predicate and partitions the container so that values for which the * predicate is true appear in the first part and those for which the predicate is * false appear in the second part. The algorithm returns an iterator just past * the last element for which the predicate returned true. Write a function that * takes a string and returns a bool indicating whether the string has five * characters or more. Use that function to partition words. Print the elements * that have five or more characters. * @see partitionByFunc(); */ void elimDupsOther(vector<string> &vs) { std::sort(vs.begin(), vs.end(), isShorter); auto it = std::unique(vs.begin(), vs.end()); vs.erase(it, vs.end()); } bool compareIsbn(const SalesData &lhs, const SalesData &rhs) { return lhs.isbn() < rhs.isbn(); } void testingSortSalesData() { vector<SalesData> vs = {SalesData("0-201-78345-X"), SalesData("0-201-78345-XX"), SalesData("0-201-78345-XY"), SalesData("0-201-789345-X")}; std::sort(vs.begin(), vs.end(), compareIsbn); for (const auto &elem : vs) { print(cout, elem) << " "; } cout << endl; } void testingElimDups() { testingSortSalesData(); vector<string> vs = {"hi", "world", "my", "my", "baby", "baby"}; elimDups(vs); for (const auto &elem : vs) { cout << elem << " "; } cout << '\n'; vs.push_back("Jag"); vs.push_back("hi"); elimDupsOther(vs); for (const auto &elem : vs) { cout << elem << " "; } cout << endl; } bool greaterThanFiveChars(const string &s) { return s.size() >= 25; } void partitionByFunc() { std::ifstream in(text_file_path, std::ifstream::in); vector<string> words; string s; while (in >> s) { words.push_back(s); } auto it = std::partition(words.begin(), words.end(), greaterThanFiveChars); int cnt = 0; for (auto beg = words.begin(); beg != it; ++beg) { cout << *beg << " "; ++cnt; if (cnt % 2 == 0) cout << '\n'; } cout << endl; } /* * Exercise 10.14: Write a lambda that takes two ints and returns their sum. * @see mathLambdas(); * * * Exercise 10.15: Write a lambda that captures an int from its enclosing * function and takes an int parameter. The lambda should return the sum of * the captured int and the int parameter. * @see mathLambdas(); * * * Exercise 10.16: Write your own version of the biggies function using lambdas. * @see @biggest(); * * Exercise 10.17: Rewrite exercise 10.12 from § 10.3.1 (p. 387) to use a * lambda in the call to sort instead of the compareIsbn function. * @see biggest(); * * Exercise 10.18: Rewrite biggies to use partition instead of find_if. * We described the partition algorithm in exercise 10.13 in § 10.3.1 (p.387). * @see biggest(); * * Exercise 10.19: Rewrite the previous exercise to use stable_partition, * which like stable_sort maintains the original element order in the * partitioned sequence. * @see biggest(); */ void mathLambdas() { auto add = [](int a, int b) { return a + b; }; auto subtract = [](auto a, auto b) { return a - b; }; auto multiply = [](auto a, auto b) { return a * b; }; auto divided = [](auto a, auto b) { return a / b; }; cout << add(3, 5) << '\n' << subtract(3, 5) << '\n' << multiply(3, 5) << '\n' << divided(3, 5) << endl; int a = 3; auto addCapture = [a](int b) { return a + b; }; cout << addCapture(5) << endl; } void biggest(vector<string> &vs, size_t sz) { std::sort(vs.begin(), vs.end(), [](const string &s1, const string &s2) { return s1.size() < s2.size(); }); std::unique(vs.begin(), vs.end()); std::stable_sort(vs.begin(), vs.end()); auto it = std::partition(vs.begin(), vs.end(), [sz](const string &s) { return s.size() > sz; }); // or it = std::find_if(vs.begin(), vs.end(), [sz](const auto &s) { return s.size() > sz; }); size_t cnt; for (auto beg = vs.begin(); beg != it; ++beg) { cout << *beg << " "; ++cnt; if (cnt % 5 == 0) cout << '\n'; } cout << endl; } const string text = " 'Lovely evening!' shouted Uncle Vernon, waving at Mrs Number Seven opposite, who was glaring from behind her net curtains. 'Did you hear that car backfire just now? Gave Petunia and me quite a turn!'\n" " He continued to grin in a horrible, manic way until all the curious neighbours had disappeared from their various windows, then the grin became a grimace of rage as he beckoned Harry back towards him.\n" " Harry moved a few steps closer, taking care to stop just short of the point at which Uncle Vernon's outstretched hands could resume their strangling.\n" " 'What the devil do you mean by it, boy?' asked Uncle Vernon in a croaky voice that trembled with fury.\n" " 'What do I mean by what?' said Harry coldly. He kept looking left and right up the street, still hoping to see the person who had made the cracking noise.\n" " 'Making a racket like a starting pistol right outside our - '\n" " 'I didn't make that noise,' said Harry firmly.\n" " Aunt Petunia's thin, horsy face now appeared beside Uncle Vernon's wide, purple one. She looked livid.\n" " 'Why were you lurking under our window?'"; void testingBiggest() { std::istringstream in(text); vector<string> vs; string s; while (in >> s) { vs.push_back(s); } biggest(vs, 5); } vector<string> of(const string &text) { std::istringstream in(text); vector<string> vs; string s; while (in >> s) { vs.push_back(s); } return vs; } void testingCountIf() { vector<string> vs = of(text); int le = 6; auto sz = std::count_if(vs.begin(), vs.end(), [=](const auto &s) { return s.size() > le;}); cout << "The count number of words longer than 6 is: " << sz << endl; } void decreaseLocal() { int i = 10; auto f = [i]() mutable -> bool { if(!i) return true; --i; return false; }; } /* * Exercise 10.22: Rewrite the program to count words of size 6 or less using * functions in place of the lambdas. * @see countByLambdas(); * * Exercise 10.23: How many arguments does bind take? * Answer: * Assuming the function to be bound have n parameters, bind take n + 1 parameters. * The additional one is for the function to be bound itself. * * Exercise 10.24: Use bind and check_size to find the first element in a * vector of ints that has a value greater than the length of a specified string value. * @see findIfByBind(); * * * Exercise 10.25: In the exercises for § 10.3.2 (p. 392) you wrote a version * of biggies that uses partition. Rewrite that function to use check_size and bind. * @see biggestByBind(); * * */ #include <algorithm> #include <functional> using namespace std::placeholders; bool greaterThanSpecStr(const string &s, string tar) { return s.size() > tar.size(); } void findIfByBind() { vector<string> vs = of(text); auto it = std::find_if(vs.begin(), vs.end(), std::bind(greaterThanSpecStr, _1, "hello")); if (it != vs.end()) { cout << "the first words greater is " << *it << endl; } } void countByLambdas() { vector<string> vs = of(text); size_t sz = 6; auto cnt = std::count_if(vs.begin(), vs.end(), [=](const auto &s){ return s.size() <= sz; }); cout << cnt << endl; } void biggestByBind() { vector<string> vs = of(text); std::sort(vs.begin(), vs.end()); auto it = std::unique(vs.begin(), vs.end(), bind(greaterThanSpecStr, _1, "hello")); std::for_each(it, vs.end(), [](const auto &s) { cout << s << " ";}); } /* * Exercise 10.26: Explain the differences among the three kinds of insert iterators. * Answer: * back_inserter uses push_back. * front_inserter uses push_front. * insert uses insert * This function takes a second argument, which must be an iterator into the given container. * Elements are inserted ahead of the element denoted by the given iterator. * * * Exercise 10.27: In addition to unique (§ 10.2.3, p. 384), the library * defines function named unique_copy that takes a third iterator denoting a * destination into which to copy the unique elements. Write a program that * uses unique_copy to copy the unique elements from a vector into an initially empty list. * @see uniqueCopyByInserter(); * * * * Exercise 10.28: Copy a vector that holds the values from 1 to 9 inclusive, * into three other containers. Use an inserter, a back_inserter, and a * front_inserter, respectivly to add elements to these containers. Predict * how the output sequence varies by the kind of inserter and verify your * predictions by running your programs. * @see usedInserter(); * */ void usedInserter() { vector<int> vi = {1, 2, 3, 4, 5, 6, 7, 8, 9}; list<int> first, second, third; std::copy(vi.begin(), vi.end(), std::back_inserter(first)); std::copy(vi.begin(), vi.end(), std::inserter(second, second.begin())); std::copy(vi.begin(), vi.end(), std::front_inserter(third)); for (const auto &elem : first) { cout << elem << " "; } cout << '\n'; for (const auto &elem : second) { cout << elem << " "; } cout << '\n'; for (const auto &elem : third) { cout << elem << " "; } cout << endl; } void uniqueCopyByInserter() { vector<string> vs = of(text); list<string> li; std::unique_copy(vs.begin(), vs.end(), std::front_inserter(li)); int cnt = 0; for (const auto &item : li) { cout << item << " "; ++cnt; if (cnt % 7 == 0) cout << '\n'; } cout << endl; } /* * Exercise 10.29: Write a program using stream iterators to read a text file into a vector of strings. * @see testingIOStreamIterator(); * * Exercise 10.30: Use stream iterators, sort, and copy to read a sequence * of integers from the standard input, sort them, and then write them back to the standard output. * @see usedIOStreamIterator(); * * * Exercise 10.31: Update the program from the previous exercise so that it * prints only the unique elements. Your program should use unqiue_copy (§10.4.1, p. 403). * @see usedIOStreamIterator(); * * * * Exercise 10.32: Rewrite the bookstore problem from § 1.6 (p. 24) using a * vector to hold the transactions and various algorithms to do the processing. * Use sort with your compareIsbn function from § 10.3.1 (p. 387) to * arrange the transactions in order, and then use find and accumulate to do the sum. * already be done. * * * Exercise 10.33: Write a program that takes the names of an input file and * two output files. The input file should hold integers. Using an * istream_iterator read the input file. Using ostream_iterators, write * the odd numbers into the first output file. Each value should be followed by a * space. Write the even numbers into the second file. Each of these values * should be placed on a separate line. * @see findOddsAndEven(); * */ #include <iterator> void testingIOStreamIterator() { std::ifstream in(text_file_path); std::istream_iterator<string> strIter(in); std::istream_iterator<string> eof; vector<string> vs; while (strIter != eof) { vs.push_back(*strIter++); } cout << "vs.size() = " << vs.size() << endl; } bool readMark() { std::ifstream in(mark_file_path); unsigned n = -1; bool flag = false; if (in >> n) { if (!n) flag = true; ++n; } std::ofstream out(mark_file_path); out << n; return flag; } void writeNumbers() { std::ofstream out(numbs_file_path, std::ofstream::app); std::default_random_engine e; std::uniform_int_distribution<unsigned > u(0, 1 << 31); if (out && readMark()) { for (int i = 1; i != (1 << 16); ++i) { out << u(e) << " "; if (i % 20 == 0) out << '\n'; } } } void usedIOStreamIterator() { std::ifstream in(numbs_file_path); std::istream_iterator<long> itIn(in); std::istream_iterator<long> eof; vector<long> vi; while (itIn != eof) { vi.push_back(*itIn++); } std::sort(vi.begin(), vi.end()); std::ostream_iterator<long> outIter(cout, " "); std::copy(vi.begin(), vi.end(), outIter); cout << endl; std::unique_copy(vi.begin(), vi.end(), outIter); cout << endl; } void findOddsAndEven() { std::ifstream in(numbs_file_path); std::ofstream outOdds("../../part_2_stdlib/numb_odds.txt"), outEven("../../part_2_stdlib/numb_even.txt"); std::ostream_iterator<unsigned > iterOutOdds(outOdds, " "), iterOutEven(outEven, "\n"); std::istream_iterator<unsigned > iterIn(in), eof; while (iterIn != eof) { if (*iterIn & 1) { *iterOutOdds++ = *iterIn; } else { *iterOutEven++ = *iterIn; } ++iterIn; } } /* * Exercise 10.34: Use reverse_iterators to print a vector in reverse order. * @see reversePrint(); * * Exercise 10.35: Now print the elements in reverse order using ordinary iterators. * @see reversePrint(); * * Exercise 10.36: Use find to find the last element in a list of ints with value 0. * @see reversePrint(); * * Exercise 10.37: Given a vector that has ten elements, copy the elements from positions 3 through 7 * in reverse order to a list. * @see reversePrint(); */ void reversePrint() { vector<int> vi{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; for (auto rbeg = vi.rbegin(); rbeg != vi.rend(); ++rbeg) { cout << *rbeg << " "; } cout << endl; for (auto end = vi.end() - 1; end != vi.begin() - 1; --end) { cout << *end << " "; } cout << endl; auto it = std::find(vi.rbegin(), vi.rend(), 0); if (it != vi.rend()) { cout << *it << endl; } list<int> li; std::copy(vi.begin() + 2, vi.begin() + 6, std::front_inserter(li)); std::for_each(li.begin(), li.end(),[](const auto &s) { cout << s << " ";}); } /* * Exercise 10.38: List the five iterator categories and the operations that each supports. * Answer: * Input iterators : ==, !=, ++, *, -> * Output iterators : ++, * * Forward iterators : ==, !=, ++, *, -> * Bidirectional iterators : ==, !=, ++, --, *, -> * Random-access iterators : ==, !=, <, <=, >, >=, ++, --, +, +=, -, -=, -(two iterators), *, ->, iter[n] == * (iter + n) * * * Exercise 10.39: What kind of iterator does a list have? What about a vector? * Answer: * list have the Bidirectional iterators. vector have the Random-access iterators. * * Exercise 10.40: What kinds of iterators do you think copy requires? What about reverse or unique? * copy : first and second are Input iterators, last is Output iterators. * reverse : Bidirectional iterators. * unique : Forward iterators. */ /* * Exercise 10.41: Based only on the algorithm and argument names, describe the operation that * the each of the following library algorithms performs: * * Answer: * replace(beg, end, old_val, new_val); // replace the old_elements in the input range as new_elements. * replace_if(beg, end, pred, new_val); // replace the elements in the input range which pred is true as new_elements. * replace_copy(beg, end, dest, old_val, new_val); // copy the new_elements which is old_elements in the input range into dest. * replace_copy_if(beg, end, dest, pred, new_val); // copy the new_elements which pred is true in the input range into dest. */ /* * Exercise 10.42: Reimplement the program that eliminated duplicate words * that we wrote in § 10.2.3 (p. 383) to use a list instead of a vector. * */ void elimDupsByList() { vector<string> vs = of(text); list<string> li; std::copy(vs.begin(), vs.end(), std::back_inserter(li)); li.sort(); li.unique(); int cnt = 0; for (const auto &elem : li) { cout << elem << " "; if (++cnt % 10 == 0) cout << '\n'; } cout << endl; } int main(int argc, char *argv[]) { findOddsAndEven(); writeNumbers(); usedIOStreamIterator(); testingIOStreamIterator(); usedInserter(); uniqueCopyByInserter(); biggestByBind(); findIfByBind(); countByLambdas(); decreaseLocal(); accumulateInts(); testingFindCounts(); changeableContains(); testingElimDups(); partitionByFunc(); mathLambdas(); testingBiggest(); testingCountIf(); reversePrint(); elimDupsByList(); return 0; }
31.959459
228
0.622786
[ "vector" ]
c5e9f19ea80170dc3ab5831b34ba7e920e78dffe
6,335
cpp
C++
spoopy/tools/vole/source/illumestimators/common/statistics.cpp
rodrigobressan/PADify
362db2b3a33793ac53f938e89f90a6ecdf778e89
[ "MIT" ]
12
2019-11-26T07:44:08.000Z
2021-03-03T09:51:43.000Z
spoopy/tools/vole/source/illumestimators/common/statistics.cpp
rodrigobressan/PADify
362db2b3a33793ac53f938e89f90a6ecdf778e89
[ "MIT" ]
13
2020-01-28T22:09:41.000Z
2022-03-11T23:43:37.000Z
spoopy/tools/vole/source/illumestimators/common/statistics.cpp
rodrigobressan/PADify
362db2b3a33793ac53f938e89f90a6ecdf778e89
[ "MIT" ]
5
2020-01-02T09:52:42.000Z
2022-02-21T15:45:23.000Z
/* Copyright(c) 2012 Christian Riess <christian.riess@cs.fau.de> and Johannes Jordan <johannes.jordan@cs.fau.de>. This file may be licensed under the terms of of the GNU General Public License, version 3, as published by the Free Software Foundation. You can find it here: http://www.gnu.org/licenses/gpl.html */ #include "statistics.h" #include <limits> namespace illumestimators { cv::Vec3d Statistics::min(const cv::Mat_<cv::Vec3d>& image) { cv::Vec3d min = cv::Vec3d(std::numeric_limits<double>::max(), std::numeric_limits<double>::max(), std::numeric_limits<double>::max()); for (cv::Mat_<cv::Vec3d>::const_iterator it = image.begin(); it != image.end(); it++) { for (int i = 0; i < 3; i++) { if ((*it)[i] < min[i]) { min[i] = (*it)[i]; } } } return min; } cv::Vec3d Statistics::min(const std::vector<cv::Vec3d>& vector) { cv::Vec3d min = cv::Vec3d(std::numeric_limits<double>::max(), std::numeric_limits<double>::max(), std::numeric_limits<double>::max()); for (std::vector<cv::Vec3d>::const_iterator it = vector.begin(); it != vector.end(); it++) { for (int i = 0; i < 3; i++) { if ((*it)[i] < min[i]) { min[i] = (*it)[i]; } } } return min; } double Statistics::min(const std::vector<double>& vector) { double min = std::numeric_limits<double>::max(); for (std::vector<double>::const_iterator it = vector.begin(); it != vector.end(); it++) { if (*it < min) { min = *it; } } return min; } double Statistics::min(const cv::Vec3d& vector) { double min = std::numeric_limits<double>::max(); for (int i = 0; i < 3; i++) { if (vector[i] < min) { min = vector[i]; } } return min; } cv::Vec3d Statistics::max(const cv::Mat_<cv::Vec3d>& image) { cv::Vec3d max = cv::Vec3d(-std::numeric_limits<double>::max(), -std::numeric_limits<double>::max(), -std::numeric_limits<double>::max()); for (cv::Mat_<cv::Vec3d>::const_iterator it = image.begin(); it != image.end(); it++) { for (int i = 0; i < 3; i++) { if ((*it)[i] > max[i]) { max[i] = (*it)[i]; } } } return max; } cv::Vec3d Statistics::max(const std::vector<cv::Vec3d>& vector) { cv::Vec3d max = cv::Vec3d(-std::numeric_limits<double>::max(), -std::numeric_limits<double>::max(), -std::numeric_limits<double>::max()); for (std::vector<cv::Vec3d>::const_iterator it = vector.begin(); it != vector.end(); it++) { for (int i = 0; i < 3; i++) { if ((*it)[i] > max[i]) { max[i] = (*it)[i]; } } } return max; } double Statistics::max(const std::vector<double>& vector) { double max = -std::numeric_limits<double>::max(); for (std::vector<double>::const_iterator it = vector.begin(); it != vector.end(); it++) { if (*it > max) { max = *it; } } return max; } double Statistics::max(const cv::Vec3d& vector) { double max = -std::numeric_limits<double>::max(); for (int i = 0; i < 3; i++) { if (vector[i] > max) { max = vector[i]; } } return max; } cv::Vec3d Statistics::mean(const cv::Mat_<cv::Vec3d>& image) { cv::Vec3d mean = cv::Vec3d(0, 0, 0); for (cv::Mat_<cv::Vec3d>::const_iterator it = image.begin(); it != image.end(); it++) { for (int i = 0; i < 3; i++) { mean[i] += (*it)[i]; } } const int size = image.rows * image.cols; for (int i = 0; i < 3; i++) { mean[i] /= size; } return mean; } cv::Vec3d Statistics::mean(const std::vector<cv::Vec3d>& vector) { cv::Vec3d mean = cv::Vec3d(0, 0, 0); for (std::vector<cv::Vec3d>::const_iterator it = vector.begin(); it != vector.end(); it++) { for (int i = 0; i < 3; i++) { mean[i] += (*it)[i]; } } const int size = vector.size(); for (int i = 0; i < 3; i++) { mean[i] /= size; } return mean; } double Statistics::mean(const std::vector<double>& vector) { double mean = 0; for (std::vector<double>::const_iterator it = vector.begin(); it != vector.end(); it++) { mean += *it; } mean /= vector.size(); return mean; } double Statistics::mean(const cv::Vec3d& vector) { double mean = 0; for (int i = 0; i < 3; i++) { mean += vector[i]; } mean /= 3; return mean; } cv::Vec3d Statistics::std(const cv::Mat_<cv::Vec3d>& image) { cv::Vec3d std = cv::Vec3d(0, 0, 0); cv::Vec3d m = mean(image); for (cv::Mat_<cv::Vec3d>::const_iterator it = image.begin(); it != image.end(); it++) { for (int i = 0; i < 3; i++) { std[i] += pow((*it)[i] - m[i], 2); } } const int size = image.rows * image.cols; for (int i = 0; i < 3; i++) { std[i] = sqrt(std[i] / size); } return std; } cv::Vec3d Statistics::std(const std::vector<cv::Vec3d>& vector) { cv::Vec3d std = cv::Vec3d(0, 0, 0); cv::Vec3d m = mean(vector); for (std::vector<cv::Vec3d>::const_iterator it = vector.begin(); it != vector.end(); it++) { for (int i = 0; i < 3; i++) { std[i] += pow((*it)[i] - m[i], 2); } } const int size = vector.size(); for (int i = 0; i < 3; i++) { std[i] = sqrt(std[i] / size); } return std; } double Statistics::std(const std::vector<double>& vector) { double std = 0; double m = mean(vector); for (std::vector<double>::const_iterator it = vector.begin(); it != vector.end(); it++) { std += pow((*it) - m, 2); } std = sqrt(std / vector.size()); return std; } cv::Vec3d Statistics::median(const cv::Mat_<cv::Vec3d>& image) { std::vector<double> v[3]; for (cv::Mat_<cv::Vec3d>::const_iterator it = image.begin(); it != image.end(); it++) { for (int i = 0; i < 3; i++) { v[i].push_back((*it)[i]); } } return cv::Vec3d(median(v[0]), median(v[1]), median(v[2])); } cv::Vec3d Statistics::median(const std::vector<cv::Vec3d>& vector) { std::vector<double> v[3]; for (std::vector<cv::Vec3d>::const_iterator it = vector.begin(); it != vector.end(); it++) { for (int i = 0; i < 3; i++) { v[i].push_back((*it)[i]); } } return cv::Vec3d(median(v[0]), median(v[1]), median(v[2])); } double Statistics::median(const std::vector<double>& vector) { if (vector.size() < 1) { return 0; } std::vector<double> v = vector; sort(v.begin(), v.end()); return v[vector.size() / 2]; } double Statistics::rms(const std::vector<double>& vector) { double meansquared = 0; for (std::vector<double>::const_iterator it = vector.begin(); it != vector.end(); it++) { meansquared += pow(*it, 2); } meansquared /= vector.size(); return sqrt(meansquared); } } // namespace illuminantestimators
21.329966
138
0.58674
[ "vector" ]
c5eca9eec44e18e81b42e56a5744c7f59fb8aa31
5,705
hpp
C++
adf/inc/anfilter.hpp
aemeltsev/adf
4ed5134c0a440c6dd545f0f394c25a52514296cd
[ "MIT" ]
1
2021-06-23T14:44:00.000Z
2021-06-23T14:44:00.000Z
adf/inc/anfilter.hpp
aemeltsev/adf
4ed5134c0a440c6dd545f0f394c25a52514296cd
[ "MIT" ]
null
null
null
adf/inc/anfilter.hpp
aemeltsev/adf
4ed5134c0a440c6dd545f0f394c25a52514296cd
[ "MIT" ]
null
null
null
#ifndef ANALOGFILTER_H #define ANALOGFILTER_H #include "genfilter.hpp" namespace adf { /** * @class AnalogFilter */ template<typename T=double> class AnalogFilter { CalcCoeffs<T>* m_calccoeffs; FiltParam<T> m_fparam; FilterType m_ftype; ApproxType m_atype; std::size_t m_order = 0; std::vector<T> n_acoefs, n_bcoefs; /**< to normalise coefs */ std::vector<T> un_acoefs, un_bcoefs; /**< to unnormalise coefs */ /** * @brief setFilterParam Filling data fields of the * @param g_passband - the passband gain ripple * @param g_stopband - the stopband gain ripple * @param f_passband - the passband edge frequency * @param f_stopband - the stopband edge frequency * @param fsamp - sample frequency * @param gain - gain miltiplier */ void setFilterParam(FiltParam<T>& other) { m_fparam.gain_passband = std::move(other.gain_passband); m_fparam.gain_stopband = std::move(other.gain_stopband); m_fparam.freq_passband = std::move(other.freq_passband); m_fparam.freq_stopband = std::move(other.freq_stopband); m_fparam.fsamp = other.fsamp; m_fparam.gain = other.gain; } /** * @brief FillZeroCoeffs - Filling normalized vectors with default values * @param avec input reference to vector of "a" coefficients for filling * @param bvec input reference to vector of "b" coefficients for filling * @param num the order * @return bool variable, success if order value not out of range */ bool FillZeroCoeffs(std::vector<T>& avec, std::vector<T>& bvec, std::size_t num) { bool success = false; if(num > 0 && num < MAX_TERMS) { //FIXME using std::vector.resize() success = true; std::size_t number_coeffs = (3 * (num + 1)) / 2; avec.reserve(number_coeffs); bvec.reserve(number_coeffs); for(std::size_t ind=0; ind<number_coeffs; ++ind) { avec.push_back(0); bvec.push_back(0); } } return success; } public: explicit AnalogFilter<T>(FiltParam<T>& fparam, FilterType& ftype, ApproxType& atype) :m_ftype(ftype) ,m_atype(atype) { setFilterParam(fparam); m_calccoeffs = new CalcCoeffs<T>(fparam, ftype, atype); } ~AnalogFilter<T>() { delete m_calccoeffs; } void setOrder() { m_calccoeffs->FilterOrder(); m_order = m_calccoeffs->getFilterOrder(); } /** * @brief NormalizeCoefficients - Calculation and filling the vectors of coefficients depending on the approximation method */ void NormalizeCoefficients() { if(FillZeroCoeffs(n_acoefs, n_bcoefs, m_order)) { switch (m_atype) { case ApproxType::BUTTER: m_calccoeffs->ButterApprox(n_acoefs, n_bcoefs); break; case ApproxType::CHEBY: m_calccoeffs->ChebyApprox(n_acoefs, n_bcoefs); break; case ApproxType::ELLIPT: m_calccoeffs->ElliptApprox(n_acoefs, n_bcoefs); break; case ApproxType::ICHEBY: m_calccoeffs->IChebyApprox(n_acoefs, n_bcoefs); break; } } else { throw std::range_error(ADF_ERROR("The order value to out of range")); } } /** * @brief */ void DenormalizeCoefficients() { T freq, // Stored value for unnormaliztion frequency BW, /* For transformation to bandstop or bandpass type */ Wo; if(m_atype == ApproxType::BUTTER || m_atype == ApproxType::CHEBY || m_atype == ApproxType::ELLIPT) { freq = m_fparam.freq_passband.first; Wo = std::sqrt(m_fparam.freq_passband.first * m_fparam.freq_passband.second); BW = m_fparam.freq_passband.second - m_fparam.freq_passband.first; } else if(m_atype == ApproxType::ICHEBY) { freq = m_fparam.freq_stopband.first; Wo = std::sqrt(m_fparam.freq_stopband.first * m_fparam.freq_stopband.second); BW = m_fparam.freq_passband.second - m_fparam.freq_passband.first; } switch (m_ftype) { case FilterType::LPF: if(FillZeroCoeffs(un_acoefs, un_bcoefs, m_order)) { m_calccoeffs->LPCoefsUnnorm(n_acoefs, n_bcoefs, un_acoefs, un_bcoefs, freq); } break; case FilterType::HPF: if(FillZeroCoeffs(un_acoefs, un_bcoefs, m_order)) { m_calccoeffs->HPCoefsUnnorm(n_acoefs, n_bcoefs, un_acoefs, un_bcoefs, freq); } break; case FilterType::PBF: m_calccoeffs->BPCoefsUnnorm(n_acoefs, n_bcoefs, un_acoefs, un_bcoefs, BW, Wo); break; case FilterType::SBF: m_calccoeffs->BSCoefsUnnorm(n_acoefs, n_bcoefs, un_acoefs, un_bcoefs, BW, Wo); break; } } std::size_t getFilterOrder() const { return m_order; } ApproxType getApproximationType() { return m_atype; } FilterType getFilterType() { return m_ftype; } std::pair<std::vector<T>, std::vector<T>> getNormalizeCoefficients() { return std::make_pair(n_acoefs, n_bcoefs); } std::pair<std::vector<T>, std::vector<T>> getDenormalizeCoefficients() { return std::make_pair(un_acoefs, un_bcoefs); } }; } //adf #endif //ANALOGFILTER_H
29.25641
127
0.585977
[ "vector" ]
c5f0ab6ed8418aaed481ece7533c30759ab37680
1,650
cpp
C++
uva.onlinejudge.org/MatrixTranspose.cpp
facug91/OJ-Solutions
9aa55be066ce5596e4e64737c28cd3ff84e092fe
[ "Apache-2.0" ]
6
2016-09-10T03:16:34.000Z
2020-04-07T14:45:32.000Z
uva.onlinejudge.org/MatrixTranspose.cpp
facug91/OJ-Solutions
9aa55be066ce5596e4e64737c28cd3ff84e092fe
[ "Apache-2.0" ]
null
null
null
uva.onlinejudge.org/MatrixTranspose.cpp
facug91/OJ-Solutions
9aa55be066ce5596e4e64737c28cd3ff84e092fe
[ "Apache-2.0" ]
2
2018-08-11T20:55:35.000Z
2020-01-15T23:23:11.000Z
/* By: facug91 From: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1836 Name: Matrix Transpose Number: 10895 Date: 18/07/2014 */ #include <iostream> #include <cstdio> #include <cstdlib> #include <string> #include <cstring> #include <cmath> #include <algorithm> #include <vector> #include <queue> #include <deque> #include <set> #include <map> #include <iterator> #include <utility> #include <list> #include <stack> #include <iomanip> #include <bitset> #define MAX_INT 2147483647 #define MAX_LONG 9223372036854775807ll #define MAX_ULONG 18446744073709551615ull #define MAX_DBL 1.7976931348623158e+308 #define EPS 1e-9 //const long double PI = 2*acos(0); #define INF 1000000000 // using namespace std; int m, n, r, a, row[10010]; vector<int> matrix[10010], pos[10010]; int main() { int i, j; while (scanf("%d %d", &m, &n) != EOF) { for (i=1; i<=n; i++) { matrix[i].clear(); pos[i].clear(); } for (i=1; i<=m; i++) { scanf("%d", &r); for (j=0; j<r; j++) scanf("%d", row+j); for (j=0; j<r; j++) { scanf("%d", &a); matrix[row[j]].push_back(a); pos[row[j]].push_back(i); } } printf("%d %d\n", n, m); for (i=1; i<=n; i++) { if (matrix[i].size() == 0) printf("0\n\n"); else { printf("%d", matrix[i].size()); for (j=0; j<matrix[i].size(); j++) printf(" %d", pos[i][j]); printf("\n"); printf("%d", matrix[i][0]); for (j=1; j<matrix[i].size(); j++) printf(" %d", matrix[i][j]); printf("\n"); } } } return 0; }
20.121951
107
0.558788
[ "vector" ]
c5fbcae5c64d552646a24747de146ecedafb51fc
6,392
hpp
C++
Sisyphe/interpreter/plugins/libdebugPlg/interpreter/src/IDebugBreakpointPtrInterpreter.hpp
tedi21/SisypheReview
f7c05bad1ccc036f45870535149d9685e1120c2c
[ "Unlicense" ]
null
null
null
Sisyphe/interpreter/plugins/libdebugPlg/interpreter/src/IDebugBreakpointPtrInterpreter.hpp
tedi21/SisypheReview
f7c05bad1ccc036f45870535149d9685e1120c2c
[ "Unlicense" ]
null
null
null
Sisyphe/interpreter/plugins/libdebugPlg/interpreter/src/IDebugBreakpointPtrInterpreter.hpp
tedi21/SisypheReview
f7c05bad1ccc036f45870535149d9685e1120c2c
[ "Unlicense" ]
null
null
null
/* * IDebugBreakpointPtrInterpreter.hpp * * * @date 12-07-2020 * @author Teddy DIDE * @version 1.00 * Debug Interpreter generated by gensources. */ #ifndef _IDEBUGBREAKPOINTPTR_INTERPRETER_H_ #define _IDEBUGBREAKPOINTPTR_INTERPRETER_H_ #include "config.hpp" #include "Macros.hpp" #include "Base.hpp" #include "Array.hpp" #include "DebugPtr.h" typedef IDebugBreakpoint* IDebugBreakpointPtr; #define A(str) encode<EncodingT,ansi>(str) #define C(str) encode<ansi,EncodingT>(str) using namespace boost; NAMESPACE_BEGIN(interp) // Classe permettant d'accéder aux informations d'un breakpoint. template <class EncodingT> class IDebugBreakpointPtrInterpreter : public Base<EncodingT> { private: IDebugBreakpointPtr m_object; void initValue(const IDebugBreakpointPtr& object); IDebugBreakpointPtr& refValue(); const IDebugBreakpointPtr& refValue() const; void tidyValue(); public: IDebugBreakpointPtrInterpreter(); IDebugBreakpointPtrInterpreter(const IDebugBreakpointPtr& object); const IDebugBreakpointPtr& value() const; void value(IDebugBreakpointPtr const& object); virtual typename EncodingT::string_t toString() const; virtual boost::shared_ptr< Base<EncodingT> > clone() const; virtual typename EncodingT::string_t getClassName() const; virtual boost::shared_ptr< Base<EncodingT> > invoke(const typename EncodingT::string_t& method, std::vector< boost::shared_ptr< Base<EncodingT> > >& params); // Sets the location that triggers a breakpoint. FACTORY_PROTOTYPE1(setOffset, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > setOffset(const boost::shared_ptr< Base<EncodingT> >& offset); // The SetOffsetExpression methods set an expression string that evaluates to the location that triggers a breakpoint. FACTORY_PROTOTYPE1(setOffsetExpression, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > setOffsetExpression(const boost::shared_ptr< Base<EncodingT> >& expression); // Sets the flags for a breakpoint. FACTORY_PROTOTYPE1(setFlags, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > setFlags(const boost::shared_ptr< Base<EncodingT> >& flags); // The SetPassCount method sets the number of times that the target must reach the breakpoint location before the breakpoint is triggered. FACTORY_PROTOTYPE1(setPassCount, In< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > setPassCount(const boost::shared_ptr< Base<EncodingT> >& count); // The GetPassCount method returns the number of times that the target was originally required to reach the breakpoint location before the breakpoint is triggered. FACTORY_PROTOTYPE1(getPassCount, InOut< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > getPassCount(boost::shared_ptr< Base<EncodingT> >& count); // The GetCurrentPassCount method returns the remaining number of times that the target must reach the breakpoint location before the breakpoint is triggered. FACTORY_PROTOTYPE1(getCurrentPassCount, InOut< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > getCurrentPassCount(boost::shared_ptr< Base<EncodingT> >& count); // The GetId method returns a breakpoint ID, which is the engine's unique identifier for a breakpoint. FACTORY_PROTOTYPE1(getId, InOut< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > getId(boost::shared_ptr< Base<EncodingT> >& bpId); // The GetOffset method returns the location that triggers a breakpoint. FACTORY_PROTOTYPE1(getOffset, InOut< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > getOffset(boost::shared_ptr< Base<EncodingT> >& offset); FACTORY_BEGIN_REGISTER CLASS_KEY_REGISTER ( IDebugBreakpointPtrInterpreter, UCS("IDebugBreakpointPtr") ); METHOD_KEY_REGISTER1( IDebugBreakpointPtrInterpreter, boost::shared_ptr< Base<EncodingT> >, setOffset, no_const_t, UCS("IDebugBreakpointPtr::SetOffset") ); METHOD_KEY_REGISTER1( IDebugBreakpointPtrInterpreter, boost::shared_ptr< Base<EncodingT> >, setOffsetExpression, no_const_t, UCS("IDebugBreakpointPtr::SetOffsetExpression") ); METHOD_KEY_REGISTER1( IDebugBreakpointPtrInterpreter, boost::shared_ptr< Base<EncodingT> >, setFlags, no_const_t, UCS("IDebugBreakpointPtr::SetFlags") ); METHOD_KEY_REGISTER1( IDebugBreakpointPtrInterpreter, boost::shared_ptr< Base<EncodingT> >, setPassCount, no_const_t, UCS("IDebugBreakpointPtr::SetPassCount") ); METHOD_KEY_REGISTER1( IDebugBreakpointPtrInterpreter, boost::shared_ptr< Base<EncodingT> >, getPassCount, no_const_t, UCS("IDebugBreakpointPtr::GetPassCount") ); METHOD_KEY_REGISTER1( IDebugBreakpointPtrInterpreter, boost::shared_ptr< Base<EncodingT> >, getCurrentPassCount, no_const_t, UCS("IDebugBreakpointPtr::GetCurrentPassCount") ); METHOD_KEY_REGISTER1( IDebugBreakpointPtrInterpreter, boost::shared_ptr< Base<EncodingT> >, getId, no_const_t, UCS("IDebugBreakpointPtr::GetId") ); METHOD_KEY_REGISTER1( IDebugBreakpointPtrInterpreter, boost::shared_ptr< Base<EncodingT> >, getOffset, no_const_t, UCS("IDebugBreakpointPtr::GetOffset") ); FACTORY_END_REGISTER FACTORY_BEGIN_UNREGISTER CLASS_KEY_UNREGISTER ( UCS("IDebugBreakpointPtr") ); METHOD_KEY_UNREGISTER1( UCS("IDebugBreakpointPtr::SetOffset") ); METHOD_KEY_UNREGISTER1( UCS("IDebugBreakpointPtr::SetOffsetExpression") ); METHOD_KEY_UNREGISTER1( UCS("IDebugBreakpointPtr::SetFlags") ); METHOD_KEY_UNREGISTER1( UCS("IDebugBreakpointPtr::SetPassCount") ); METHOD_KEY_UNREGISTER1( UCS("IDebugBreakpointPtr::GetPassCount") ); METHOD_KEY_UNREGISTER1( UCS("IDebugBreakpointPtr::GetCurrentPassCount") ); METHOD_KEY_UNREGISTER1( UCS("IDebugBreakpointPtr::GetId") ); METHOD_KEY_UNREGISTER1( UCS("IDebugBreakpointPtr::GetOffset") ); FACTORY_END_UNREGISTER }; template <class EncodingT> bool check_IDebugBreakpointPtr(boost::shared_ptr< Base<EncodingT> > const& val, IDebugBreakpointPtr& a); template <class EncodingT> bool reset_IDebugBreakpointPtr(boost::shared_ptr< Base<EncodingT> >& val, IDebugBreakpointPtr const& a); NAMESPACE_END #undef A #undef C #include "IDebugBreakpointPtrInterpreter_impl.hpp" #endif
49.169231
179
0.767209
[ "object", "vector" ]
680e87b3aecc5ddd69d01638d6cdd2247562192a
724
cc
C++
caffe2/utils/cast_test.cc
Hacky-DH/pytorch
80dc4be615854570aa39a7e36495897d8a040ecc
[ "Intel" ]
60,067
2017-01-18T17:21:31.000Z
2022-03-31T21:37:45.000Z
caffe2/utils/cast_test.cc
Hacky-DH/pytorch
80dc4be615854570aa39a7e36495897d8a040ecc
[ "Intel" ]
66,955
2017-01-18T17:21:38.000Z
2022-03-31T23:56:11.000Z
caffe2/utils/cast_test.cc
Hacky-DH/pytorch
80dc4be615854570aa39a7e36495897d8a040ecc
[ "Intel" ]
19,210
2017-01-18T17:45:04.000Z
2022-03-31T23:51:56.000Z
#include <memory> #include <vector> #include <gtest/gtest.h> #include "caffe2/utils/cast.h" namespace caffe2 { TEST(CastTest, GetCastDataType) { auto castOp = [](std::string t) { // Ensure lowercase. std::transform(t.begin(), t.end(), t.begin(), ::tolower); auto op = CreateOperatorDef("Cast", "", {}, {}); AddArgument("to", t, &op); return op; }; #define X(t) \ EXPECT_EQ( \ TensorProto_DataType_##t, \ cast::GetCastDataType(ArgumentHelper(castOp(#t)), "to")); X(FLOAT); X(INT32); X(BYTE); X(STRING); X(BOOL); X(UINT8); X(INT8); X(UINT16); X(INT16); X(INT64); X(FLOAT16); X(DOUBLE); #undef X } } // namespace caffe2
18.1
63
0.560773
[ "vector", "transform" ]
680f1b10d014d3c8c9b186661f57a860be12ba95
1,051
cpp
C++
practice/algorithms/dynamic-programming/lego-blocks/lego-blocks.cpp
zeyuanxy/HackerRank
5194a4af780ece396501c215996685d1be529e73
[ "MIT" ]
4
2017-01-18T17:51:58.000Z
2019-10-20T12:14:37.000Z
practice/algorithms/dynamic-programming/lego-blocks/lego-blocks.cpp
zeyuanxy/HackerRank
5194a4af780ece396501c215996685d1be529e73
[ "MIT" ]
null
null
null
practice/algorithms/dynamic-programming/lego-blocks/lego-blocks.cpp
zeyuanxy/HackerRank
5194a4af780ece396501c215996685d1be529e73
[ "MIT" ]
8
2016-03-14T17:16:59.000Z
2021-06-26T10:11:33.000Z
#include <iostream> #include <vector> using namespace std; const long long mod = 1000000007; long long power(long long base, int degree) { long long ret = 1; while (degree) { if (degree % 2 == 1) { ret = ret * base % mod; } base = base * base % mod; degree /= 2; } return ret; } int main() { int T; cin >> T; vector<long long> f(1001); f[0] = 1; for (int i = 1; i <= 1000; ++i) for (int j = 1; j <= 4; ++j) if (i >= j) f[i] = (f[i] + f[i - j]) % mod; for (int i = 0; i < T; ++i) { int N, M; cin >> N >> M; vector<long long> g(M + 1), h(M + 1); for (int j = 1; j <= M; ++j) g[j] = power(f[j], N); h[1] = 1; for (int j = 2; j <= M; ++j) { long long sum = 0; for (int k = 1; k < j; ++k) sum = (sum + h[k] * g[j - k]) % mod; h[j] = (g[j] + mod - sum) % mod; } cout << h[M] << endl; } return 0; }
23.355556
52
0.381541
[ "vector" ]
680f988c2bf9b525c507cdc6a39d3024493de953
23,744
cpp
C++
src/ydlidar_node.cpp
airuchen/ydlidar_ros2
5b345510ba26130590a44d92b85e94eca29f58f1
[ "Apache-2.0" ]
null
null
null
src/ydlidar_node.cpp
airuchen/ydlidar_ros2
5b345510ba26130590a44d92b85e94eca29f58f1
[ "Apache-2.0" ]
null
null
null
src/ydlidar_node.cpp
airuchen/ydlidar_ros2
5b345510ba26130590a44d92b85e94eca29f58f1
[ "Apache-2.0" ]
null
null
null
/* Copyright 2018 ADLINK Technology, Inc. Developer: * Alan Chen (alan.chen@adlinktech.com * HaoChih, LIN (haochih.lin@adlinktech.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. This is the modified version of ydlidar pkg for ROS 2.0 environment. The original (ROS1) verion and sdk source code are belong to "EAI TEAM" (For further info: EAI official website: http://www.ydlidar.com) */ // Define common dialogue functions #define ROS_INFO RCUTILS_LOG_INFO #define ROS_ERROR RCUTILS_LOG_ERROR #define ROS_FATAL RCUTILS_LOG_FATAL #define ROS_WARN RCUTILS_LOG_WARN #define ROS_DEBUG RCUTILS_LOG_DEBUG #define _USE_MATH_DEFINES #include "rclcpp/rclcpp.hpp" #include "sensor_msgs/msg/laser_scan.hpp" #include "ydlidar_driver.h" #include <vector> #include <iostream> #include <memory> #include <string> #include <chrono> #include <signal.h> #include <math.h> #define DELAY_SECONDS 2 #define DEG2RAD(x) ((x)*M_PI / 180.) using namespace ydlidar; #define ROS2Verision "0.0.1" static bool flag = true; static int nodes_count = 720; static double each_angle = 0.5; int type = 0; int print = 0; void publish_scan(rclcpp::Publisher<sensor_msgs::msg::LaserScan>::SharedPtr pub, node_info* nodes, size_t node_count, rclcpp::Time start, double scan_time, double angle_min, double angle_max, std::string frame_id, std::vector<double> ignore_array, double min_range, double max_range) { sensor_msgs::msg::LaserScan scan_msg; int counts = (int)(node_count * ((angle_max - angle_min) / 360.0)); int angle_start = (int)(180.0 + angle_min); int node_start = (int)(node_count * (angle_start / 360.0)); scan_msg.ranges.resize(counts); scan_msg.intensities.resize(counts); double range = 0.0; double intensity = 0.0; int index = 0; for (size_t i = 0; i < node_count; i++) { range = (double)(nodes[i].distance_q2 / 4.0 / 1000.0); intensity = (double)(nodes[i].sync_quality >> 2); if (i < node_count / 2) { index = node_count / 2 - 1 - i; } else { index = node_count - 1 - (i - node_count / 2); } if ((range > max_range) || (range < min_range)) { range = 0.0; } int pos = index - node_start; if (0 <= pos && pos < counts) { if (ignore_array.size() != 0) { double angle = angle_min + pos * (angle_max - angle_min) / (double)counts; for (uint16_t j = 0; j < ignore_array.size(); j = j + 2) //magic { if ((ignore_array[j] < angle) && (angle <= ignore_array[j + 1])) { range = 0.0; break; } } } scan_msg.ranges[pos] = range; scan_msg.intensities[pos] = intensity; } } scan_msg.header.stamp = start; scan_msg.header.frame_id = frame_id; double radian_min = DEG2RAD(angle_min); double radian_max = DEG2RAD(angle_max); scan_msg.angle_min = radian_min; scan_msg.angle_max = radian_max; scan_msg.angle_increment = (scan_msg.angle_max - scan_msg.angle_min) / (double)(counts - 1); scan_msg.scan_time = scan_time; scan_msg.time_increment = scan_time / (double)counts; scan_msg.range_min = min_range; scan_msg.range_max = max_range; pub->publish(scan_msg); } std::vector<double> split(const std::string& s, char delim) { std::vector<double> elems; std::stringstream ss(s); std::string number; while (std::getline(ss, number, delim)) { elems.push_back(atof(number.c_str())); } return elems; } bool getDeviceInfo(std::string port, int& samp_rate, double _frequency, int baudrate) { if (!YDlidarDriver::singleton()) { return false; } device_info devinfo; if (YDlidarDriver::singleton()->getDeviceInfo(devinfo) != RESULT_OK) { if (print == 3) ROS_ERROR("YDLIDAR get DeviceInfo Error\n"); return false; } sampling_rate _rate; scan_frequency _scan_frequency; int _samp_rate = 4; std::string model; double freq = 7.0; int hz = 0; type = devinfo.model; switch (devinfo.model) { case 1: model = "F4"; _samp_rate = 4; freq = 7.0; break; case 4: model = "S4"; if (baudrate == 153600) { model = "S4Pro"; } _samp_rate = 4; freq = 7.0; break; case 5: model = "G4"; YDlidarDriver::singleton()->getSamplingRate(_rate); switch (samp_rate) { case 4: _samp_rate = 0; break; case 8: _samp_rate = 1; break; case 9: _samp_rate = 2; break; default: _samp_rate = _rate.rate; break; } while (_samp_rate != _rate.rate) { YDlidarDriver::singleton()->setSamplingRate(_rate); } switch (_rate.rate) { case 0: _samp_rate = 4; break; case 1: nodes_count = 1440; each_angle = 0.25; _samp_rate = 8; break; case 2: nodes_count = 1440; each_angle = 0.25; _samp_rate = 9; break; } if (YDlidarDriver::singleton()->getScanFrequency(_scan_frequency) != RESULT_OK) { ROS_ERROR("YDLIDAR get frequency Error\n"); return false; } freq = _scan_frequency.frequency / 100; hz = _frequency - freq; if (hz > 0) { while (hz != 0) { YDlidarDriver::singleton()->setScanFrequencyAdd(_scan_frequency); hz--; } freq = _scan_frequency.frequency / 100.0; } else { while (hz != 0) { YDlidarDriver::singleton()->setScanFrequencyDis(_scan_frequency); hz++; } freq = _scan_frequency.frequency / 100.0; } break; case 6: model = "X4"; _samp_rate = 5; freq = 7.0; break; case 8: model = "F4Pro"; YDlidarDriver::singleton()->getSamplingRate(_rate); switch (samp_rate) { case 4: _samp_rate = 0; break; case 6: _samp_rate = 1; break; default: _samp_rate = _rate.rate; break; } while (_samp_rate != _rate.rate) { YDlidarDriver::singleton()->setSamplingRate(_rate); } switch (_rate.rate) { case 0: _samp_rate = 4; break; case 1: nodes_count = 1440; each_angle = 0.25; _samp_rate = 6; break; } if (YDlidarDriver::singleton()->getScanFrequency(_scan_frequency) != RESULT_OK) { ROS_ERROR("YDLIDAR get frequency Error\n"); return false; } freq = _scan_frequency.frequency / 100; hz = _frequency - freq; if (hz > 0) { while (hz != 0) { YDlidarDriver::singleton()->setScanFrequencyAdd(_scan_frequency); hz--; } freq = _scan_frequency.frequency / 100.0; } else { while (hz != 0) { YDlidarDriver::singleton()->setScanFrequencyDis(_scan_frequency); hz++; } freq = _scan_frequency.frequency / 100.0; } break; case 9: model = "G4C"; _samp_rate = 4; freq = 7.0; break; default: model = "Unknown"; } samp_rate = _samp_rate; uint16_t maxv = (uint16_t)(devinfo.firmware_version >> 8); uint16_t midv = (uint16_t)(devinfo.firmware_version & 0xff) / 10; uint16_t minv = (uint16_t)(devinfo.firmware_version & 0xff) % 10; printf("[YDLIDAR INFO] Connection established in %s:\n" "Firmware version: %u.%u.%u\n" "Hardware version: %u\n" "Model: %s\n" "Serial: ", port.c_str(), maxv, midv, minv, (uint16_t)devinfo.hardware_version, model.c_str()); for (int i = 0; i < 16; i++) { printf("%01X", devinfo.serialnum[i] & 0xff); } printf("\n"); printf("[YDLIDAR INFO] Current Sampling Rate : %dK\n", _samp_rate); printf("[YDLIDAR INFO] Current Scan Frequency : %fHz\n", freq); return true; } bool getDeviceHealth() { if (!YDlidarDriver::singleton()) { return false; } result_t op_result; device_health healthinfo; op_result = YDlidarDriver::singleton()->getHealth(healthinfo); if (op_result == RESULT_OK) { printf("[YDLIDAR INFO] YDLIDAR running correctly! The health status: %s\n", healthinfo.status == 0 ? "well" : "bad"); if (healthinfo.status == 2) { if (print == 3) ROS_ERROR( "Error, YDLIDAR internal error detected. Please reboot the device to retry."); return false; } else { return true; } } else { if (print == 3) ROS_ERROR("Error, cannot retrieve YDLIDAR health code: %x", op_result); return false; } } int main(int argc, char* argv[]) { rclcpp::init(argc, argv); auto node = rclcpp::Node::make_shared("ydlidar_node"); std::string port; int baudrate = 115200; std::string model; std::string frame_id; bool angle_fixed, intensities_, low_exposure, reversion, resolution_fixed, heartbeat; double angle_max, angle_min; result_t op_result; int samp_rate; std::string list; std::vector<double> ignore_array; double max_range, min_range; double _frequency; auto scan_pub = node->create_publisher<sensor_msgs::msg::LaserScan>("scan", rmw_qos_profile_sensor_data); node->get_parameter_or("angle_fixed", angle_fixed, true); node->get_parameter_or("resolution_fixed", resolution_fixed, true); node->get_parameter_or("heartbeat", heartbeat, false); node->get_parameter_or("low_exposure", low_exposure, false); node->get_parameter_or("baudrate", baudrate, 115200); node->get_parameter_or("angle_max", angle_max, 180.0); node->get_parameter_or("angle_min", angle_min, -180.0); // degree node->get_parameter_or("samp_rate", samp_rate, 4); node->get_parameter_or("range_max", max_range, 16.0); // m node->get_parameter_or("range_min", min_range, 0.08); // m node->get_parameter_or("frequency", _frequency, 7.0); // Hz node->get_parameter_or("port", port, std::string("/dev/ydlidar")); node->get_parameter_or("frame_id", frame_id, std::string("laser_frame")); node->get_parameter_or("ignore_array", list, std::string(" ")); ignore_array = split(list, ','); reversion = false; if (ignore_array.size() % 2) { ROS_ERROR("ignore array is odd need be even"); } for (uint16_t i = 0; i < ignore_array.size(); i++) { if (ignore_array[i] < -180 && ignore_array[i] > 180) { ROS_ERROR("ignore array should be between -180 and 180"); } } YDlidarDriver::initDriver(); if (!YDlidarDriver::singleton()) { ROS_ERROR("YDLIDAR Create Driver fail, exit\n"); return -2; } if (_frequency < 5) { _frequency = 7.0; } if (_frequency > 12) { _frequency = 12; } if (angle_max < angle_min) { double temp = angle_max; angle_max = angle_min; angle_min = temp; } // check lidar type std::map<int, bool> checkmodel; checkmodel.insert(std::map<int, bool>::value_type(115200, false)); checkmodel.insert(std::map<int, bool>::value_type(128000, false)); checkmodel.insert(std::map<int, bool>::value_type(153600, false)); checkmodel.insert(std::map<int, bool>::value_type(230400, false)); printf("[YDLIDAR INFO] Current ROS 2.0 Driver Version: %s\n", ((std::string)ROS2Verision).c_str()); printf("[YDLIDAR INFO] Current SDK Version: %s\n", YDlidarDriver::singleton()->getSDKVersion().c_str()); again: op_result = YDlidarDriver::singleton()->connect(port.c_str(), (uint32_t)baudrate); if (op_result != RESULT_OK) { int seconds = 0; while (seconds <= DELAY_SECONDS && flag) { //sleep(2); rclcpp::sleep_for(std::chrono::milliseconds(2000) ); seconds = seconds + 2; YDlidarDriver::singleton()->disconnect(); op_result = YDlidarDriver::singleton()->connect(port.c_str(), (uint32_t)baudrate); printf("[YDLIDAR INFO] Try to connect the port %s again after %d s .\n", port.c_str(), seconds); if (op_result == RESULT_OK) { break; } } if (seconds > DELAY_SECONDS) { ROS_ERROR("YDLIDAR Cannot bind to the specified serial port %s", port.c_str()); YDlidarDriver::singleton()->disconnect(); YDlidarDriver::done(); return -1; } } bool ret = getDeviceHealth(); if (!getDeviceInfo(port, samp_rate, _frequency, baudrate) && !ret) { checkmodel[baudrate] = true; map<int, bool>::iterator it; for (it = checkmodel.begin(); it != checkmodel.end(); ++it) { if (it->second) continue; print++; YDlidarDriver::singleton()->disconnect(); YDlidarDriver::done(); YDlidarDriver::initDriver(); if (!YDlidarDriver::singleton()) { ROS_ERROR("YDLIDAR Create Driver fail, exit\n"); return -1; } baudrate = it->first; goto again; } ROS_ERROR("[YDLIDAR ERROR] Unsupported lidar\n"); YDlidarDriver::singleton()->disconnect(); YDlidarDriver::done(); return -1; } printf("[YDLIDAR INFO] Connected to YDLIDAR on port %s at %d \n", port.c_str(), baudrate); print = 0; if (type != 4) { intensities_ = false; } else { intensities_ = true; if (baudrate != 153600) { intensities_ = false; } } YDlidarDriver::singleton()->setIntensities(intensities_); if (intensities_) { scan_exposure exposure; int cnt = 0; while ((YDlidarDriver::singleton()->setLowExposure(exposure) == RESULT_OK) && (cnt < 3)) { if (exposure.exposure != low_exposure) { ROS_INFO("set EXPOSURE MODEL SUCCESS!!!"); break; } cnt++; } if (cnt >= 3) { ROS_ERROR("set LOW EXPOSURE MODEL FALIED!!!"); } } if (type == 5 || type == 8 || type == 9) { scan_heart_beat beat; if (type != 8) reversion = true; result_t ans = YDlidarDriver::singleton()->setScanHeartbeat(beat); if (heartbeat) { if (beat.enable && ans == RESULT_OK) { ans = YDlidarDriver::singleton()->setScanHeartbeat(beat); } if (!beat.enable && ans == RESULT_OK) { YDlidarDriver::singleton()->setHeartBeat(true); } } else { if (!beat.enable && ans == RESULT_OK) { ans = YDlidarDriver::singleton()->setScanHeartbeat(beat); } if (beat.enable && ans == RESULT_OK) { YDlidarDriver::singleton()->setHeartBeat(false); } } if (_frequency < 7 && samp_rate > 6) { nodes_count = 1600; } else if (_frequency < 6 && samp_rate == 9) { nodes_count = 1800; } } result_t ans = YDlidarDriver::singleton()->startScan(); if (ans != RESULT_OK) { ans = YDlidarDriver::singleton()->startScan(); if (ans != RESULT_OK) { ROS_ERROR("start YDLIDAR is failed! Exit!! ......"); YDlidarDriver::singleton()->disconnect(); YDlidarDriver::done(); return 0; } } printf("[YDLIDAR INFO] Now YDLIDAR is scanning ......\n"); flag = false; rclcpp::Time start_scan_time; rclcpp::Time end_scan_time; double scan_duration; rclcpp::Rate rate(30); int max_nodes_count = nodes_count; each_angle = 360.0 / (double)(nodes_count); while (rclcpp::ok()) { try { node_info nodes[nodes_count]; size_t count = _countof(nodes); start_scan_time = rclcpp::Clock(RCL_ROS_TIME).now(); op_result = YDlidarDriver::singleton()->grabScanData(nodes, count); end_scan_time = rclcpp::Clock(RCL_ROS_TIME).now(); if (op_result == RESULT_OK) { op_result = YDlidarDriver::singleton()->ascendScanData(nodes, count); if (op_result == RESULT_OK) { if (angle_fixed) { if (!resolution_fixed) { max_nodes_count = count; } else { max_nodes_count = nodes_count; } each_angle = 360.0 / (double)(max_nodes_count); node_info all_nodes[max_nodes_count]; memset(all_nodes, 0, max_nodes_count * sizeof(node_info)); uint64_t end_time = nodes[0].stamp; uint64_t start_time = nodes[0].stamp; for (size_t i = 0; i < count; i++) { if (nodes[i].distance_q2 != 0) { double angle = (double)((nodes[i].angle_q6_checkbit >> LIDAR_RESP_MEASUREMENT_ANGLE_SHIFT) / 64.0); if (reversion) { angle = angle + 180; if (angle >= 360) { angle = angle - 360; } nodes[i].angle_q6_checkbit = ((uint16_t)(angle * 64.0)) << LIDAR_RESP_MEASUREMENT_ANGLE_SHIFT; } int inter = (int)(angle / each_angle); double angle_pre = angle - inter * each_angle; double angle_next = (inter + 1) * each_angle - angle; if (angle_pre < angle_next) { if (inter < max_nodes_count) { all_nodes[inter] = nodes[i]; } } else { if (inter < max_nodes_count - 1) { all_nodes[inter + 1] = nodes[i]; } } } if (nodes[i].stamp < start_time) { start_time = nodes[i].stamp; } if (nodes[i].stamp > end_time) { end_time = nodes[i].stamp; } } scan_duration = (end_scan_time - start_scan_time).nanoseconds()/10e9; publish_scan(scan_pub, all_nodes, max_nodes_count, start_scan_time, scan_duration, angle_min, angle_max, frame_id, ignore_array, min_range, max_range); } else { int start_node = 0, end_node = 0; int i = 0; while (nodes[i++].distance_q2 == 0 && i < count) ; start_node = i - 1; i = count - 1; while (nodes[i--].distance_q2 == 0 && i >= 0) ; end_node = i + 1; angle_min = (double)(nodes[start_node].angle_q6_checkbit >> LIDAR_RESP_MEASUREMENT_ANGLE_SHIFT) / 64.0; angle_max = (double)(nodes[end_node].angle_q6_checkbit >> LIDAR_RESP_MEASUREMENT_ANGLE_SHIFT) / 64.0; publish_scan(scan_pub, &nodes[start_node], end_node - start_node + 1, start_scan_time, scan_duration, angle_min, angle_max, frame_id, ignore_array, min_range, max_range); } } } rclcpp::spin_some(node); rate.sleep(); } catch (std::exception& e) { // std::cout << "Unhandled Exception: " << e.what() << std::endl; break; } catch (...){//anthor exception ROS_ERROR("Unhandled Exception:Unknown "); break; } } YDlidarDriver::singleton()->disconnect(); printf("[YDLIDAR INFO] Now YDLIDAR is stopping .......\n"); YDlidarDriver::done(); return 0; }
31.658667
137
0.484712
[ "vector", "model" ]
6813616d460d8c0b4b9072ff6697661fe579a684
2,113
hpp
C++
api/core/nodejs/NJSRandomNumberGenerator.hpp
kodxana/lib-ledger-core
96f04d378b7747e1b80b49da7ae637eb33b23678
[ "MIT" ]
null
null
null
api/core/nodejs/NJSRandomNumberGenerator.hpp
kodxana/lib-ledger-core
96f04d378b7747e1b80b49da7ae637eb33b23678
[ "MIT" ]
null
null
null
api/core/nodejs/NJSRandomNumberGenerator.hpp
kodxana/lib-ledger-core
96f04d378b7747e1b80b49da7ae637eb33b23678
[ "MIT" ]
null
null
null
// AUTOGENERATED FILE - DO NOT MODIFY! // This file generated by Djinni from random.djinni #ifndef DJINNI_GENERATED_NJSRANDOMNUMBERGENERATOR_HPP #define DJINNI_GENERATED_NJSRANDOMNUMBERGENERATOR_HPP #include <cstdint> #include <vector> #include <nan.h> #include <node.h> #include "../../../core/src/api/RandomNumberGenerator.hpp" using namespace v8; using namespace node; using namespace std; using namespace ledger::core::api; class NJSRandomNumberGenerator: public Nan::ObjectWrap, public ledger::core::api::RandomNumberGenerator { public: static void Initialize(Local<Object> target); ~NJSRandomNumberGenerator() { persistent().Reset(); njs_impl.Reset(); njs_impl.Reset(); }; NJSRandomNumberGenerator(Local<Object> njs_implementation){njs_impl.Reset(njs_implementation);}; /** * Generates random bytes. * @params size number of bytes to generate * @return 'size' random bytes */ std::vector<uint8_t> getRandomBytes(int32_t size); /** * Generates random 32 bits integer. * @return random 32 bits integer */ int32_t getRandomInt(); /** * Generates random 64 bits integer. * @return random 64 bits integer */ int64_t getRandomLong(); /** * Generates random byte. * @return random byte */ int8_t getRandomByte(); private: /** * Generates random bytes. * @params size number of bytes to generate * @return 'size' random bytes */ static NAN_METHOD(getRandomBytes); /** * Generates random 32 bits integer. * @return random 32 bits integer */ static NAN_METHOD(getRandomInt); /** * Generates random 64 bits integer. * @return random 64 bits integer */ static NAN_METHOD(getRandomLong); /** * Generates random byte. * @return random byte */ static NAN_METHOD(getRandomByte); static NAN_METHOD(New); static NAN_METHOD(addRef); static NAN_METHOD(removeRef); Nan::Persistent<Object> njs_impl; }; #endif //DJINNI_GENERATED_NJSRANDOMNUMBERGENERATOR_HPP
23.477778
105
0.669664
[ "object", "vector" ]
681a2de3f897c0454a4b7d382ec65984f7b116fd
4,561
cc
C++
ros/src/computing/perception/localization/packages/orb_localizer/src/analysis/orbslam2_python.cc
izeki/Autoware
21dcd18c4166331c290bd573733e0b881ca29ad7
[ "BSD-3-Clause" ]
64
2018-11-19T02:34:05.000Z
2021-12-27T06:19:48.000Z
ros/src/computing/perception/localization/packages/orb_localizer/src/analysis/orbslam2_python.cc
izeki/Autoware
21dcd18c4166331c290bd573733e0b881ca29ad7
[ "BSD-3-Clause" ]
1
2019-01-24T14:30:58.000Z
2019-01-24T14:30:58.000Z
ros/src/computing/perception/localization/packages/orb_localizer/src/analysis/orbslam2_python.cc
izeki/Autoware
21dcd18c4166331c290bd573733e0b881ca29ad7
[ "BSD-3-Clause" ]
34
2018-11-27T08:57:32.000Z
2022-02-18T08:06:04.000Z
#include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include "Map.h" #include "MapPoint.h" #include "KeyFrame.h" #include "KeyFrameDatabase.h" #include "Converter.h" #include <string> #include <vector> using namespace std; using boost::python::vector_indexing_suite; vector<int> doAdd (int p, int q) { vector<int> pqr; pqr.push_back (p); pqr.push_back (q); return pqr; } class MapPointWrapper { public: MapPointWrapper (ORB_SLAM2::MapPoint *p) : _mp(p) { cv::Mat wpos = p->GetWorldPos(); x = wpos.at<double>(0); y = wpos.at<double>(1); z = wpos.at<double>(2); } bool operator == (const MapPointWrapper &x) const { return this->_mp == x._mp; } bool operator != (const MapPointWrapper &x) const { return this->_mp != x._mp; } double x, y, z; private: ORB_SLAM2::MapPoint *_mp; }; class KeyFrameWrapper { public: KeyFrameWrapper (ORB_SLAM2::KeyFrame *kf) : _kf (kf) { // Pose in ORB-SLAM2 coordinate cv::Mat t = kf->GetCameraCenter(); cv::Mat orient = kf->GetRotation().t(); vector<float> q = ORB_SLAM2::Converter::toQuaternion(orient); x = t.at<float>(0); y = t.at<float>(0); z = t.at<float>(0); qx = q[0]; qy = q[1]; qz = q[2]; qw = q[3]; // Pose in Metric coordinate if (kf->extPosition.empty() or kf->extOrientation.empty()) { xr = yr = zr = qxr = qyr = qzr = qwr = NAN; } else { xr = kf->extPosition.at<double>(0); yr = kf->extPosition.at<double>(1); zr = kf->extPosition.at<double>(2); qxr = kf->extOrientation.at<double>(0); qyr = kf->extOrientation.at<double>(1); qzr = kf->extOrientation.at<double>(2); qwr = kf->extOrientation.at<double>(3); } } bool operator == (const KeyFrameWrapper &x) const { return this->_kf == x._kf; } bool operator != (const KeyFrameWrapper &x) const { return this->_kf != x._kf; } double timestamp() const { return _kf->mTimeStamp; } // Coordinate in ORB-SLAM system double x, y, z, qx, qy, qz, qw; // coordinate in metric system double xr, yr, zr, qxr, qyr, qzr, qwr; private: ORB_SLAM2::KeyFrame *_kf; }; class MapWrapper { public: MapWrapper (const string &loadPath) { fakeVocab = new ORB_SLAM2::ORBVocabulary (); kfdb = new ORB_SLAM2::KeyFrameDatabase (*fakeVocab); maprf = new ORB_SLAM2::Map (); maprf->loadFromDisk(loadPath, kfdb); } vector<KeyFrameWrapper> getKeyFrames () { vector<KeyFrameWrapper> kfList; vector<ORB_SLAM2::KeyFrame*> kfsList = maprf->kfListSorted; kfList.reserve(kfsList.size()); for (auto kfs: kfsList) { if (!kfs->isBad()) { KeyFrameWrapper kfw (kfs); kfList.push_back (kfw); } } return kfList; } vector<MapPointWrapper> getMapPoints () { vector<MapPointWrapper> mpList; vector<ORB_SLAM2::MapPoint*> srcMpList = maprf->GetAllMapPoints(); mpList.reserve(srcMpList.size()); for (auto mp: srcMpList) { if (!mp->isBad()) { MapPointWrapper mpp (mp); mpList.push_back(mpp); } } return mpList; } private: ORB_SLAM2::Map *maprf; ORB_SLAM2::KeyFrameDatabase *kfdb; ORB_SLAM2::ORBVocabulary *fakeVocab; }; BOOST_PYTHON_MODULE (_orb_slam2) { using namespace boost::python; class_ <vector<int> > ("IntArray") .def (vector_indexing_suite<vector<int> > ()); def ("doAdd", &doAdd); class_ <MapPointWrapper> ("MapPoint", no_init) .def_readonly("x", &MapPointWrapper::x) .def_readonly("y", &MapPointWrapper::y) .def_readonly("z", &MapPointWrapper::z); class_ <KeyFrameWrapper> ("KeyFrame", no_init) .def_readonly("x", &KeyFrameWrapper::x) .def_readonly("y", &KeyFrameWrapper::y) .def_readonly("z", &KeyFrameWrapper::z) .def_readonly("qx", &KeyFrameWrapper::qx) .def_readonly("qy", &KeyFrameWrapper::qy) .def_readonly("qz", &KeyFrameWrapper::qz) .def_readonly("qw", &KeyFrameWrapper::qw) .def_readonly("xr", &KeyFrameWrapper::xr) .def_readonly("yr", &KeyFrameWrapper::yr) .def_readonly("zr", &KeyFrameWrapper::zr) .def_readonly("qxr", &KeyFrameWrapper::qxr) .def_readonly("qyr", &KeyFrameWrapper::qyr) .def_readonly("qzr", &KeyFrameWrapper::qzr) .def_readonly("qwr", &KeyFrameWrapper::qwr) .def ("timestamp", &KeyFrameWrapper::timestamp); class_ <vector<KeyFrameWrapper> > ("KeyFrameList") .def (vector_indexing_suite<vector<KeyFrameWrapper> > ()); class_ <vector<MapPointWrapper> > ("MapPointList") .def (vector_indexing_suite<vector<MapPointWrapper> > ()); class_ <MapWrapper> ("Map", init<const string &>()) .def ("getKeyFrames", &MapWrapper::getKeyFrames) .def ("getMapPoints", &MapWrapper::getMapPoints); }
22.691542
68
0.671783
[ "vector" ]