hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
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
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
77k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
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
7
1.05M
avg_line_length
float64
1.21
653k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
1
5c093c8085970f18b15ba463ae86b785f68bb36b
12,570
cc
C++
serving/processor/serving/model_config.cc
aalbersk/DeepRec
f673a950780959b44dcda99398880a1d883ab338
[ "Apache-2.0" ]
292
2021-12-24T03:24:33.000Z
2022-03-31T15:41:05.000Z
serving/processor/serving/model_config.cc
aalbersk/DeepRec
f673a950780959b44dcda99398880a1d883ab338
[ "Apache-2.0" ]
54
2021-12-24T06:40:09.000Z
2022-03-30T07:57:24.000Z
serving/processor/serving/model_config.cc
aalbersk/DeepRec
f673a950780959b44dcda99398880a1d883ab338
[ "Apache-2.0" ]
75
2021-12-24T04:48:21.000Z
2022-03-29T10:13:39.000Z
#include <stdlib.h> #include "serving/processor/serving/model_config.h" #include "serving/processor/serving/tracer.h" #include "include/json/json.h" #include "tensorflow/core/util/env_var.h" #include "tensorflow/core/lib/core/errors.h" namespace tensorflow { namespace processor { namespace { constexpr int DEFAULT_CPUS = 8; Status AddOSSAccessPrefix(std::string& dir, const ModelConfig* config) { auto offset = dir.find("oss://"); // error oss format if (offset == std::string::npos) { return tensorflow::errors::Internal( "Invalid user input oss dir, ", dir); } std::string tmp(dir.substr(6)); offset = tmp.find("/"); if (offset == std::string::npos) { return tensorflow::errors::Internal( "Invalid user input oss dir, ", dir); } dir = strings::StrCat(dir.substr(0, offset+6), "\x01id=", config->oss_access_id, "\x02key=", config->oss_access_key, "\x02host=", config->oss_endpoint, tmp.substr(offset)); return Status::OK(); } } Status ModelConfigFactory::Create(const char* model_config, ModelConfig** config) { if (strlen(model_config) <= 0) { return Status(error::Code::INVALID_ARGUMENT, "[TensorFlow] Invalid ModelConfig json."); } Json::Reader reader; Json::Value json_config; if (!reader.parse(model_config, json_config)) { return Status(error::Code::INVALID_ARGUMENT, "[TensorFlow] Parse ModelConfig json failed."); } int64 schedule_threads; ReadInt64FromEnvVar("SCHEDULABLE_CPUS", DEFAULT_CPUS, &schedule_threads); *config = new ModelConfig; if (!json_config["session_num"].isNull()) { (*config)->session_num = json_config["session_num"].asInt(); } else { (*config)->session_num = 1; } (*config)->select_session_policy = "MOD"; if (!json_config["select_session_policy"].isNull()) { (*config)->select_session_policy = json_config["select_session_policy"].asString(); } if ((*config)->select_session_policy != "MOD" && (*config)->select_session_policy != "RR") { return Status(error::Code::INVALID_ARGUMENT, "[TensorFlow] select_session_policy must be 'RR' or 'MOD'"); } bool enable_inline_execute = false; if (!json_config["enable_inline_execute"].isNull()) { enable_inline_execute = json_config["enable_inline_execute"].asBool(); } if (enable_inline_execute) { if (setenv("RUN_ALL_KERNELS_INLINE", "1", 1) != 0) { LOG(WARNING) << "Set RUN_ALL_KERNELS_INLINE env error: " << json_config["enable_inline_execute"].asBool(); } } if (!json_config["omp_num_threads"].isNull()) { if (setenv("OMP_NUM_THREADS", json_config["omp_num_threads"].asString().c_str(), 1) != 0) { LOG(WARNING) << "Set OMP_NUM_THREADS env error: " << json_config["omp_num_threads"]; } } if (!json_config["kmp_blocktime"].isNull()) { if (setenv("KMP_BLOCKTIME", json_config["kmp_blocktime"].asString().c_str(), 1) != 0) { LOG(WARNING) << "Set KMP_BLOCKTIME env error: " << json_config["kmp_blocktime"]; } } if (!json_config["inter_op_parallelism_threads"].isNull()) { (*config)->inter_threads = json_config["inter_op_parallelism_threads"].asInt(); } else { (*config)->inter_threads = schedule_threads / 2; } if (!json_config["intra_op_parallelism_threads"].isNull()) { (*config)->intra_threads = json_config["intra_op_parallelism_threads"].asInt(); } else { (*config)->intra_threads = schedule_threads / 2; } if (!json_config["init_timeout_minutes"].isNull()) { (*config)->init_timeout_minutes = json_config["init_timeout_minutes"].asInt(); } else { (*config)->init_timeout_minutes = -1; } if (!json_config["signature_name"].isNull()) { (*config)->signature_name = json_config["signature_name"].asString(); } else { return Status(error::Code::NOT_FOUND, "[TensorFlow] No signature_name in ModelConfig."); } if ((*config)->signature_name.empty()) { return Status(error::Code::INVALID_ARGUMENT, "[TensorFlow] Signature_name shouldn't be empty string."); } if (!json_config["warmup_file_name"].isNull()) { (*config)->warmup_file_name = json_config["warmup_file_name"].asString(); } else { (*config)->warmup_file_name = ""; } if (!json_config["serialize_protocol"].isNull()) { (*config)->serialize_protocol = json_config["serialize_protocol"].asString(); } else { return Status(error::Code::NOT_FOUND, "[TensorFlow] No serialize_protocol in ModelConfig."); } if ((*config)->serialize_protocol.empty()) { return Status(error::Code::INVALID_ARGUMENT, "[TensorFlow] serialize_protocol shouldn't be empty string."); } if (!json_config["checkpoint_dir"].isNull()) { (*config)->checkpoint_dir = json_config["checkpoint_dir"].asString(); } else { return Status(error::Code::NOT_FOUND, "[TensorFlow] No checkpoint_dir in ModelConfig."); } if (!json_config["savedmodel_dir"].isNull()) { (*config)->savedmodel_dir = json_config["savedmodel_dir"].asString(); } else { return Status(error::Code::NOT_FOUND, "[TensorFlow] No savedmodel_dir in ModelConfig."); } if (!json_config["feature_store_type"].isNull()) { (*config)->feature_store_type = json_config["feature_store_type"].asString(); } else { return Status(error::Code::NOT_FOUND, "[TensorFlow] No feature_store_type in ModelConfig."); } if ((*config)->feature_store_type.empty()) { return Status(error::Code::INVALID_ARGUMENT, "[TensorFlow] feature_store_type shouldn't be empty string."); } // @feature_store_type: // 'redis/cluster_redis' or 'local' if ((*config)->feature_store_type == "cluster_redis" || (*config)->feature_store_type == "redis") { if (!json_config["redis_url"].isNull()) { (*config)->redis_url = json_config["redis_url"].asString(); } else { return Status(error::Code::NOT_FOUND, "[TensorFlow] Should set redis_url in ModelConfig \ when feature_store_type=cluster_redis."); } if (!json_config["redis_password"].isNull()) { (*config)->redis_password = json_config["redis_password"].asString(); } else { return Status(error::Code::NOT_FOUND, "[TensorFlow] Should set redis_password in ModelConfig \ when feature_store_type=cluster_redis."); } if (!json_config["read_thread_num"].isNull()) { (*config)->read_thread_num = json_config["read_thread_num"].asInt(); } else { (*config)->read_thread_num = 4; } if (!json_config["update_thread_num"].isNull()) { (*config)->update_thread_num = json_config["update_thread_num"].asInt(); } else { (*config)->update_thread_num = 2; } } if (!json_config["model_store_type"].isNull()) { (*config)->model_store_type = json_config["model_store_type"].asString(); } else { return Status(error::Code::NOT_FOUND, "[TensorFlow] No model_store_type in ModelConfig."); } if ((*config)->model_store_type != "local") { if ((*config)->checkpoint_dir.find((*config)->model_store_type) == std::string::npos) { return Status(error::Code::INVALID_ARGUMENT, "[TensorFlow] Mismatch model_store_type and checkpoint_dir."); } if ((*config)->savedmodel_dir.find((*config)->model_store_type) == std::string::npos) { return Status(error::Code::INVALID_ARGUMENT, "[TensorFlow] Mismatch model_store_type and savedmodel_dir."); } } if ((*config)->model_store_type == "oss") { if (!json_config["oss_endpoint"].isNull()) { (*config)->oss_endpoint = json_config["oss_endpoint"].asString(); } else { return Status(error::Code::NOT_FOUND, "[TensorFlow] No oss_endpoint in ModelConfig."); } if ((*config)->oss_endpoint.empty()) { return Status(error::Code::INVALID_ARGUMENT, "[TensorFlow] oss_endpoint shouldn't be empty string."); } if (!json_config["oss_access_id"].isNull()) { (*config)->oss_access_id = json_config["oss_access_id"].asString(); } else { return Status(error::Code::NOT_FOUND, "[TensorFlow] No oss_access_id in ModelConfig."); } if ((*config)->oss_access_id.empty()) { return Status(error::Code::INVALID_ARGUMENT, "[TensorFlow] oss_access_id shouldn't be empty string."); } if (!json_config["oss_access_key"].isNull()) { (*config)->oss_access_key = json_config["oss_access_key"].asString(); } else { return Status(error::Code::NOT_FOUND, "[TensorFlow] No oss_access_key in ModelConfig."); } if ((*config)->oss_access_key.empty()) { return Status(error::Code::INVALID_ARGUMENT, "[TensorFlow] oss_access_key shouldn't be empty string."); } TF_RETURN_IF_ERROR(AddOSSAccessPrefix( (*config)->savedmodel_dir, *config)); TF_RETURN_IF_ERROR(AddOSSAccessPrefix( (*config)->checkpoint_dir, *config)); } // timeout of distribute lock if (!json_config["lock_timeout"].isNull()) { (*config)->lock_timeout = json_config["lock_timeout"].asInt(); } else { (*config)->lock_timeout = 15 * 60; // 900 seconds } (*config)->use_per_session_threads = false; if (!json_config["use_per_session_threads"].isNull()) { (*config)->use_per_session_threads = json_config["use_per_session_threads"].asBool(); } (*config)->shard_embedding = false; bool shard_embedding = false; if (!json_config["shard_embedding"].isNull()) { shard_embedding = json_config["shard_embedding"].asBool(); } if (shard_embedding) { if ((*config)->feature_store_type != "local") { return Status(error::Code::INVALID_ARGUMENT, "[TensorFlow] Sharded embedding must be load in local," "this require feature_store_type must be 'local' mode."); } (*config)->shard_embedding = true; if (json_config["embedding_names"].isNull() || json_config["shard_instance_count"].isNull() || json_config["id_type"].isNull()) { return Status(error::Code::INVALID_ARGUMENT, "[TensorFlow] Shard embedding require args: embedding_names, " "shard_instance_count and id_type."); } std::string embedding_names = json_config["embedding_names"].asString(); (*config)->shard_instance_count = json_config["shard_instance_count"].asInt(); // "string" or "int64" (*config)->id_type = json_config["id_type"].asString(); // "name1;name2;name3" auto idx = embedding_names.find(";"); while (idx != std::string::npos) { (*config)->shard_embedding_names.push_back(embedding_names.substr(0, idx)); embedding_names = embedding_names.substr(idx+1); idx = embedding_names.find(";"); } (*config)->shard_embedding_names.push_back(embedding_names); } // enable trace timeline if (!json_config["timeline_start_step"].isNull() && !json_config["timeline_interval_step"].isNull() && !json_config["timeline_trace_count"].isNull() && !json_config["timeline_path"].isNull()) { auto path = json_config["timeline_path"].asString(); auto start_step = json_config["timeline_start_step"].asInt(); auto interval_step = json_config["timeline_interval_step"].asInt(); auto trace_count = json_config["timeline_trace_count"].asInt(); // save timeline to local if (path[0] == '/') { Tracer::GetTracer()->SetParams(start_step, interval_step, trace_count, path); } else if (path.find("oss://") != std::string::npos) { // save timeline to oss if ((*config)->oss_endpoint == "" || (*config)->oss_access_id == "" || (*config)->oss_access_key == "") { return Status(error::Code::INVALID_ARGUMENT, "Timeline require oss_endpoint, oss_access_id, and oss_access_key."); } Tracer::GetTracer()->SetParams(start_step, interval_step, trace_count, (*config)->oss_endpoint, (*config)->oss_access_id, (*config)->oss_access_key, path); } else { return Status(error::Code::INVALID_ARGUMENT, "[TensorFlow] Only support save timeline to local or oss now."); } } return Status::OK(); } } // processor } // tensorflow
33.430851
83
0.638186
5c0bcc63b1882c769eadd024b77e906337024e57
437
hpp
C++
nd-coursework/books/cpp/C++Templates/basics/byref.hpp
crdrisko/nd-grad
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
[ "MIT" ]
1
2020-09-26T12:38:55.000Z
2020-09-26T12:38:55.000Z
nd-coursework/books/cpp/C++Templates/basics/byref.hpp
crdrisko/nd-research
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
[ "MIT" ]
null
null
null
nd-coursework/books/cpp/C++Templates/basics/byref.hpp
crdrisko/nd-research
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
[ "MIT" ]
null
null
null
// Copyright (c) 2017 by Addison-Wesley, David Vandevoorde, Nicolai M. Josuttis, and Douglas Gregor. All rights reserved. // See the LICENSE file in the project root for more information. // // Name: byref.hpp // Author: crdrisko // Date: 08/13/2020-12:12:50 // Description: Missing file from book #ifndef BYREF_HPP #define BYREF_HPP template<typename T> T const& checked(T const& a, T const& b) { return test() ? a : b; } #endif
23
121
0.709382
5c0d9b4f004dcd5e404e8024d67e964b9bfb5d83
8,061
cc
C++
build/x86/python/m5/internal/enum_TimingExprOp.py.cc
billionshang/gem5
18cc4294f32315595f865d07d1f33434e92b06b2
[ "BSD-3-Clause" ]
null
null
null
build/x86/python/m5/internal/enum_TimingExprOp.py.cc
billionshang/gem5
18cc4294f32315595f865d07d1f33434e92b06b2
[ "BSD-3-Clause" ]
null
null
null
build/x86/python/m5/internal/enum_TimingExprOp.py.cc
billionshang/gem5
18cc4294f32315595f865d07d1f33434e92b06b2
[ "BSD-3-Clause" ]
null
null
null
#include "sim/init.hh" namespace { const uint8_t data_m5_internal_enum_TimingExprOp[] = { 120,156,197,88,239,114,211,214,18,223,35,201,78,236,56,196, 36,144,240,39,128,129,2,190,92,18,67,248,219,194,48,165, 109,218,161,211,134,123,37,58,80,181,115,85,199,58,177,21, 108,201,149,142,67,220,73,190,52,157,182,47,208,71,232,135, 62,64,223,227,190,209,237,238,202,114,36,59,164,124,184,19, 50,241,201,209,239,236,217,179,187,231,183,171,117,26,48,248, 201,225,231,195,10,64,244,167,6,224,226,175,128,54,64,71, 128,45,64,72,1,110,25,94,229,32,188,3,110,14,126,2, 176,53,144,26,236,225,68,135,111,52,240,75,188,39,15,109, 157,17,1,253,34,72,3,236,28,188,240,143,131,33,243,240, 170,8,225,119,32,132,240,5,188,116,39,192,157,132,159,80, 59,78,10,172,112,18,8,44,50,88,0,119,138,193,34,184, 37,158,76,65,191,12,178,4,246,52,137,217,199,80,237,117, 84,59,195,106,255,75,106,93,92,57,14,238,49,18,71,187, 190,38,73,131,36,249,188,25,214,130,42,116,216,60,78,227, 30,185,133,15,179,96,207,50,58,151,70,79,128,125,130,209, 147,105,116,30,236,121,70,23,210,232,41,176,79,49,122,58, 141,158,1,251,12,163,103,211,232,34,216,139,140,158,75,163, 231,193,62,207,232,133,52,90,1,187,194,232,197,52,122,9, 236,75,140,94,78,163,239,129,253,30,163,87,210,232,85,176, 175,50,122,45,141,86,193,174,50,250,143,52,122,29,236,235, 140,254,51,141,222,0,251,6,163,75,105,116,25,236,101,70, 107,105,244,38,216,55,25,189,149,70,87,192,94,97,244,118, 26,189,3,246,29,70,239,166,209,123,96,223,99,244,126,26, 125,0,246,3,70,223,79,163,31,128,253,1,163,15,193,126, 72,204,179,170,179,72,97,239,127,248,83,21,56,83,37,28, 182,100,24,121,129,239,120,254,70,224,105,180,158,167,129,8, 223,160,97,98,192,252,143,137,249,127,0,211,222,213,6,204, 223,5,16,244,12,208,214,96,151,39,187,26,244,171,176,35, 96,211,0,87,135,29,60,38,71,38,53,5,236,105,240,173, 78,2,187,56,26,200,207,243,96,168,152,246,155,204,207,88, 211,4,236,230,96,39,7,214,203,29,141,128,87,5,8,127, 135,31,22,89,233,36,43,213,96,7,71,3,246,12,216,205, 195,11,20,66,104,179,64,172,22,47,119,208,83,68,172,170, 129,214,174,165,220,37,87,92,47,244,235,29,169,40,18,142, 244,123,29,231,185,215,241,252,230,234,118,55,124,214,173,22, 19,185,32,90,238,214,85,203,228,141,58,69,164,211,85,172, 48,240,165,154,194,201,134,231,187,78,39,112,123,109,169,38, 73,155,179,225,181,165,227,240,226,211,78,55,8,213,106,24, 6,161,73,65,101,176,29,212,135,59,40,164,141,118,16,201, 42,157,198,199,152,164,94,145,244,70,151,53,146,1,108,44, 109,118,101,212,8,189,174,194,187,138,53,146,52,105,171,210, 45,241,16,213,113,168,117,124,85,107,53,55,162,154,213,170, 135,210,106,73,191,214,148,157,187,75,65,232,53,61,127,41, 82,245,245,182,92,90,185,121,235,238,210,251,75,183,107,235, 61,175,237,214,182,31,220,171,117,251,170,21,248,181,206,221, 154,231,43,137,97,106,215,198,2,180,140,66,20,186,232,181, 215,116,60,118,210,105,201,118,87,134,211,132,158,33,51,68, 89,148,68,94,232,162,42,166,113,150,195,143,46,22,181,41, 177,230,145,155,13,114,157,56,102,164,89,69,87,45,224,149, 6,225,34,113,102,19,127,5,93,50,50,199,162,53,141,215, 254,77,241,137,209,77,157,152,16,131,59,204,51,36,28,74, 62,162,171,247,129,201,146,131,205,60,196,36,66,238,197,172, 10,251,52,162,56,169,209,80,185,1,209,111,128,241,70,250, 236,192,128,90,123,58,8,191,12,170,72,5,18,209,121,60, 240,71,102,167,85,37,243,215,152,35,170,229,69,193,107,159, 111,130,230,156,79,22,70,230,95,253,103,235,155,178,161,162, 11,8,124,29,244,42,141,186,239,7,170,82,119,221,74,93, 169,208,91,239,41,25,85,84,80,185,18,85,233,114,205,227, 9,205,134,250,250,221,132,86,68,1,164,85,252,224,122,13, 133,15,115,252,192,183,16,73,133,20,105,5,110,132,56,169, 104,74,101,146,145,138,130,28,176,33,204,32,135,68,233,120, 148,59,134,207,79,18,75,152,166,213,124,66,170,72,182,55, 84,145,249,89,143,34,135,45,33,156,169,72,138,183,234,237, 158,100,237,72,38,133,6,209,52,182,225,200,201,120,138,28, 75,226,192,206,249,129,239,246,209,86,175,113,141,204,56,197, 148,44,49,41,79,34,33,39,112,204,227,223,188,152,215,26, 198,128,134,249,132,138,243,20,4,96,34,136,1,23,144,150, 123,88,140,170,26,87,19,246,143,179,245,18,205,104,179,185, 72,195,57,26,206,211,112,33,9,193,81,198,97,122,52,14, 247,233,108,141,157,103,55,233,226,244,196,77,55,147,113,167, 247,51,14,11,168,69,153,163,81,126,237,103,142,65,197,54, 124,76,35,138,114,78,234,16,61,167,210,78,25,198,202,40, 153,48,45,104,182,159,44,28,52,179,76,193,152,76,120,110, 18,121,211,12,110,166,24,108,210,125,49,125,205,211,73,221, 116,72,34,38,174,121,150,84,229,14,136,122,133,134,139,239, 34,244,251,20,108,142,81,240,33,153,81,30,80,112,154,169, 87,196,79,89,107,232,131,251,24,190,91,231,70,168,71,188, 51,14,224,221,85,154,233,227,17,120,135,148,27,248,253,105, 138,114,100,170,150,118,111,13,39,253,5,242,42,77,182,5, 108,26,94,248,11,216,7,104,220,7,220,228,62,128,123,9, 110,74,227,194,174,115,109,143,39,57,10,207,134,14,243,131, 247,123,84,192,177,27,6,219,253,74,176,81,81,236,63,213, 225,71,87,162,229,43,209,67,172,176,149,199,92,219,226,26, 27,87,209,80,118,169,10,210,214,213,237,134,228,183,42,63, 57,78,92,244,28,46,128,206,224,109,141,188,59,73,193,213, 146,168,115,249,143,84,72,85,255,200,227,94,28,198,157,220, 248,156,14,46,114,208,117,177,128,28,43,10,182,206,137,43, 63,247,112,188,138,159,143,232,34,40,2,18,232,75,139,105, 197,182,179,91,228,160,121,35,195,163,35,116,202,172,225,41, 95,37,252,201,239,243,135,62,122,146,30,191,96,107,36,136, 66,63,3,49,4,137,48,72,143,97,54,17,37,230,72,252, 63,192,121,116,64,79,193,245,201,162,62,130,37,176,108,69, 247,89,52,110,49,62,135,95,83,73,152,52,2,250,160,151, 77,55,2,198,176,182,49,181,222,234,101,111,100,139,32,93, 84,171,30,145,88,92,217,246,243,122,255,85,50,108,65,177, 178,31,37,207,38,227,35,29,178,238,219,125,150,209,171,244, 172,152,211,82,220,185,69,195,202,144,54,34,193,142,200,208, 11,240,230,30,192,137,223,44,223,144,53,6,219,63,51,193, 81,30,249,174,19,91,254,104,24,234,126,100,18,98,206,208, 160,37,149,3,235,12,182,186,170,207,253,83,124,228,16,162, 242,177,134,45,82,220,244,83,119,96,94,134,65,189,54,169, 21,49,151,97,240,86,99,182,199,245,198,151,175,185,226,240, 245,155,183,9,167,38,90,13,93,124,226,186,124,80,35,240, 49,82,190,226,178,155,89,30,217,96,245,214,15,219,128,203, 234,108,6,249,234,203,94,59,187,227,216,216,250,232,150,79, 188,173,67,183,224,250,200,22,235,111,78,177,198,79,177,254, 230,20,90,231,203,79,29,252,177,244,218,99,219,102,15,148, 81,139,25,120,245,251,94,125,196,194,153,113,129,145,243,214, 2,117,192,190,217,3,101,84,37,107,198,23,50,138,158,183, 234,126,118,239,220,193,66,234,114,22,255,44,148,117,204,137, 241,253,243,111,148,27,57,223,122,155,243,173,55,156,111,189, 229,249,105,57,117,46,179,244,212,223,194,188,201,110,46,31, 32,49,66,111,140,230,97,244,198,229,209,4,242,15,79,32, 223,85,167,51,200,179,48,43,95,26,89,85,23,179,46,122, 63,200,167,254,71,158,138,178,219,78,188,65,74,93,27,89, 104,250,171,219,74,250,238,237,149,231,193,189,59,89,37,103, 14,149,29,245,116,61,58,212,211,245,136,175,96,109,164,132, 142,95,193,168,4,127,253,107,108,213,195,119,210,27,112,229, 125,20,119,98,143,233,251,64,244,35,14,244,125,174,48,83, 16,121,141,254,189,160,99,219,51,45,12,189,84,46,24,165, 169,130,81,152,208,185,213,158,198,23,85,209,40,148,166,69, 65,251,127,127,254,2,56,224,64,222, }; EmbeddedPython embedded_m5_internal_enum_TimingExprOp( "m5/internal/enum_TimingExprOp.py", "/mnt/hgfs/ShareShen/gem5-origin-stable-2015-9-3/build/x86/python/m5/internal/enum_TimingExprOp.py", "m5.internal.enum_TimingExprOp", data_m5_internal_enum_TimingExprOp, 1962, 5657); } // anonymous namespace
57.578571
104
0.667907
5c0e580eaed59257243f065ff4702d3e069c0041
246
cpp
C++
cpp/hello.cpp
voltrevo/project-euler
0db5451f72b1353b295e56f928c968801e054444
[ "MIT" ]
null
null
null
cpp/hello.cpp
voltrevo/project-euler
0db5451f72b1353b295e56f928c968801e054444
[ "MIT" ]
null
null
null
cpp/hello.cpp
voltrevo/project-euler
0db5451f72b1353b295e56f928c968801e054444
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { for (int i = 0; i != 6; ++i) cout << "Hello "[i] << ' '; for (int i = 0; i != 6; ++i) cout << *("World!" + i) << ' '; cout << endl; return 0; }
15.375
39
0.390244
5c0f58021247e45903b7b462b8c643e455f8a267
75,637
cpp
C++
src/interpreter/Interpreter.cpp
continue-nature/yvm
6416cc5e60a76f64c4272e0dff909507f140b11e
[ "MIT" ]
110
2019-04-10T08:57:54.000Z
2022-03-13T03:37:20.000Z
src/interpreter/Interpreter.cpp
racaljk/ssvm
dfa6fa64fbe8682f77430246dff7f5c2ed9c4e41
[ "MIT" ]
4
2019-04-23T03:03:45.000Z
2021-12-31T09:55:53.000Z
src/interpreter/Interpreter.cpp
racaljk/ssvm
dfa6fa64fbe8682f77430246dff7f5c2ed9c4e41
[ "MIT" ]
31
2019-05-05T01:21:44.000Z
2022-03-16T15:25:24.000Z
#include "../classfile/AccessFlag.h" #include "../classfile/ClassFile.h" #include "../misc/Debug.h" #include "../misc/Option.h" #include "../runtime/JavaClass.h" #include "../runtime/JavaHeap.hpp" #include "CallSite.h" #include "Interpreter.hpp" #include "MethodResolve.h" #include "SymbolicRef.h" #include <cassert> #include <cmath> #include <functional> #include <iostream> using namespace std; #define IS_COMPUTATIONAL_TYPE_1(value) \ (typeid(*value) != typeid(JDouble) && typeid(*value) != typeid(JLong)) #define IS_COMPUTATIONAL_TYPE_2(value) \ (typeid(*value) == typeid(JDouble) || typeid(*value) == typeid(JLong)) #pragma warning(disable : 4715) #pragma warning(disable : 4244) Interpreter::~Interpreter() { delete frames; } JType *Interpreter::execNativeMethod(const string &className, const string &methodName, const string &methodDescriptor) { string nativeMethod(className); nativeMethod.append("."); nativeMethod.append(methodName); nativeMethod.append("."); nativeMethod.append(methodDescriptor); if (yrt.nativeMethods.find(nativeMethod) != yrt.nativeMethods.end()) { return ((*yrt.nativeMethods.find(nativeMethod)).second)( &yrt, frames->top()->localSlots, frames->top()->maxLocal); } GC_SAFE_POINT if (yrt.gc->shallGC()) { yrt.gc->stopTheWorld(); yrt.gc->gc(frames, GCPolicy::GC_MARK_AND_SWEEP); } return nullptr; } JType *Interpreter::execByteCode(const JavaClass *jc, u1 *code, u4 codeLength, u2 exceptLen, ExceptionTable *exceptTab) { for (decltype(codeLength) op = 0; op < codeLength; op++) { // If callee propagates a unhandled exception, try to handle it. When // we can not handle it, propagates it to upper and returns if (exception.hasUnhandledException()) { op--; auto *throwobj = frames->top()->pop<JObject>(); if (throwobj == nullptr) { throw runtime_error("null pointer"); } if (!hasInheritanceRelationship( throwobj->jc, yrt.ma->loadClassIfAbsent("java/lang/Throwable"))) { throw runtime_error("it's not a throwable object"); } if (handleException(jc, exceptLen, exceptTab, throwobj, op)) { while (!frames->top()->emptyStack()) { frames->top()->pop<JType>(); } frames->top()->push(throwobj); exception.sweepException(); } else { return throwobj; } } #ifdef YVM_DEBUG_SHOW_BYTECODE for (int i = 0; i < frames.size(); i++) { cout << "-"; } Inspector::printOpcode(code, op); #endif // Interpreting through big switching switch (code[op]) { case op_nop: { // DO NOTHING :-) } break; case op_aconst_null: { frames->top()->push(nullptr); } break; case op_iconst_m1: { frames->top()->push(new JInt(-1)); } break; case op_iconst_0: { frames->top()->push(new JInt(0)); } break; case op_iconst_1: { frames->top()->push(new JInt(1)); } break; case op_iconst_2: { frames->top()->push(new JInt(2)); } break; case op_iconst_3: { frames->top()->push(new JInt(3)); } break; case op_iconst_4: { frames->top()->push(new JInt(4)); } break; case op_iconst_5: { frames->top()->push(new JInt(5)); } break; case op_lconst_0: { frames->top()->push(new JLong(0)); } break; case op_lconst_1: { frames->top()->push(new JLong(1)); } break; case op_fconst_0: { frames->top()->push(new JFloat(0.0f)); } break; case op_fconst_1: { frames->top()->push(new JFloat(1.0f)); } break; case op_fconst_2: { frames->top()->push(new JFloat(2.0f)); } break; case op_dconst_0: { frames->top()->push(new JDouble(0.0)); } break; case op_dconst_1: { frames->top()->push(new JDouble(1.0)); } break; case op_bipush: { const u1 byte = consumeU1(code, op); frames->top()->push(new JInt(byte)); } break; case op_sipush: { const u2 byte = consumeU2(code, op); frames->top()->push(new JInt(byte)); } break; case op_ldc: { const u1 index = consumeU1(code, op); loadConstantPoolItem2Stack(jc, static_cast<u2>(index)); } break; case op_ldc_w: { const u2 index = consumeU2(code, op); loadConstantPoolItem2Stack(jc, index); } break; case op_ldc2_w: { const u2 index = consumeU2(code, op); if (typeid(*jc->raw.constPoolInfo[index]) == typeid(CONSTANT_Double)) { auto val = dynamic_cast<CONSTANT_Double *>( jc->raw.constPoolInfo[index]) ->val; JDouble *dval = new JDouble; dval->val = val; frames->top()->push(dval); } else if (typeid(*jc->raw.constPoolInfo[index]) == typeid(CONSTANT_Long)) { auto val = dynamic_cast<CONSTANT_Long *>( jc->raw.constPoolInfo[index]) ->val; JLong *lval = new JLong; lval->val = val; frames->top()->push(lval); } else { throw runtime_error( "invalid symbolic reference index on " "constant pool"); } } break; case op_iload: { const u1 index = consumeU1(code, op); frames->top()->load<JInt>(index); } break; case op_lload: { const u1 index = consumeU1(code, op); frames->top()->load<JLong>(index); } break; case op_fload: { const u1 index = consumeU1(code, op); frames->top()->load<JFloat>(index); } break; case op_dload: { const u1 index = consumeU1(code, op); frames->top()->load<JDouble>(index); } break; case op_aload: { const u1 index = consumeU1(code, op); frames->top()->load<JRef>(index); } break; case op_iload_0: { frames->top()->load<JInt>(0); } break; case op_iload_1: { frames->top()->load<JInt>(1); } break; case op_iload_2: { frames->top()->load<JInt>(2); } break; case op_iload_3: { frames->top()->load<JInt>(3); } break; case op_lload_0: { frames->top()->load<JLong>(0); } break; case op_lload_1: { frames->top()->load<JLong>(1); } break; case op_lload_2: { frames->top()->load<JLong>(2); } break; case op_lload_3: { frames->top()->load<JLong>(3); } break; case op_fload_0: { frames->top()->load<JFloat>(0); } break; case op_fload_1: { frames->top()->load<JFloat>(1); } break; case op_fload_2: { frames->top()->load<JFloat>(2); } break; case op_fload_3: { frames->top()->load<JFloat>(3); } break; case op_dload_0: { frames->top()->load<JDouble>(0); } break; case op_dload_1: { frames->top()->load<JDouble>(1); } break; case op_dload_2: { frames->top()->load<JDouble>(2); } break; case op_dload_3: { frames->top()->load<JDouble>(3); } break; case op_aload_0: { frames->top()->load<JRef>(0); } break; case op_aload_1: { frames->top()->load<JRef>(1); } break; case op_aload_2: { frames->top()->load<JRef>(2); } break; case op_aload_3: { frames->top()->load<JRef>(3); } break; case op_saload: case op_caload: case op_baload: case op_iaload: { auto *index = frames->top()->pop<JInt>(); const auto *arrref = frames->top()->pop<JArray>(); if (!arrref) { throw runtime_error("nullpointerexception"); } auto *elem = dynamic_cast<JInt *>( yrt.jheap->getElement(*arrref, index->val)); frames->top()->push(elem); } break; case op_laload: { auto *index = frames->top()->pop<JInt>(); const auto *arrref = frames->top()->pop<JArray>(); if (!arrref) { throw runtime_error("nullpointerexception"); } auto *elem = dynamic_cast<JLong *>( yrt.jheap->getElement(*arrref, index->val)); frames->top()->push(elem); } break; case op_faload: { auto *index = frames->top()->pop<JInt>(); const auto *arrref = frames->top()->pop<JArray>(); if (!arrref) { throw runtime_error("nullpointerexception"); } auto *elem = dynamic_cast<JFloat *>( yrt.jheap->getElement(*arrref, index->val)); frames->top()->push(elem); } break; case op_daload: { auto *index = frames->top()->pop<JInt>(); const auto *arrref = frames->top()->pop<JArray>(); if (!arrref) { throw runtime_error("nullpointerexception"); } auto *elem = dynamic_cast<JDouble *>( yrt.jheap->getElement(*arrref, index->val)); frames->top()->push(elem); } break; case op_aaload: { auto *index = frames->top()->pop<JInt>(); const auto *arrref = frames->top()->pop<JArray>(); if (!arrref) { throw runtime_error("nullpointerexception"); } auto *elem = dynamic_cast<JRef *>( yrt.jheap->getElement(*arrref, index->val)); frames->top()->push(elem); } break; case op_istore: { const u1 index = consumeU1(code, op); frames->top()->store<JInt>(index); } break; case op_lstore: { const u1 index = consumeU1(code, op); frames->top()->store<JLong>(index); } break; case op_fstore: { const u1 index = consumeU1(code, op); frames->top()->store<JFloat>(index); } break; case op_dstore: { const u1 index = consumeU1(code, op); frames->top()->store<JDouble>(index); } break; case op_astore: { const u1 index = consumeU1(code, op); frames->top()->store<JRef>(index); } break; case op_istore_0: { frames->top()->store<JInt>(0); } break; case op_istore_1: { frames->top()->store<JInt>(1); } break; case op_istore_2: { frames->top()->store<JInt>(2); } break; case op_istore_3: { frames->top()->store<JInt>(3); } break; case op_lstore_0: { frames->top()->store<JLong>(0); } break; case op_lstore_1: { frames->top()->store<JLong>(1); } break; case op_lstore_2: { frames->top()->store<JLong>(2); } break; case op_lstore_3: { frames->top()->store<JLong>(3); } break; case op_fstore_0: { frames->top()->store<JFloat>(0); } break; case op_fstore_1: { frames->top()->store<JFloat>(1); } break; case op_fstore_2: { frames->top()->store<JFloat>(2); } break; case op_fstore_3: { frames->top()->store<JFloat>(3); } break; case op_dstore_0: { frames->top()->store<JDouble>(0); } break; case op_dstore_1: { frames->top()->store<JDouble>(1); } break; case op_dstore_2: { frames->top()->store<JDouble>(2); } break; case op_dstore_3: { frames->top()->store<JDouble>(3); } break; case op_astore_0: { frames->top()->store<JRef>(0); } break; case op_astore_1: { frames->top()->store<JRef>(1); } break; case op_astore_2: { frames->top()->store<JRef>(2); } break; case op_astore_3: { frames->top()->store<JRef>(3); } break; case op_iastore: { auto *value = frames->top()->pop<JInt>(); auto *index = frames->top()->pop<JInt>(); auto *arrref = frames->top()->pop<JArray>(); if (arrref == nullptr) { throw runtime_error("null pointer"); } if (index->val > arrref->length || index->val < 0) { throw runtime_error("array index out of bounds"); } yrt.jheap->putElement(*arrref, index->val, value); } break; case op_lastore: { auto *value = frames->top()->pop<JLong>(); auto *index = frames->top()->pop<JInt>(); auto *arrref = frames->top()->pop<JArray>(); if (arrref == nullptr) { throw runtime_error("null pointer"); } if (index->val > arrref->length || index->val < 0) { throw runtime_error("array index out of bounds"); } yrt.jheap->putElement(*arrref, index->val, value); } break; case op_fastore: { auto *value = frames->top()->pop<JFloat>(); auto *index = frames->top()->pop<JInt>(); auto *arrref = frames->top()->pop<JArray>(); if (arrref == nullptr) { throw runtime_error("null pointer"); } if (index->val > arrref->length || index->val < 0) { throw runtime_error("array index out of bounds"); } yrt.jheap->putElement(*arrref, index->val, value); } break; case op_dastore: { auto *value = frames->top()->pop<JDouble>(); auto *index = frames->top()->pop<JInt>(); auto *arrref = frames->top()->pop<JArray>(); if (arrref == nullptr) { throw runtime_error("null pointer"); } if (index->val > arrref->length || index->val < 0) { throw runtime_error("array index out of bounds"); } yrt.jheap->putElement(*arrref, index->val, value); } break; case op_aastore: { auto *value = frames->top()->pop<JType>(); auto *index = frames->top()->pop<JInt>(); auto *arrref = frames->top()->pop<JArray>(); if (arrref == nullptr) { throw runtime_error("null pointer"); } if (index->val > arrref->length || index->val < 0) { throw runtime_error("array index out of bounds"); } yrt.jheap->putElement(*arrref, index->val, value); } break; case op_bastore: { auto *value = frames->top()->pop<JInt>(); value->val = static_cast<int8_t>(value->val); auto *index = frames->top()->pop<JInt>(); auto *arrref = frames->top()->pop<JArray>(); if (arrref == nullptr) { throw runtime_error("null pointer"); } if (index->val > arrref->length || index->val < 0) { throw runtime_error("array index out of bounds"); } yrt.jheap->putElement(*arrref, index->val, value); } break; case op_sastore: case op_castore: { auto *value = frames->top()->pop<JInt>(); value->val = static_cast<int16_t>(value->val); auto *index = frames->top()->pop<JInt>(); auto *arrref = frames->top()->pop<JArray>(); if (arrref == nullptr) { throw runtime_error("null pointer"); } if (index->val > arrref->length || index->val < 0) { throw runtime_error("array index out of bounds"); } yrt.jheap->putElement(*arrref, index->val, value); } break; case op_pop: { frames->top()->pop<JType>(); } break; case op_pop2: { frames->top()->pop<JType>(); frames->top()->pop<JType>(); } break; case op_dup: { JType *value = frames->top()->pop<JType>(); assert(typeid(*value) != typeid(JLong) && typeid(*value) != typeid(JDouble)); frames->top()->push(value); frames->top()->push(cloneValue(value)); } break; case op_dup_x1: { JType *value1 = frames->top()->pop<JType>(); JType *value2 = frames->top()->pop<JType>(); assert(IS_COMPUTATIONAL_TYPE_1(value1)); assert(IS_COMPUTATIONAL_TYPE_1(value2)); frames->top()->push(cloneValue(value1)); frames->top()->push(value2); frames->top()->push(value1); } break; case op_dup_x2: { JType *value1 = frames->top()->pop<JType>(); JType *value2 = frames->top()->pop<JType>(); JType *value3 = frames->top()->pop<JType>(); if (IS_COMPUTATIONAL_TYPE_1(value1) && IS_COMPUTATIONAL_TYPE_1(value2) && IS_COMPUTATIONAL_TYPE_1(value3)) { // use structure 1 frames->top()->push(cloneValue(value1)); frames->top()->push(value3); frames->top()->push(value2); frames->top()->push(value1); } else if (IS_COMPUTATIONAL_TYPE_1(value1) && IS_COMPUTATIONAL_TYPE_2(value2)) { // use structure 2 frames->top()->push(value3); frames->top()->push(cloneValue(value1)); frames->top()->push(value2); frames->top()->push(value1); } else { SHOULD_NOT_REACH_HERE } } break; case op_dup2: { JType *value1 = frames->top()->pop<JType>(); JType *value2 = frames->top()->pop<JType>(); if (IS_COMPUTATIONAL_TYPE_1(value1) && IS_COMPUTATIONAL_TYPE_1(value2)) { // use structure 1 frames->top()->push(cloneValue(value2)); frames->top()->push(cloneValue(value1)); frames->top()->push(value2); frames->top()->push(value1); } else if (IS_COMPUTATIONAL_TYPE_2(value1)) { // use structure 2 frames->top()->push(value2); frames->top()->push(cloneValue(value1)); frames->top()->push(value1); } else { SHOULD_NOT_REACH_HERE } } break; case op_dup2_x1: { JType *value1 = frames->top()->pop<JType>(); JType *value2 = frames->top()->pop<JType>(); JType *value3 = frames->top()->pop<JType>(); if (IS_COMPUTATIONAL_TYPE_1(value1) && IS_COMPUTATIONAL_TYPE_1(value2) && IS_COMPUTATIONAL_TYPE_1(value3)) { // use structure 1 frames->top()->push(cloneValue(value2)); frames->top()->push(cloneValue(value1)); frames->top()->push(value3); frames->top()->push(value2); frames->top()->push(value1); } else if (IS_COMPUTATIONAL_TYPE_2(value1) && IS_COMPUTATIONAL_TYPE_1(value2)) { // use structure 2 frames->top()->push(value3); frames->top()->push(cloneValue(value1)); frames->top()->push(value2); frames->top()->push(value1); } else { SHOULD_NOT_REACH_HERE } } break; case op_dup2_x2: { JType *value1 = frames->top()->pop<JType>(); JType *value2 = frames->top()->pop<JType>(); JType *value3 = frames->top()->pop<JType>(); JType *value4 = frames->top()->pop<JType>(); if (IS_COMPUTATIONAL_TYPE_1(value1) && IS_COMPUTATIONAL_TYPE_1(value2) && IS_COMPUTATIONAL_TYPE_1(value3) && IS_COMPUTATIONAL_TYPE_1(value4)) { // use structure 1 frames->top()->push(cloneValue(value2)); frames->top()->push(cloneValue(value1)); frames->top()->push(value4); frames->top()->push(value3); frames->top()->push(value2); frames->top()->push(value1); } else if (IS_COMPUTATIONAL_TYPE_2(value1) && IS_COMPUTATIONAL_TYPE_1(value2) && IS_COMPUTATIONAL_TYPE_1(value3)) { // use structure 2 frames->top()->push(value4); frames->top()->push(cloneValue(value1)); frames->top()->push(value4); frames->top()->push(value2); frames->top()->push(value1); } else { SHOULD_NOT_REACH_HERE } } break; case op_swap: { JType *value1 = frames->top()->pop<JType>(); JType *value2 = frames->top()->pop<JType>(); assert(IS_COMPUTATIONAL_TYPE_1(value1)); assert(IS_COMPUTATIONAL_TYPE_1(value2)); if (typeid(*value1) == typeid(JInt) && typeid(*value2) == typeid(JInt)) { swap(value1, value2); } else if (typeid(*value1) == typeid(JInt) && typeid(*value2) == typeid(JFloat)) { const int32_t temp = dynamic_cast<JInt *>(value1)->val; dynamic_cast<JInt *>(value1)->val = static_cast<int32_t>( dynamic_cast<JFloat *>(value2)->val); dynamic_cast<JFloat *>(value2)->val = static_cast<float>(temp); } else if (typeid(*value1) == typeid(JFloat) && typeid(*value2) == typeid(JInt)) { const float temp = dynamic_cast<JFloat *>(value1)->val; dynamic_cast<JFloat *>(value1)->val = static_cast<int32_t>(dynamic_cast<JInt *>(value2)->val); dynamic_cast<JInt *>(value2)->val = static_cast<int32_t>(temp); } else if (typeid(*value1) == typeid(JFloat) && typeid(*value2) == typeid(JFloat)) { swap(value1, value2); } else { SHOULD_NOT_REACH_HERE } } break; case op_iadd: { binaryArithmetic<JInt>(plus<>()); } break; case op_ladd: { binaryArithmetic<JLong>(plus<>()); } break; case op_fadd: { binaryArithmetic<JFloat>(plus<>()); } break; case op_dadd: { binaryArithmetic<JDouble>(plus<>()); } break; case op_isub: { binaryArithmetic<JInt>(minus<>()); } break; case op_lsub: { binaryArithmetic<JLong>(minus<>()); } break; case op_fsub: { binaryArithmetic<JFloat>(minus<>()); } break; case op_dsub: { binaryArithmetic<JDouble>(minus<>()); } break; case op_imul: { binaryArithmetic<JInt>(multiplies<>()); } break; case op_lmul: { binaryArithmetic<JLong>(multiplies<>()); } break; case op_fmul: { binaryArithmetic<JFloat>(multiplies<>()); } break; case op_dmul: { binaryArithmetic<JDouble>(multiplies<>()); } break; case op_idiv: { binaryArithmetic<JInt>(divides<>()); } break; case op_ldiv: { binaryArithmetic<JLong>(divides<>()); } break; case op_fdiv: { binaryArithmetic<JFloat>(divides<>()); } break; case op_ddiv: { binaryArithmetic<JDouble>(divides<>()); } break; case op_irem: { binaryArithmetic<JInt>(modulus<>()); } break; case op_lrem: { binaryArithmetic<JLong>(modulus<>()); } break; case op_frem: { binaryArithmetic<JFloat>(std::fmod<float, float>); } break; case op_drem: { binaryArithmetic<JFloat>(std::fmod<double, double>); } break; case op_ineg: { unaryArithmetic<JInt>(negate<>()); } break; case op_lneg: { unaryArithmetic<JLong>(negate<>()); } break; case op_fneg: { unaryArithmetic<JFloat>(negate<>()); } break; case op_dneg: { unaryArithmetic<JDouble>(negate<>()); } break; case op_ishl: { binaryArithmetic<JInt>([](int32_t a, int32_t b) -> int32_t { return a * pow(2, b & 0x1f); }); } break; case op_lshl: { binaryArithmetic<JLong>([](int64_t a, int64_t b) -> int64_t { return a * pow(2, b & 0x3f); }); } break; case op_ishr: { binaryArithmetic<JInt>([](int32_t a, int32_t b) -> int32_t { return floor(a / pow(2, b & 0x1f)); }); } break; case op_lshr: { binaryArithmetic<JLong>([](int64_t a, int64_t b) -> int64_t { return floor(a / pow(2, b & 0x3f)); }); } break; case op_iushr: { binaryArithmetic<JInt>([](int32_t a, int32_t b) -> int32_t { if (a > 0) { return a >> (b & 0x1f); } else if (a < 0) { return (a >> (b & 0x1f)) + (2 << ~(b & 0x1f)); } else { throw runtime_error("0 is not handled"); } }); } break; case op_lushr: { binaryArithmetic<JLong>([](int64_t a, int64_t b) -> int64_t { if (a > 0) { return a >> (b & 0x3f); } else if (a < 0) { return (a >> (b & 0x1f)) + (2L << ~(b & 0x3f)); } else { throw runtime_error("0 is not handled"); } }); } break; case op_iand: { binaryArithmetic<JInt>(bit_and<>()); } break; case op_land: { binaryArithmetic<JLong>(bit_and<>()); } break; case op_ior: { binaryArithmetic<JInt>(bit_or<>()); } break; case op_lor: { binaryArithmetic<JLong>(bit_or<>()); } break; case op_ixor: { binaryArithmetic<JInt>(bit_xor<>()); } break; case op_lxor: { binaryArithmetic<JLong>(bit_xor<>()); } break; case op_iinc: { const u1 index = code[++op]; const int8_t count = code[++op]; const int32_t extendedCount = count; if (IS_JINT(frames->top()->getLocalVariable(index))) { dynamic_cast<JInt *>(frames->top()->getLocalVariable(index)) ->val += extendedCount; } else if (IS_JLong(frames->top()->getLocalVariable(index))) { dynamic_cast<JLong *>( frames->top()->getLocalVariable(index)) ->val += extendedCount; } else if (IS_JFloat(frames->top()->getLocalVariable(index))) { dynamic_cast<JFloat *>( frames->top()->getLocalVariable(index)) ->val += extendedCount; } else if (IS_JDouble(frames->top()->getLocalVariable(index))) { dynamic_cast<JDouble *>( frames->top()->getLocalVariable(index)) ->val += extendedCount; } else { SHOULD_NOT_REACH_HERE } } break; case op_i2l: { typeCast<JInt, JLong>(); } break; case op_i2f: { typeCast<JInt, JFloat>(); } break; case op_i2d: { typeCast<JInt, JDouble>(); } break; case op_l2i: { typeCast<JLong, JInt>(); } break; case op_l2f: { typeCast<JLong, JFloat>(); } break; case op_l2d: { typeCast<JLong, JDouble>(); } break; case op_f2i: { typeCast<JFloat, JInt>(); } break; case op_f2l: { typeCast<JFloat, JLong>(); } break; case op_f2d: { typeCast<JFloat, JDouble>(); } break; case op_d2i: { typeCast<JDouble, JInt>(); } break; case op_d2l: { typeCast<JDouble, JLong>(); } break; case op_d2f: { typeCast<JDouble, JFloat>(); } break; case op_i2c: case op_i2b: { auto *value = frames->top()->pop<JInt>(); auto *result = new JInt; result->val = (int8_t)(value->val); frames->top()->push(result); } break; case op_i2s: { auto *value = frames->top()->pop<JInt>(); auto *result = new JInt; result->val = (int16_t)(value->val); frames->top()->push(result); } break; case op_lcmp: { auto *value2 = frames->top()->pop<JLong>(); auto *value1 = frames->top()->pop<JLong>(); if (value1->val > value2->val) { auto *result = new JInt(1); frames->top()->push(result); } else if (value1->val == value2->val) { auto *result = new JInt(0); frames->top()->push(result); } else { auto *result = new JInt(-1); frames->top()->push(result); } } break; case op_fcmpg: case op_fcmpl: { auto *value2 = frames->top()->pop<JFloat>(); auto *value1 = frames->top()->pop<JFloat>(); if (value1->val > value2->val) { auto *result = new JInt(1); frames->top()->push(result); } else if (abs(value1->val - value2->val) < 0.000001) { auto *result = new JInt(0); frames->top()->push(result); } else { auto *result = new JInt(-1); frames->top()->push(result); } } break; case op_dcmpl: case op_dcmpg: { auto *value2 = frames->top()->pop<JDouble>(); auto *value1 = frames->top()->pop<JDouble>(); if (value1->val > value2->val) { auto *result = new JInt(1); frames->top()->push(result); } else if (abs(value1->val - value2->val) < 0.000000000001) { auto *result = new JInt(0); frames->top()->push(result); } else { auto *result = new JInt(-1); frames->top()->push(result); } } break; case op_ifeq: { u4 currentOffset = op - 1; int16_t branchindex = consumeU2(code, op); auto *value = frames->top()->pop<JInt>(); if (value->val == 0) { op = currentOffset + branchindex; } } break; case op_ifne: { u4 currentOffset = op - 1; int16_t branchindex = consumeU2(code, op); auto *value = frames->top()->pop<JInt>(); if (value->val != 0) { op = currentOffset + branchindex; } } break; case op_iflt: { u4 currentOffset = op - 1; int16_t branchindex = consumeU2(code, op); auto *value = frames->top()->pop<JInt>(); if (value->val < 0) { op = currentOffset + branchindex; } } break; case op_ifge: { u4 currentOffset = op - 1; int16_t branchindex = consumeU2(code, op); auto *value = frames->top()->pop<JInt>(); if (value->val >= 0) { op = currentOffset + branchindex; } } break; case op_ifgt: { u4 currentOffset = op - 1; int16_t branchindex = consumeU2(code, op); auto *value = frames->top()->pop<JInt>(); if (value->val > 0) { op = currentOffset + branchindex; } } break; case op_ifle: { u4 currentOffset = op - 1; int16_t branchindex = consumeU2(code, op); auto *value = frames->top()->pop<JInt>(); if (value->val <= 0) { op = currentOffset + branchindex; } } break; case op_if_icmpeq: { u4 currentOffset = op - 1; int16_t branchindex = consumeU2(code, op); auto *value2 = frames->top()->pop<JInt>(); auto *value1 = frames->top()->pop<JInt>(); if (value1->val == value2->val) { op = currentOffset + branchindex; } } break; case op_if_icmpne: { u4 currentOffset = op - 1; int16_t branchindex = consumeU2(code, op); auto *value2 = frames->top()->pop<JInt>(); auto *value1 = frames->top()->pop<JInt>(); if (value1->val != value2->val) { op = currentOffset + branchindex; } } break; case op_if_icmplt: { u4 currentOffset = op - 1; int16_t branchindex = consumeU2(code, op); auto *value2 = frames->top()->pop<JInt>(); auto *value1 = frames->top()->pop<JInt>(); if (value1->val < value2->val) { op = currentOffset + branchindex; } } break; case op_if_icmpge: { u4 currentOffset = op - 1; int16_t branchindex = consumeU2(code, op); auto *value2 = frames->top()->pop<JInt>(); auto *value1 = frames->top()->pop<JInt>(); if (value1->val >= value2->val) { op = currentOffset + branchindex; } } break; case op_if_icmpgt: { u4 currentOffset = op - 1; int16_t branchindex = consumeU2(code, op); auto *value2 = frames->top()->pop<JInt>(); auto *value1 = frames->top()->pop<JInt>(); if (value1->val > value2->val) { op = currentOffset + branchindex; } } break; case op_if_icmple: { u4 currentOffset = op - 1; int16_t branchindex = consumeU2(code, op); auto *value2 = frames->top()->pop<JInt>(); auto *value1 = frames->top()->pop<JInt>(); if (value1->val <= value2->val) { op = currentOffset + branchindex; } } break; case op_if_acmpeq: { u4 currentOffset = op - 1; int16_t branchindex = consumeU2(code, op); auto *value2 = frames->top()->pop<JObject>(); auto *value1 = frames->top()->pop<JObject>(); if (value1->offset == value2->offset && value1->jc == value2->jc) { op = currentOffset + branchindex; } } break; case op_if_acmpne: { u4 currentOffset = op - 1; int16_t branchindex = consumeU2(code, op); auto *value2 = frames->top()->pop<JObject>(); auto *value1 = frames->top()->pop<JObject>(); if (value1->offset != value2->offset || value1->jc != value2->jc) { op = currentOffset + branchindex; } } break; case op_goto: { u4 currentOffset = op - 1; int16_t branchindex = consumeU2(code, op); op = currentOffset + branchindex; } break; case op_jsr: { throw runtime_error("unsupported opcode [jsr]"); } break; case op_ret: { throw runtime_error("unsupported opcode [ret]"); } break; case op_tableswitch: { u4 currentOffset = op - 1; op++; op++; op++; // 3 bytes padding int32_t defaultIndex = consumeU4(code, op); int32_t low = consumeU4(code, op); int32_t high = consumeU4(code, op); vector<int32_t> jumpOffset; FOR_EACH(i, high - low + 1) { jumpOffset.push_back(consumeU4(code, op)); } auto *index = frames->top()->pop<JInt>(); if (index->val < low || index->val > high) { op = currentOffset + defaultIndex; } else { op = currentOffset + jumpOffset[index->val - low]; } } break; case op_lookupswitch: { u4 currentOffset = op - 1; op++; op++; op++; // 3 bytes padding int32_t defaultIndex = consumeU4(code, op); int32_t npair = consumeU4(code, op); map<int32_t, int32_t> matchOffset; FOR_EACH(i, npair) { matchOffset.insert( make_pair(consumeU4(code, op), consumeU4(code, op))); } auto *key = frames->top()->pop<JInt>(); auto res = matchOffset.find(key->val); if (res != matchOffset.end()) { op = currentOffset + (*res).second; } else { op = currentOffset + defaultIndex; } } break; case op_ireturn: { return cloneValue(frames->top()->pop<JInt>()); } break; case op_lreturn: { return cloneValue(frames->top()->pop<JLong>()); } break; case op_freturn: { return cloneValue(frames->top()->pop<JFloat>()); } break; case op_dreturn: { return cloneValue(frames->top()->pop<JDouble>()); } break; case op_areturn: { return cloneValue(frames->top()->pop<JType>()); } break; case op_return: { return nullptr; } break; case op_getstatic: { const u2 index = consumeU2(code, op); auto symbolicRef = parseFieldSymbolicReference(jc, index); yrt.ma->linkClassIfAbsent(symbolicRef.jc->getClassName()); yrt.ma->initClassIfAbsent(*this, symbolicRef.jc->getClassName()); JType *field = symbolicRef.jc->getStaticVar( symbolicRef.name, symbolicRef.descriptor); frames->top()->push(field); } break; case op_putstatic: { u2 index = consumeU2(code, op); JType *value = frames->top()->pop<JType>(); auto symbolicRef = parseFieldSymbolicReference(jc, index); yrt.ma->linkClassIfAbsent(symbolicRef.jc->getClassName()); yrt.ma->initClassIfAbsent(*this, symbolicRef.jc->getClassName()); symbolicRef.jc->setStaticVar(symbolicRef.name, symbolicRef.descriptor, value); } break; case op_getfield: { u2 index = consumeU2(code, op); JObject *objectref = frames->top()->pop<JObject>(); auto symbolicRef = parseFieldSymbolicReference(jc, index); JType *field = cloneValue(yrt.jheap->getFieldByName( symbolicRef.jc, symbolicRef.name, symbolicRef.descriptor, objectref)); frames->top()->push(field); } break; case op_putfield: { const u2 index = consumeU2(code, op); JType *value = frames->top()->pop<JType>(); JObject *objectref = frames->top()->pop<JObject>(); auto symbolicRef = parseFieldSymbolicReference(jc, index); yrt.jheap->putFieldByName(symbolicRef.jc, symbolicRef.name, symbolicRef.descriptor, objectref, value); } break; case op_invokevirtual: { const u2 index = consumeU2(code, op); assert(typeid(*jc->raw.constPoolInfo[index]) == typeid(CONSTANT_Methodref)); auto symbolicRef = parseMethodSymbolicReference(jc, index); if (symbolicRef.name == "<init>") { runtime_error( "invoking method should not be instance " "initialization method\n"); } if (!IS_SIGNATURE_POLYMORPHIC_METHOD( symbolicRef.jc->getClassName(), symbolicRef.name)) { invokeVirtual(symbolicRef.name, symbolicRef.descriptor); } else { // TODO:TO BE IMPLEMENTED } } break; case op_invokespecial: { const u2 index = consumeU2(code, op); SymbolicRef symbolicRef; if (typeid(*jc->raw.constPoolInfo[index]) == typeid(CONSTANT_InterfaceMethodref)) { symbolicRef = parseInterfaceMethodSymbolicReference(jc, index); } else if (typeid(*jc->raw.constPoolInfo[index]) == typeid(CONSTANT_Methodref)) { symbolicRef = parseMethodSymbolicReference(jc, index); } else { SHOULD_NOT_REACH_HERE } // If all of the following are true, let C be the direct // superclass of the current class : JavaClass *symbolicRefClass = symbolicRef.jc; if ("<init>" != symbolicRef.name) { if (!IS_CLASS_INTERFACE( symbolicRefClass->raw.accessFlags)) { if (symbolicRefClass->getClassName() == jc->getSuperClassName()) { if (IS_CLASS_SUPER(jc->raw.accessFlags)) { invokeSpecial(yrt.ma->findJavaClass( jc->getSuperClassName()), symbolicRef.name, symbolicRef.descriptor); break; } } } } // Otherwise let C be the symbolic reference class invokeSpecial(symbolicRef.jc, symbolicRef.name, symbolicRef.descriptor); } break; case op_invokestatic: { // Invoke a class (static) method const u2 index = consumeU2(code, op); if (typeid(*jc->raw.constPoolInfo[index]) == typeid(CONSTANT_InterfaceMethodref)) { auto symbolicRef = parseInterfaceMethodSymbolicReference(jc, index); invokeStatic(symbolicRef.jc, symbolicRef.name, symbolicRef.descriptor); } else if (typeid(*jc->raw.constPoolInfo[index]) == typeid(CONSTANT_Methodref)) { auto symbolicRef = parseMethodSymbolicReference(jc, index); invokeStatic(symbolicRef.jc, symbolicRef.name, symbolicRef.descriptor); } else { SHOULD_NOT_REACH_HERE } } break; case op_invokeinterface: { const u2 index = consumeU2(code, op); ++op; // read count and discard ++op; // opcode padding 0; if (typeid(*jc->raw.constPoolInfo[index]) == typeid(CONSTANT_InterfaceMethodref)) { auto symbolicRef = parseInterfaceMethodSymbolicReference(jc, index); invokeInterface(symbolicRef.jc, symbolicRef.name, symbolicRef.descriptor); } } break; case op_invokedynamic: { throw runtime_error("unsupported opcode [invokedynamic]"); } break; case op_new: { const u2 index = consumeU2(code, op); JObject *objectref = execNew(jc, index); frames->top()->push(objectref); } break; case op_newarray: { const u1 atype = code[++op]; JInt *count = frames->top()->pop<JInt>(); if (count->val < 0) { throw runtime_error("negative array size"); } JArray *arrayref = yrt.jheap->createPODArray(atype, count->val); frames->top()->push(arrayref); } break; case op_anewarray: { const u2 index = consumeU2(code, op); auto symbolicRef = parseClassSymbolicReference(jc, index); JInt *count = frames->top()->pop<JInt>(); if (count->val < 0) { throw runtime_error("negative array size"); } JArray *arrayref = yrt.jheap->createObjectArray(*symbolicRef.jc, count->val); frames->top()->push(arrayref); } break; case op_arraylength: { JArray *arrayref = frames->top()->pop<JArray>(); if (arrayref == nullptr) { throw runtime_error("null pointer\n"); } JInt *length = new JInt; length->val = arrayref->length; frames->top()->push(length); } break; case op_athrow: { auto *throwobj = frames->top()->pop<JObject>(); if (throwobj == nullptr) { throw runtime_error("null pointer"); } if (!hasInheritanceRelationship( throwobj->jc, yrt.ma->loadClassIfAbsent("java/lang/Throwable"))) { throw runtime_error("it's not a throwable object"); } if (handleException(jc, exceptLen, exceptTab, throwobj, op)) { while (!frames->top()->emptyStack()) { frames->top()->pop<JType>(); } frames->top()->push(throwobj); } else /* Exception can not handled within method handlers */ { exception.markException(); exception.setThrowExceptionInfo(throwobj); return throwobj; } } break; case op_checkcast: { throw runtime_error("unsupported opcode [checkcast]"); } break; case op_instanceof: { const u2 index = consumeU2(code, op); auto *objectref = frames->top()->pop<JObject>(); if (objectref == nullptr) { frames->top()->push(new JInt(0)); } if (checkInstanceof(jc, index, objectref)) { frames->top()->push(new JInt(1)); } else { frames->top()->push(new JInt(0)); } } break; case op_monitorenter: { JType *ref = frames->top()->pop<JType>(); if (ref == nullptr) { throw runtime_error("null pointer"); } if (!yrt.jheap->hasMonitor(ref)) { dynamic_cast<JObject *>(ref)->offset = yrt.jheap->createMonitor(); } yrt.jheap->findMonitor(ref)->enter(this_thread::get_id()); } break; case op_monitorexit: { JType *ref = frames->top()->pop<JType>(); if (ref == nullptr) { throw runtime_error("null pointer"); } if (!yrt.jheap->hasMonitor(ref)) { dynamic_cast<JObject *>(ref)->offset = yrt.jheap->createMonitor(); } yrt.jheap->findMonitor(ref)->exit(); } break; case op_wide: { throw runtime_error("unsupported opcode [wide]"); } break; case op_multianewarray: { throw runtime_error("unsupported opcode [multianewarray]"); } break; case op_ifnull: { u4 currentOffset = op - 1; int16_t branchIndex = consumeU2(code, op); JObject *value = frames->top()->pop<JObject>(); if (value == nullptr) { op = currentOffset + branchIndex; } } break; case op_ifnonnull: { u4 currentOffset = op - 1; int16_t branchIndex = consumeU2(code, op); JObject *value = frames->top()->pop<JObject>(); if (value != nullptr) { op = currentOffset + branchIndex; } } break; case op_goto_w: { u4 currentOffset = op - 1; int32_t branchIndex = consumeU4(code, op); op = currentOffset + branchIndex; } break; case op_jsr_w: { throw runtime_error("unsupported opcode [jsr_w]"); } break; case op_breakpoint: case op_impdep1: case op_impdep2: { // Reserved opcodde cerr << "Are you a dot.class hacker? Or you were entered a " "strange region."; exit(EXIT_FAILURE); } break; default: cerr << "The YVM can not recognize this opcode. Bytecode file " "was be corrupted."; exit(EXIT_FAILURE); } } return nullptr; } //-------------------------------------------------------------------------------- // This function does "ldc" opcode jc type of JavaClass, which indicate where // to resolve //-------------------------------------------------------------------------------- void Interpreter::loadConstantPoolItem2Stack(const JavaClass *jc, u2 index) { if (typeid(*jc->raw.constPoolInfo[index]) == typeid(CONSTANT_Integer)) { auto val = dynamic_cast<CONSTANT_Integer *>(jc->raw.constPoolInfo[index])->val; JInt *ival = new JInt; ival->val = val; frames->top()->push(ival); } else if (typeid(*jc->raw.constPoolInfo[index]) == typeid(CONSTANT_Float)) { auto val = dynamic_cast<CONSTANT_Float *>(jc->raw.constPoolInfo[index])->val; JFloat *fval = new JFloat; fval->val = val; frames->top()->push(fval); } else if (typeid(*jc->raw.constPoolInfo[index]) == typeid(CONSTANT_String)) { auto val = jc->getString( dynamic_cast<CONSTANT_String *>(jc->raw.constPoolInfo[index]) ->stringIndex); JObject *str = yrt.jheap->createObject( *yrt.ma->loadClassIfAbsent("java/lang/String")); JArray *value = yrt.jheap->createCharArray(val, val.length()); // Put string into str's field; according the source file of // java.lang.Object, we know that its first field was used to store // chars yrt.jheap->putFieldByOffset(*str, 0, value); frames->top()->push(str); } else if (typeid(*jc->raw.constPoolInfo[index]) == typeid(CONSTANT_Class)) { throw runtime_error("nonsupport region"); } else if (typeid(*jc->raw.constPoolInfo[index]) == typeid(CONSTANT_MethodType)) { throw runtime_error("nonsupport region"); } else if (typeid(*jc->raw.constPoolInfo[index]) == typeid(CONSTANT_MethodHandle)) { throw runtime_error("nonsupport region"); } else { throw runtime_error( "invalid symbolic reference index on constant " "pool"); } } bool Interpreter::handleException(const JavaClass *jc, u2 exceptLen, ExceptionTable *exceptTab, const JObject *objectref, u4 &op) { FOR_EACH(i, exceptLen) { const string &catchTypeName = jc->getString(dynamic_cast<CONSTANT_Class *>( jc->raw.constPoolInfo[exceptTab[i].catchType]) ->nameIndex); if (hasInheritanceRelationship( yrt.ma->findJavaClass(objectref->jc->getClassName()), yrt.ma->findJavaClass(catchTypeName)) && exceptTab[i].startPC <= op && op < exceptTab[i].endPC) { // start<=op<end // If we found a proper exception handler, set current pc as // handlerPC of this exception table item; op = exceptTab[i].handlerPC - 1; return true; } if (exceptTab[i].catchType == 0) { op = exceptTab[i].handlerPC - 1; return true; } } return false; } JObject *Interpreter::execNew(const JavaClass *jc, u2 index) { yrt.ma->linkClassIfAbsent(const_cast<JavaClass *>(jc)->getClassName()); yrt.ma->initClassIfAbsent(*this, const_cast<JavaClass *>(jc)->getClassName()); if (typeid(*jc->raw.constPoolInfo[index]) != typeid(CONSTANT_Class)) { throw runtime_error( "operand index of new is not a class or " "interface\n"); } string className = jc->getString( dynamic_cast<CONSTANT_Class *>(jc->raw.constPoolInfo[index]) ->nameIndex); JavaClass *newClass = yrt.ma->loadClassIfAbsent(className); return yrt.jheap->createObject(*newClass); } bool Interpreter::checkInstanceof(const JavaClass *jc, u2 index, JType *objectref) { string TclassName = (char *)dynamic_cast<CONSTANT_Utf8 *>( jc->raw.constPoolInfo[dynamic_cast<CONSTANT_Class *>( jc->raw.constPoolInfo[index]) ->nameIndex]) ->bytes; constexpr short TYPE_ARRAY = 1; constexpr short TYPE_CLASS = 2; constexpr short TYPE_INTERFACE = 3; short tType = 0; if (TclassName.find('[') != string::npos) { tType = TYPE_ARRAY; } else { if (IS_CLASS_INTERFACE( yrt.ma->findJavaClass(TclassName)->raw.accessFlags)) { tType = TYPE_INTERFACE; } else { tType = TYPE_CLASS; } } if (typeid(objectref) == typeid(JObject)) { if (!IS_CLASS_INTERFACE( dynamic_cast<JObject *>(objectref)->jc->raw.accessFlags)) { // If it's an ordinary class if (tType == TYPE_CLASS) { if (yrt.ma->findJavaClass(dynamic_cast<JObject *>(objectref) ->jc->getClassName()) ->getClassName() == TclassName || yrt.ma->findJavaClass(dynamic_cast<JObject *>(objectref) ->jc->getSuperClassName()) ->getClassName() == TclassName) { return true; } } else if (tType == TYPE_INTERFACE) { auto &&interfaceIdxs = dynamic_cast<JObject *>(objectref) ->jc->getInterfacesIndex(); FOR_EACH(i, interfaceIdxs.size()) { string interfaceName = dynamic_cast<JObject *>(objectref)->jc->getString( dynamic_cast<CONSTANT_Class *>( dynamic_cast<JObject *>(objectref) ->jc->raw.constPoolInfo[interfaceIdxs[i]]) ->nameIndex); if (interfaceName == TclassName) { return true; } } } else { SHOULD_NOT_REACH_HERE } } else { // Otherwise, it's an interface class if (tType == TYPE_CLASS) { if (TclassName == "java/lang/Object") { return true; } } else if (tType == TYPE_INTERFACE) { if (TclassName == dynamic_cast<JObject *>(objectref) ->jc->getClassName() || TclassName == dynamic_cast<JObject *>(objectref) ->jc->getSuperClassName()) { return true; } } else { SHOULD_NOT_REACH_HERE } } } else if (typeid(objectref) == typeid(JArray)) { if (tType == TYPE_CLASS) { if (TclassName == "java/lang/Object") { return true; } } else if (tType == TYPE_INTERFACE) { auto *firstComponent = dynamic_cast<JObject *>( yrt.jheap->getElement(*dynamic_cast<JArray *>(objectref), 0)); auto &&interfaceIdxs = firstComponent->jc->getInterfacesIndex(); FOR_EACH(i, interfaceIdxs.size()) { if (firstComponent->jc->getString( dynamic_cast<CONSTANT_Class *>( firstComponent->jc->raw .constPoolInfo[interfaceIdxs[i]]) ->nameIndex) == TclassName) { return true; } } } else if (tType == TYPE_ARRAY) { throw runtime_error("to be continue\n"); } else { SHOULD_NOT_REACH_HERE } } else { SHOULD_NOT_REACH_HERE } } void Interpreter::pushMethodArguments(vector<int> &parameter, bool isObjectMethod) { if (parameter.size() > 0) { for (int localIndex = parameter.size() - (isObjectMethod ? 0 : 1), paramIndex = parameter.size() - 1; paramIndex >= 0; localIndex--, paramIndex--) { if (parameter[paramIndex] == T_INT || parameter[paramIndex] == T_BOOLEAN || parameter[paramIndex] == T_CHAR || parameter[paramIndex] == T_BYTE || parameter[paramIndex] == T_SHORT) { frames->top()->setLocalVariable( localIndex, frames->nextFrame()->pop<JInt>()); } else if (parameter[paramIndex] == T_FLOAT) { frames->top()->setLocalVariable( localIndex, frames->nextFrame()->pop<JFloat>()); } else if (parameter[paramIndex] == T_DOUBLE) { frames->top()->setLocalVariable( localIndex, frames->nextFrame()->pop<JDouble>()); } else if (parameter[paramIndex] == T_LONG) { frames->top()->setLocalVariable( localIndex, frames->nextFrame()->pop<JLong>()); } else if (parameter[paramIndex] == T_EXTRA_ARRAY) { frames->top()->setLocalVariable( localIndex, frames->nextFrame()->pop<JArray>()); } else if (parameter[paramIndex] == T_EXTRA_OBJECT) { frames->top()->setLocalVariable( localIndex, frames->nextFrame()->pop<JObject>()); } else { SHOULD_NOT_REACH_HERE; } } } if (isObjectMethod) { frames->top()->setLocalVariable(0, frames->nextFrame()->pop<JObject>()); } } //-------------------------------------------------------------------------------- // Invoke by given name, this method was be used internally //-------------------------------------------------------------------------------- void Interpreter::invokeByName(JavaClass *jc, const string &name, const string &descriptor) { const int returnType = get<0>(peelMethodParameterAndType(descriptor)); MethodInfo *m = jc->findMethod(name, descriptor); CallSite csite = CallSite::makeCallSite(jc, m); if (!csite.isCallable()) { return; } frames->pushFrame(csite.maxLocal, csite.maxStack); JType *returnValue{}; if (IS_METHOD_NATIVE(m->accessFlags)) { returnValue = cloneValue(execNativeMethod(jc->getClassName(), name, descriptor)); } else { returnValue = cloneValue(execByteCode(jc, csite.code, csite.codeLength, csite.exceptionLen, csite.exception)); } frames->popFrame(); // Since invokeByName() was merely used to call <clinit> and main method // of running program, therefore, if an exception reached here, we don't // need to push its value into upper frame again (In fact there is no more // frame), we just print stack trace inforamtion to notice user and // return directly if (returnType != T_EXTRA_VOID) { frames->top()->push(returnValue); } if (exception.hasUnhandledException()) { exception.extendExceptionStackTrace(name); exception.printStackTrace(); } GC_SAFE_POINT if (yrt.gc->shallGC()) { yrt.gc->stopTheWorld(); yrt.gc->gc(frames, GCPolicy::GC_MARK_AND_SWEEP); } } //-------------------------------------------------------------------------------- // Invoke interface method //-------------------------------------------------------------------------------- void Interpreter::invokeInterface(const JavaClass *jc, const string &name, const string &descriptor) { auto parameterAndReturnType = peelMethodParameterAndType(descriptor); const int returnType = get<0>(parameterAndReturnType); auto parameter = get<1>(parameterAndReturnType); auto csite = findInstanceMethod(jc, name, descriptor); if (!csite.isCallable()) { csite = findInstanceMethodOnSupers(jc, name, descriptor); if (!csite.isCallable()) { csite = findMaximallySpecifiedMethod(jc, name, descriptor); if (!csite.isCallable()) { throw runtime_error("can not find method " + name + " " + descriptor); } } } if (IS_METHOD_NATIVE(csite.accessFlags)) { csite.maxLocal = csite.maxStack = parameter.size() + 1; } frames->pushFrame(csite.maxLocal, csite.maxStack); pushMethodArguments(parameter, true); JType *returnValue{}; if (IS_METHOD_NATIVE(csite.accessFlags)) { returnValue = cloneValue( execNativeMethod(csite.jc->getClassName(), name, descriptor)); } else { returnValue = cloneValue(execByteCode(csite.jc, csite.code, csite.codeLength, csite.exceptionLen, csite.exception)); } frames->popFrame(); if (returnType != T_EXTRA_VOID) { frames->top()->push(returnValue); } if (exception.hasUnhandledException()) { frames->top()->grow(1); frames->top()->push(returnValue); if (exception.hasUnhandledException()) { exception.extendExceptionStackTrace(name); } } GC_SAFE_POINT if (yrt.gc->shallGC()) { yrt.gc->stopTheWorld(); yrt.gc->gc(frames, GCPolicy::GC_MARK_AND_SWEEP); } } //-------------------------------------------------------------------------------- // Invoke instance method; dispatch based on class //-------------------------------------------------------------------------------- void Interpreter::invokeVirtual(const string &name, const string &descriptor) { auto parameterAndReturnType = peelMethodParameterAndType(descriptor); const int returnType = get<0>(parameterAndReturnType); auto parameter = get<1>(parameterAndReturnType); auto *thisRef = (JObject *)frames->top() ->stackSlots[frames->top()->stackTop - parameter.size() - 1]; auto csite = findInstanceMethod(thisRef->jc, name, descriptor); if (!csite.isCallable()) { csite = findInstanceMethodOnSupers(thisRef->jc, name, descriptor); if (!csite.isCallable()) { csite = findMaximallySpecifiedMethod(thisRef->jc, name, descriptor); if (!csite.isCallable()) { throw runtime_error("can not find method " + name + " " + descriptor); } } } if (IS_METHOD_NATIVE(csite.accessFlags)) { csite.maxLocal = csite.maxStack = parameter.size() + 1; } frames->pushFrame(csite.maxLocal, csite.maxStack); pushMethodArguments(parameter, true); JType *returnValue{}; if (csite.isCallable()) { if (IS_METHOD_NATIVE(csite.accessFlags)) { returnValue = cloneValue( execNativeMethod(csite.jc->getClassName(), name, descriptor)); } else { returnValue = cloneValue(execByteCode(csite.jc, csite.code, csite.codeLength, csite.exceptionLen, csite.exception)); } } else { throw runtime_error("can not find method to call"); } frames->popFrame(); if (returnType != T_EXTRA_VOID) { frames->top()->push(returnValue); } if (exception.hasUnhandledException()) { frames->top()->grow(1); frames->top()->push(returnValue); if (exception.hasUnhandledException()) { exception.extendExceptionStackTrace(name); } } GC_SAFE_POINT if (yrt.gc->shallGC()) { yrt.gc->stopTheWorld(); yrt.gc->gc(frames, GCPolicy::GC_MARK_AND_SWEEP); } } //-------------------------------------------------------------------------------- // Invoke instance method; special handling for superclass, private, // and instance initialization method invocations //-------------------------------------------------------------------------------- void Interpreter::invokeSpecial(const JavaClass *jc, const string &name, const string &descriptor) { auto parameterAndReturnType = peelMethodParameterAndType(descriptor); const int returnType = get<0>(parameterAndReturnType); auto parameter = get<1>(parameterAndReturnType); auto csite = findInstanceMethod(jc, name, descriptor); if (!csite.isCallable()) { csite = findInstanceMethodOnSupers(jc, name, descriptor); if (!csite.isCallable()) { csite = findJavaLangObjectMethod(jc, name, descriptor); if (!csite.isCallable()) { csite = findMaximallySpecifiedMethod(jc, name, descriptor); if (!csite.isCallable()) { throw runtime_error("can not find method " + name + " " + descriptor); } } } } if (IS_METHOD_NATIVE(csite.accessFlags)) { csite.maxLocal = csite.maxStack = parameter.size() + 1; } frames->pushFrame(csite.maxLocal, csite.maxStack); pushMethodArguments(parameter, true); JType *returnValue{}; if (IS_METHOD_NATIVE(csite.accessFlags)) { returnValue = cloneValue( execNativeMethod(csite.jc->getClassName(), name, descriptor)); } else { returnValue = cloneValue(execByteCode(csite.jc, csite.code, csite.codeLength, csite.exceptionLen, csite.exception)); } frames->popFrame(); if (returnType != T_EXTRA_VOID) { frames->top()->push(returnValue); } if (exception.hasUnhandledException()) { frames->top()->grow(1); frames->top()->push(returnValue); if (exception.hasUnhandledException()) { exception.extendExceptionStackTrace(name); } } GC_SAFE_POINT if (yrt.gc->shallGC()) { yrt.gc->stopTheWorld(); yrt.gc->gc(frames, GCPolicy::GC_MARK_AND_SWEEP); } } void Interpreter::invokeStatic(const JavaClass *jc, const string &name, const string &descriptor) { // Get instance method name and descriptor from CONSTANT_Methodref // locating by index and get interface method parameter and return value // descriptor yrt.ma->linkClassIfAbsent(const_cast<JavaClass *>(jc)->getClassName()); yrt.ma->initClassIfAbsent(*this, const_cast<JavaClass *>(jc)->getClassName()); auto parameterAndReturnType = peelMethodParameterAndType(descriptor); const int returnType = get<0>(parameterAndReturnType); auto parameter = get<1>(parameterAndReturnType); auto csite = CallSite::makeCallSite(jc, jc->findMethod(name, descriptor)); if (!csite.isCallable()) { throw runtime_error("can not find method " + name + " " + descriptor); } assert(IS_METHOD_STATIC(csite.accessFlags) == true); assert(IS_METHOD_ABSTRACT(csite.accessFlags) == false); assert("<init>" != name); if (IS_METHOD_NATIVE(csite.accessFlags)) { csite.maxLocal = csite.maxStack = parameter.size(); } frames->pushFrame(csite.maxLocal, csite.maxStack); pushMethodArguments(parameter, false); JType *returnValue{}; if (IS_METHOD_NATIVE(csite.accessFlags)) { returnValue = cloneValue( execNativeMethod(csite.jc->getClassName(), name, descriptor)); } else { returnValue = cloneValue(execByteCode(csite.jc, csite.code, csite.codeLength, csite.exceptionLen, csite.exception)); } frames->popFrame(); if (returnType != T_EXTRA_VOID) { frames->top()->push(returnValue); } if (exception.hasUnhandledException()) { frames->top()->grow(1); frames->top()->push(returnValue); if (exception.hasUnhandledException()) { exception.extendExceptionStackTrace(name); } } GC_SAFE_POINT if (yrt.gc->shallGC()) { yrt.gc->stopTheWorld(); yrt.gc->gc(frames, GCPolicy::GC_MARK_AND_SWEEP); } }
40.104454
82
0.464178
5c1015809f4e4a48c90df6c135764a90c7f180dc
2,593
cpp
C++
OpenHolo_WRP/openwrp_console_ver 1.0/openwrp/WRP.cpp
KetiLeeJeongHun/OpenHologram
c6cdddb5106fe0079d9810eea588d28aa71f0023
[ "BSD-2-Clause" ]
17
2017-11-07T06:44:11.000Z
2021-11-14T05:06:08.000Z
OpenHolo_WRP/openwrp_console_ver 1.0/openwrp/WRP.cpp
KetiLeeJeongHun/OpenHologram
c6cdddb5106fe0079d9810eea588d28aa71f0023
[ "BSD-2-Clause" ]
1
2017-09-26T04:35:31.000Z
2017-09-26T04:35:31.000Z
OpenHolo_WRP/openwrp_console_ver 1.0/openwrp/WRP.cpp
KetiLeeJeongHun/OpenHologram
c6cdddb5106fe0079d9810eea588d28aa71f0023
[ "BSD-2-Clause" ]
9
2017-09-13T08:01:45.000Z
2020-04-28T10:11:14.000Z
#ifdef _OPENMP #include<omp.h> #endif #include "WRP.h" int OPHWRP::readxyz(string filename) //read point cloud { int dimen = 3; ifstream infilee(filename); string temp, temp2mat; vector <string> temsplit; if (!infilee) { cerr << "can not read the file"; return -1; } while (getline(infilee, temp)) { istringstream LineBand(temp); while (LineBand >> temp2mat) { // printf("temp2mat=%e\n", stof(temp2mat.data())); vec_xyz.push_back(stod(temp2mat.data())); } } int num = vec_xyz.size() / dimen; obj_num = num; cwoObjPoint *op = (cwoObjPoint*)malloc(num*sizeof(cwoObjPoint)); for (int i = 0; i < num; i++){ double x, y, z; x = vec_xyz.at(dimen*i); y = vec_xyz.at(dimen*i + 1); z = vec_xyz.at(dimen*i + 2); op[i].x = x; op[i].y = y; op[i].z = z; } obj = op; return 0; } int OPHWRP::Setparameter(float m_wavelength, float m_pixelpitch, float m_resolution) { SetWaveLength(m_wavelength); SetPitch(m_pixelpitch); SetDstPitch(m_pixelpitch); Create(m_resolution, m_resolution, 1); return 0; } int OPHWRP::Fresnelpropagation(float z) { Diffract(z, CWO_FRESNEL_CONV); return 0; } int OPHWRP::SavetoImage(char* filename) { SaveAsImage(filename, CWO_SAVE_AS_ARG); return 0; } void OPHWRP::SingleWRP(float z) //generate WRP plane { float wn = GetWaveNum(); float wl = GetWaveLength(); int Nx = GetNx(); int Ny = GetNy(); float spx = GetPx(); // float spy = GetPy(); float sox = GetOx();//point offset float soy = GetOy(); float soz = GetOz(); float dpx = GetDstPx();//wrp pitch float dpy = GetDstPy(); float dox = GetDstOx();//wrp offset float doy = GetDstOy(); int Nx_h = Nx >> 1; int Ny_h = Ny >> 1; cwoObjPoint *pc = obj; int num = obj_num; #ifdef _OPENMP omp_set_num_threads(GetThreads()); #pragma omp parallel for #endif for (int k = 0; k < num; k++){ float dz = z - pc[k].z; float tw = (int)fabs(wl*dz / dpx / dpx / 2 + 0.5) * 2 - 1; int w = (int)tw; int tx = (int)(pc[k].x / dpx) + Nx_h; int ty = (int)(pc[k].y / dpy) + Ny_h; printf("num=%d, tx=%d, ty=%d, w=%d\n", k, tx, ty, w); for (int wy = -w; wy < w; wy++){ for (int wx = -w; wx<w; wx++){//WRP coordinate double dx = wx*dpx; double dy = wy*dpy; double dz = z - pc[k].z; double sign = (dz>0.0) ? (1.0) : (-1.0); double r = sign*sqrt(dx*dx + dy*dy + dz*dz); cwoComplex tmp; CWO_RE(tmp) = cosf(wn*r) / (r + 0.05); CWO_IM(tmp) = sinf(wn*r) / (r + 0.05); if (tx + wx >= 0 && tx + wx < Nx && ty + wy >= 0 && ty + wy < Ny) AddPixel(wx + tx, wy + ty, tmp); } } } }
18.132867
84
0.59275
5c101ef567bb4dc304f721fc2f04dec87b513df2
5,698
hpp
C++
benchmarks/statistical/dataflow_declarations.hpp
vamatya/benchmarks
8a86c6eebac5f9a29a0e37a62bdace45395c8d73
[ "BSL-1.0" ]
null
null
null
benchmarks/statistical/dataflow_declarations.hpp
vamatya/benchmarks
8a86c6eebac5f9a29a0e37a62bdace45395c8d73
[ "BSL-1.0" ]
null
null
null
benchmarks/statistical/dataflow_declarations.hpp
vamatya/benchmarks
8a86c6eebac5f9a29a0e37a62bdace45395c8d73
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2012 Daniel Kogler // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) //this file simply enumerates a multitude of functions used to define the action //used in the benchmark. Which function is used is decided based on input args #include <hpx/hpx.hpp> #include <hpx/hpx_init.hpp> #include <hpx/include/lcos.hpp> #include <hpx/include/actions.hpp> #include <hpx/include/iostreams.hpp> #include <hpx/include/components.hpp> #include <hpx/util/high_resolution_timer.hpp> #include <hpx/components/dataflow/dataflow.hpp> #include <hpx/components/dataflow/dataflow_trigger.hpp> #include <vector> #include <string> using std::vector; using std::string; using boost::program_options::variables_map; using boost::program_options::options_description; using boost::uint64_t; using hpx::util::high_resolution_timer; using hpx::cout; using hpx::flush; //global dummy variables of several different primitive types int ivar = 1; long lvar = 1; float fvar = 1; double dvar = 1; /////////////////////////////////////////////////////////////////////////////// //forward declarations template <typename Vector, typename Package, typename Result> void run_empty(uint64_t number); /////////////////////////////////////////////////////////////////////////////// //empty functions for plain_result_actions template<typename A1> A1 empty_thread(){ A1 dummy = 0; return dummy; } template<typename A1> A1 empty_thread(A1 arg1){; return arg1; } template<typename A1> A1 empty_thread(A1 arg1, A1 arg2){ return arg2; } template<typename A1> A1 empty_thread(A1 arg1, A1 arg2, A1 arg3){ return arg3; } template<typename A1> A1 empty_thread(A1 arg1, A1 arg2, A1 arg3, A1 arg4){ return arg4; } typedef hpx::actions::plain_result_action0<int, empty_thread> empty_actioni0; HPX_REGISTER_PLAIN_ACTION(empty_actioni0); typedef hpx::actions::plain_result_action0<long, empty_thread> empty_actionl0; HPX_REGISTER_PLAIN_ACTION(empty_actionl0); typedef hpx::actions::plain_result_action0<float, empty_thread> empty_actionf0; HPX_REGISTER_PLAIN_ACTION(empty_actionf0); typedef hpx::actions::plain_result_action0<double, empty_thread> empty_actiond0; HPX_REGISTER_PLAIN_ACTION(empty_actiond0); typedef hpx::actions::plain_result_action1<int, int, empty_thread> empty_actioni1; HPX_REGISTER_PLAIN_ACTION(empty_actioni1); typedef hpx::actions::plain_result_action1<long, long, empty_thread> empty_actionl1; HPX_REGISTER_PLAIN_ACTION(empty_actionl1); typedef hpx::actions::plain_result_action1<float, float, empty_thread> empty_actionf1; HPX_REGISTER_PLAIN_ACTION(empty_actionf1); typedef hpx::actions::plain_result_action1<double, double, empty_thread> empty_actiond1; HPX_REGISTER_PLAIN_ACTION(empty_actiond1); typedef hpx::actions::plain_result_action2<int, int, int, empty_thread> empty_actioni2; HPX_REGISTER_PLAIN_ACTION(empty_actioni2); typedef hpx::actions::plain_result_action2<long, long, long, empty_thread> empty_actionl2; HPX_REGISTER_PLAIN_ACTION(empty_actionl2); typedef hpx::actions::plain_result_action2<float, float, float, empty_thread> empty_actionf2; HPX_REGISTER_PLAIN_ACTION(empty_actionf2); typedef hpx::actions::plain_result_action2<double, double, double, empty_thread> empty_actiond2; HPX_REGISTER_PLAIN_ACTION(empty_actiond2); typedef hpx::actions::plain_result_action3< int, int, int, int, empty_thread> empty_actioni3; HPX_REGISTER_PLAIN_ACTION(empty_actioni3); typedef hpx::actions::plain_result_action3< long, long, long, long, empty_thread> empty_actionl3; HPX_REGISTER_PLAIN_ACTION(empty_actionl3); typedef hpx::actions::plain_result_action3< float, float, float, float, empty_thread> empty_actionf3; HPX_REGISTER_PLAIN_ACTION(empty_actionf3); typedef hpx::actions::plain_result_action3< double, double, double, double, empty_thread> empty_actiond3; HPX_REGISTER_PLAIN_ACTION(empty_actiond3); typedef hpx::actions::plain_result_action4< int, int, int, int, int, empty_thread> empty_actioni4; HPX_REGISTER_PLAIN_ACTION(empty_actioni4); typedef hpx::actions::plain_result_action4< long, long, long, long, long, empty_thread> empty_actionl4; HPX_REGISTER_PLAIN_ACTION(empty_actionl4); typedef hpx::actions::plain_result_action4< float, float, float, float, float, empty_thread> empty_actionf4; HPX_REGISTER_PLAIN_ACTION(empty_actionf4); typedef hpx::actions::plain_result_action4< double, double, double, double, double, empty_thread> empty_actiond4; HPX_REGISTER_PLAIN_ACTION(empty_actiond4); typedef hpx::lcos::dataflow<empty_actioni0> eflowi0; typedef hpx::lcos::dataflow<empty_actionl0> eflowl0; typedef hpx::lcos::dataflow<empty_actionf0> eflowf0; typedef hpx::lcos::dataflow<empty_actiond0> eflowd0; typedef hpx::lcos::dataflow<empty_actioni1> eflowi1; typedef hpx::lcos::dataflow<empty_actionl1> eflowl1; typedef hpx::lcos::dataflow<empty_actionf1> eflowf1; typedef hpx::lcos::dataflow<empty_actiond1> eflowd1; typedef hpx::lcos::dataflow<empty_actioni2> eflowi2; typedef hpx::lcos::dataflow<empty_actionl2> eflowl2; typedef hpx::lcos::dataflow<empty_actionf2> eflowf2; typedef hpx::lcos::dataflow<empty_actiond2> eflowd2; typedef hpx::lcos::dataflow<empty_actioni3> eflowi3; typedef hpx::lcos::dataflow<empty_actionl3> eflowl3; typedef hpx::lcos::dataflow<empty_actionf3> eflowf3; typedef hpx::lcos::dataflow<empty_actiond3> eflowd3; typedef hpx::lcos::dataflow<empty_actioni4> eflowi4; typedef hpx::lcos::dataflow<empty_actionl4> eflowl4; typedef hpx::lcos::dataflow<empty_actionf4> eflowf4; typedef hpx::lcos::dataflow<empty_actiond4> eflowd4;
34.957055
81
0.777115
5c11ebf22b456bb03e0c41dc3f4f23c87a67614b
495
cpp
C++
source/lab4/classic_newton.cpp
Jovvik/methopt-lab-1
2c3acaf653c7214a925ed1292b9d1d30a33d2737
[ "Unlicense" ]
null
null
null
source/lab4/classic_newton.cpp
Jovvik/methopt-lab-1
2c3acaf653c7214a925ed1292b9d1d30a33d2737
[ "Unlicense" ]
null
null
null
source/lab4/classic_newton.cpp
Jovvik/methopt-lab-1
2c3acaf653c7214a925ed1292b9d1d30a33d2737
[ "Unlicense" ]
null
null
null
#include "lab4/classic_newton.h" #include <lab3/solver.h> #include <utility> #include "iostream" using namespace lab4; ClassicNewton::ClassicNewton() : p(lab2::Vector({1})) {} lab2::Vector ClassicNewton::iteration(lab2::NFunction& f, double) { lab2::Vector x = get_points().back(); p = lab3::Solver::solve(f.hessian(x), f.grad(x) * (-1)); return x + p; } bool ClassicNewton::is_done(lab2::NFunction&, double epsilon) const { return p.norm() < epsilon; }
23.571429
76
0.644444
5c1530cf4db20b54211ff2453e929b1abe998a88
564
cpp
C++
src/dummy_server/src/dummy_server_handler.cpp
maxerMU/db-course
3927f1cf0ccb2a937d571626dcc42d725a89d3f6
[ "Apache-2.0" ]
null
null
null
src/dummy_server/src/dummy_server_handler.cpp
maxerMU/db-course
3927f1cf0ccb2a937d571626dcc42d725a89d3f6
[ "Apache-2.0" ]
null
null
null
src/dummy_server/src/dummy_server_handler.cpp
maxerMU/db-course
3927f1cf0ccb2a937d571626dcc42d725a89d3f6
[ "Apache-2.0" ]
null
null
null
#include "dummy_server_handler.h" #include <iostream> DummyServerHandler::DummyServerHandler( const std::shared_ptr<BaseConfig> &config) { append_string = config->get_string_field({"AppendString"}); } void DummyServerHandler::handle_request(const std::shared_ptr<Request> &req) { std::cout << req->get_body() << std::endl; std::cout << req->get_target() << std::endl; req_body = req->get_body(); } void DummyServerHandler::make_response(const std::shared_ptr<Response> &resp) { std::string res = req_body + append_string; resp->set_body(res); }
29.684211
79
0.723404
5c1579f5da212410199c1703479b91eda172214f
54,852
cpp
C++
modules/juce_gui_basics/layout/juce_FlexBox.cpp
dikadk/JUCE
514c6c8de8bd34c0663d1d691a034b48922af5c8
[ "ISC" ]
null
null
null
modules/juce_gui_basics/layout/juce_FlexBox.cpp
dikadk/JUCE
514c6c8de8bd34c0663d1d691a034b48922af5c8
[ "ISC" ]
null
null
null
modules/juce_gui_basics/layout/juce_FlexBox.cpp
dikadk/JUCE
514c6c8de8bd34c0663d1d691a034b48922af5c8
[ "ISC" ]
null
null
null
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2020 - Raw Material Software Limited JUCE is an open source library subject to commercial or open-source licensing. By using JUCE, you agree to the terms of both the JUCE 6 End-User License Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020). End User License Agreement: www.juce.com/juce-6-licence Privacy Policy: www.juce.com/juce-privacy-policy Or: You may also use this code under the terms of the GPL v3 (see www.gnu.org/licenses). JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ namespace juce { struct FlexBoxLayoutCalculation { using Coord = double; enum class Axis { main, cross }; FlexBoxLayoutCalculation(FlexBox &fb, Coord w, Coord h) : owner(fb), parentWidth(w), parentHeight(h), numItems(owner.items.size()), isRowDirection(fb.flexDirection == FlexBox::Direction::row || fb.flexDirection == FlexBox::Direction::rowReverse), containerLineLength(getContainerSize(Axis::main)) { lineItems.calloc(numItems * numItems); lineInfo.calloc(numItems); } struct ItemWithState { ItemWithState(FlexItem &source) noexcept : item(&source) {} FlexItem *item; Coord lockedWidth = 0, lockedHeight = 0; Coord lockedMarginLeft = 0, lockedMarginRight = 0, lockedMarginTop = 0, lockedMarginBottom = 0; Coord preferredWidth = 0, preferredHeight = 0; bool locked = false; void resetItemLockedSize() noexcept { lockedWidth = preferredWidth; lockedHeight = preferredHeight; lockedMarginLeft = getValueOrZeroIfAuto(item->margin.left); lockedMarginRight = getValueOrZeroIfAuto(item->margin.right); lockedMarginTop = getValueOrZeroIfAuto(item->margin.top); lockedMarginBottom = getValueOrZeroIfAuto(item->margin.bottom); } }; struct RowInfo { int numItems; Coord crossSize, lineY, totalLength; }; FlexBox &owner; const Coord parentWidth, parentHeight; const int numItems; const bool isRowDirection; const Coord containerLineLength; int numberOfRows = 1; Coord containerCrossLength = 0; HeapBlock<ItemWithState *> lineItems; HeapBlock<RowInfo> lineInfo; Array<ItemWithState> itemStates; ItemWithState &getItem(int x, int y) const noexcept { return *lineItems[y * numItems + x]; } static bool isAuto(Coord value) noexcept { return value == FlexItem::autoValue; } static bool isAssigned(Coord value) noexcept { return value != FlexItem::notAssigned; } static Coord getValueOrZeroIfAuto(Coord value) noexcept { return isAuto(value) ? Coord() : value; } //============================================================================== bool isSingleLine() const { return owner.flexWrap == FlexBox::Wrap::noWrap; } template <typename Value> Value &pickForAxis(Axis axis, Value &x, Value &y) const { return (isRowDirection ? axis == Axis::main : axis == Axis::cross) ? x : y; } auto &getStartMargin(Axis axis, ItemWithState &item) const { return pickForAxis(axis, item.item->margin.left, item.item->margin.top); } auto &getEndMargin(Axis axis, ItemWithState &item) const { return pickForAxis(axis, item.item->margin.right, item.item->margin.bottom); } auto &getStartLockedMargin(Axis axis, ItemWithState &item) const { return pickForAxis(axis, item.lockedMarginLeft, item.lockedMarginTop); } auto &getEndLockedMargin(Axis axis, ItemWithState &item) const { return pickForAxis(axis, item.lockedMarginRight, item.lockedMarginBottom); } auto &getLockedSize(Axis axis, ItemWithState &item) const { return pickForAxis(axis, item.lockedWidth, item.lockedHeight); } auto &getPreferredSize(Axis axis, ItemWithState &item) const { return pickForAxis(axis, item.preferredWidth, item.preferredHeight); } Coord getContainerSize(Axis axis) const { return pickForAxis(axis, parentWidth, parentHeight); } auto &getItemSize(Axis axis, ItemWithState &item) const { return pickForAxis(axis, item.item->width, item.item->height); } auto &getMinSize(Axis axis, ItemWithState &item) const { return pickForAxis(axis, item.item->minWidth, item.item->minHeight); } auto &getMaxSize(Axis axis, ItemWithState &item) const { return pickForAxis(axis, item.item->maxWidth, item.item->maxHeight); } //============================================================================== void createStates() { itemStates.ensureStorageAllocated(numItems); for (auto &item : owner.items) itemStates.add(item); std::stable_sort(itemStates.begin(), itemStates.end(), [](const ItemWithState &i1, const ItemWithState &i2) { return i1.item->order < i2.item->order; }); for (auto &item : itemStates) { for (auto &axis : {Axis::main, Axis::cross}) getPreferredSize(axis, item) = computePreferredSize(axis, item); } } void initialiseItems() noexcept { if (isSingleLine()) // for single-line, all items go in line 1 { lineInfo[0].numItems = numItems; int i = 0; for (auto &item : itemStates) { item.resetItemLockedSize(); lineItems[i++] = &item; } } else // if multi-line, group the flexbox items into multiple lines { auto currentLength = containerLineLength; int column = 0, row = 0; bool firstRow = true; for (auto &item : itemStates) { item.resetItemLockedSize(); const auto flexitemLength = getItemMainSize(item); if (flexitemLength > currentLength) { if (!firstRow) row++; if (row >= numItems) break; column = 0; currentLength = containerLineLength; numberOfRows = jmax(numberOfRows, row + 1); } currentLength -= flexitemLength; lineItems[row * numItems + column] = &item; ++column; lineInfo[row].numItems = jmax(lineInfo[row].numItems, column); firstRow = false; } } } void resolveFlexibleLengths() noexcept { for (int row = 0; row < numberOfRows; ++row) { resetRowItems(row); for (int maxLoops = numItems; --maxLoops >= 0;) { resetUnlockedRowItems(row); if (layoutRowItems(row)) break; } } } void resolveAutoMarginsOnMainAxis() noexcept { for (int row = 0; row < numberOfRows; ++row) { Coord allFlexGrow = 0; const auto numColumns = lineInfo[row].numItems; const auto remainingLength = containerLineLength - lineInfo[row].totalLength; for (int column = 0; column < numColumns; ++column) { auto &item = getItem(column, row); if (isAuto(getStartMargin(Axis::main, item))) ++allFlexGrow; if (isAuto(getEndMargin(Axis::main, item))) ++allFlexGrow; } const auto changeUnitWidth = remainingLength / allFlexGrow; if (changeUnitWidth > 0) { for (int column = 0; column < numColumns; ++column) { auto &item = getItem(column, row); if (isAuto(getStartMargin(Axis::main, item))) getStartLockedMargin(Axis::main, item) = changeUnitWidth; if (isAuto(getEndMargin(Axis::main, item))) getEndLockedMargin(Axis::main, item) = changeUnitWidth; } } } } void calculateCrossSizesByLine() noexcept { // https://www.w3.org/TR/css-flexbox-1/#algo-cross-line // If the flex container is single-line and has a definite cross size, the cross size of the // flex line is the flex container’s inner cross size. if (isSingleLine()) { lineInfo[0].crossSize = getContainerSize(Axis::cross); } else { for (int row = 0; row < numberOfRows; ++row) { Coord maxSize = 0; const auto numColumns = lineInfo[row].numItems; for (int column = 0; column < numColumns; ++column) maxSize = jmax(maxSize, getItemCrossSize(getItem(column, row))); lineInfo[row].crossSize = maxSize; } } } void calculateCrossSizeOfAllItems() noexcept { for (int row = 0; row < numberOfRows; ++row) { const auto numColumns = lineInfo[row].numItems; for (int column = 0; column < numColumns; ++column) { auto &item = getItem(column, row); if (isAssigned(item.item->maxHeight) && item.lockedHeight > item.item->maxHeight) item.lockedHeight = item.item->maxHeight; if (isAssigned(item.item->maxWidth) && item.lockedWidth > item.item->maxWidth) item.lockedWidth = item.item->maxWidth; } } } void alignLinesPerAlignContent() noexcept { containerCrossLength = getContainerSize(Axis::cross); if (owner.alignContent == FlexBox::AlignContent::flexStart) { for (int row = 0; row < numberOfRows; ++row) for (int row2 = row; row2 < numberOfRows; ++row2) lineInfo[row].lineY = row == 0 ? 0 : lineInfo[row - 1].lineY + lineInfo[row - 1].crossSize; } else if (owner.alignContent == FlexBox::AlignContent::flexEnd) { for (int row = 0; row < numberOfRows; ++row) { Coord crossHeights = 0; for (int row2 = row; row2 < numberOfRows; ++row2) crossHeights += lineInfo[row2].crossSize; lineInfo[row].lineY = containerCrossLength - crossHeights; } } else { Coord totalHeight = 0; for (int row = 0; row < numberOfRows; ++row) totalHeight += lineInfo[row].crossSize; if (owner.alignContent == FlexBox::AlignContent::stretch) { const auto difference = jmax(Coord(), (containerCrossLength - totalHeight) / numberOfRows); for (int row = 0; row < numberOfRows; ++row) { lineInfo[row].crossSize += difference; lineInfo[row].lineY = row == 0 ? 0 : lineInfo[row - 1].lineY + lineInfo[row - 1].crossSize; } } else if (owner.alignContent == FlexBox::AlignContent::center) { const auto additionalength = (containerCrossLength - totalHeight) / 2; for (int row = 0; row < numberOfRows; ++row) lineInfo[row].lineY = row == 0 ? additionalength : lineInfo[row - 1].lineY + lineInfo[row - 1].crossSize; } else if (owner.alignContent == FlexBox::AlignContent::spaceBetween) { const auto additionalength = numberOfRows <= 1 ? Coord() : jmax(Coord(), (containerCrossLength - totalHeight) / static_cast<Coord>(numberOfRows - 1)); lineInfo[0].lineY = 0; for (int row = 1; row < numberOfRows; ++row) lineInfo[row].lineY += additionalength + lineInfo[row - 1].lineY + lineInfo[row - 1].crossSize; } else if (owner.alignContent == FlexBox::AlignContent::spaceAround) { const auto additionalength = numberOfRows <= 1 ? Coord() : jmax(Coord(), (containerCrossLength - totalHeight) / static_cast<Coord>(2 + (2 * (numberOfRows - 1)))); lineInfo[0].lineY = additionalength; for (int row = 1; row < numberOfRows; ++row) lineInfo[row].lineY += (2 * additionalength) + lineInfo[row - 1].lineY + lineInfo[row - 1].crossSize; } } } void resolveAutoMarginsOnCrossAxis() noexcept { for (int row = 0; row < numberOfRows; ++row) { const auto numColumns = lineInfo[row].numItems; const auto crossSizeForLine = lineInfo[row].crossSize; for (int column = 0; column < numColumns; ++column) { auto &item = getItem(column, row); getStartLockedMargin(Axis::cross, item) = [&] { if (isAuto(getStartMargin(Axis::cross, item)) && isAuto(getEndMargin(Axis::cross, item))) return (crossSizeForLine - getLockedSize(Axis::cross, item)) / 2; if (isAuto(getStartMargin(Axis::cross, item))) return crossSizeForLine - getLockedSize(Axis::cross, item) - getEndMargin(Axis::cross, item); return getStartLockedMargin(Axis::cross, item); }(); } } } // Align all flex items along the cross-axis per align-self, if neither of the item’s cross-axis margins are auto. void alignItemsInCrossAxisInLinesPerAlignSelf() noexcept { for (int row = 0; row < numberOfRows; ++row) { const auto numColumns = lineInfo[row].numItems; const auto lineSize = lineInfo[row].crossSize; for (int column = 0; column < numColumns; ++column) { auto &item = getItem(column, row); if (isAuto(getStartMargin(Axis::cross, item)) || isAuto(getEndMargin(Axis::cross, item))) continue; const auto alignment = [&] { switch (item.item->alignSelf) { case FlexItem::AlignSelf::stretch: return FlexBox::AlignItems::stretch; case FlexItem::AlignSelf::flexStart: return FlexBox::AlignItems::flexStart; case FlexItem::AlignSelf::flexEnd: return FlexBox::AlignItems::flexEnd; case FlexItem::AlignSelf::center: return FlexBox::AlignItems::center; case FlexItem::AlignSelf::autoAlign: break; } return owner.alignItems; }(); getStartLockedMargin(Axis::cross, item) = [&] { switch (alignment) { // https://www.w3.org/TR/css-flexbox-1/#valdef-align-items-flex-start // The cross-start margin edge of the flex item is placed flush with the // cross-start edge of the line. case FlexBox::AlignItems::flexStart: return (Coord)getStartMargin(Axis::cross, item); // https://www.w3.org/TR/css-flexbox-1/#valdef-align-items-flex-end // The cross-end margin edge of the flex item is placed flush with the cross-end // edge of the line. case FlexBox::AlignItems::flexEnd: return lineSize - getLockedSize(Axis::cross, item) - getEndMargin(Axis::cross, item); // https://www.w3.org/TR/css-flexbox-1/#valdef-align-items-center // The flex item’s margin box is centered in the cross axis within the line. case FlexBox::AlignItems::center: return getStartMargin(Axis::cross, item) + (lineSize - getLockedSize(Axis::cross, item) - getStartMargin(Axis::cross, item) - getEndMargin(Axis::cross, item)) / 2; // https://www.w3.org/TR/css-flexbox-1/#valdef-align-items-stretch case FlexBox::AlignItems::stretch: return (Coord)getStartMargin(Axis::cross, item); } jassertfalse; return 0.0; }(); if (alignment == FlexBox::AlignItems::stretch) { auto newSize = isAssigned(getItemSize(Axis::cross, item)) ? computePreferredSize(Axis::cross, item) : lineSize - getStartMargin(Axis::cross, item) - getEndMargin(Axis::cross, item); if (isAssigned(getMaxSize(Axis::cross, item))) newSize = jmin(newSize, (Coord)getMaxSize(Axis::cross, item)); if (isAssigned(getMinSize(Axis::cross, item))) newSize = jmax(newSize, (Coord)getMinSize(Axis::cross, item)); getLockedSize(Axis::cross, item) = newSize; } } } } void alignItemsByJustifyContent() noexcept { Coord additionalMarginRight = 0, additionalMarginLeft = 0; recalculateTotalItemLengthPerLineArray(); for (int row = 0; row < numberOfRows; ++row) { const auto numColumns = lineInfo[row].numItems; Coord x = 0; if (owner.justifyContent == FlexBox::JustifyContent::flexEnd) { x = containerLineLength - lineInfo[row].totalLength; } else if (owner.justifyContent == FlexBox::JustifyContent::center) { x = (containerLineLength - lineInfo[row].totalLength) / 2; } else if (owner.justifyContent == FlexBox::JustifyContent::spaceBetween) { additionalMarginRight = jmax(Coord(), (containerLineLength - lineInfo[row].totalLength) / jmax(1, numColumns - 1)); } else if (owner.justifyContent == FlexBox::JustifyContent::spaceAround) { additionalMarginLeft = additionalMarginRight = jmax(Coord(), (containerLineLength - lineInfo[row].totalLength) / jmax(1, 2 * numColumns)); } for (int column = 0; column < numColumns; ++column) { auto &item = getItem(column, row); getStartLockedMargin(Axis::main, item) += additionalMarginLeft; getEndLockedMargin(Axis::main, item) += additionalMarginRight; item.item->currentBounds.setPosition(isRowDirection ? (float)(x + item.lockedMarginLeft) : (float)item.lockedMarginLeft, isRowDirection ? (float)item.lockedMarginTop : (float)(x + item.lockedMarginTop)); x += getItemMainSize(item); } } } void layoutAllItems() noexcept { for (int row = 0; row < numberOfRows; ++row) { const auto lineY = lineInfo[row].lineY; const auto numColumns = lineInfo[row].numItems; for (int column = 0; column < numColumns; ++column) { auto &item = getItem(column, row); if (isRowDirection) item.item->currentBounds.setY((float)(lineY + item.lockedMarginTop)); else item.item->currentBounds.setX((float)(lineY + item.lockedMarginLeft)); item.item->currentBounds.setSize((float)item.lockedWidth, (float)item.lockedHeight); } } reverseLocations(); reverseWrap(); } private: void resetRowItems(const int row) noexcept { const auto numColumns = lineInfo[row].numItems; for (int column = 0; column < numColumns; ++column) resetItem(getItem(column, row)); } void resetUnlockedRowItems(const int row) noexcept { const auto numColumns = lineInfo[row].numItems; for (int column = 0; column < numColumns; ++column) { auto &item = getItem(column, row); if (!item.locked) resetItem(item); } } void resetItem(ItemWithState &item) noexcept { item.locked = false; for (auto &axis : {Axis::main, Axis::cross}) getLockedSize(axis, item) = computePreferredSize(axis, item); } bool layoutRowItems(const int row) noexcept { const auto numColumns = lineInfo[row].numItems; auto flexContainerLength = containerLineLength; Coord totalItemsLength = 0, totalFlexGrow = 0, totalFlexShrink = 0; for (int column = 0; column < numColumns; ++column) { const auto &item = getItem(column, row); if (item.locked) { flexContainerLength -= getItemMainSize(item); } else { totalItemsLength += getItemMainSize(item); totalFlexGrow += item.item->flexGrow; totalFlexShrink += item.item->flexShrink; } } Coord changeUnit = 0; const auto difference = flexContainerLength - totalItemsLength; const bool positiveFlexibility = difference > 0; if (positiveFlexibility) { if (totalFlexGrow != 0.0) changeUnit = difference / totalFlexGrow; } else { if (totalFlexShrink != 0.0) changeUnit = difference / totalFlexShrink; } bool ok = true; for (int column = 0; column < numColumns; ++column) { auto &item = getItem(column, row); if (!item.locked) if (!addToItemLength(item, (positiveFlexibility ? item.item->flexGrow : item.item->flexShrink) * changeUnit, row)) ok = false; } return ok; } void recalculateTotalItemLengthPerLineArray() noexcept { for (int row = 0; row < numberOfRows; ++row) { lineInfo[row].totalLength = 0; const auto numColumns = lineInfo[row].numItems; for (int column = 0; column < numColumns; ++column) lineInfo[row].totalLength += getItemMainSize(getItem(column, row)); } } void reverseLocations() noexcept { if (owner.flexDirection == FlexBox::Direction::rowReverse) { for (auto &item : owner.items) item.currentBounds.setX((float)(containerLineLength - item.currentBounds.getRight())); } else if (owner.flexDirection == FlexBox::Direction::columnReverse) { for (auto &item : owner.items) item.currentBounds.setY((float)(containerLineLength - item.currentBounds.getBottom())); } } void reverseWrap() noexcept { if (owner.flexWrap == FlexBox::Wrap::wrapReverse) { if (isRowDirection) { for (auto &item : owner.items) item.currentBounds.setY((float)(containerCrossLength - item.currentBounds.getBottom())); } else { for (auto &item : owner.items) item.currentBounds.setX((float)(containerCrossLength - item.currentBounds.getRight())); } } } Coord getItemMainSize(const ItemWithState &item) const noexcept { return isRowDirection ? item.lockedWidth + item.lockedMarginLeft + item.lockedMarginRight : item.lockedHeight + item.lockedMarginTop + item.lockedMarginBottom; } Coord getItemCrossSize(const ItemWithState &item) const noexcept { return isRowDirection ? item.lockedHeight + item.lockedMarginTop + item.lockedMarginBottom : item.lockedWidth + item.lockedMarginLeft + item.lockedMarginRight; } bool addToItemLength(ItemWithState &item, const Coord length, int row) const noexcept { bool ok = false; const auto prefSize = computePreferredSize(Axis::main, item); const auto pickForMainAxis = [this](auto &a, auto &b) -> auto & { return pickForAxis(Axis::main, a, b); }; if (isAssigned(pickForMainAxis(item.item->maxWidth, item.item->maxHeight)) && pickForMainAxis(item.item->maxWidth, item.item->maxHeight) < prefSize + length) { pickForMainAxis(item.lockedWidth, item.lockedHeight) = pickForMainAxis(item.item->maxWidth, item.item->maxHeight); item.locked = true; } else if (isAssigned(prefSize) && pickForMainAxis(item.item->minWidth, item.item->minHeight) > prefSize + length) { pickForMainAxis(item.lockedWidth, item.lockedHeight) = pickForMainAxis(item.item->minWidth, item.item->minHeight); item.locked = true; } else { ok = true; pickForMainAxis(item.lockedWidth, item.lockedHeight) = prefSize + length; } lineInfo[row].totalLength += pickForMainAxis(item.lockedWidth, item.lockedHeight) + pickForMainAxis(item.lockedMarginLeft, item.lockedMarginTop) + pickForMainAxis(item.lockedMarginRight, item.lockedMarginBottom); return ok; } Coord computePreferredSize(Axis axis, ItemWithState &itemWithState) const noexcept { const auto &item = *itemWithState.item; auto preferredSize = (item.flexBasis > 0 && axis == Axis::main) ? item.flexBasis : (isAssigned(getItemSize(axis, itemWithState)) ? getItemSize(axis, itemWithState) : getMinSize(axis, itemWithState)); const auto minSize = getMinSize(axis, itemWithState); if (isAssigned(minSize) && preferredSize < minSize) return minSize; const auto maxSize = getMaxSize(axis, itemWithState); if (isAssigned(maxSize) && maxSize < preferredSize) return maxSize; return preferredSize; } }; //============================================================================== FlexBox::FlexBox() noexcept = default; FlexBox::~FlexBox() noexcept = default; FlexBox::FlexBox(JustifyContent jc) noexcept : justifyContent(jc) {} FlexBox::FlexBox(Direction d, Wrap w, AlignContent ac, AlignItems ai, JustifyContent jc) noexcept : flexDirection(d), flexWrap(w), alignContent(ac), alignItems(ai), justifyContent(jc) { } void FlexBox::performLayout(Rectangle<float> targetArea) { if (!items.isEmpty()) { FlexBoxLayoutCalculation layout(*this, targetArea.getWidth(), targetArea.getHeight()); layout.createStates(); layout.initialiseItems(); layout.resolveFlexibleLengths(); layout.resolveAutoMarginsOnMainAxis(); layout.calculateCrossSizesByLine(); layout.calculateCrossSizeOfAllItems(); layout.alignLinesPerAlignContent(); layout.resolveAutoMarginsOnCrossAxis(); layout.alignItemsInCrossAxisInLinesPerAlignSelf(); layout.alignItemsByJustifyContent(); layout.layoutAllItems(); for (auto &item : items) { item.currentBounds += targetArea.getPosition(); if (auto *comp = item.associatedComponent) comp->setBounds(Rectangle<int>::leftTopRightBottom((int)item.currentBounds.getX(), (int)item.currentBounds.getY(), (int)item.currentBounds.getRight(), (int)item.currentBounds.getBottom())); if (auto *box = item.associatedFlexBox) box->performLayout(item.currentBounds); } } } void FlexBox::performLayout(Rectangle<int> targetArea) { performLayout(targetArea.toFloat()); } //============================================================================== FlexItem::FlexItem() noexcept {} FlexItem::FlexItem(float w, float h) noexcept : currentBounds(w, h), minWidth(w), minHeight(h) {} FlexItem::FlexItem(float w, float h, Component &c) noexcept : FlexItem(w, h) { associatedComponent = &c; } FlexItem::FlexItem(float w, float h, FlexBox &fb) noexcept : FlexItem(w, h) { associatedFlexBox = &fb; } FlexItem::FlexItem(Component &c) noexcept : associatedComponent(&c) {} FlexItem::FlexItem(FlexBox &fb) noexcept : associatedFlexBox(&fb) {} FlexItem::Margin::Margin() noexcept : left(), right(), top(), bottom() {} FlexItem::Margin::Margin(float v) noexcept : left(v), right(v), top(v), bottom(v) {} FlexItem::Margin::Margin(float t, float r, float b, float l) noexcept : left(l), right(r), top(t), bottom(b) {} //============================================================================== FlexItem FlexItem::withFlex(float newFlexGrow) const noexcept { auto fi = *this; fi.flexGrow = newFlexGrow; return fi; } FlexItem FlexItem::withFlex(float newFlexGrow, float newFlexShrink) const noexcept { auto fi = withFlex(newFlexGrow); fi.flexShrink = newFlexShrink; return fi; } FlexItem FlexItem::withFlex(float newFlexGrow, float newFlexShrink, float newFlexBasis) const noexcept { auto fi = withFlex(newFlexGrow, newFlexShrink); fi.flexBasis = newFlexBasis; return fi; } FlexItem FlexItem::withWidth(float newWidth) const noexcept { auto fi = *this; fi.width = newWidth; return fi; } FlexItem FlexItem::withMinWidth(float newMinWidth) const noexcept { auto fi = *this; fi.minWidth = newMinWidth; return fi; } FlexItem FlexItem::withMaxWidth(float newMaxWidth) const noexcept { auto fi = *this; fi.maxWidth = newMaxWidth; return fi; } FlexItem FlexItem::withMinHeight(float newMinHeight) const noexcept { auto fi = *this; fi.minHeight = newMinHeight; return fi; } FlexItem FlexItem::withMaxHeight(float newMaxHeight) const noexcept { auto fi = *this; fi.maxHeight = newMaxHeight; return fi; } FlexItem FlexItem::withHeight(float newHeight) const noexcept { auto fi = *this; fi.height = newHeight; return fi; } FlexItem FlexItem::withMargin(Margin m) const noexcept { auto fi = *this; fi.margin = m; return fi; } FlexItem FlexItem::withOrder(int newOrder) const noexcept { auto fi = *this; fi.order = newOrder; return fi; } FlexItem FlexItem::withAlignSelf(AlignSelf a) const noexcept { auto fi = *this; fi.alignSelf = a; return fi; } //============================================================================== //============================================================================== #if JUCE_UNIT_TESTS class FlexBoxTests : public UnitTest { public: FlexBoxTests() : UnitTest("FlexBox", UnitTestCategories::gui) {} void runTest() override { using AlignSelf = FlexItem::AlignSelf; using Direction = FlexBox::Direction; const Rectangle<float> rect(10.0f, 20.0f, 300.0f, 200.0f); const auto doLayout = [&rect](Direction direction, Array<FlexItem> items) { juce::FlexBox flex; flex.flexDirection = direction; flex.items = std::move(items); flex.performLayout(rect); return flex; }; beginTest("flex item with mostly auto properties"); { const auto test = [this, &doLayout](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds) { const auto flex = doLayout(direction, {juce::FlexItem{}.withAlignSelf(alignment)}); expect(flex.items.getFirst().currentBounds == expectedBounds); }; test(Direction::row, AlignSelf::autoAlign, {rect.getX(), rect.getY(), 0.0f, rect.getHeight()}); test(Direction::row, AlignSelf::stretch, {rect.getX(), rect.getY(), 0.0f, rect.getHeight()}); test(Direction::row, AlignSelf::flexStart, {rect.getX(), rect.getY(), 0.0f, 0.0f}); test(Direction::row, AlignSelf::flexEnd, {rect.getX(), rect.getBottom(), 0.0f, 0.0f}); test(Direction::row, AlignSelf::center, {rect.getX(), rect.getCentreY(), 0.0f, 0.0f}); test(Direction::column, AlignSelf::autoAlign, {rect.getX(), rect.getY(), rect.getWidth(), 0.0f}); test(Direction::column, AlignSelf::stretch, {rect.getX(), rect.getY(), rect.getWidth(), 0.0f}); test(Direction::column, AlignSelf::flexStart, {rect.getX(), rect.getY(), 0.0f, 0.0f}); test(Direction::column, AlignSelf::flexEnd, {rect.getRight(), rect.getY(), 0.0f, 0.0f}); test(Direction::column, AlignSelf::center, {rect.getCentreX(), rect.getY(), 0.0f, 0.0f}); } beginTest("flex item with specified width and height"); { constexpr auto w = 50.0f; constexpr auto h = 60.0f; const auto test = [&](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds) { const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withWidth(w).withHeight(h)}); expect(flex.items.getFirst().currentBounds == expectedBounds); }; test(Direction::row, AlignSelf::autoAlign, {rect.getX(), rect.getY(), w, h}); test(Direction::row, AlignSelf::stretch, {rect.getX(), rect.getY(), w, h}); test(Direction::row, AlignSelf::flexStart, {rect.getX(), rect.getY(), w, h}); test(Direction::row, AlignSelf::flexEnd, {rect.getX(), rect.getBottom() - h, w, h}); test(Direction::row, AlignSelf::center, {rect.getX(), rect.getY() + (rect.getHeight() - h) * 0.5f, w, h}); test(Direction::column, AlignSelf::autoAlign, {rect.getX(), rect.getY(), w, h}); test(Direction::column, AlignSelf::stretch, {rect.getX(), rect.getY(), w, h}); test(Direction::column, AlignSelf::flexStart, {rect.getX(), rect.getY(), w, h}); test(Direction::column, AlignSelf::flexEnd, {rect.getRight() - w, rect.getY(), w, h}); test(Direction::column, AlignSelf::center, {rect.getX() + (rect.getWidth() - w) * 0.5f, rect.getY(), w, h}); } beginTest("flex item with oversized width and height"); { const auto w = rect.getWidth() * 2; const auto h = rect.getHeight() * 2; const auto test = [this, &doLayout, &w, &h](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds) { const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withWidth(w).withHeight(h)}); expect(flex.items.getFirst().currentBounds == expectedBounds); }; const Rectangle<float> baseRow(rect.getX(), rect.getY(), rect.getWidth(), h); test(Direction::row, AlignSelf::autoAlign, baseRow); test(Direction::row, AlignSelf::stretch, baseRow); test(Direction::row, AlignSelf::flexStart, baseRow); test(Direction::row, AlignSelf::flexEnd, baseRow.withBottomY(rect.getBottom())); test(Direction::row, AlignSelf::center, baseRow.withCentre(rect.getCentre())); const Rectangle<float> baseColumn(rect.getX(), rect.getY(), w, rect.getHeight()); test(Direction::column, AlignSelf::autoAlign, baseColumn); test(Direction::column, AlignSelf::stretch, baseColumn); test(Direction::column, AlignSelf::flexStart, baseColumn); test(Direction::column, AlignSelf::flexEnd, baseColumn.withRightX(rect.getRight())); test(Direction::column, AlignSelf::center, baseColumn.withCentre(rect.getCentre())); } beginTest("flex item with minimum width and height"); { constexpr auto w = 50.0f; constexpr auto h = 60.0f; const auto test = [&](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds) { const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withMinWidth(w).withMinHeight(h)}); expect(flex.items.getFirst().currentBounds == expectedBounds); }; test(Direction::row, AlignSelf::autoAlign, {rect.getX(), rect.getY(), w, rect.getHeight()}); test(Direction::row, AlignSelf::stretch, {rect.getX(), rect.getY(), w, rect.getHeight()}); test(Direction::row, AlignSelf::flexStart, {rect.getX(), rect.getY(), w, h}); test(Direction::row, AlignSelf::flexEnd, {rect.getX(), rect.getBottom() - h, w, h}); test(Direction::row, AlignSelf::center, {rect.getX(), rect.getY() + (rect.getHeight() - h) * 0.5f, w, h}); test(Direction::column, AlignSelf::autoAlign, {rect.getX(), rect.getY(), rect.getWidth(), h}); test(Direction::column, AlignSelf::stretch, {rect.getX(), rect.getY(), rect.getWidth(), h}); test(Direction::column, AlignSelf::flexStart, {rect.getX(), rect.getY(), w, h}); test(Direction::column, AlignSelf::flexEnd, {rect.getRight() - w, rect.getY(), w, h}); test(Direction::column, AlignSelf::center, {rect.getX() + (rect.getWidth() - w) * 0.5f, rect.getY(), w, h}); } beginTest("flex item with maximum width and height"); { constexpr auto w = 50.0f; constexpr auto h = 60.0f; const auto test = [&](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds) { const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withMaxWidth(w).withMaxHeight(h)}); expect(flex.items.getFirst().currentBounds == expectedBounds); }; test(Direction::row, AlignSelf::autoAlign, {rect.getX(), rect.getY(), 0.0f, h}); test(Direction::row, AlignSelf::stretch, {rect.getX(), rect.getY(), 0.0f, h}); test(Direction::row, AlignSelf::flexStart, {rect.getX(), rect.getY(), 0.0f, 0.0f}); test(Direction::row, AlignSelf::flexEnd, {rect.getX(), rect.getBottom(), 0.0f, 0.0f}); test(Direction::row, AlignSelf::center, {rect.getX(), rect.getCentreY(), 0.0f, 0.0f}); test(Direction::column, AlignSelf::autoAlign, {rect.getX(), rect.getY(), w, 0.0f}); test(Direction::column, AlignSelf::stretch, {rect.getX(), rect.getY(), w, 0.0f}); test(Direction::column, AlignSelf::flexStart, {rect.getX(), rect.getY(), 0.0f, 0.0f}); test(Direction::column, AlignSelf::flexEnd, {rect.getRight(), rect.getY(), 0.0f, 0.0f}); test(Direction::column, AlignSelf::center, {rect.getCentreX(), rect.getY(), 0.0f, 0.0f}); } beginTest("flex item with specified flex"); { const auto test = [this, &doLayout](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds) { const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withFlex(1.0f)}); expect(flex.items.getFirst().currentBounds == expectedBounds); }; test(Direction::row, AlignSelf::autoAlign, {rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight()}); test(Direction::row, AlignSelf::stretch, {rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight()}); test(Direction::row, AlignSelf::flexStart, {rect.getX(), rect.getY(), rect.getWidth(), 0.0f}); test(Direction::row, AlignSelf::flexEnd, {rect.getX(), rect.getBottom(), rect.getWidth(), 0.0f}); test(Direction::row, AlignSelf::center, {rect.getX(), rect.getCentreY(), rect.getWidth(), 0.0f}); test(Direction::column, AlignSelf::autoAlign, {rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight()}); test(Direction::column, AlignSelf::stretch, {rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight()}); test(Direction::column, AlignSelf::flexStart, {rect.getX(), rect.getY(), 0.0f, rect.getHeight()}); test(Direction::column, AlignSelf::flexEnd, {rect.getRight(), rect.getY(), 0.0f, rect.getHeight()}); test(Direction::column, AlignSelf::center, {rect.getCentreX(), rect.getY(), 0.0f, rect.getHeight()}); } beginTest("flex item with margin"); { const FlexItem::Margin margin(10.0f, 20.0f, 30.0f, 40.0f); const auto test = [this, &doLayout, &margin](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds) { const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withMargin(margin)}); expect(flex.items.getFirst().currentBounds == expectedBounds); }; const auto remainingHeight = rect.getHeight() - margin.top - margin.bottom; const auto remainingWidth = rect.getWidth() - margin.left - margin.right; test(Direction::row, AlignSelf::autoAlign, {rect.getX() + margin.left, rect.getY() + margin.top, 0.0f, remainingHeight}); test(Direction::row, AlignSelf::stretch, {rect.getX() + margin.left, rect.getY() + margin.top, 0.0f, remainingHeight}); test(Direction::row, AlignSelf::flexStart, {rect.getX() + margin.left, rect.getY() + margin.top, 0.0f, 0.0f}); test(Direction::row, AlignSelf::flexEnd, {rect.getX() + margin.left, rect.getBottom() - margin.bottom, 0.0f, 0.0f}); test(Direction::row, AlignSelf::center, {rect.getX() + margin.left, rect.getY() + margin.top + remainingHeight * 0.5f, 0.0f, 0.0f}); test(Direction::column, AlignSelf::autoAlign, {rect.getX() + margin.left, rect.getY() + margin.top, remainingWidth, 0.0f}); test(Direction::column, AlignSelf::stretch, {rect.getX() + margin.left, rect.getY() + margin.top, remainingWidth, 0.0f}); test(Direction::column, AlignSelf::flexStart, {rect.getX() + margin.left, rect.getY() + margin.top, 0.0f, 0.0f}); test(Direction::column, AlignSelf::flexEnd, {rect.getRight() - margin.right, rect.getY() + margin.top, 0.0f, 0.0f}); test(Direction::column, AlignSelf::center, {rect.getX() + margin.left + remainingWidth * 0.5f, rect.getY() + margin.top, 0.0f, 0.0f}); } const AlignSelf alignments[]{AlignSelf::autoAlign, AlignSelf::stretch, AlignSelf::flexStart, AlignSelf::flexEnd, AlignSelf::center}; beginTest("flex item with auto margin"); { for (const auto &alignment : alignments) { for (const auto &direction : {Direction::row, Direction::column}) { const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withMargin((float)FlexItem::autoValue)}); expect(flex.items.getFirst().currentBounds == Rectangle<float>(rect.getCentre(), rect.getCentre())); } } const auto testTop = [this, &doLayout](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds) { const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withMargin({(float)FlexItem::autoValue, 0.0f, 0.0f, 0.0f})}); expect(flex.items.getFirst().currentBounds == expectedBounds); }; for (const auto &alignment : alignments) testTop(Direction::row, alignment, {rect.getX(), rect.getBottom(), 0.0f, 0.0f}); testTop(Direction::column, AlignSelf::autoAlign, {rect.getX(), rect.getBottom(), rect.getWidth(), 0.0f}); testTop(Direction::column, AlignSelf::stretch, {rect.getX(), rect.getBottom(), rect.getWidth(), 0.0f}); testTop(Direction::column, AlignSelf::flexStart, {rect.getX(), rect.getBottom(), 0.0f, 0.0f}); testTop(Direction::column, AlignSelf::flexEnd, {rect.getRight(), rect.getBottom(), 0.0f, 0.0f}); testTop(Direction::column, AlignSelf::center, {rect.getCentreX(), rect.getBottom(), 0.0f, 0.0f}); const auto testBottom = [this, &doLayout](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds) { const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withMargin({0.0f, 0.0f, (float)FlexItem::autoValue, 0.0f})}); expect(flex.items.getFirst().currentBounds == expectedBounds); }; for (const auto &alignment : alignments) testBottom(Direction::row, alignment, {rect.getX(), rect.getY(), 0.0f, 0.0f}); testBottom(Direction::column, AlignSelf::autoAlign, {rect.getX(), rect.getY(), rect.getWidth(), 0.0f}); testBottom(Direction::column, AlignSelf::stretch, {rect.getX(), rect.getY(), rect.getWidth(), 0.0f}); testBottom(Direction::column, AlignSelf::flexStart, {rect.getX(), rect.getY(), 0.0f, 0.0f}); testBottom(Direction::column, AlignSelf::flexEnd, {rect.getRight(), rect.getY(), 0.0f, 0.0f}); testBottom(Direction::column, AlignSelf::center, {rect.getCentreX(), rect.getY(), 0.0f, 0.0f}); const auto testLeft = [this, &doLayout](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds) { const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withMargin({0.0f, 0.0f, 0.0f, (float)FlexItem::autoValue})}); expect(flex.items.getFirst().currentBounds == expectedBounds); }; testLeft(Direction::row, AlignSelf::autoAlign, {rect.getRight(), rect.getY(), 0.0f, rect.getHeight()}); testLeft(Direction::row, AlignSelf::stretch, {rect.getRight(), rect.getY(), 0.0f, rect.getHeight()}); testLeft(Direction::row, AlignSelf::flexStart, {rect.getRight(), rect.getY(), 0.0f, 0.0f}); testLeft(Direction::row, AlignSelf::flexEnd, {rect.getRight(), rect.getBottom(), 0.0f, 0.0f}); testLeft(Direction::row, AlignSelf::center, {rect.getRight(), rect.getCentreY(), 0.0f, 0.0f}); for (const auto &alignment : alignments) testLeft(Direction::column, alignment, {rect.getRight(), rect.getY(), 0.0f, 0.0f}); const auto testRight = [this, &doLayout](Direction direction, AlignSelf alignment, Rectangle<float> expectedBounds) { const auto flex = doLayout(direction, {juce::FlexItem().withAlignSelf(alignment).withMargin({0.0f, (float)FlexItem::autoValue, 0.0f, 0.0f})}); expect(flex.items.getFirst().currentBounds == expectedBounds); }; testRight(Direction::row, AlignSelf::autoAlign, {rect.getX(), rect.getY(), 0.0f, rect.getHeight()}); testRight(Direction::row, AlignSelf::stretch, {rect.getX(), rect.getY(), 0.0f, rect.getHeight()}); testRight(Direction::row, AlignSelf::flexStart, {rect.getX(), rect.getY(), 0.0f, 0.0f}); testRight(Direction::row, AlignSelf::flexEnd, {rect.getX(), rect.getBottom(), 0.0f, 0.0f}); testRight(Direction::row, AlignSelf::center, {rect.getX(), rect.getCentreY(), 0.0f, 0.0f}); for (const auto &alignment : alignments) testRight(Direction::column, alignment, {rect.getX(), rect.getY(), 0.0f, 0.0f}); } beginTest("in a multiline layout, items too large to fit on the main axis are given a line to themselves"); { const auto spacer = 10.0f; for (const auto alignment : alignments) { juce::FlexBox flex; flex.flexWrap = FlexBox::Wrap::wrap; flex.items = {FlexItem().withAlignSelf(alignment).withWidth(spacer).withHeight(spacer), FlexItem().withAlignSelf(alignment).withWidth(rect.getWidth() * 2).withHeight(rect.getHeight()), FlexItem().withAlignSelf(alignment).withWidth(spacer).withHeight(spacer)}; flex.performLayout(rect); expect(flex.items[0].currentBounds == Rectangle<float>(rect.getX(), rect.getY(), spacer, spacer)); expect(flex.items[1].currentBounds == Rectangle<float>(rect.getX(), rect.getY() + spacer, rect.getWidth(), rect.getHeight())); expect(flex.items[2].currentBounds == Rectangle<float>(rect.getX(), rect.getBottom() + spacer, 10.0f, 10.0f)); } } } }; static FlexBoxTests flexBoxTests; #endif } // namespace juce
46.563667
225
0.518887
5c1d185ee8efa07f9a35db7b874ca2d7bd117211
483
cpp
C++
ZorkGame/ZorkGame/ZorkGame.cpp
PabloSanchezTrujillo/Zork
f861f56df8c37a126c9f90147efbc75c91a04f47
[ "MIT" ]
null
null
null
ZorkGame/ZorkGame/ZorkGame.cpp
PabloSanchezTrujillo/Zork
f861f56df8c37a126c9f90147efbc75c91a04f47
[ "MIT" ]
null
null
null
ZorkGame/ZorkGame/ZorkGame.cpp
PabloSanchezTrujillo/Zork
f861f56df8c37a126c9f90147efbc75c91a04f47
[ "MIT" ]
null
null
null
#include <iostream> #include "World.h" using namespace std; int main() { World* house = new World(); cout << "You are in the: " << house->getPlayer()->getLocation()->getName() << ". " << house->getPlayer()->getLocation()->getDescription() << endl; cout << "\n"; // GameLoop while(!house->getPlayer()->isPlayerOutside()) { for(Entity* entity : house->getEntities()) { entity->update(); } } cout << "The end." << endl; cout << "\n"; system("pause"); return 0; }
19.32
83
0.594203
5c1dbca35795cb3a90df53cc6d6c751addffd42a
452
cpp
C++
misc.cpp
bannid/CardGame
c5df2adb7a96df506fa24544cd8499076bb3ebbc
[ "Zlib" ]
null
null
null
misc.cpp
bannid/CardGame
c5df2adb7a96df506fa24544cd8499076bb3ebbc
[ "Zlib" ]
null
null
null
misc.cpp
bannid/CardGame
c5df2adb7a96df506fa24544cd8499076bb3ebbc
[ "Zlib" ]
null
null
null
#include "misc.h" float LinearInterpolation(float first, float second, float weight){ float result = weight * second + (1.0f - weight) * first; return result; } float CosineInterpolation(float first, float second, float weight){ float modifiedWeight = (1 - cos(weight * 3.14))/2.0f; modifiedWeight = pow(modifiedWeight, 0.2f); float result = modifiedWeight * second + (1.0f - modifiedWeight) * first; return result; }
28.25
78
0.679204
5c1dd2542f6af6e2d960967edc4454c44d4afaa9
4,650
cpp
C++
tests/core/RemoteNodeTest.cpp
cybergarage/round-cc
13fb5c39e9bc14a4ad19f9a63d8d97ddda475ca1
[ "BSD-3-Clause" ]
null
null
null
tests/core/RemoteNodeTest.cpp
cybergarage/round-cc
13fb5c39e9bc14a4ad19f9a63d8d97ddda475ca1
[ "BSD-3-Clause" ]
null
null
null
tests/core/RemoteNodeTest.cpp
cybergarage/round-cc
13fb5c39e9bc14a4ad19f9a63d8d97ddda475ca1
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************** * * Round for C++ * * Copyright (C) Satoshi Konno 2015 * * This is licensed under BSD-style license, see file COPYING. * ******************************************************************/ #include <boost/test/unit_test.hpp> #include <sstream> #include <string.h> #include <round/core/RemoteNode.h> #include <round/Server.h> #include "TestNode.h" #include "TestServer.h" using namespace std; using namespace Round; BOOST_AUTO_TEST_SUITE(node) BOOST_AUTO_TEST_CASE(RoundRemoteNodeConstructorTest) { for (int n = 0; n < 200; n+=10) { stringstream addr; addr << n << "." << n << "." << n << "." << n; RemoteNode remoteNode(addr.str(), n); Error error; std::string remoteAddr; BOOST_CHECK(remoteNode.getRequestAddress(&remoteAddr, &error)); BOOST_CHECK_EQUAL(addr.str().compare(remoteAddr), 0); int remotePort; BOOST_CHECK(remoteNode.getRequestPort(&remotePort, &error)); BOOST_CHECK_EQUAL(n, remotePort); BOOST_CHECK_EQUAL(remoteNode.hasClusterName(), false); } } BOOST_AUTO_TEST_CASE(RoundRemoteNodeCopyConstructorTest) { for (int n = 0; n < 200; n+=10) { stringstream addr; addr << n << "." << n << "." << n << "." << n; RemoteNode testNode(addr.str(), n); RemoteNode remoteNode(&testNode); Error error; std::string remoteAddr; BOOST_CHECK(remoteNode.getRequestAddress(&remoteAddr, &error)); BOOST_CHECK_EQUAL(addr.str().compare(remoteAddr), 0); int remotePort; BOOST_CHECK(remoteNode.getRequestPort(&remotePort, &error)); BOOST_CHECK_EQUAL(n, remotePort); BOOST_CHECK_EQUAL(remoteNode.hasClusterName(), false); } } BOOST_AUTO_TEST_CASE(RoundRemoteNodeSetterTest) { for (int n = 0; n < 200; n+=10) { RemoteNode remoteNode; stringstream addr; addr << n << "." << n << "." << n << "." << n; BOOST_CHECK(remoteNode.setRequestAddress(addr.str())); int port = n; BOOST_CHECK(remoteNode.setRequestPort(port)); stringstream cluster; cluster << "cluster" << n; BOOST_CHECK(remoteNode.setClusterName(cluster.str())); Error error; std::string remoteAddr; BOOST_CHECK(remoteNode.getRequestAddress(&remoteAddr, &error)); BOOST_CHECK_EQUAL(addr.str().compare(remoteAddr), 0); int remotePort; BOOST_CHECK(remoteNode.getRequestPort(&remotePort, &error)); BOOST_CHECK_EQUAL(port, remotePort); std::string remoteCluster; BOOST_CHECK(remoteNode.getClusterName(&remoteCluster, &error)); BOOST_CHECK_EQUAL(cluster.str().compare(remoteCluster), 0); } } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE(rpc) BOOST_AUTO_TEST_CASE(RemoteNodeScriptManagerTest) { Error err; TestServer serverNode; BOOST_CHECK(serverNode.start(&err)); std::string serverIp; BOOST_CHECK(serverNode.getRequestAddress(&serverIp, &err)); int serverPort; BOOST_CHECK(serverNode.getRequestPort(&serverPort, &err)); RemoteNode node(serverIp, serverPort); NodeTestController nodeTestController; nodeTestController.runScriptManagerTest(&node); BOOST_CHECK(serverNode.stop(&err)); } BOOST_AUTO_TEST_CASE(RemoteNodeAliasManagerTest) { Error err; TestServer serverNode; BOOST_CHECK(serverNode.start(&err)); std::string serverIp; BOOST_CHECK(serverNode.getRequestAddress(&serverIp, &err)); int serverPort; BOOST_CHECK(serverNode.getRequestPort(&serverPort, &err)); RemoteNode node(serverIp, serverPort); NodeTestController nodeTestController; nodeTestController.runAliasManagerTest(&node); BOOST_CHECK(serverNode.stop(&err)); } BOOST_AUTO_TEST_CASE(RemoteNodeRouteManagerTest) { Error err; TestServer serverNode; BOOST_CHECK(serverNode.start(&err)); std::string serverIp; BOOST_CHECK(serverNode.getRequestAddress(&serverIp, &err)); int serverPort; BOOST_CHECK(serverNode.getRequestPort(&serverPort, &err)); RemoteNode node(serverIp, serverPort); NodeTestController nodeTestController; nodeTestController.runRouteManagerTest(&node); BOOST_CHECK(serverNode.stop(&err)); } BOOST_AUTO_TEST_CASE(RemoteNodeSystemMethodTest) { Error err; TestServer serverNode; BOOST_CHECK(serverNode.start(&err)); std::string serverIp; BOOST_CHECK(serverNode.getRequestAddress(&serverIp, &err)); int serverPort; BOOST_CHECK(serverNode.getRequestPort(&serverPort, &err)); RemoteNode node(serverIp, serverPort); NodeTestController nodeTestController; nodeTestController.runSystemMethodTest(&node); BOOST_CHECK(serverNode.stop(&err)); } BOOST_AUTO_TEST_SUITE_END()
25.690608
68
0.693763
5c201c7101b0d40c9e79c696d239e37debac77e5
826
cpp
C++
LeetCode/338.Counting_Bits.cpp
w181496/OJ
67d1d32770376865eba8a9dd1767e97dae68989a
[ "MIT" ]
9
2017-10-08T16:22:03.000Z
2021-08-20T09:32:17.000Z
LeetCode/338.Counting_Bits.cpp
w181496/OJ
67d1d32770376865eba8a9dd1767e97dae68989a
[ "MIT" ]
null
null
null
LeetCode/338.Counting_Bits.cpp
w181496/OJ
67d1d32770376865eba8a9dd1767e97dae68989a
[ "MIT" ]
2
2018-01-15T16:35:44.000Z
2019-03-21T18:30:04.000Z
class Solution { public: vector<int> countBits(int num) { vector<int>ans; int two[30]; int now; int SIZE = 30; two[0] = 1; for(int i = 1; i < SIZE; i++) two[i] = two[i - 1] * 2; ans.push_back(0); if(num == 0) return ans; ans.push_back(1); if(num == 1) return ans; for(int i = 2; i <= num; i++) { bool flag = false; for(int j = 0; j < SIZE; j++) { if(two[j] == i) { ans.push_back(1); flag = true; break; } else if(i > two[j]) { now = two[j]; } } if(!flag) ans.push_back(ans[i - now] + 1); } return ans; } };
25.030303
54
0.349879
5c2593ad5f628d6b76fbef2e0291fcc06a85e5bd
618
cxx
C++
phys-services/private/phys-services/I3FileOMKey2MBIDFactory.cxx
hschwane/offline_production
e14a6493782f613b8bbe64217559765d5213dc1e
[ "MIT" ]
1
2020-12-24T22:00:01.000Z
2020-12-24T22:00:01.000Z
phys-services/private/phys-services/I3FileOMKey2MBIDFactory.cxx
hschwane/offline_production
e14a6493782f613b8bbe64217559765d5213dc1e
[ "MIT" ]
null
null
null
phys-services/private/phys-services/I3FileOMKey2MBIDFactory.cxx
hschwane/offline_production
e14a6493782f613b8bbe64217559765d5213dc1e
[ "MIT" ]
3
2020-07-17T09:20:29.000Z
2021-03-30T16:44:18.000Z
#include "phys-services/I3FileOMKey2MBIDFactory.h" #include "phys-services/I3FileOMKey2MBID.h" I3_SERVICE_FACTORY(I3FileOMKey2MBIDFactory); I3FileOMKey2MBIDFactory::I3FileOMKey2MBIDFactory(const I3Context& context) : I3ServiceFactory(context) { AddParameter("Infile", "The file to read the OMKey to MBID conversions", infile_); } bool I3FileOMKey2MBIDFactory::InstallService(I3Context& services) { if(!service_) service_ = I3OMKey2MBIDPtr ( new I3FileOMKey2MBID(infile_)); return services.Put(service_); } void I3FileOMKey2MBIDFactory::Configure() { GetParameter("Infile",infile_); }
23.769231
74
0.770227
5c26e96cdadb3a82867cfd4e722783b4e51e1851
4,730
cpp
C++
Test/NfcCxTests/Simulation/NciHciDataPacket.cpp
Bhaskers-Blu-Org2/NFC-Class-Extension-Driver
77c80d6d2c8f7876e68e3df847a926a045d81711
[ "MIT" ]
32
2015-11-19T07:23:11.000Z
2019-04-08T18:50:08.000Z
Test/NfcCxTests/Simulation/NciHciDataPacket.cpp
Bhaskers-Blu-Org2/NFC-Class-Extension-Driver
77c80d6d2c8f7876e68e3df847a926a045d81711
[ "MIT" ]
33
2015-11-12T08:23:52.000Z
2018-12-06T02:34:07.000Z
Test/NfcCxTests/Simulation/NciHciDataPacket.cpp
Microsoft/NFC-Class-Extension-Driver
77c80d6d2c8f7876e68e3df847a926a045d81711
[ "MIT" ]
28
2015-08-11T14:34:10.000Z
2018-07-26T14:15:53.000Z
// // Copyright (c) Microsoft Corporation. All Rights Reserved // #include "Precomp.h" #include <array> #include "NciHciDataPacket.h" NciHciDataPacket::NciHciDataPacket( _In_ uint8_t connectionId, _In_ uint8_t pipeId, _In_ phHciNfc_MsgType_t messageType, _In_ uint8_t instruction, _In_ std::initializer_list<uint8_t> payload) : NciHciDataPacket(connectionId, pipeId, messageType, instruction, payload.begin(), uint8_t(payload.size()), true) { } NciHciDataPacket::NciHciDataPacket( _In_ uint8_t connectionId, _In_ uint8_t pipeId, _In_ phHciNfc_MsgType_t messageType, _In_ uint8_t instruction, _In_ std::initializer_list<uint8_t> payload, _In_ bool finalPacket) : NciHciDataPacket(connectionId, pipeId, messageType, instruction, payload.begin(), uint8_t(payload.size()), finalPacket) { } NciHciDataPacket::NciHciDataPacket( _In_ uint8_t connectionId, _In_ uint8_t pipeId, _In_ phHciNfc_MsgType_t messageType, _In_ uint8_t instruction, _In_reads_(payloadLength) const uint8_t* payload, _In_ uint8_t payloadLength, _In_ bool finalPacket) : NciDataPacket(connectionId, GenerateFirstPacket(pipeId, messageType, instruction, payload, payloadLength, finalPacket).data(), CalculateFirstPacketLength(payloadLength), true) { } NciHciDataPacket::NciHciDataPacket( _In_ uint8_t connectionId, _In_ uint8_t pipeId, _In_ std::initializer_list<uint8_t> payload) : NciHciDataPacket(connectionId, pipeId, payload.begin(), uint8_t(payload.size()), true) { } NciHciDataPacket::NciHciDataPacket( _In_ uint8_t connectionId, _In_ uint8_t pipeId, _In_ std::initializer_list<uint8_t> payload, _In_ bool finalPacket) : NciHciDataPacket(connectionId, pipeId, payload.begin(), uint8_t(payload.size()), finalPacket) { } NciHciDataPacket::NciHciDataPacket( _In_ uint8_t connectionId, _In_ uint8_t pipeId, _In_reads_(payloadLength) const uint8_t* payload, _In_ uint8_t payloadLength, _In_ bool finalPacket) : NciDataPacket(connectionId, GenerateSubsequentPacket(pipeId, payload, payloadLength, finalPacket).data(), CalculateSubsequentPacketLength(payloadLength), true) { } constexpr uint8_t NciHciDataPacket::GenerateHcpHeader(bool isFinalPacket, uint8_t pipeId) { // ETSI Host Controller Interface (HCI), Version 12.1.0, Section 5.1, HCP packets constexpr uint8_t chainBit = 0x80; // bit 8 constexpr uint8_t instructionMask = 0x7F; // bits [0,7] return (isFinalPacket ? chainBit : 0x00) | (pipeId & instructionMask); } std::array<uint8_t, NciPacketRaw::MaxPayloadLength> NciHciDataPacket::GenerateFirstPacket( _In_ uint8_t pipeId, _In_ phHciNfc_MsgType_t messageType, _In_ uint8_t instruction, _In_reads_(payloadLength) const uint8_t* payload, _In_ uint8_t payloadLength, _In_ bool finalPacket) { std::array<uint8_t, NciPacketRaw::MaxPayloadLength> packet = {}; // Add HCP packet header packet[0] = GenerateHcpHeader(finalPacket, pipeId); // Add HCP message header // ETSI Host Controller Interface (HCI), Version 12.1.0, Section 5.2, HCP message structure constexpr uint8_t messageTypeBitShift = 6; constexpr uint8_t messageTypeBitMask = 0xC0; // bits [7,8] constexpr uint8_t instructionBitMask = 0x3F; // bits [0,6] packet[1] = ((messageType << messageTypeBitShift) & messageTypeBitMask) | (instruction & instructionBitMask); // Ensure HCI payload isn't too big. if (payloadLength > NciHciDataPacket::MaxFirstPayloadSize) { throw std::exception("NciHciDataPacket payload is too big."); } // Copy payload. std::copy(payload, payload + payloadLength, packet.data() + 2); return packet; } constexpr uint8_t NciHciDataPacket::CalculateFirstPacketLength(uint8_t payloadLength) { return payloadLength + 2; // Add 2 bytes for HCP header + HCP message header } std::array<uint8_t, NciPacketRaw::MaxPayloadLength> NciHciDataPacket::GenerateSubsequentPacket( _In_ uint8_t pipeId, _In_reads_(payloadLength) const uint8_t* payload, _In_ uint8_t payloadLength, _In_ bool finalPacket) { std::array<uint8_t, NciPacketRaw::MaxPayloadLength> packet = {}; // Add HCP packet header packet[0] = GenerateHcpHeader(finalPacket, pipeId); if (payloadLength > NciHciDataPacket::MaxSubsequentPayloadSize) { throw std::exception("NciHciDataPacket payload is too big."); } std::copy(payload, payload + payloadLength, packet.data() + 1); return packet; } constexpr uint8_t NciHciDataPacket::CalculateSubsequentPacketLength(uint8_t payloadLength) { return payloadLength + 1; // Add 1 byte for HCP header }
30.915033
179
0.734672
5c271252cbafd78ad5faa7c1951f52283703ad04
3,350
hpp
C++
src/ExtFilterEventListClustering/DBusNumericUtil.hpp
voxie-viewer/voxie
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
[ "MIT" ]
4
2016-06-03T18:41:43.000Z
2020-04-17T20:28:58.000Z
src/ExtFilterEventListClustering/DBusNumericUtil.hpp
voxie-viewer/voxie
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
[ "MIT" ]
null
null
null
src/ExtFilterEventListClustering/DBusNumericUtil.hpp
voxie-viewer/voxie
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
[ "MIT" ]
null
null
null
/* * Copyright (c) 2014-2022 The Voxie Authors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once #include <VoxieClient/DBusUtil.hpp> #include <QtDBus/QDBusArgument> #include <QtDBus/QDBusVariant> namespace vx { namespace DBusNumericUtilIntern { template <typename ValueType, typename ResultType> bool dbusTryGetNumberFromArgumentValue(const QDBusArgument& arg, ResultType& result) { if (dbusGetSignature<ValueType>() == dbusGetArgumentSignature(arg)) { result = static_cast<ResultType>(dbusGetArgumentValueUnchecked<ValueType>(arg)); return true; } else { return false; } } template <typename ValueType, typename ResultType> bool dbusTryGetNumber(const QVariant& var, ResultType& result) { if (var.userType() == qMetaTypeId<QDBusArgument>()) { QDBusArgument arg = var.value<QDBusArgument>(); return dbusTryGetNumberFromArgumentValue<ValueType>(arg, result); } else if (var.userType() == qMetaTypeId<ValueType>()) { result = static_cast<ResultType>(var.value<ValueType>()); return true; } else { return false; } } } // namespace DBusNumericUtilIntern // Helper function for extracting any-type numbers from DBus variants and // converting them to the desired target type template <typename T> T dbusGetNumber(const QDBusVariant& variant) { using namespace DBusNumericUtilIntern; QVariant qVariant = variant.variant(); T result = T(); // Try every numeric type bool success = dbusTryGetNumber<double>(qVariant, result) || dbusTryGetNumber<qint64>(qVariant, result) || dbusTryGetNumber<quint64>(qVariant, result) || dbusTryGetNumber<qint32>(qVariant, result) || dbusTryGetNumber<quint32>(qVariant, result) || dbusTryGetNumber<qint16>(qVariant, result) || dbusTryGetNumber<quint16>(qVariant, result) || dbusTryGetNumber<quint8>(qVariant, result) || dbusTryGetNumber<bool>(qVariant, result); if (success) { return result; } else { throw Exception( "de.uni_stuttgart.Voxie.Error", QString() + "Unexpected DBus variant, expected a numeric type, got " + QMetaType::typeName(qVariant.userType())); } } } // namespace vx
36.413043
80
0.702687
5c28e1034573a00ce52b97665327d13d08dae8f1
126
cpp
C++
chapter_4/ex_4.12.cpp
YasserKa/Cpp_Primer
198b10255fd67e31c15423a5e44b7f02abb8bdc2
[ "MIT" ]
null
null
null
chapter_4/ex_4.12.cpp
YasserKa/Cpp_Primer
198b10255fd67e31c15423a5e44b7f02abb8bdc2
[ "MIT" ]
null
null
null
chapter_4/ex_4.12.cpp
YasserKa/Cpp_Primer
198b10255fd67e31c15423a5e44b7f02abb8bdc2
[ "MIT" ]
null
null
null
/** * i != (j < k) * i != (true/false) * i != (0/1) * It means checking if i is 1 or 0 which is resulted from j < k */
15.75
64
0.484127
5c2a0e0b5db3dd339cf779e28b84ec2b4392f540
8,773
cc
C++
game.cc
therealsachin/player-isolation
f564734cae052ceb3aacbd83fb57bbce7a8e80a1
[ "MIT" ]
null
null
null
game.cc
therealsachin/player-isolation
f564734cae052ceb3aacbd83fb57bbce7a8e80a1
[ "MIT" ]
null
null
null
game.cc
therealsachin/player-isolation
f564734cae052ceb3aacbd83fb57bbce7a8e80a1
[ "MIT" ]
null
null
null
// The MIT License (MIT) // Copyright (c) 2016 Sachin Shenoy // Player Isolation is a game played between two players, on a 5 by 5 // grid. The first player, player one, has white tokens, while player // two has black token. The game starts by player one placing a white // token on one of the 25 squares. After that, player two places black // token on one of the empty squares. Further on each player, places // another of their token, making one of the possible queen type move // from their current token position. This movement, can't jump any // already existing tokens. The first player who cannot play a legal // move (during their turn) loses. #include <stdio.h> #include <iostream> #include <queue> using namespace std; // Value to mark that the cell is out of valid board range. const char BORDER = 5; // Value to mark that the cell is empty. const char EMPTY = 0; // Value to mark that the cell is occupied by player one. const char P1 = 1; // Value to mark that the cell is occupied by player two. const char P2 = 2; const int LOSS_VALUE = -1000; const int WIN_VALUE = +1000; const int INF = 1000000; const int MOVES[] = {1, -1, 7, -7, 6, -6, 8, -8}; const int SCORE_PER_CELL = 16; // Helper macros. #define OPPONENT(p) ((p == P1) ? P2 : P1) #define PLAYER(p) ((p == P1) ? '1' : '2') #define POS_TO_X(pos) ((pos - 8) / 7) #define POS_TO_Y(pos) ((pos - 8) % 7) #define XY_TO_POS(x, y) (x*7+y+8) #define DEBUG(x) ; class Board { public: char board[49]; int p1; int p2; Board(); bool hasLost(int i); bool isLegal(int x, int y); void play(int x, int y, char player); void printBoard(); void printPossibleMoves(char player); }; Board::Board() { for (int i=0; i<7; ++i) { board[0*7+i] = board[i*7+0] = board[6*7+i] = board[i*7+6] = BORDER; } for (int i=1; i<6; ++i) { for (int j=1; j<6; ++j) { board[i*7+j] = EMPTY; } } p1 = p2 = 0; } bool Board::isLegal(int x, int y) { return board[x*7+y+8] == EMPTY; } void Board::play(int x, int y, char player) { int pos = x*7+y+8; board[pos] = player; if (player == P1) p1 = pos; else p2 = pos; } void Board::printBoard() { for (int i=1; i<6; ++i) { cout << "| "; for (int j=1; j<6; ++j) { char cell = board[i*7+j]; if (cell == 0) { cout << " | "; } else { if (p1 == i*7+j || p2 == i*7+j) { cout << PLAYER(cell) << " | "; } else { cout << "X | "; } } } cout << endl; } } bool Board::hasLost(int i) { if (i == 0) return false; if (board[i+1] == 0 || board[i-1] == 0 || board[i+7] == 0 || board[i-7] == 0 || board[i+6] == 0 || board[i-6] == 0 || board[i+8] == 0 || board[i-8] == 0) return false; return true; } class Mirror { public: int getMove(Board* board, char player, int max_depth); private: Board* board; }; int Mirror::getMove(Board* board, char player, int max_depth) { this->board = board; int pp = (player == P1) ? board->p2 : board->p1; int px = POS_TO_X(pp); int py = POS_TO_Y(pp); int x = 4 - px; int y = 4 - py; return XY_TO_POS(x, y); } class Scorer { public: virtual int getScore(Board* board, char player) = 0; }; class DijkstraScorer : public Scorer { public: int getScore(Board* board, char player); private: int dijkstra(Board* board, char player); }; int DijkstraScorer::getScore(Board* board, char player) { return dijkstra(board, player) - dijkstra(board, OPPONENT(player)); } int DijkstraScorer::dijkstra(Board* board, char player) { queue<int> q; int steps[49]; for (int i = 0; i < 49; ++i) steps[i] = -1; int total_cells = 0; int total_steps = 0; int pos = (player == P1) ? board->p1 : board->p2; q.push(pos); steps[pos] = 0; while (!q.empty()) { int pos = q.front(); q.pop(); total_steps += steps[pos]; total_cells += 1; int step = steps[pos] + 1; for (int i = 0; i < 8; ++i) { int move = MOVES[i]; int p = pos; while (true) { p += move; char& cell = board->board[p]; if (cell != EMPTY) { break; } if (steps[p] != -1) { break; } steps[p] = step; q.push(p); } } } return total_cells * SCORE_PER_CELL - total_steps; } class Negamax { public: Negamax(); Negamax(Scorer* scorer); int getMove(Board* board, char player, int max_depth); int depth_count; private: Board* board; Scorer* scorer; int max_depth; int negamax(int ap_pos, int pp_pos, int depth, int alpha, int beta, int* best_move); void printDebug(int depth, const string& action, int score); void printMove(int depth, int x, int y); bool hasLost(int pos) { return board->hasLost(pos); } }; Negamax::Negamax() { this->scorer = new DijkstraScorer(); } Negamax::Negamax(Scorer* scorer) { if (scorer == NULL) { scorer = new DijkstraScorer(); } this->scorer = scorer; } int Negamax::getMove(Board* board, char player, int max_depth) { this->board = board; this->max_depth = max_depth; this->depth_count = 0; int ap_pos = (player == P1) ? board->p1 : board->p2; int pp_pos = (player == P1) ? board->p2 : board->p1; int move = 0; negamax(ap_pos, pp_pos, 1, -INF, INF, &move); return move; } void Negamax::printDebug(int depth, const string& action, int score) { for (int i = 0; i < depth; ++i) cout << " "; cout << depth << " " << action << " " << score << endl; } void Negamax::printMove(int depth, int x, int y) { for (int i = 0; i < depth; ++i) cout << " "; cout << depth << " MOVE " << x << "," << y << endl; } int Negamax::negamax(int ap_pos, int pp_pos, int depth, int alpha, int beta, int* best_move) { if (hasLost(ap_pos)) { DEBUG(printDebug(depth, "LOST", LOSS_VALUE + depth)); return LOSS_VALUE + depth; } char player = board->board[ap_pos]; if (depth == max_depth) { depth_count++; int score = scorer->getScore(board, player); DEBUG(printDebug(depth, "SCORE", score)); return score; } int best_score = -INF; char opponent = OPPONENT(player); for (int i = 0; i < 8; ++i) { int pos = ap_pos; int move = MOVES[i]; while (true) { pos += move; char& cell = board->board[pos]; if (cell != EMPTY) { break; } DEBUG(printMove(depth, POS_TO_X(pos), POS_TO_Y(pos))); cell = player; int score = -1 * negamax(pp_pos, pos, depth+1, -beta, -alpha, NULL); cell = 0; if (score > best_score) { best_score = score; if (best_move != NULL) { *best_move = pos; } } alpha = (alpha >= score) ? alpha : score; if (alpha >= beta) { DEBUG(printDebug(depth, "BEST", best_score)); return best_score; } } } DEBUG(printDebug(depth, "BEST", best_score)); return best_score; } void Board::printPossibleMoves(char player) { int ap_pos = (player == P1) ? p1 : p2; char brd[49]; for (int i = 0; i < 49; ++i) { brd[i] = board[i]; } for (int i = 0; i < 8; ++i) { int pos = ap_pos; int move = MOVES[i]; while (true) { pos += move; char& cell = brd[pos]; if (cell != EMPTY) { break; } cell = 3; } } for (int i=1; i<6; ++i) { cout << "| "; for (int j=1; j<6; ++j) { char cell = brd[i*7+j]; if (cell == 0) { cout << " | "; } else { if (p1 == i*7+j || p2 == i*7+j) { cout << PLAYER(cell) << " | "; } else if (cell == 3) { cout << "* | "; } else { cout << "X | "; } } } cout << endl; } } void play_match(char player, Board& board); int main(int argc, char* argv[]) { for (int i = 0; i < 5; ++i) { for (int j = 0; j < 5; ++j) { if (i == 0 && j == 0) continue; Board board; board.play(0, 0, P1); board.play(i, j, P2); play_match(P1, board); } } return 0; } void play_match(char player, Board& board) { int best_move; Negamax negamax; Negamax mirror; int count = 0; while (true) { int ap_pos = (player == P1) ? board.p1 : board.p2; int pp_pos = (player == P1) ? board.p2 : board.p1; if (board.hasLost(ap_pos)) { cout << "Player:" << PLAYER(player) << " Lost." << endl; break; } int best_move; if (count % 2 == 0) { best_move = mirror.getMove(&board, player, 25); } else { best_move = negamax.getMove(&board, player, 25); } count++; int x, y; x = POS_TO_X(best_move); y = POS_TO_Y(best_move); cout << "Moved " << PLAYER(player) << " M: " << x << ", " << y << endl; board.play(x, y, player); board.printBoard(); cout << endl; player = OPPONENT(player); } }
23.839674
94
0.554998
5c2cb34533524ee582232ac99c94f7525ef3a6d7
7,536
cpp
C++
winnie1/new_delete_example/new_delete.cpp
r-lyeh/malloc-survey
6da5aca6aa2720d64bff709c111a5d8a5fa7a1be
[ "Zlib" ]
16
2015-06-26T20:58:23.000Z
2017-11-05T09:46:45.000Z
winnie1/new_delete_example/new_delete.cpp
r-lyeh/test-allocators
6da5aca6aa2720d64bff709c111a5d8a5fa7a1be
[ "Zlib" ]
1
2015-07-22T22:48:56.000Z
2015-07-22T22:48:56.000Z
winnie1/new_delete_example/new_delete.cpp
r-lyeh/test-allocators
6da5aca6aa2720d64bff709c111a5d8a5fa7a1be
[ "Zlib" ]
2
2015-09-26T17:40:20.000Z
2016-06-23T17:15:23.000Z
#include "winnie_alloc.h" #include "new_delete.h" #if defined(NDEBUG) && OP_NEW_DEBUG #undef NDEBUG #pragma message ("warning: NDEBUG and OP_NEW_DEBUG do not match. forcing #undef NDEBUG") #endif #include "assert.h" #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <new> #include "string.h" #if OP_NEW_USE_WINNIE_ALLOC #define OP_NEW_DEBUG_BREAK __asm int 3 //#define OP_NEW_DEBUG_BREAK DebugBreak() namespace { #if OP_NEW_DEBUG //begin of allocated block linked list //should be initialized at compile-time, before any new/delete operations. DebugHeader fake_header = { &fake_header, &fake_header }; #endif #if OP_NEW_MULTITHREADING CRITICAL_SECTION OperatorNewCriticalSection; bool OperatorNewCriticalSectionInitialized = false; struct LockOpNew { LockOpNew() { if (OperatorNewCriticalSectionInitialized) //allow one thread entering before initialization EnterCriticalSection(&OperatorNewCriticalSection); } ~LockOpNew() { if (OperatorNewCriticalSectionInitialized) //allow one thread entering before initialization LeaveCriticalSection(&OperatorNewCriticalSection); } }; #endif //OP_NEW_MULTITHREADING const unsigned guard_begin = 0x12345678; const unsigned guard_end = 0x87654321; const unsigned guard_after_delete = 0xDeadBeaf; unsigned op_new_alloc_num = 0; DWORD thread_id = 0; void *OpNewAlloc(size_t size) { size_t real_size = size; #if OP_NEW_DEBUG #if (!OP_NEW_MULTITHREADING) //assert, that only one thread owns new/delete DWORD cur_thread_id = GetCurrentThreadId(); if (thread_id) { if (thread_id != cur_thread_id) OP_NEW_ASSERT( !"Allocation from different threads detected in single thread mode." "You should enable OP_NEW_MULTITHREADING from new_detete_config.h"); } else { thread_id = cur_thread_id; } #endif //!OP_NEW_MULTITHREADING real_size+= sizeof(guard_begin) + sizeof(guard_end) + sizeof(DebugHeader); unsigned block_num; #endif //OP_NEW_DEBUG void *p; { #if OP_NEW_MULTITHREADING LockOpNew lock; #if OP_NEW_DEBUG DWORD cur_thread_id = GetCurrentThreadId(); if (thread_id) { if (thread_id != cur_thread_id && !OperatorNewCriticalSectionInitialized) OP_NEW_ASSERT( !"Allocation from different threads detected, but OperatorNewCriticalSectionInit was not called." "You should call OperatorNewCriticalSectionInit before any allocations from any second thread."); } else { thread_id = cur_thread_id; } #endif //OP_NEW_DEBUG #endif //OP_NEW_MULTITHREADING p= Winnie::Alloc(real_size); #if OP_NEW_DEBUG block_num = ++op_new_alloc_num; { DebugHeader *ph = (DebugHeader *)p; ph->prev = &fake_header; ph->next = fake_header.next; fake_header.next->prev = ph; fake_header.next= ph; } #endif } //end of multithread protection #if OP_NEW_DEBUG if (block_num == op_new_break_alloc) { OP_NEW_DEBUG_BREAK; } DebugHeader *ph = (DebugHeader *)p; ph->block_num = block_num; ph->size = size; unsigned *p_guard_begin = (unsigned *)(ph+1); *p_guard_begin = guard_begin; void *p_user_memory= (p_guard_begin + 1); unsigned *p_guard_end = (unsigned *)((char*)p_user_memory + size); *p_guard_end = guard_end; memset(p_user_memory, 0xCC, size); p = p_user_memory; #endif return p; } void OpNewFree(void *p_user_memory) { void *p = p_user_memory; #if OP_NEW_DEBUG OpNewAssertIsValid(p_user_memory); DebugHeader *ph = OpNewGetHeader(p_user_memory); unsigned *p_guard_begin = (unsigned *)p_user_memory - 1; *p_guard_begin = guard_after_delete; p= ph; #endif { #if OP_NEW_MULTITHREADING LockOpNew lock; #endif #if OP_NEW_DEBUG ph->prev->next = ph->next; ph->next->prev = ph->prev; memset(ph, 0xDD, ph->size + sizeof(DebugHeader)+2*sizeof(unsigned)); #endif Winnie::Free(p); } //end of multithread protection } } //namespace unsigned op_new_break_alloc = 0; void OperatorNewCriticalSectionInit() { #if OP_NEW_MULTITHREADING if (!OperatorNewCriticalSectionInitialized) { InitializeCriticalSection(&OperatorNewCriticalSection); OperatorNewCriticalSectionInitialized = true; } #endif } #if OP_NEW_DEBUG void OpNewAssertIsValid(void *p_user_memory) { OP_NEW_ASSERT(p_user_memory); unsigned *p_guard_begin = (unsigned *)p_user_memory - 1; DebugHeader *ph = (DebugHeader *)p_guard_begin-1; size_t size =ph->size; unsigned *p_guard_end = (unsigned *)((char *)p_user_memory + size); if (*p_guard_begin == guard_after_delete) { OP_NEW_ASSERT(!"possibly this block was already deleted"); } if (*p_guard_begin != guard_begin) { if (*(p_guard_begin-1) == guard_begin) //MSVC place size of array in first 4 bytes { OP_NEW_ASSERT( !"likely, applying delete to memory, allocated by new TYPE[], where TYPE has non-trivial destructor (use delete[])"); } OP_NEW_ASSERT(!"deletion of invalid block or non-block, heap-buffer underrun, or other error"); } if (*p_guard_end != guard_end) { OP_NEW_ASSERT(!"possibly heap-buffer overrun"); } } void *OpNewBegin() { return OpNewGetHeadersBlock(fake_header.next); } void *OpNewEnd() { return OpNewGetHeadersBlock(&fake_header); } void *OpNewNextBlock(void *p_user_memory) { return OpNewGetHeadersBlock(OpNewGetHeader(p_user_memory)->next); } void *OpNewGetBlockPointer(void *p) { if (!p) return NULL; for ( void *pum = OpNewBegin(), *p_end = OpNewEnd(); pum != p_end; pum = OpNewNextBlock(pum)) { DebugHeader *ph = OpNewGetHeader(pum); if ( p >= pum && p < ((char*)pum + ph->size)) return pum; } return NULL; } void OpNewValidateHeap() { for ( void *pum = OpNewBegin(), *p_end = OpNewEnd(); pum != p_end; pum = OpNewNextBlock(pum)) { OpNewAssertIsValid(pum); } } void *OpNewGetHeadersBlock(DebugHeader *p_header) { void *p_user_memory = (unsigned*)(p_header+1)+1; return p_user_memory; } DebugHeader *OpNewGetHeader(void *p_user_memory) { OpNewAssertIsValid(p_user_memory); return (DebugHeader*)((unsigned*)p_user_memory-1)-1; } #endif //OP_NEW_DEBUG void *operator new(size_t size) { void *p = OpNewAlloc(size); #if OP_NEW_DEBUG OpNewGetHeader(p)->is_array = false; #endif return p; } void *operator new[](size_t size) { void *p = OpNewAlloc(size); #if OP_NEW_DEBUG OpNewGetHeader(p)->is_array = true; #endif return p; } void operator delete(void *p) throw() { if (p) { #if OP_NEW_DEBUG int is_array= OpNewGetHeader(p)->is_array; #endif OpNewFree(p); #if OP_NEW_DEBUG OP_NEW_ASSERT(!is_array && "what allocated with new[], should be released by delete[], not delete"); #endif } } void operator delete[](void *p)throw() { if (p) { #if OP_NEW_DEBUG int is_array= OpNewGetHeader(p)->is_array; #endif OpNewFree(p); #if OP_NEW_DEBUG OP_NEW_ASSERT(is_array && "what allocated with new, should be released by delete, not delete[]"); #endif } } void *operator new(size_t size, const std::nothrow_t&) throw() { try { void *p = OpNewAlloc(size); #if OP_NEW_DEBUG OpNewGetHeader(p)->is_array = false; #endif return p; } catch (...) { return NULL; } } void *operator new[](size_t size, const std::nothrow_t&) throw() { try { void *p = OpNewAlloc(size); #if OP_NEW_DEBUG OpNewGetHeader(p)->is_array = true; #endif return p; } catch (...) { return NULL; } } #endif //OP_NEW_USE_WINNIE_ALLOC
20.096
126
0.697452
5c3215dc46c4abbfc288ff7b72f4d89b5f9fd65d
1,718
cpp
C++
08.cpp
0xmanjoos/cpp_collection
306164ed398410674a814839f510d7b6c85a222d
[ "MIT" ]
1
2021-01-24T01:48:57.000Z
2021-01-24T01:48:57.000Z
08.cpp
0xmanjoos/cpp_collection
306164ed398410674a814839f510d7b6c85a222d
[ "MIT" ]
null
null
null
08.cpp
0xmanjoos/cpp_collection
306164ed398410674a814839f510d7b6c85a222d
[ "MIT" ]
null
null
null
#include <iostream> // linked lists hee hee ha fucking kill me // SOURCE: https://www.geeksforgeeks.org/linked-list-set-1-introduction/ // modified a bit class Node { public: // int data and pointer to class node? int data; Node* next; // pointer to the next node // example: second->data=2; second->next = third; }; // function for printing out the linked list void printl(Node* n) { // Node* n == the pointer to the next node within the list.. probably... while (n != NULL) { std::cout<< n->data << std::endl; // print the value of data n = n -> next; // update the value of n? } } int main() { // init maybe? idk these fuckers dont explain Node* head = NULL; Node* second = NULL; Node* third = NULL; // allocate 3 new nodes in the heap head = new Node(); second = new Node(); third = new Node(); /* Three blocks have been allocated dynamically. We have pointers to these three blocks as head, second and third head second third | | | | | | +---+-----+ +----+----+ +----+----+ | # | # | | # | # | | # | # | +---+-----+ +----+----+ +----+----+ represents any random value. Data is random because we haven’t assigned anything yet */ head -> data = 1; // assign data in first node head -> next = second; // Link first node with // the second node second -> data = 2; // int data, the value of data in this node :) second -> next = third; // link the next node, which is third third -> data = 3; third -> next = NULL; printl(head); return 0; }
27.709677
95
0.531432
5c322cb45c47b708d9092a6333ec3074dfddea97
5,672
cpp
C++
Dynamic Library/MacOS/libWUSB/WUSB.cpp
mcka-dev/WUSBFT
3f53c051e13ea94a44ba22a0c22528b57221934f
[ "MIT" ]
1
2017-08-23T16:22:50.000Z
2017-08-23T16:22:50.000Z
Dynamic Library/MacOS/libWUSB/WUSB.cpp
mcka-dev/WUSBFT
3f53c051e13ea94a44ba22a0c22528b57221934f
[ "MIT" ]
null
null
null
Dynamic Library/MacOS/libWUSB/WUSB.cpp
mcka-dev/WUSBFT
3f53c051e13ea94a44ba22a0c22528b57221934f
[ "MIT" ]
null
null
null
#include "WUSB.h" #include "ftd2xx.h" #define CRC_Init 0xDE //CRC Initial value FT_HANDLE ftHandle; //device handle FT_STATUS ftStatus; //device status const unsigned char FEND = 0xC0, //Frame END FESC = 0xDB, //Frame ESCape TFEND = 0xDC, //Transposed Frame END TFESC = 0xDD; //Transposed Frame ESCape void DowCRC(unsigned char b, unsigned char &crc); bool RxByte(unsigned char &b); #ifdef _WINDOWS BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } #endif //----------------------- Access check for USB resource: -------------------- EXTERN_HEADER bool AccessUSB(int DevNum) { FT_HANDLE ftHandle_t; FT_STATUS ftStatus_t; ftStatus_t = FT_Open(DevNum, &ftHandle_t); if (!FT_SUCCESS(ftStatus_t)) { return false; } else { FT_Close(ftHandle_t); return true; } } //------------------------ Get number of USB devices: ----------------------- EXTERN_HEADER bool NumUSB(unsigned int &numDevs) { FT_STATUS ftStatus_t; ftStatus_t = FT_ListDevices(&numDevs, NULL, FT_LIST_NUMBER_ONLY); return FT_SUCCESS(ftStatus_t); } //----------------------------- Open USB ------------------------------------ EXTERN_HEADER bool OpenUSB(int DevNum, unsigned int baud) { ftStatus = FT_Open(DevNum, &ftHandle); if (!FT_SUCCESS(ftStatus)) { //device open error return false; } ftStatus = FT_SetLatencyTimer(ftHandle, 1); if (!FT_SUCCESS(ftStatus)) { //set latency error return false; } ftStatus = FT_SetBaudRate(ftHandle, baud); if (!FT_SUCCESS(ftStatus)) { //set baud error return false; } ftStatus = FT_SetDataCharacteristics(ftHandle, FT_BITS_8, FT_STOP_BITS_1, FT_PARITY_NONE); if (!FT_SUCCESS(ftStatus)) { //set mode error return false; } ftStatus = FT_SetTimeouts(ftHandle, 1000, 1000); if (!FT_SUCCESS(ftStatus)) { //set timeouts error return false; } ftStatus = FT_Purge(ftHandle, FT_PURGE_RX | FT_PURGE_TX); if (!FT_SUCCESS(ftStatus)) { //purge error return false; } return true; } //------------------------------ Close USB: --------------------------------- EXTERN_HEADER bool CloseUSB(void) { ftStatus = FT_Close(ftHandle); return FT_SUCCESS(ftStatus); } //------------- Purge USB: terminates TX and RX and clears buffers: --------- EXTERN_HEADER bool PurgeUSB(void) { ftStatus = FT_Purge(ftHandle, FT_PURGE_RX | FT_PURGE_TX); return FT_SUCCESS(ftStatus); } //--------------------------------------------------------------------------- void DowCRC(unsigned char b, unsigned char &crc) { for (int i = 0; i < 8; i++) { if (((b ^ crc) & 1) != 0) { crc = ((crc ^ 0x18) >> 1) | 0x80; } else { crc = (crc >> 1) & ~0x80; } b = b >> 1; } } //--------------------------------------------------------------------------- bool RxByte(unsigned char &b) { DWORD r; ftStatus = FT_Read(ftHandle, &b, 1, &r); if (!FT_SUCCESS(ftStatus)) { return false; } if (r != 1) { return false; } return true; } //--------------------------- Receive frame: -------------------------------- EXTERN_HEADER bool RxFrameUSB(unsigned int To, unsigned char &ADD, unsigned char &CMD, unsigned char &N, unsigned char *Data) { int i; unsigned char b = 0, crc = CRC_Init; //init CRC ftStatus = FT_SetTimeouts(ftHandle, To, 1000); if (!FT_SUCCESS(ftStatus)) { //set timeouts error return false; } for (i = 0; i < 512 && b != FEND; i++) { if (!RxByte(b)) { //frame synchronzation break; } } if (b != FEND) { //timeout or sync error return false; } DowCRC(b, crc); //update CRC N = 0; ADD = 0; for (i = -3; i <= N; i++) { if (!RxByte(b)) { //timeout error break; } if (b == FESC) { if (!RxByte(b)) { //timeout error break; } else { if (b == TFEND) { //TFEND <- FEND b = FEND; } else { if (b == TFESC) { //TFESC <- FESC b = FESC; } else { break; } } } } if (i == -3) { if ((b & 0x80) == 0) { //CMD (b.7=0) CMD = b; i++; } else { //ADD (b.7=1) b = b & 0x7F; ADD = b; } } else { if (i == -2) { if ((b & 0x80) != 0) { //CMD error (b.7=1) break; } else { //CMD CMD = b; } } else { if (i == -1) { //N N = b; } else { if (i != N) { //data Data[i] = b; } } } } DowCRC(b, crc); //update CRC } return ((i == N + 1) && !crc); //RX or CRC error } //--------------------------- Transmit frame: ------------------------------- EXTERN_HEADER bool TxFrameUSB(unsigned char ADDR, unsigned char CMD, unsigned char N, unsigned char *Data) { unsigned char Buff[518]; DWORD r, j = 0; unsigned char d, crc = CRC_Init; //init CRC for (int i = -4; i <= N; i++) { if ((i == -3) && (!ADDR)) { i++; } if (i == -4) { //FEND d = FEND; } else { if (i == -3) { //address d = ADDR & 0x7F; } else { if (i == -2) { //command d = CMD & 0x7F; } else { if (i == -1) { //N d = N; } else { if (i == N) { //CRC d = crc; } else //data { d = Data[i]; } } } } } DowCRC(d, crc); if (i == -3) { d = d | 0x80; } if (i > -4) { if ((d == FEND) || (d == FESC)) { Buff[j++] = FESC; if (d == FEND) { d = TFEND; } else { d = TFESC; } } } Buff[j++] = d; } ftStatus = FT_Write(ftHandle, Buff, j, &r); if (!FT_SUCCESS(ftStatus)) { return false; } if (r != j) { return false; } return true; }
18.535948
86
0.518159
5c36e5b32504023f0f525737ac7a754118636085
5,414
cc
C++
src/nixtag.cc
JiriVanek/nix-mx
1e8fec06d4aae67116d5e3b212784f6606dbaeaf
[ "BSD-3-Clause" ]
null
null
null
src/nixtag.cc
JiriVanek/nix-mx
1e8fec06d4aae67116d5e3b212784f6606dbaeaf
[ "BSD-3-Clause" ]
null
null
null
src/nixtag.cc
JiriVanek/nix-mx
1e8fec06d4aae67116d5e3b212784f6606dbaeaf
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2016, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. #include "nixtag.h" #include "mex.h" #include <nix.hpp> #include "arguments.h" #include "filters.h" #include "handle.h" #include "mkarray.h" #include "struct.h" namespace nixtag { mxArray *describe(const nix::Tag &tag) { struct_builder sb({ 1 }, { "id", "type", "name", "definition", "position", "extent", "units" }); sb.set(tag.id()); sb.set(tag.type()); sb.set(tag.name()); sb.set(tag.definition()); sb.set(tag.position()); sb.set(tag.extent()); sb.set(tag.units()); return sb.array(); } void addReference(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); currObj.addReference(input.str(2)); } void addReferences(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); std::vector<nix::DataArray> curr = input.entity_vec<nix::DataArray>(2); currObj.references(curr); } void addSource(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); currObj.addSource(input.str(2)); } void addSources(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); std::vector<nix::Source> curr = input.entity_vec<nix::Source>(2); currObj.sources(curr); } void createFeature(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); nix::Feature newFeat = currObj.createFeature(input.str(2), input.ltype(3)); output.set(0, handle(newFeat)); } void openReferenceIdx(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); nix::ndsize_t idx = (nix::ndsize_t)input.num<double>(2); output.set(0, currObj.getReference(idx)); } void openFeatureIdx(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); nix::ndsize_t idx = (nix::ndsize_t)input.num<double>(2); output.set(0, currObj.getFeature(idx)); } void openSourceIdx(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); nix::ndsize_t idx = (nix::ndsize_t)input.num<double>(2); output.set(0, currObj.getSource(idx)); } void compare(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); nix::Tag other = input.entity<nix::Tag>(2); output.set(0, currObj.compare(other)); } void sourcesFiltered(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); std::vector<nix::Source> res = filterFullEntity<nix::Source>(input, [currObj](const nix::util::Filter<nix::Source>::type &filter) { return currObj.sources(filter); }); output.set(0, res); } void referencesFiltered(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); std::vector<nix::DataArray> res = filterFullEntity<nix::DataArray>(input, [currObj](const nix::util::Filter<nix::DataArray>::type &filter) { return currObj.references(filter); }); output.set(0, res); } void featuresFiltered(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); std::vector<nix::Feature> res = filterEntity<nix::Feature>(input, [currObj](const nix::util::Filter<nix::Feature>::type &filter) { return currObj.features(filter); }); output.set(0, res); } void retrieveData(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); std::string name_id = input.str(2); mxArray *data = make_mx_array_from_ds(currObj.retrieveData(name_id)); output.set(0, data); } void retrieveDataIdx(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); nix::ndsize_t idx = (nix::ndsize_t)input.num<double>(2); mxArray *data = make_mx_array_from_ds(currObj.retrieveData(idx)); output.set(0, data); } void retrieveFeatureData(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); std::string name_id = input.str(2); mxArray *data = make_mx_array_from_ds(currObj.retrieveFeatureData(name_id)); output.set(0, data); } void retrieveFeatureDataIdx(const extractor &input, infusor &output) { nix::Tag currObj = input.entity<nix::Tag>(1); nix::ndsize_t idx = (nix::ndsize_t)input.num<double>(2); mxArray *data = make_mx_array_from_ds(currObj.retrieveFeatureData(idx)); output.set(0, data); } } // namespace nixtag
36.093333
111
0.593831
5c388318a3c9af8911eed5f695c3eb46da682f06
459
hpp
C++
Paper/Group.hpp
mokafolio/Paper
d7e9c1450b29b1d3d8873de4f959bffa02232055
[ "MIT" ]
20
2016-12-13T22:34:35.000Z
2021-09-20T12:44:56.000Z
Paper/Group.hpp
mokafolio/Paper
d7e9c1450b29b1d3d8873de4f959bffa02232055
[ "MIT" ]
null
null
null
Paper/Group.hpp
mokafolio/Paper
d7e9c1450b29b1d3d8873de4f959bffa02232055
[ "MIT" ]
null
null
null
#ifndef PAPER_GROUP_HPP #define PAPER_GROUP_HPP #include <Paper/Item.hpp> #include <Paper/Constants.hpp> namespace paper { class Document; class STICK_API Group : public Item { friend class Item; public: static constexpr EntityType itemType = EntityType::Group; Group(); void setClipped(bool _b); bool isClipped() const; Group clone() const; }; } #endif //PAPER_GROUP_HPP
14.806452
65
0.627451
5c39d404f1e2252e54a71db14346b6dbd5fa7b4d
3,560
cpp
C++
flextyper/test/tst_stat.cpp
wassermanlab/OpenFlexTyper_restore
f599011a8f856bd81e73e5472d50980b4695055c
[ "MIT" ]
1
2020-02-20T20:01:38.000Z
2020-02-20T20:01:38.000Z
flextyper/test/tst_stat.cpp
wassermanlab/OpenFlexTyper_restore
f599011a8f856bd81e73e5472d50980b4695055c
[ "MIT" ]
null
null
null
flextyper/test/tst_stat.cpp
wassermanlab/OpenFlexTyper_restore
f599011a8f856bd81e73e5472d50980b4695055c
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////// /// /// Copyright (c) 2019, Wasserman lab /// /// FILE tst_stats.cpp /// /// DESCRIPTION This file contains tests for the stats class /// /// Initial version @ Godfrain Jacques Kounkou /// //////////////////////////////////////////////////////////////////////// #include <gtest/gtest.h> #include "stats.cpp" #include <experimental/filesystem> using namespace std; using namespace ft; namespace fs = experimental::filesystem; namespace ft { class TestStats : public ::testing::Test { protected: virtual void SetUp() { ofstream output_expected("output_expected.log"); if (output_expected.is_open()) { output_expected << "ATTATCTATCTACTACTTCTATCTACTCTA : 3\n"; output_expected << "CTAGCATCGATCGATCGATCGATCGACTGC : 5\n"; output_expected << "CTTTTTTTTATCTACTTACTATCTTTTTTT : 1\n"; output_expected << "GGGGCTGACTACGTAGCTACGATCGATCGT : 4\n"; } output_expected.close(); } virtual void TeadDown() { // std::remove("output_expected.log"); } public: bool compareFiles(const string& file1, const string& file2) { ifstream f1(file1), f2(file2); string content1, content2; string line; if (f1.is_open()) { while (getline(f1, line)) content1 += line; } f1.close(); line.clear(); if (f2.is_open()) { while (getline(f2, line)) content2 += line; } f2.close(); return content1 == content2; } public: Stats _stats; }; #define TEST_DESCRIPTION(desc) RecordProperty("description", desc) //====================================================================== TEST_F(TestStats, printKmerCountToFile) { TEST_DESCRIPTION("This test will chech that the function creates an ouput file"); map<string, uint> counter {{ "ATTATCTATCTACTACTTCTATCTACTCTA", 3}, { "GGGGCTGACTACGTAGCTACGATCGATCGT", 4}, { "CTTTTTTTTATCTACTTACTATCTTTTTTT", 1}, { "CTAGCATCGATCGATCGATCGATCGACTGC", 5}}; fs::path output ("output.log"); _stats.printKmerCountToFile(output, counter); EXPECT_NO_FATAL_FAILURE(); EXPECT_NO_THROW(); EXPECT_TRUE(fs::exists(output)); } //====================================================================== TEST_F(TestStats, printKmerCountToFileEmpty) { TEST_DESCRIPTION("This test will chech that the function creates an ouput file"); map<string, uint> counter {}; fs::path output ("output.log"); _stats.printKmerCountToFile(output, counter); EXPECT_NO_FATAL_FAILURE(); EXPECT_NO_THROW(); EXPECT_FALSE(fs::exists(output)); } //====================================================================== TEST_F(TestStats, printKmerCountToFileCompareContent) { TEST_DESCRIPTION("This test will chech that the function creates an ouput file"); map<string, uint> counter {{ "ATTATCTATCTACTACTTCTATCTACTCTA", 3}, { "GGGGCTGACTACGTAGCTACGATCGATCGT", 4}, { "CTTTTTTTTATCTACTTACTATCTTTTTTT", 1}, { "CTAGCATCGATCGATCGATCGATCGACTGC", 5}}; fs::path output ("output.log"); fs::path expectedOutpt ("output_expected.log"); _stats.printKmerCountToFile(output, counter); EXPECT_NO_FATAL_FAILURE(); EXPECT_NO_THROW(); EXPECT_TRUE(compareFiles(output, expectedOutpt)); } }
28.48
85
0.562079
5c39de7473c67da99a4e3e6af7b76cfc4f6b483d
1,328
cpp
C++
dependencies/PyMesh/tools/Wires/Parameters/VertexCustomOffsetParameter.cpp
aprieels/3D-watermarking-spectral-decomposition
dcab78857d0bb201563014e58900917545ed4673
[ "MIT" ]
5
2018-06-04T19:52:02.000Z
2022-01-22T09:04:00.000Z
dependencies/PyMesh/tools/Wires/Parameters/VertexCustomOffsetParameter.cpp
aprieels/3D-watermarking-spectral-decomposition
dcab78857d0bb201563014e58900917545ed4673
[ "MIT" ]
null
null
null
dependencies/PyMesh/tools/Wires/Parameters/VertexCustomOffsetParameter.cpp
aprieels/3D-watermarking-spectral-decomposition
dcab78857d0bb201563014e58900917545ed4673
[ "MIT" ]
null
null
null
/* This file is part of PyMesh. Copyright (c) 2015 by Qingnan Zhou */ #include "VertexCustomOffsetParameter.h" using namespace PyMesh; VertexCustomOffsetParameter::VertexCustomOffsetParameter( WireNetwork::Ptr wire_network, const MatrixFr& offset) : PatternParameter(wire_network), m_derivative(offset) { } void VertexCustomOffsetParameter::apply( VectorF& results, const Variables& vars) { const size_t dim = m_wire_network->get_dim(); const size_t num_vertices = m_wire_network->get_num_vertices(); const size_t roi_size = m_roi.size(); assert(results.size() == dim * num_vertices); if (m_formula != "") evaluate_formula(vars); for (size_t i=0; i<roi_size; i++) { size_t v_idx = m_roi[i]; assert(v_idx < num_vertices); results.segment(v_idx*dim, dim) += m_derivative.row(v_idx) * m_value; } } MatrixFr VertexCustomOffsetParameter::compute_derivative() const { const size_t num_vertices = m_wire_network->get_num_vertices(); const size_t dim = m_wire_network->get_dim(); const size_t roi_size = m_roi.size(); MatrixFr derivative = MatrixFr::Zero(num_vertices, dim); for (size_t i=0; i<roi_size; i++) { size_t v_idx = m_roi[i]; derivative.row(v_idx) += m_derivative.row(v_idx); } return derivative; }
34.051282
77
0.692771
5c3bc9320dc133c5b9595487d4f56053eb4b36f8
2,478
hpp
C++
src/bonefish/dealer/wamp_dealer_registration.hpp
aiwc/extlib-bonefish
2f0d15960b5178d2ab24fd8e11965a80ace2cb5a
[ "Apache-2.0" ]
58
2015-08-24T18:43:56.000Z
2022-01-09T00:55:06.000Z
src/bonefish/dealer/wamp_dealer_registration.hpp
aiwc/extlib-bonefish
2f0d15960b5178d2ab24fd8e11965a80ace2cb5a
[ "Apache-2.0" ]
47
2015-08-25T11:04:51.000Z
2018-02-28T22:38:12.000Z
src/bonefish/dealer/wamp_dealer_registration.hpp
aiwc/extlib-bonefish
2f0d15960b5178d2ab24fd8e11965a80ace2cb5a
[ "Apache-2.0" ]
32
2015-08-25T15:14:45.000Z
2020-03-23T09:35:31.000Z
/** * Copyright (C) 2015 Topology LP * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef BONEFISH_DEALER_WAMP_DEALER_SUBSCRIPTION_HPP #define BONEFISH_DEALER_WAMP_DEALER_SUBSCRIPTION_HPP #include <bonefish/identifiers/wamp_registration_id.hpp> #include <bonefish/session/wamp_session.hpp> #include <unordered_set> namespace bonefish { class wamp_dealer_registration { public: wamp_dealer_registration(); wamp_dealer_registration(const std::shared_ptr<wamp_session>& session, const wamp_registration_id& registration_id); ~wamp_dealer_registration(); void set_session(const std::shared_ptr<wamp_session>& session); void set_registration_id(const wamp_registration_id& registration_id); const wamp_registration_id& get_registration_id() const; const std::shared_ptr<wamp_session>& get_session() const; private: std::shared_ptr<wamp_session> m_session; wamp_registration_id m_registration_id; }; inline wamp_dealer_registration::wamp_dealer_registration() : m_session() , m_registration_id() { } inline wamp_dealer_registration::wamp_dealer_registration(const std::shared_ptr<wamp_session>& session, const wamp_registration_id& registration_id) : m_session(session) , m_registration_id(registration_id) { } inline wamp_dealer_registration::~wamp_dealer_registration() { } inline void wamp_dealer_registration::set_session(const std::shared_ptr<wamp_session>& session) { m_session = session; } inline void wamp_dealer_registration::set_registration_id(const wamp_registration_id& registration_id) { m_registration_id = registration_id; } inline const std::shared_ptr<wamp_session>& wamp_dealer_registration::get_session() const { return m_session; } inline const wamp_registration_id& wamp_dealer_registration::get_registration_id() const { return m_registration_id; } } // namespace bonefish #endif // BONEFISH_DEALER_WAMP_DEALER_SUBSCRIPTION_HPP
28.813953
103
0.778854
5c3d62f0e2a30326c8f0458fe39c3355f406e1a8
983
cc
C++
examples/vision_graph/src/NoS/applications/OSNode/OmnetIf_pkt.cc
zoranzhao/NoSDSE
0e3148572e7cdf3a2d012c95c81863864da236d6
[ "MIT" ]
3
2019-01-26T20:35:47.000Z
2019-07-18T22:09:22.000Z
examples/vision_graph/src/NoS/applications/OSNode/OmnetIf_pkt.cc
zoranzhao/NoSSim
7b0e9edde0fe19f83d7aaa946fd580a6d9dab978
[ "BSD-3-Clause" ]
null
null
null
examples/vision_graph/src/NoS/applications/OSNode/OmnetIf_pkt.cc
zoranzhao/NoSSim
7b0e9edde0fe19f83d7aaa946fd580a6d9dab978
[ "BSD-3-Clause" ]
3
2017-09-08T22:13:28.000Z
2019-06-29T21:42:53.000Z
#include <iostream> #include <sstream> #include "OmnetIf_pkt.h" OmnetIf_pkt::OmnetIf_pkt() { fileBuffer_arraysize = 0; this->fileBuffer = NULL; } OmnetIf_pkt::~OmnetIf_pkt() { delete [] fileBuffer; } void OmnetIf_pkt::setFileBufferArraySize(unsigned int size) { char *fileBuffer_var2 = (size==0) ? NULL : new char[size]; unsigned int sz = fileBuffer_arraysize < size ? fileBuffer_arraysize : size; for (unsigned int i=0; i<sz; i++) fileBuffer_var2[i] = this->fileBuffer[i]; for (unsigned int i=sz; i<size; i++) fileBuffer_var2[i] = 0; fileBuffer_arraysize = size; delete [] this->fileBuffer; this->fileBuffer = fileBuffer_var2; } unsigned int OmnetIf_pkt::getFileBufferArraySize() const { return fileBuffer_arraysize; } char OmnetIf_pkt::getFileBuffer(unsigned int k) const { return fileBuffer[k]; } void OmnetIf_pkt::setFileBuffer(unsigned int k, char fileBuffer) { this->fileBuffer[k] = fileBuffer; }
20.061224
80
0.690743
5c3da2baceaccc641b25645c84ef2f97b3d802c2
2,002
cc
C++
RecoTracker/TkNavigation/test/TkMSParameterizationTest.cc
NTrevisani/cmssw
a212a27526f34eb9507cf8b875c93896e6544781
[ "Apache-2.0" ]
2
2020-01-27T15:21:37.000Z
2020-05-11T11:13:18.000Z
RecoTracker/TkNavigation/test/TkMSParameterizationTest.cc
NTrevisani/cmssw
a212a27526f34eb9507cf8b875c93896e6544781
[ "Apache-2.0" ]
8
2020-03-20T23:18:36.000Z
2020-05-27T11:00:06.000Z
RecoTracker/TkNavigation/test/TkMSParameterizationTest.cc
NTrevisani/cmssw
a212a27526f34eb9507cf8b875c93896e6544781
[ "Apache-2.0" ]
3
2019-03-09T13:06:43.000Z
2020-07-03T00:47:30.000Z
#include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/ESHandle.h" #include "RecoTracker/TkNavigation/interface/TkMSParameterization.h" #include "RecoTracker/Record/interface/TkMSParameterizationRecord.h" class TkMSParameterizationTest final : public edm::EDAnalyzer { public: explicit TkMSParameterizationTest(const edm::ParameterSet&) {} private: void analyze(const edm::Event&, const edm::EventSetup&) override; }; void TkMSParameterizationTest::analyze(const edm::Event&, const edm::EventSetup& iSetup) { using namespace tkMSParameterization; edm::ESHandle<TkMSParameterization> paramH; iSetup.get<TkMSParameterizationRecord>().get(paramH); auto const& msParam = *paramH; // test MSParam { std::cout << "\n\nProduced MSParam" << std::endl; unsigned short f, t; for (auto const& e : msParam()) { std::tie(f, t) = unpackLID(e.first); std::cout << "from/to " << f << "->" << t << std::endl; for (auto const& d : e.second()) { std::cout << d().size() << ' '; } std::cout << std::endl; } int lst[] = {0, 1, 29}; for (auto st : lst) for (int il = 1; il < 5; ++il) { int ll = st + il; if (st == 0 && il == 5) ll = 29; std::cout << "from/to " << st << "->" << ll << std::endl; auto const& d = *msParam.fromTo(st, ll); int lb = 0; for (auto const& ld : d()) { lb++; if (ld().empty()) continue; std::cout << lb << ": "; for (auto const& e : ld()) std::cout << e << ' '; std::cout << std::endl; } } } }; //define this as a plug-in DEFINE_FWK_MODULE(TkMSParameterizationTest);
30.333333
90
0.606394
5c3f75e171fb117831597306fe89412e84c90c9f
2,204
cpp
C++
iotivity-1.0.1/resource/csdk/security/unittest/svcresourcetest.cpp
gerald-yang/ubuntu-iotivity-demo
17e799e209442bbefb2df846e329c802ee5255f7
[ "Apache-2.0" ]
1,433
2015-04-30T09:26:53.000Z
2022-03-26T12:44:12.000Z
AllJoyn/Samples/OICAdapter/iotivity-1.0.0/resource/csdk/security/unittest/svcresourcetest.cpp
buocnhay/samples-1
ddd614bb5ae595f03811e3dfa15a5d107005d0fc
[ "MIT" ]
530
2015-05-02T09:12:48.000Z
2018-01-03T17:52:01.000Z
AllJoyn/Samples/OICAdapter/iotivity-1.0.0/resource/csdk/security/unittest/svcresourcetest.cpp
buocnhay/samples-1
ddd614bb5ae595f03811e3dfa15a5d107005d0fc
[ "MIT" ]
1,878
2015-04-30T04:18:57.000Z
2022-03-15T16:51:17.000Z
//****************************************************************** // // Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= #include "gtest/gtest.h" #include <pwd.h> #include <grp.h> #include <linux/limits.h> #include <sys/stat.h> #include "ocstack.h" #include "oic_malloc.h" #include "cJSON.h" #include "cainterface.h" #include "secureresourcemanager.h" #include "securevirtualresourcetypes.h" #include "srmresourcestrings.h" #include "svcresource.h" #include "srmtestcommon.h" using namespace std; #ifdef __cplusplus extern "C" { #endif extern char * BinToSvcJSON(const OicSecSvc_t * svc); extern OicSecSvc_t * JSONToSvcBin(const char * jsonStr); extern void DeleteSVCList(OicSecSvc_t* svc); #ifdef __cplusplus } #endif static const char* JSON_FILE_NAME = "oic_unittest.json"; #define NUM_SVC_IN_JSON_DB (2) // JSON Marshalling Tests TEST(SVCResourceTest, JSONMarshallingTests) { char *jsonStr1 = ReadFile(JSON_FILE_NAME); if (jsonStr1) { OicSecSvc_t * svc = JSONToSvcBin(jsonStr1); EXPECT_TRUE(NULL != svc); int cnt = 0; OicSecSvc_t * tempSvc = svc; while(tempSvc) { EXPECT_EQ(tempSvc->svct, ACCESS_MGMT_SERVICE); cnt++; tempSvc = tempSvc->next; } EXPECT_EQ(cnt, NUM_SVC_IN_JSON_DB); char * jsonStr2 = BinToSvcJSON(svc); EXPECT_TRUE(NULL != jsonStr2); OICFree(jsonStr1); OICFree(jsonStr2); DeleteSVCList(svc); } }
26.878049
75
0.627495
5c4291a9eb3539d3bbeb778695a5e4c600527e93
4,642
cpp
C++
core/src/plugin/PluginDiscovery.cpp
tristanseifert/lichtenstein_client
16b0d35915d11cd8cdf71d56c3d0f3d7268fe7cf
[ "BSD-3-Clause" ]
null
null
null
core/src/plugin/PluginDiscovery.cpp
tristanseifert/lichtenstein_client
16b0d35915d11cd8cdf71d56c3d0f3d7268fe7cf
[ "BSD-3-Clause" ]
null
null
null
core/src/plugin/PluginDiscovery.cpp
tristanseifert/lichtenstein_client
16b0d35915d11cd8cdf71d56c3d0f3d7268fe7cf
[ "BSD-3-Clause" ]
null
null
null
#include "PluginDiscovery.h" #include "LichtensteinPluginHandler.h" #include "HardwareInfoStruct.h" #include "../util/StringUtils.h" #include <unistd.h> #include <fcntl.h> #include <sys/ioctl.h> // includes for i2c #ifdef __linux__ #include <linux/i2c.h> #include <linux/i2c-dev.h> #endif #include <glog/logging.h> /** * Initializes the plugin discovery system. */ PluginDiscovery::PluginDiscovery(LichtensteinPluginHandler *_handler) : handler(_handler) { this->config = this->handler->getConfig(); } /** * Cleans up any allocated resources. */ PluginDiscovery::~PluginDiscovery() { } /** * Attempts to discover hardware. All EEPROMs in the specified range are read, * and their info structs parsed. * * If the first I2C read times out, it's assumed no chips are at that address; * any subsequent timeouts are considered errors. */ int PluginDiscovery::discover(void) { int err = 0, numAddresses = 0; // get a vector of all addresses std::string addrStr = this->config->Get("discovery", "eeprom_addresses", "0x50,0x51,0x52,0x53"); std::vector<int> addr; numAddresses = StringUtils::parseCsvList(addrStr, addr, 16); LOG(INFO) << "Checking " << numAddresses << " addresses"; // read each memory for(auto it = addr.begin(); it != addr.end(); it++) { int addr = *it; VLOG(1) << "Reading EEPROM at 0x" << std::hex << addr; err = this->discoverAtAddress(addr); // handle errors if(err < 0) { LOG(ERROR) << "Failed reading EEPROM at 0x" << std::hex << addr << std::dec << ": " << err << std::endl; // errors other than a nonexistent device are fatal if(err != kDiscoveryErrNoSuchDevice) { return err; } } } // return error status return err; } /** * Reads the memory at the given I2C location, and attempts to match plugins to * the input and output channels defined by the plugin. */ int PluginDiscovery::discoverAtAddress(int addr) { int err; void *romData = nullptr; size_t romDataLen = 0; // read the ROM err = this->readConfigRom(addr, &romData, &romDataLen); if(err < 0) { LOG(ERROR) << "Couldn't read ROM: " << err; return err; } // TODO: implement return 0; } /** * Reads the config ROM into memory, then provides the caller the address and * length of the data. * * @note Release the buffer with free() when done. */ int PluginDiscovery::readConfigRom(int addr, void **data, size_t *len) { int err = 0, fd = -1; void *readBuf = nullptr; // validate arguments CHECK(data != nullptr) << "data out pointer may not be null"; CHECK(len != nullptr) << "length out pointer may not be null"; CHECK(addr > 0) << "I2C address may not be negative"; CHECK(addr < 0x80) << "I2C address may not be more than 0x7F"; // get bus number from config int busNr = this->config->GetInteger("discovery", "eeprom_bus", 0); CHECK(busNr >= 0) << "Address is negative, wtf (got " << busNr << ", check discovery.eeprom_bus)"; // create bus name const size_t busPathSz = 32 + 1; char busPath[busPathSz]; memset(&busPath, 0, busPathSz); snprintf(busPath, (busPathSz - 1), "/dev/i2c-%d", busNr); // open i2c device fd = open(busPath, O_RDWR); if(fd < 0) { PLOG(ERROR) << "Couldn't open I2C bus at " << busPath; return kDiscoveryErrIo; } // send slave address #ifdef __linux__ err = ioctl(fd, I2C_SLAVE, addr); if(err < 0) { PLOG(ERROR) << "Couldn't set I2C slave address"; close(fd); return kDiscoveryErrIoctl; } #endif // allocate buffer and clear it (fixed size for now); then set its location static const size_t readBufLen = 256; readBuf = malloc(readBufLen); memset(readBuf, 0, readBufLen); *data = readBuf; #ifdef __linux__ // write buffer for read command static const char readCmdBuf[1] = { 0x00 }; // build i2c txn: random read starting at 0x00, 256 bytes. static const size_t txMsgsCount = 2; struct i2c_msg txnMsgs[txMsgsCount] = { { .addr = static_cast<__u16>(addr), .flags = I2C_M_RD, .len = sizeof(readCmdBuf), .buf = (__u8 *) (&readCmdBuf) }, { .addr = static_cast<__u16>(addr), .flags = I2C_M_RD, .len = readBufLen, .buf = static_cast<__u8 *>(readBuf), } }; struct i2c_rdwr_ioctl_data txn = { .msgs = txnMsgs, .nmsgs = txMsgsCount }; err = ioctl(fd, I2C_RDWR, &txn); if(err < 0) { PLOG(ERROR) << "Couldn't read from EEPROM (assuming no such device)"; close(fd); return kDiscoveryErrNoSuchDevice; } #endif // success, write the output buffer location *len = readBufLen; return 0; }
23.21
100
0.646273
5c469e86a1ad9a6493481c2c4b692795a8225067
12,826
cpp
C++
libraries/zmusic/mididevices/music_alsa_mididevice.cpp
Erick194/gzdoom
dcb7755716b7f4f6edce6f28b9e316d6de7eda15
[ "RSA-MD" ]
2
2020-04-19T13:37:34.000Z
2021-06-09T04:26:25.000Z
libraries/zmusic/mididevices/music_alsa_mididevice.cpp
Erick194/gzdoom
dcb7755716b7f4f6edce6f28b9e316d6de7eda15
[ "RSA-MD" ]
null
null
null
libraries/zmusic/mididevices/music_alsa_mididevice.cpp
Erick194/gzdoom
dcb7755716b7f4f6edce6f28b9e316d6de7eda15
[ "RSA-MD" ]
null
null
null
/* ** Provides an ALSA implementation of a MIDI output device. ** **--------------------------------------------------------------------------- ** Copyright 2008-2010 Randy Heit ** Copyright 2020 Petr Mrazek ** 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. The name of the author may not be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. **--------------------------------------------------------------------------- ** */ #if defined __linux__ && defined HAVE_SYSTEM_MIDI #include <thread> #include <mutex> #include <condition_variable> #include "mididevice.h" #include "zmusic/m_swap.h" #include "zmusic/mus2midi.h" #include "music_alsa_state.h" #include <alsa/asoundlib.h> namespace { enum class EventType { Null, Delay, Action }; struct EventState { int ticks = 0; snd_seq_event_t data; int size_of = 0; void Clear() { ticks = 0; snd_seq_ev_clear(&data); size_of = 0; } }; class AlsaMIDIDevice : public MIDIDevice { public: AlsaMIDIDevice(int dev_id, int (*printfunc_)(const char *, ...)); ~AlsaMIDIDevice(); int Open() override; void Close() override; bool IsOpen() const override; int GetTechnology() const override; int SetTempo(int tempo) override; int SetTimeDiv(int timediv) override; int StreamOut(MidiHeader *data) override; int StreamOutSync(MidiHeader *data) override; int Resume() override; void Stop() override; bool FakeVolume() override { // Not sure if we even can control the volume this way with Alsa, so make it fake. return true; }; bool Pause(bool paused) override; void InitPlayback() override; bool Update() override; void PrecacheInstruments(const uint16_t *instruments, int count) override {} bool CanHandleSysex() const override { // Assume we can, let Alsa sort it out. We do not truly have full control. return true; } void SendStopEvents(); void SetExit(bool exit); bool WaitForExit(std::chrono::microseconds usec, snd_seq_queue_status_t * status); EventType PullEvent(EventState & state); void PumpEvents(); protected: AlsaSequencer &sequencer; int (*printfunc)(const char*, ...); MidiHeader *Events = nullptr; bool Started = false; uint32_t Position = 0; const static int IntendedPortId = 0; bool Connected = false; int PortId = -1; int QueueId = -1; int DestinationClientId; int DestinationPortId; int Technology; int Tempo = 480000; int TimeDiv = 480; std::thread PlayerThread; bool Exit = false; std::mutex ExitLock; std::condition_variable ExitCond; }; } AlsaMIDIDevice::AlsaMIDIDevice(int dev_id, int (*printfunc_)(const char*, ...) = nullptr) : sequencer(AlsaSequencer::Get()), printfunc(printfunc_) { auto & internalDevices = sequencer.GetInternalDevices(); auto & device = internalDevices.at(dev_id); DestinationClientId = device.ClientID; DestinationPortId = device.PortNumber; Technology = device.GetDeviceClass(); } AlsaMIDIDevice::~AlsaMIDIDevice() { Close(); } int AlsaMIDIDevice::Open() { if (!sequencer.IsOpen()) { return 1; } if(PortId < 0) { snd_seq_port_info_t *pinfo; snd_seq_port_info_alloca(&pinfo); snd_seq_port_info_set_port(pinfo, IntendedPortId); snd_seq_port_info_set_port_specified(pinfo, 1); snd_seq_port_info_set_name(pinfo, "GZDoom Music"); snd_seq_port_info_set_capability(pinfo, 0); snd_seq_port_info_set_type(pinfo, SND_SEQ_PORT_TYPE_MIDI_GENERIC | SND_SEQ_PORT_TYPE_APPLICATION); int err = 0; err = snd_seq_create_port(sequencer.handle, pinfo); PortId = IntendedPortId; } if (QueueId < 0) { QueueId = snd_seq_alloc_named_queue(sequencer.handle, "GZDoom Queue"); } if (!Connected) { Connected = (snd_seq_connect_to(sequencer.handle, PortId, DestinationClientId, DestinationPortId) == 0); } return 0; } void AlsaMIDIDevice::Close() { if(Connected) { snd_seq_disconnect_to(sequencer.handle, PortId, DestinationClientId, DestinationPortId); Connected = false; } if(QueueId >= 0) { snd_seq_free_queue(sequencer.handle, QueueId); QueueId = -1; } if(PortId >= 0) { snd_seq_delete_port(sequencer.handle, PortId); PortId = -1; } } bool AlsaMIDIDevice::IsOpen() const { return Connected; } int AlsaMIDIDevice::GetTechnology() const { return Technology; } int AlsaMIDIDevice::SetTempo(int tempo) { Tempo = tempo; return 0; } int AlsaMIDIDevice::SetTimeDiv(int timediv) { TimeDiv = timediv; return 0; } EventType AlsaMIDIDevice::PullEvent(EventState & state) { state.Clear(); if(!Events) { Callback(CallbackData); if(!Events) { return EventType::Null; } } if (Position >= Events->dwBytesRecorded) { Events = Events->lpNext; Position = 0; if (Callback != NULL) { Callback(CallbackData); } if(!Events) { return EventType::Null; } } uint32_t *event = (uint32_t *)(Events->lpData + Position); state.ticks = event[0]; // Advance to next event. if (event[2] < 0x80000000) { // Short message state.size_of = 12; } else { // Long message state.size_of = 12 + ((MEVENT_EVENTPARM(event[2]) + 3) & ~3); } if (MEVENT_EVENTTYPE(event[2]) == MEVENT_TEMPO) { int tempo = MEVENT_EVENTPARM(event[2]); if(Tempo != tempo) { Tempo = tempo; snd_seq_change_queue_tempo(sequencer.handle, QueueId, Tempo, &state.data); return EventType::Action; } } else if (MEVENT_EVENTTYPE(event[2]) == MEVENT_LONGMSG) { // SysEx messages... uint8_t * data = (uint8_t *)&event[3]; int len = MEVENT_EVENTPARM(event[2]); if (len > 1 && (data[0] == 0xF0 || data[0] == 0xF7)) { snd_seq_ev_set_sysex(&state.data, len, (void *)data); return EventType::Action; } } else if (MEVENT_EVENTTYPE(event[2]) == 0) { // Short MIDI event int command = event[2] & 0xF0; int channel = event[2] & 0x0F; int parm1 = (event[2] >> 8) & 0x7f; int parm2 = (event[2] >> 16) & 0x7f; switch (command) { case MIDI_NOTEOFF: snd_seq_ev_set_noteoff(&state.data, channel, parm1, parm2); return EventType::Action; case MIDI_NOTEON: snd_seq_ev_set_noteon(&state.data, channel, parm1, parm2); return EventType::Action; case MIDI_POLYPRESS: // FIXME: Seems to be missing in the Alsa sequencer implementation break; case MIDI_CTRLCHANGE: snd_seq_ev_set_controller(&state.data, channel, parm1, parm2); return EventType::Action; case MIDI_PRGMCHANGE: snd_seq_ev_set_pgmchange(&state.data, channel, parm1); return EventType::Action; case MIDI_CHANPRESS: snd_seq_ev_set_chanpress(&state.data, channel, parm1); return EventType::Action; case MIDI_PITCHBEND: { long bend = ((long)parm1 + (long)(parm2 << 7)) - 0x2000; snd_seq_ev_set_pitchbend(&state.data, channel, bend); return EventType::Action; } default: break; } } // We didn't really recognize the event, treat it as a delay return EventType::Delay; } void AlsaMIDIDevice::SetExit(bool exit) { std::unique_lock<std::mutex> lock(ExitLock); if(exit != Exit) { Exit = exit; ExitCond.notify_all(); } } bool AlsaMIDIDevice::WaitForExit(std::chrono::microseconds usec, snd_seq_queue_status_t * status) { std::unique_lock<std::mutex> lock(ExitLock); if(Exit) { return true; } ExitCond.wait_for(lock, usec); if(Exit) { return true; } snd_seq_get_queue_status(sequencer.handle, QueueId, status); return false; } /* * Pumps events from the input to the output in a worker thread. * It tries to keep the amount of events (time-wise) in the ALSA sequencer queue to be between 40 and 80ms by sleeping where necessary. * This means Alsa can play them safely without running out of things to do, and we have good control over the events themselves (volume, pause, etc.). */ void AlsaMIDIDevice::PumpEvents() { const std::chrono::microseconds pump_step(40000); // TODO: fill in error handling throughout this. snd_seq_queue_tempo_t *tempo; snd_seq_queue_tempo_alloca(&tempo); snd_seq_queue_tempo_set_tempo(tempo, Tempo); snd_seq_queue_tempo_set_ppq(tempo, TimeDiv); snd_seq_set_queue_tempo(sequencer.handle, QueueId, tempo); snd_seq_start_queue(sequencer.handle, QueueId, NULL); snd_seq_drain_output(sequencer.handle); int buffer_ticks = 0; EventState event; snd_seq_queue_status_t *status; snd_seq_queue_status_malloc(&status); while (true) { auto type = PullEvent(event); // if we reach the end of events, await our doom at a steady rate while looking for more events if(type == EventType::Null) { if(WaitForExit(pump_step, status)) { break; } continue; } // chomp delays as they come... if(type == EventType::Delay) { buffer_ticks += event.ticks; Position += event.size_of; continue; } // Figure out if we should sleep (the event is too far in the future for us to care), and for how long int next_event_tick = buffer_ticks + event.ticks; int queue_tick = snd_seq_queue_status_get_tick_time(status); int tick_delta = next_event_tick - queue_tick; auto usecs = std::chrono::microseconds(tick_delta * Tempo / TimeDiv); auto schedule_time = std::max(std::chrono::microseconds(0), usecs - pump_step); if(schedule_time >= pump_step) { if(WaitForExit(schedule_time, status)) { break; } continue; } if (tick_delta < 0) { if(printfunc) { printfunc("Alsa sequencer underrun: %d ticks!\n", tick_delta); } } // We found an event worthy of sending to the sequencer snd_seq_ev_set_source(&event.data, PortId); snd_seq_ev_set_subs(&event.data); snd_seq_ev_schedule_tick(&event.data, QueueId, false, buffer_ticks + event.ticks); int result = snd_seq_event_output(sequencer.handle, &event.data); if(result < 0) { if(printfunc) { printfunc("Alsa sequencer did not accept event: error %d!\n", result); } if(WaitForExit(pump_step, status)) { break; } continue; } buffer_ticks += event.ticks; Position += event.size_of; snd_seq_drain_output(sequencer.handle); } snd_seq_queue_status_free(status); snd_seq_drop_output(sequencer.handle); // FIXME: the event source should give use these, but it doesn't. { for (int channel = 0; channel < 16; ++channel) { snd_seq_event_t ev; snd_seq_ev_clear(&ev); snd_seq_ev_set_source(&ev, PortId); snd_seq_ev_set_subs(&ev); snd_seq_ev_schedule_tick(&ev, QueueId, true, 0); snd_seq_ev_set_controller(&ev, channel, MIDI_CTL_ALL_NOTES_OFF, 0); snd_seq_event_output(sequencer.handle, &ev); snd_seq_ev_set_controller(&ev, channel, MIDI_CTL_RESET_CONTROLLERS, 0); snd_seq_event_output(sequencer.handle, &ev); } snd_seq_drain_output(sequencer.handle); snd_seq_sync_output_queue(sequencer.handle); } snd_seq_sync_output_queue(sequencer.handle); snd_seq_stop_queue(sequencer.handle, QueueId, NULL); snd_seq_drain_output(sequencer.handle); } int AlsaMIDIDevice::Resume() { if(!Connected) { return 1; } SetExit(false); PlayerThread = std::thread(&AlsaMIDIDevice::PumpEvents, this); return 0; } void AlsaMIDIDevice::InitPlayback() { SetExit(false); } void AlsaMIDIDevice::Stop() { SetExit(true); PlayerThread.join(); } bool AlsaMIDIDevice::Pause(bool paused) { // TODO: implement return false; } int AlsaMIDIDevice::StreamOut(MidiHeader *header) { header->lpNext = NULL; if (Events == NULL) { Events = header; Position = 0; } else { MidiHeader **p; for (p = &Events; *p != NULL; p = &(*p)->lpNext) { } *p = header; } return 0; } int AlsaMIDIDevice::StreamOutSync(MidiHeader *header) { return StreamOut(header); } bool AlsaMIDIDevice::Update() { return true; } MIDIDevice *CreateAlsaMIDIDevice(int mididevice) { return new AlsaMIDIDevice(mididevice, musicCallbacks.Alsa_MessageFunc); } #endif
25.198428
151
0.710432
5c4bd0115b98a0e53944cadf2f743dde628c407f
443
cpp
C++
heap/kSortedArray.cpp
sumana2001/problems450
90b804b7063bb3f11f90b7506576ed14d27e1776
[ "MIT" ]
null
null
null
heap/kSortedArray.cpp
sumana2001/problems450
90b804b7063bb3f11f90b7506576ed14d27e1776
[ "MIT" ]
null
null
null
heap/kSortedArray.cpp
sumana2001/problems450
90b804b7063bb3f11f90b7506576ed14d27e1776
[ "MIT" ]
1
2021-08-19T12:20:06.000Z
2021-08-19T12:20:06.000Z
#include<bits/stdc++.h> using namespace std; int main(){ int arr[]={6, 5, 3, 2, 8, 10, 9}; int n=sizeof(arr)/sizeof(arr[0]); int k=3; priority_queue<int,vector<int>,greater<int> > pq; for(int i=0;i<n;i++){ pq.push(arr[i]); if(pq.size()==k+1){ cout<<pq.top()<<" "; pq.pop(); } } while(!pq.empty()){ cout<<pq.top()<<" "; pq.pop(); } return 0; }
21.095238
53
0.446953
5c4e7d0561f155e336d64344bb8746b7ae1bbc17
3,927
cpp
C++
Source/ISnd2/LoadOgg.cpp
mice777/Insanity3D
49dc70130f786439fb0e4f91b75b6b686a134760
[ "Apache-2.0" ]
2
2022-02-11T11:59:44.000Z
2022-02-16T20:33:25.000Z
Source/ISnd2/LoadOgg.cpp
mice777/Insanity3D
49dc70130f786439fb0e4f91b75b6b686a134760
[ "Apache-2.0" ]
null
null
null
Source/ISnd2/LoadOgg.cpp
mice777/Insanity3D
49dc70130f786439fb0e4f91b75b6b686a134760
[ "Apache-2.0" ]
null
null
null
#include "all.h" #include "loader.h" extern"C"{ #include "vorbis\vorbisfile.h" } #ifdef _DEBUG #pragma comment(lib, "ogg_d.lib") #pragma comment(lib, "vorbis_d.lib") #else #pragma comment(lib, "ogg.lib") #pragma comment(lib, "vorbis.lib") #endif //---------------------------- const int BITDEPTH = 16; //bitdepth of data //---------------------------- static class C_ogg_loader: public C_sound_loader{ static size_t read_func(void *ptr, size_t size, size_t nmemb, void *datasource){ PC_dta_stream dta = (PC_dta_stream)datasource; return dta->Read(ptr, size*nmemb); } static int seek_func(void *datasource, __int64 offset, int whence){ PC_dta_stream dta = (PC_dta_stream)datasource; return dta->Seek((int)offset, whence); } static int close_func(void *datasource){ PC_dta_stream dta = (PC_dta_stream)datasource; dta->Release(); return 0; //return dtaClose((int)datasource) ? 0 : -1; } static long tell_func(void *datasource){ PC_dta_stream dta = (PC_dta_stream)datasource; return dta->Seek(0, DTA_SEEK_CUR); } public: C_ogg_loader() { RegisterSoundLoader(this); } //---------------------------- virtual dword Open(PC_dta_stream dta, const char *file_name, void *header, dword hdr_size, S_wave_format *wf){ //if header is not RIFF, don't bother if(hdr_size<4) return 0; if((*(dword*)header) != 0x5367674f) return 0; OggVorbis_File *vf = new OggVorbis_File; //try to open the file ov_callbacks ovc = { read_func, seek_func, close_func, tell_func }; int vret = ov_open_callbacks(dta, vf, (char*)header, hdr_size, ovc); if(vret != 0){ delete vf; return 0; } //init format vorbis_info *vi = ov_info(vf, -1); assert(vi); wf->num_channels = vi->channels; wf->bytes_per_sample = BITDEPTH/8 * wf->num_channels; wf->samples_per_sec = vi->rate; wf->size = (int)ov_pcm_total(vf, -1) * wf->bytes_per_sample; return (dword)vf; } //---------------------------- virtual void Close(dword handle){ OggVorbis_File *vf = (OggVorbis_File*)handle; assert(vf); ov_clear(vf); delete vf; } //---------------------------- virtual int Read(dword handle, void *mem, dword size){ OggVorbis_File *vf = (OggVorbis_File*)handle; dword read = 0; //must read in multiple chunks (design of VorbisFile?) while(read < size){ int current_section; dword to_read = size - read; int rd1 = ov_read(vf, ((char*)mem) + read, to_read, 0, //little/big endian BITDEPTH/8, //byte-depth BITDEPTH==8 ? 0 : 1, //unsigned=0, signed=1 &current_section); assert(rd1); if(rd1<0) return -1; read += rd1; } assert(read==size); return read; } //---------------------------- virtual int Seek(dword handle, dword pos){ OggVorbis_File *vf = (OggVorbis_File*)handle; //convert position back to samples dword sample = pos / (vf->vi->channels * 2); ov_pcm_seek(vf, sample); /* assert(pos==0); if(pos!=0) return -1; if(ov_pcm_tell(vf)!=0){ //re-open int h = (int)vf->datasource; vf->datasource = NULL; int ok; ok = ov_clear(vf); assert(!ok); dtaSeek(h, 0, DTA_SEEK_SET); ov_callbacks ovc = { read_func, seek_func, close_func, tell_func }; ok = ov_open_callbacks((void*)h, vf, NULL, 0, ovc); assert(!ok); } */ return pos; } } ogg_loader; //----------------------------
26.355705
113
0.531449
5c56baa2acd3c5c05d37e50e16780bdc49fe6f47
6,068
cpp
C++
QtWebApp/httpserver/staticfilecontroller.cpp
cbcalves/crudQtTest
f10c83934abaca6d17f57e2b0aa0e6c8844bfdda
[ "MIT" ]
null
null
null
QtWebApp/httpserver/staticfilecontroller.cpp
cbcalves/crudQtTest
f10c83934abaca6d17f57e2b0aa0e6c8844bfdda
[ "MIT" ]
null
null
null
QtWebApp/httpserver/staticfilecontroller.cpp
cbcalves/crudQtTest
f10c83934abaca6d17f57e2b0aa0e6c8844bfdda
[ "MIT" ]
null
null
null
/** @file @author Stefan Frings */ #include "staticfilecontroller.h" #include <QFileInfo> #include <QDir> #include <QDateTime> using namespace stefanfrings; StaticFileController::StaticFileController( const QSettings* settings, QObject* parent ) : HttpRequestHandler( parent ), m_encoding( settings->value( "encoding", "UTF-8" ).toString() ), m_docroot( settings->value( "path", "." ).toString() ), m_maxAge( settings->value( "maxAge", "60000" ).toInt() ), m_cacheTimeout( settings->value( "cacheTime", "60000" ).toInt() ), m_maxCachedFileSize( settings->value( "maxCachedFileSize", "65536" ).toInt() ) { if ( !( m_docroot.startsWith( ":/" ) || m_docroot.startsWith( "qrc://" ) ) ) { // Convert relative path to absolute, based on the directory of the config file. #ifdef Q_OS_WIN32 if ( QDir::isRelativePath( docroot ) && settings->format() != QSettings::NativeFormat ) #else if ( QDir::isRelativePath( m_docroot ) ) #endif { QFileInfo configFile( settings->fileName() ); m_docroot=QFileInfo( configFile.absolutePath(), m_docroot ).absoluteFilePath(); } } m_cache.setMaxCost( settings->value( "cacheSize", "1000000" ).toInt() ); #ifdef SUPERVERBOSE qDebug( "StaticFileController: docroot=%s, encoding=%s, maxAge=%i", qPrintable( m_docroot ), qPrintable( m_encoding ), m_maxAge ); long int cacheMaxCost=(long int)m_cache.maxCost(); qDebug( "StaticFileController: cache timeout=%i, size=%li", m_cacheTimeout, cacheMaxCost ); #endif } void StaticFileController::service( HttpRequest& request, HttpResponse& response ) { QByteArray path = request.getPath(); // Check if we have the file in cache qint64 now = QDateTime::currentMSecsSinceEpoch(); m_mutex.lock(); CacheEntry* entry = m_cache.object( path ); if ( entry && ( m_cacheTimeout == 0 || entry->created>now - m_cacheTimeout ) ) { QByteArray document = entry->document; //copy the cached document, because other threads may destroy the cached entry immediately after mutex unlock. QByteArray filename = entry->filename; m_mutex.unlock(); #ifdef SUPERVERBOSE qDebug( "StaticFileController: Cache hit for %s", path.data() ); #endif setContentType( filename, response ); response.setHeader( "Cache-Control", "max-age=" + QByteArray::number( m_maxAge / 1000 ) ); response.write( document, true ); return; } m_mutex.unlock(); // The file is not in cache. #ifdef SUPERVERBOSE qDebug( "StaticFileController: Cache miss for %s", path.data() ); #endif // Forbid access to files outside the docroot directory if ( path.contains( "/.." ) ) { qWarning( "StaticFileController: detected forbidden characters in path %s", path.data() ); response.setStatus( 403, "forbidden" ); response.write( "403 forbidden", true ); return; } // If the filename is a directory, append index.html. if ( QFileInfo( m_docroot + path ).isDir() ) { path += "/index.html"; } // Try to open the file QFile file( m_docroot + path ); #ifdef SUPERVERBOSE qDebug( "StaticFileController: Open file %s", qPrintable( file.fileName() ) ); #endif if ( file.open( QIODevice::ReadOnly ) ) { setContentType( path, response ); response.setHeader( "Cache-Control", "max-age=" + QByteArray::number( m_maxAge / 1000 ) ); response.setHeader( "Content-Length", QByteArray::number( file.size() ) ); if ( file.size() <= m_maxCachedFileSize ) { // Return the file content and store it also in the cache entry = new CacheEntry(); while ( !file.atEnd() && !file.error() ) { QByteArray buffer = file.read( 65536 ); response.write( buffer, false ); entry->document.append( buffer, false ); } entry->created = now; entry->filename = path; m_mutex.lock(); m_cache.insert( request.getPath(), entry, entry->document.size() ); m_mutex.unlock(); } else { // Return the file content, do not store in cache while ( !file.atEnd() && !file.error() ) { response.write( file.read( 65536 ) ); } } file.close(); return; } if ( file.exists() ) { qWarning( "StaticFileController: Cannot open existing file %s for reading", qPrintable( file.fileName() ) ); response.setStatus( 403, "forbidden" ); response.write( "403 forbidden", true ); return; } response.setStatus( 404, "not found" ); response.write( "404 not found", true ); } void StaticFileController::setContentType( const QString& fileName, HttpResponse& response ) const { // Todo: add all of your content types const QMap<QString, QString> contentTypeMap = { { ".png", "image/png" }, { ".jpg", "image/jpeg" }, { ".gif", "image/gif" }, { ".pdf", "application/pdf" }, { ".txt", "text/plain; charset=" + m_encoding }, { ".html", "text/html; charset=" + m_encoding }, { ".htm", "text/html; charset=" + m_encoding }, { ".css", "text/css" }, { ".js", "text/javascript" }, { ".svg", "image/svg+xml" }, { ".woff", "font/woff" }, { ".woff2", "font/woff2" }, { ".ttf", "application/x-font-ttf" }, { ".eot", "application/vnd.ms-fontobject" }, { ".otf", "application/font-otf" }, { ".json", "application/json" }, { ".xml", "text/xml" }, }; for ( auto contentType = contentTypeMap.cbegin(); contentType != contentTypeMap.cend(); ++contentType ) { if ( fileName.endsWith( contentType.key() ) ) { response.setHeader( "Content-Type", qPrintable( contentType.value() ) ); return; } } qWarning( "StaticFileController: unknown MIME type for filename '%s'", qPrintable( fileName ) ); }
38.897436
157
0.599044
5c56c79b9d72ec05c7afc418b555be8c4cd08aee
579
hpp
C++
src/common/idtypes/brushid.hpp
squeevee/Addle
20ec4335669fbd88d36742f586899d8416920959
[ "MIT" ]
3
2020-03-05T06:36:51.000Z
2020-06-20T03:25:02.000Z
src/common/idtypes/brushid.hpp
squeevee/Addle
20ec4335669fbd88d36742f586899d8416920959
[ "MIT" ]
13
2020-03-11T17:43:42.000Z
2020-12-11T03:36:05.000Z
src/common/idtypes/brushid.hpp
squeevee/Addle
20ec4335669fbd88d36742f586899d8416920959
[ "MIT" ]
1
2020-09-28T06:53:46.000Z
2020-09-28T06:53:46.000Z
/** * Addle source code * @file * @copyright Copyright 2020 Eleanor Hawk * @copyright Modification and distribution permitted under the terms of the * MIT License. See "LICENSE" for full details. */ #ifndef BRUSHID_HPP #define BRUSHID_HPP #include "addleid.hpp" #include "brushengineid.hpp" namespace Addle { class ADDLE_COMMON_EXPORT BrushId final : public AddleId { ID_TYPE_BOILERPLATE(BrushId) }; } // namespace Addle Q_DECLARE_METATYPE(Addle::BrushId) Q_DECLARE_TYPEINFO(Addle::BrushId, Q_PRIMITIVE_TYPE); ID_TYPE_BOILERPLATE2(BrushId); #endif // BRUSHID_HPP
20.678571
76
0.768566
5c5ac118797daf1cc64df7b8b0f9c2c3a17b9590
9,723
hpp
C++
include/libndgpp/net/basic_ipv4_address.hpp
goodfella/libndgpp
2e3d4b993a04664905c1e257fb2af3a5faab5296
[ "MIT" ]
null
null
null
include/libndgpp/net/basic_ipv4_address.hpp
goodfella/libndgpp
2e3d4b993a04664905c1e257fb2af3a5faab5296
[ "MIT" ]
null
null
null
include/libndgpp/net/basic_ipv4_address.hpp
goodfella/libndgpp
2e3d4b993a04664905c1e257fb2af3a5faab5296
[ "MIT" ]
null
null
null
#ifndef LIBNDGPP_NET_BASIC_IPV4_ADDRESS_HPP #define LIBNDGPP_NET_BASIC_IPV4_ADDRESS_HPP #include <cstdint> #include <array> #include <ostream> #include <stdexcept> #include <string> #include <type_traits> #include <libndgpp/error.hpp> #include <libndgpp/net/ipv4_array.hpp> namespace ndgpp { namespace net { template <uint32_t Min, uint32_t Max> struct basic_ipv4_address_validator { constexpr bool operator () (uint32_t value) { if (value < Min || value > Max) { throw ndgpp_error(std::out_of_range, "supplied address out of range"); } return true; } }; template <> struct basic_ipv4_address_validator<0, 0xffffffff> { constexpr bool operator () (uint32_t value) noexcept { return true; } }; /** IPv4 address value type * * @tparam Min The minimum address value in network byte order * @tparam Max The maximum address value in network byte order * * @par Move Semantics * Move operations behave just like copy operations */ template <uint32_t Min = 0, uint32_t Max = 0xffffffff> class basic_ipv4_address final { public: using value_type = ndgpp::net::ipv4_array; /// The minimum address value in network byte order static constexpr uint32_t min = Min; /// The maximum address value in network byte order static constexpr uint32_t max = Max; using constrained_bool_type = std::conditional_t<Min == 0x0 && Max == 0xffffffff, std::false_type, std::true_type>; static constexpr bool constrained = constrained_bool_type::value; /// Constructs an address assigned to Min constexpr basic_ipv4_address() noexcept; template <uint32_t MinO, uint32_t MaxO> constexpr basic_ipv4_address(const basic_ipv4_address<MinO, MaxO> & other) noexcept(MinO >= Min && MaxO <= Max); /// Constructs an address assigned to the value provided constexpr basic_ipv4_address(const value_type value) noexcept(!constrained); /** Constructs an address from an unsigned 32 bit integer * * The parameter's value is mapped to the address octet like * so: * * address[0] = (value >> 24) & 0xff000000; * address[1] = (value >> 16) & 0x00ff0000; * address[2] = (value >> 8) & 0x0000ff00; * address[3] = value & 0x000000ff; * * @param An unsigned 32 bit integer */ explicit constexpr basic_ipv4_address(const uint32_t value) noexcept(!constrained); /** Constructs an address from a string * * @param value A string representing an IP address in dotted * quad notation. The string can be optionally * terminated by a colon. */ explicit basic_ipv4_address(const std::string & value); basic_ipv4_address & operator = (const basic_ipv4_address & value) noexcept; /// Assignes the address based on the value_type value basic_ipv4_address & operator = (const value_type value) noexcept(!constrained); /// Assignes the address based on the passed in unsigned 32 bit value basic_ipv4_address & operator = (const uint32_t value) noexcept (!constrained); /// Assignes the address based on the passed in dotted quad string value basic_ipv4_address & operator = (const std::string & value); void swap(basic_ipv4_address & other) noexcept; constexpr uint8_t operator[] (const std::size_t index) const noexcept; constexpr ndgpp::net::ipv4_array value() const noexcept; /** Returns the address as an unsigned 32 bit integer * * The address is mapped to the value like so: * * addr[0] << 24 | addr[1] << 16 | addr[2] << 8 | addr[3] */ constexpr uint32_t to_uint32() const noexcept; /// Returns the address as a dotted quad string std::string to_string() const; private: ndgpp::net::ipv4_array value_ = {ndgpp::net::make_ipv4_array(Min)}; }; template <uint32_t Min, uint32_t Max> constexpr basic_ipv4_address<Min, Max>::basic_ipv4_address() noexcept = default; template <uint32_t Min, uint32_t Max> template <uint32_t MinO, uint32_t MaxO> constexpr basic_ipv4_address<Min, Max>::basic_ipv4_address(const basic_ipv4_address<MinO, MaxO> & addr) noexcept(MinO >= Min && MaxO <= Max): value_ {addr.value()} { if (!(MinO >= Min && MaxO <= Max)) { basic_ipv4_address_validator<Min, Max> {} (this->to_uint32()); } } template <uint32_t Min, uint32_t Max> constexpr basic_ipv4_address<Min, Max>::basic_ipv4_address(const ndgpp::net::ipv4_array value) noexcept(!basic_ipv4_address::constrained): value_ {value} { basic_ipv4_address_validator<Min, Max> {} (this->to_uint32()); } template <uint32_t Min, uint32_t Max> constexpr basic_ipv4_address<Min, Max>::basic_ipv4_address(const uint32_t value) noexcept(!basic_ipv4_address::constrained): value_ {ndgpp::net::make_ipv4_array(value)} { basic_ipv4_address_validator<Min, Max> {} (value); } template <uint32_t Min, uint32_t Max> basic_ipv4_address<Min, Max>::basic_ipv4_address(const std::string & value): value_ {ndgpp::net::make_ipv4_array(value)} { basic_ipv4_address_validator<Min, Max> {} (this->to_uint32()); } template <uint32_t Min, uint32_t Max> basic_ipv4_address<Min, Max> & basic_ipv4_address<Min, Max>::operator = (const basic_ipv4_address &) noexcept = default; template <uint32_t Min, uint32_t Max> basic_ipv4_address<Min, Max> & basic_ipv4_address<Min, Max>::operator = (const ndgpp::net::ipv4_array rhs) noexcept(!basic_ipv4_address::constrained) { this->value_ = rhs; basic_ipv4_address_validator<Min, Max> {} (this->to_uint32()); return *this; } template <uint32_t Min, uint32_t Max> basic_ipv4_address<Min, Max> & basic_ipv4_address<Min, Max>::operator = (const uint32_t rhs) noexcept(!basic_ipv4_address::constrained) { this->value_ = ndgpp::net::make_ipv4_array(rhs); basic_ipv4_address_validator<Min, Max> {} (rhs); return *this; } template <uint32_t Min, uint32_t Max> basic_ipv4_address<Min, Max> & basic_ipv4_address<Min, Max>::operator = (const std::string & rhs) { this->value_ = ndgpp::net::make_ipv4_array(rhs); basic_ipv4_address_validator<Min, Max> {} (this->to_uint32()); return *this; } template <uint32_t Min, uint32_t Max> void basic_ipv4_address<Min, Max>::swap(basic_ipv4_address & other) noexcept { std::swap(this->value_, other.value_); } template <uint32_t Min, uint32_t Max> inline constexpr uint8_t basic_ipv4_address<Min, Max>::operator [] (const std::size_t index) const noexcept { return this->value_[index]; } template <uint32_t Min, uint32_t Max> inline constexpr ndgpp::net::ipv4_array basic_ipv4_address<Min, Max>::value() const noexcept { return this->value_; } template <uint32_t Min, uint32_t Max> inline constexpr uint32_t basic_ipv4_address<Min, Max>::to_uint32() const noexcept { return ndgpp::net::to_uint32(this->value_); } template <uint32_t Min, uint32_t Max> inline std::string basic_ipv4_address<Min, Max>::to_string() const { return ndgpp::net::to_string(this->value_); } template <uint32_t Min, uint32_t Max> void swap(basic_ipv4_address<Min, Max> & lhs, basic_ipv4_address<Min, Max> & rhs) { lhs.swap(rhs); } template <uint32_t Min, uint32_t Max> inline std::ostream & operator <<(std::ostream & stream, const basic_ipv4_address<Min, Max> address) { stream << static_cast<uint16_t>(address[0]); for (std::size_t i = 1; i < std::tuple_size<typename ndgpp::net::basic_ipv4_address<Min, Max>::value_type>::value; ++i) { stream.put('.'); stream << static_cast<uint16_t>(address[i]); } return stream; } template <uint32_t Min, uint32_t Max> inline bool operator ==(const basic_ipv4_address<Min, Max> lhs, const basic_ipv4_address<Min, Max> rhs) { return lhs.value() == rhs.value(); } template <uint32_t Min, uint32_t Max> inline bool operator !=(const basic_ipv4_address<Min, Max> lhs, const basic_ipv4_address<Min, Max> rhs) { return !(lhs == rhs); } template <uint32_t Min, uint32_t Max> inline bool operator <(const basic_ipv4_address<Min, Max> lhs, const basic_ipv4_address<Min, Max> rhs) { return lhs.value() < rhs.value(); } template <uint32_t Min, uint32_t Max> inline bool operator >=(const basic_ipv4_address<Min, Max> lhs, const basic_ipv4_address<Min, Max> rhs) { return !(lhs < rhs); } template <uint32_t Min, uint32_t Max> inline bool operator >(const basic_ipv4_address<Min, Max> lhs, const basic_ipv4_address<Min, Max> rhs) { return rhs < lhs; } template <uint32_t Min, uint32_t Max> inline bool operator <=(const basic_ipv4_address<Min, Max> lhs, const basic_ipv4_address<Min, Max> rhs) { return !(rhs < lhs); } }} #endif
33.297945
145
0.62851
5c5b2e32ee0cb2e0eff0ad49eb36a5548fb36d85
1,303
cpp
C++
src/test.cpp
bveenema/MM_Lib-Particle
84973f565d4b6de8edd395c09fd9cb7e37a4042e
[ "MIT" ]
null
null
null
src/test.cpp
bveenema/MM_Lib-Particle
84973f565d4b6de8edd395c09fd9cb7e37a4042e
[ "MIT" ]
null
null
null
src/test.cpp
bveenema/MM_Lib-Particle
84973f565d4b6de8edd395c09fd9cb7e37a4042e
[ "MIT" ]
null
null
null
// Example usage for MM_Lib-Particle library by Veenema Design Works. #include "Particle.h" #include "MM_Lib-Particle.h" void setup(); void loop(); SYSTEM_MODE(SEMI_AUTOMATIC); // Initialize the Manager (MUST BE DONE BEFORE ANY SETTINGS OR STATE) MM_Manager AppManager(10); // Initialize objects from the lib MM_Input<int> MyInt("Setting", 0); MM_Input<unsigned> MyUnsigned("Unsigned"); MM_Input<uint8_t> MyUint8_t("uint8_t"); MM_Input<float> MyFloat("float"); MM_Input<double> MyDouble("double"); MM_Input<upFloat_t<3>> MyUPFloat3("Psuedo-Float"); void setup() { delay(1000); MyInt = -30; MyInt.min = -256; MyInt.max = 256; MyInt.def = 10; strcpy(MyInt.unit, "Unit"); MyUnsigned = 10; MyUint8_t = 255; MyFloat = 3.14; MyDouble = 3.14568910289471292842582; MyUPFloat3 = (float)6; AppManager.Add(MyInt); AppManager.Add(MyUnsigned); AppManager.Add(MyUint8_t); AppManager.Add(MyFloat); AppManager.Add(MyDouble); AppManager.Add(MyUPFloat3); AppManager.OnReady([](){ AppManager.test(); }); } void loop() { static unsigned LastValueUpdate = 0; if(millis() - LastValueUpdate > 250) { LastValueUpdate = millis(); // MyInt += 1; // AppManager.DebugPrintf("MyInt: %i", (int)MyInt); } } void serialEvent() { if(WiFi.listening()) return; AppManager.Read(Serial.read()); }
20.68254
69
0.707598
5c5d4896cdef7918d1b9b1b525726cbddbafd513
597
hxx
C++
code/src/Profile.hxx
Angew/AnyBak
66146b4b94e18ce7d215f1132752d33e4cddf1ed
[ "MIT" ]
null
null
null
code/src/Profile.hxx
Angew/AnyBak
66146b4b94e18ce7d215f1132752d33e4cddf1ed
[ "MIT" ]
null
null
null
code/src/Profile.hxx
Angew/AnyBak
66146b4b94e18ce7d215f1132752d33e4cddf1ed
[ "MIT" ]
null
null
null
#pragma once #include "RuleSet.hh" #include "VolumeRegistry.hh" #include "VolumeSet.hh" #include <memory> class Profile { public: const RuleSet& getRuleSet() const { return getRuleSet_impl(); } RuleSet& getRuleSet() { return getRuleSet_impl(); } const VolumeRegistry& getVolumeRegistry() const { return getVolumeRegistry_impl(); } VolumeRegistry& getVolumeRegistry() { return getVolumeRegistry_impl(); } virtual bool createVolumes(VolumeSet &volumes) const = 0; protected: virtual RuleSet& getRuleSet_impl() const = 0; virtual VolumeRegistry& getVolumeRegistry_impl() const = 0; };
22.961538
85
0.755444
5c5e6063275e112ec3c117a6c97cc9442bf36d9b
996
cpp
C++
leetcode/1014.cpp
laiyuling424/LeetCode
afb582026b4d9a4082fdb99fc65b437e55d1f64d
[ "Apache-2.0" ]
null
null
null
leetcode/1014.cpp
laiyuling424/LeetCode
afb582026b4d9a4082fdb99fc65b437e55d1f64d
[ "Apache-2.0" ]
null
null
null
leetcode/1014.cpp
laiyuling424/LeetCode
afb582026b4d9a4082fdb99fc65b437e55d1f64d
[ "Apache-2.0" ]
null
null
null
// // Created by 赖於领 on 2021/9/1. // #include <vector> #include <iostream> using namespace std; //最佳观光组合 class Solution { public: int maxScoreSightseeingPair(vector<int> &values) { // if (values.size() == 2) { // return values[0] + values[1] - 1; // } //values[i]+values[j]+i-j = int n = values.size(); vector<int> r(n, 0); vector<int> sums(n, 0); r[0] = values[0]; sums[0] = INT_MIN; for (int i = 1; i < n; i++) { r[i] = max(r[i - 1], values[i - 1]) - 1; sums[i] = max(sums[i - 1], r[i] + values[i]); cout << "i is " << i << " " << r[i] << " " << sums[i] << endl; } return sums[n - 1]; } }; //int main() { // // Solution *solution = new Solution(); //// vector<int> a = {8, 1, 5, 2, 6}; // vector<int> a = {1, 2}; //// vector<int> a = {1, 3, 5}; // cout << solution->maxScoreSightseeingPair(a) << endl; // // return 0; //}
21.191489
78
0.447791
5c5f2368e1c6d05bba92409dbfefcac47bc0d744
1,343
cpp
C++
src/src/collision_sphere.cpp
crr0004/terrian_prototype
34b04239ee2fb01e48f1602ff6dd08e8bd26da63
[ "MIT" ]
2
2015-11-05T20:08:00.000Z
2016-07-07T04:17:07.000Z
src/src/collision_sphere.cpp
crr0004/terrian_prototype
34b04239ee2fb01e48f1602ff6dd08e8bd26da63
[ "MIT" ]
3
2016-10-29T02:20:49.000Z
2017-04-01T11:09:53.000Z
src/src/collision_sphere.cpp
crr0004/terrian_prototype
34b04239ee2fb01e48f1602ff6dd08e8bd26da63
[ "MIT" ]
null
null
null
#include "collision/spherecollider.hpp" #include "collision/aabbcollider.hpp" #include <cstddef> using namespace Collision; SphereCollider::SphereCollider(const glm::vec3& center, const float radius){ this->center = glm::vec3(center); this->radius = radius; } bool SphereCollider::visitCollide(Collider* node){ return node->visitCollide(this); } bool SphereCollider::visitCollide(AABBCollider* aabb){ glm::vec3 q; glm::vec3 center = getTransformedCenter(); glm::vec3 min = aabb->getTransformedMin(); glm::vec3 max = aabb->getTransformedMax(); for (int i = 0; i < 3; i++) { float v = center[i]; if (v < min[i]) v = min[i]; // v = max(v, b.min[i]) if (v > max[i]) v = max[i]; // v = min(v, b.max[i]) q[i] = v; } glm::vec3 v = q - center; return glm::dot(v,v) <= this->radius * this->radius; } bool SphereCollider::visitCollide(SphereCollider* sphere){ glm::vec3 d = this->getTransformedCenter() - sphere->getTransformedCenter(); float dist2 = glm::dot(d, d); float radiusSum = this->radius + sphere->getRadius(); return dist2 <= radiusSum * radiusSum; } void SphereCollider::notifyCollider(Collider* collider){ } glm::vec3 SphereCollider::getTransformedCenter(){ return glm::vec3(moveable.getCulumativeMatrix() * glm::vec4(center, 1.0f)); } Geometry::Moveable& SphereCollider::getMoveable(){ return moveable; }
28.574468
77
0.694713
5c60f0151b28f916dc90688f5b7d0b866658f1ec
676
cpp
C++
demos/multiplatform/delay/source/main.cpp
SarahS16/SJSU-Dev2
47f9ddb7d3c3743f839b57f381bf979dd61d49ab
[ "Apache-2.0" ]
6
2020-06-20T23:56:42.000Z
2021-12-18T08:13:54.000Z
demos/multiplatform/delay/source/main.cpp
SarahS16/SJSU-Dev2
47f9ddb7d3c3743f839b57f381bf979dd61d49ab
[ "Apache-2.0" ]
153
2020-06-09T14:49:29.000Z
2022-01-31T16:39:39.000Z
demos/multiplatform/delay/source/main.cpp
SarahS16/SJSU-Dev2
47f9ddb7d3c3743f839b57f381bf979dd61d49ab
[ "Apache-2.0" ]
10
2020-08-02T00:55:38.000Z
2022-01-24T23:06:51.000Z
#include <cinttypes> #include <cstdint> #include "utility/log.hpp" #include "utility/time/time.hpp" int main() { sjsu::LogInfo("Delay Application Starting..."); sjsu::LogInfo("This demo prints a statement every second using Delay(1s)."); sjsu::LogInfo( "Notice that the uptime does not increase by 1 second but by a little " "more then that."); sjsu::LogInfo( "This is due to the fact that we delay for a whole second, but it takes " "time to print each statement."); int counter = 0; while (true) { sjsu::LogInfo( "[%d] Uptime = %" PRId64 "ns", counter++, sjsu::Uptime().count()); sjsu::Delay(1s); } return 0; }
23.310345
79
0.633136
5c63ad45055fc5b87ccc0f9aa9c7696d28857b5d
4,991
cc
C++
Source/BladeBase/source/graphics/RenderProperty.cc
OscarGame/blade
6987708cb011813eb38e5c262c7a83888635f002
[ "MIT" ]
146
2018-12-03T08:08:17.000Z
2022-03-21T06:04:06.000Z
Source/BladeBase/source/graphics/RenderProperty.cc
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
1
2019-01-18T03:35:49.000Z
2019-01-18T03:36:08.000Z
Source/BladeBase/source/graphics/RenderProperty.cc
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
31
2018-12-03T10:32:43.000Z
2021-10-04T06:31:44.000Z
/******************************************************************** created: 2011/12/21 filename: RenderProperty.cc author: Crazii purpose: *********************************************************************/ #include <BladePCH.h> #include <interface/public/graphics/RenderProperty.h> #include <interface/public/graphics/ITexture.h> namespace Blade { template class FixedArray<HRENDERPROPERTY,RPT_COUNT>; /************************************************************************/ /* */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// IRenderProperty* IRenderProperty::createProperty(RENDER_PROPERTY eProp) { switch(eProp) { case RPT_COLOR: return BLADE_NEW ColorProperty(); case RPT_COLORWIRTE: return BLADE_NEW ColorWriteProperty(); case RPT_FOG: return BLADE_NEW FogProperty(); case RPT_ALPHABLEND: return BLADE_NEW AlphaBlendProperty(); case RPT_DEPTH: return BLADE_NEW DepthProperty(); case RPT_STENCIL: return BLADE_NEW StencilProperty(); case RPT_SCISSOR: return BLADE_NEW ScissorProperty(); default: break; } assert(false); return NULL; } ////////////////////////////////////////////////////////////////////////// IRenderProperty* IRenderProperty::cloneProperty(IRenderProperty* prop) { if(prop == NULL) return NULL; switch(prop->getType()) { case RPT_COLOR: return BLADE_NEW ColorProperty( *static_cast<ColorProperty*>(prop) ); case RPT_COLORWIRTE: return BLADE_NEW ColorWriteProperty( *static_cast<ColorWriteProperty*>(prop) ); case RPT_FOG: return BLADE_NEW FogProperty( *static_cast<FogProperty*>(prop) ); case RPT_ALPHABLEND: return BLADE_NEW AlphaBlendProperty( *static_cast<AlphaBlendProperty*>(prop) ); case RPT_DEPTH: return BLADE_NEW DepthProperty( *static_cast<DepthProperty*>(prop) ); case RPT_STENCIL: return BLADE_NEW StencilProperty( *static_cast<StencilProperty*>(prop) ); case RPT_SCISSOR: return BLADE_NEW ScissorProperty( *static_cast<ScissorProperty*>(prop) ); default: break; } assert(false); return NULL; } /************************************************************************/ /* */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// bool RenderPropertySet::addProperty(const HRENDERPROPERTY& hProp) { if( hProp == NULL || this->hasProperty(hProp->getType())) return false; RENDER_PROPERTY eRP = hProp->getType(); if( eRP < RPT_COUNT ) { HRENDERPROPERTY& hTarget = mPropertyList[eRP]; assert(hTarget == NULL ); hTarget = hProp; mPropertyMask.raiseBitAtIndex(eRP); return true; } else return false; } ////////////////////////////////////////////////////////////////////////// bool RenderPropertySet::setProperty(const HRENDERPROPERTY& hProp) { if( hProp == NULL ) return false; RENDER_PROPERTY eRP = hProp->getType(); if( eRP < RPT_COUNT ) { mPropertyList[eRP] = hProp; mPropertyMask.raiseBitAtIndex(eRP); return true; } else return false; } ////////////////////////////////////////////////////////////////////////// bool RenderPropertySet::removeProperty(RENDER_PROPERTY eRP) { if( eRP < RPT_COUNT ) { HRENDERPROPERTY& hProp = mPropertyList[eRP]; hProp.clear(); mPropertyMask.clearBitAtIndex(eRP); return true; } else return false; } ////////////////////////////////////////////////////////////////////////// void RenderPropertySet::mergeProperties(const RenderPropertySet& mergeSource) { for(int i = RPT_BEGIN; i < RPT_COUNT; ++i) { RENDER_PROPERTY eProp = (RENDER_PROPERTY)i; if( mergeSource.hasProperty(eProp) ) this->setProperty(mergeSource.getProperty(eProp)); } //mCullMode = mergeSource.mCullMode; //FIXME: } ////////////////////////////////////////////////////////////////////////// const HRENDERPROPTYSET& RenderPropertySet::getDefaultRenderProperty() { static HRENDERPROPTYSET DEFAULT_PROPERTY; if( DEFAULT_PROPERTY == NULL ) { DEFAULT_PROPERTY.lock(); DEFAULT_PROPERTY.bind( BLADE_NEW RenderPropertySet() ); Lock::memoryBarrier(); DEFAULT_PROPERTY.unlock(); } return DEFAULT_PROPERTY; } /************************************************************************/ /* */ /************************************************************************/ const Sampler Sampler::DEFAULT; const Sampler Sampler::DEFAULT_RTT(TAM_CLAMP, TAM_CLAMP, TAM_CLAMP, TFM_LINEAR, TFM_LINEAR, TFM_LINEAR, 0.0f, 0.0f); const Sampler Sampler::DEFAULT_RTT_DEPTH(TAM_CLAMP, TAM_CLAMP, TAM_CLAMP, TFM_POINT, TFM_POINT, TFM_POINT, 0.0f, 0.0f); }//namespace Blade
31
120
0.530154
5c65d2b705eadf9e53f5d161593f3221b758eaa0
2,763
cpp
C++
src/ChunkHandlerSFNC.cpp
Peralex/pxgf
a4ea0ad5d2d2ff3b909782c22ef6488a0ac81662
[ "Apache-2.0" ]
1
2017-12-20T14:27:01.000Z
2017-12-20T14:27:01.000Z
src/ChunkHandlerSFNC.cpp
Peralex/pxgf
a4ea0ad5d2d2ff3b909782c22ef6488a0ac81662
[ "Apache-2.0" ]
null
null
null
src/ChunkHandlerSFNC.cpp
Peralex/pxgf
a4ea0ad5d2d2ff3b909782c22ef6488a0ac81662
[ "Apache-2.0" ]
null
null
null
// Copyright 2006 Peralex Electronics (Pty) Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // LIBRARY INCLUDE FILES #include <cstring> #include "handlers/ChunkHandlerSFNC.h" #include "handlers/PxgfHandlerException.h" #include "SwapEndian.h" namespace pxgf { using namespace std; cChunkHandlerSFNC::cChunkHandlerSFNC() : m_pCallbackSFNCHandler(nullptr) { } void cChunkHandlerSFNC::registerCallbackHandler(cCallbackSFNC *pHandler) { m_pCallbackSFNCHandler = pHandler; } bool cChunkHandlerSFNC::processChunk(const vector<char> &vchData, bool bBigEndian) { // check that there is enough data for an even number of floats if(((vchData.size()) & 0x3) != 0) return false; if(m_pCallbackSFNCHandler == nullptr) { return true; } int64_t lTimestamp_ns = *(int64_t *)vchData.data(); int iLength = (vchData.size() - 8) / sizeof(float); //vector<float> vfIqData (iLength); m_vfIqData.resize(iLength); memcpy(&m_vfIqData[0], &vchData[8], iLength * sizeof(float)); if(cPXGWriterBase::getIsLocalBigEndian() != bBigEndian) { SWAP_INT64(lTimestamp_ns); for(vector<float>::iterator it = m_vfIqData.begin(); it != m_vfIqData.end(); it++) SWAP_FLOAT(*it); } m_pCallbackSFNCHandler->callbackSFNC(lTimestamp_ns, m_vfIqData); return true; } void cChunkHandlerSFNC::writeChunkSFNC(cPXGWriterBase &stream, int64_t lTimestamp_ns, const vector<float> &vfIqData) const { stream.writeChunkHeader(*this, 8 + vfIqData.size() * sizeof(float)); stream.writeInt64(lTimestamp_ns); stream.writeFloatArray(vfIqData); } void cChunkHandlerSFNC::repack(const cPackingSIQP &oInputPacking, const cPackingSIQP &oOutputPacking, const vector<float> &vfInputIQData, vector<float> &vfOutputData) { if(oInputPacking.equals(oOutputPacking)) { vfOutputData = vfInputIQData; return; } // check that there are an even number of elements if((vfInputIQData.size() & 0x1) != 0) throw cPxgfHandlerException("The length of vfInputIQData must be even."); // swap IQ data vfOutputData.resize(vfInputIQData.size()); for(unsigned uSample = 0; uSample < vfInputIQData.size(); uSample += 2) { vfOutputData[uSample] = vfInputIQData[uSample + 1]; vfOutputData[uSample + 1] = vfInputIQData[uSample]; } } }
32.892857
167
0.734347
5c67c4dc7eed0fa630f41634250e101387f5b1a3
2,710
cpp
C++
src/baekjoon_solutions/q2178/main_q2178.cpp
OptimistLabyrinth/competitive_programming
92ef372053813fbeca8f7b1f0cde90555e2ea1d8
[ "Apache-2.0" ]
null
null
null
src/baekjoon_solutions/q2178/main_q2178.cpp
OptimistLabyrinth/competitive_programming
92ef372053813fbeca8f7b1f0cde90555e2ea1d8
[ "Apache-2.0" ]
null
null
null
src/baekjoon_solutions/q2178/main_q2178.cpp
OptimistLabyrinth/competitive_programming
92ef372053813fbeca8f7b1f0cde90555e2ea1d8
[ "Apache-2.0" ]
null
null
null
#include <deque> #include <iostream> #include <sstream> #include <vector> using namespace std; int horizontal_length; int vertical_length; vector<vector<bool>> maze; vector<vector<bool>> is_visited; deque<pair<int, int>> neighboring_paths; int number_of_needed_pop_front; int current_new_path_count; int row_step[4] = {-1, 0, 1, 0}; int col_step[4] = {0, -1, 0, 1}; int path_length; void add_new_path_if_possible(const pair<int, int>& current); int main() { std::string line; std::string token; std::getline(std::cin, line); { std::stringstream ss(line); std::getline(ss, token, ' '); vertical_length = stoi(token); std::getline(ss, token); horizontal_length = stoi(token); } maze.resize(vertical_length, vector<bool>(horizontal_length, false)); is_visited.resize(vertical_length, vector<bool>(horizontal_length, false)); for (int c = 0; c < vertical_length; ++c) { std::getline(std::cin, line); for (int r = 0; r < horizontal_length; ++r) { if (line[r] == '1') { maze[c][r] = true; } else if (line[r] == '0') { maze[c][r] = false; } } } neighboring_paths.emplace_back(0, 0); is_visited[0][0] = true; number_of_needed_pop_front = 1; pair<int, int> current(0, 0); bool found_path = false; while (not neighboring_paths.empty()) { current_new_path_count = 0; for (int i = 0; i < number_of_needed_pop_front; ++i) { current = neighboring_paths.front(); neighboring_paths.pop_front(); if (current.first == horizontal_length - 1 and current.second == vertical_length - 1) { found_path = true; break; } add_new_path_if_possible(current); } if (found_path) { break; } number_of_needed_pop_front = current_new_path_count; ++path_length; } cout << path_length + 1<< "\n"; return 0; } void add_new_path_if_possible(const pair<int, int>& current) { int current_row = 0; int current_col = 0; for (int i = 0; i < 4; ++i) { current_row = current.first + row_step[i]; current_col = current.second + col_step[i]; if (0 <= current_row and current_row < horizontal_length and 0 <= current_col and current_col < vertical_length and maze[current_col][current_row] and not is_visited[current_col][current_row]) { neighboring_paths.emplace_back(current_row, current_col); is_visited[current_col][current_row] = true; ++current_new_path_count; } } }
31.511628
99
0.597786
5c683a17d743c3a35d9e5f54c3197d497153624c
3,505
cpp
C++
Source/10.0.18362.0/ucrt/env/get_environment_from_os.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
2
2021-01-27T10:19:30.000Z
2021-02-09T06:24:30.000Z
Source/10.0.18362.0/ucrt/env/get_environment_from_os.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
null
null
null
Source/10.0.18362.0/ucrt/env/get_environment_from_os.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
1
2021-01-27T10:19:36.000Z
2021-01-27T10:19:36.000Z
// // get_environment_from_os.cpp // // Copyright (c) Microsoft Corporation. All rights reserved. // // Defines a pair of functions to get the environment strings from the operating // system. These functions copy the environment strings into a CRT-allocated // buffer and return a pointer to that buffer. The caller is responsible for // freeing the returned buffer (via _crt_free). // #include <corecrt_internal.h> #include <corecrt_internal_traits.h> #include <stdlib.h> namespace { struct environment_strings_traits { typedef wchar_t* type; static bool close(_In_ type p) throw() { FreeEnvironmentStringsW(p); return true; } static type get_invalid_value() throw() { return nullptr; } }; typedef __crt_unique_handle_t<environment_strings_traits> environment_strings_handle; } static wchar_t const* __cdecl find_end_of_double_null_terminated_sequence(wchar_t const* const first) throw() { wchar_t const* last = first; for (; *last != '\0'; last += wcslen(last) + 1) { } return last + 1; // Return the pointer one-past-the-end of the double null terminator } extern "C" wchar_t* __cdecl __dcrt_get_wide_environment_from_os() throw() { environment_strings_handle const environment(GetEnvironmentStringsW()); if (!environment) return nullptr; // Find the wchar_t const* const first = environment.get(); wchar_t const* const last = find_end_of_double_null_terminated_sequence(first); size_t const required_count = last - first; __crt_unique_heap_ptr<wchar_t> buffer(_malloc_crt_t(wchar_t, required_count)); if (!buffer) return nullptr; // Note that the multiplication here cannot overflow: memcpy(buffer.get(), environment.get(), required_count * sizeof(wchar_t)); return buffer.detach(); } extern "C" char* __cdecl __dcrt_get_narrow_environment_from_os() throw() { // Note that we call GetEnvironmentStringsW and convert to multibyte. The // GetEnvironmentStringsA function returns the environment in the OEM code // page, but we need the strings in ANSI. environment_strings_handle const environment(GetEnvironmentStringsW()); if (!environment.is_valid()) return nullptr; wchar_t const* const first = environment.get(); wchar_t const* const last = find_end_of_double_null_terminated_sequence(first); size_t const required_wide_count = last - first; #pragma warning(suppress:__WARNING_W2A_BEST_FIT) // 38021 Prefast recommends WC_NO_BEST_FIT_CHARS. size_t const required_narrow_count = static_cast<size_t>(__acrt_WideCharToMultiByte( CP_ACP, 0, environment.get(), static_cast<int>(required_wide_count), nullptr, 0, nullptr, nullptr)); if (required_narrow_count == 0) return nullptr; __crt_unique_heap_ptr<char> buffer(_malloc_crt_t(char, required_narrow_count)); if (!buffer) return nullptr; #pragma warning(suppress:__WARNING_W2A_BEST_FIT) // 38021 Prefast recommends WC_NO_BEST_FIT_CHARS. int const conversion_result = __acrt_WideCharToMultiByte( CP_ACP, 0, environment.get(), static_cast<int>(required_wide_count), buffer.get(), static_cast<int>(required_narrow_count), nullptr, nullptr); if (conversion_result == 0) return nullptr; return buffer.detach(); }
28.729508
109
0.694722
5c6fc2ea2c3eef41dd62d1afbe34ac4cbeea7a44
29,192
cpp
C++
Source/Core/BuildCommon/CDisneySceneBuildProcessor.cpp
schuttejoe/ShootyEngine
56a7fab5a479ec93d7f641bb64b8170f3b0d3095
[ "MIT" ]
81
2018-07-31T17:13:47.000Z
2022-03-03T09:24:22.000Z
Source/Core/BuildCommon/CDisneySceneBuildProcessor.cpp
schuttejoe/ShootyEngine
56a7fab5a479ec93d7f641bb64b8170f3b0d3095
[ "MIT" ]
2
2018-10-15T04:39:43.000Z
2019-12-05T03:46:50.000Z
Source/Core/BuildCommon/CDisneySceneBuildProcessor.cpp
schuttejoe/ShootyEngine
56a7fab5a479ec93d7f641bb64b8170f3b0d3095
[ "MIT" ]
9
2018-10-11T06:32:12.000Z
2020-10-01T03:46:37.000Z
//================================================================================================================================= // Joe Schutte //================================================================================================================================= #include "BuildCommon/CDisneySceneBuildProcessor.h" #include "BuildCommon/ImportMaterial.h" #include "BuildCommon/ModelBuildPipeline.h" #include "BuildCommon/BakeModel.h" #include "BuildCommon/BuildModel.h" #include "BuildCore/BuildContext.h" #include "SceneLib/SceneResource.h" #include "SceneLib/SubSceneResource.h" #include "Assets/AssetFileUtils.h" #include "UtilityLib/JsonUtilities.h" #include "UtilityLib/MurmurHash.h" #include "IoLib/Directory.h" #include "MathLib/FloatFuncs.h" #include "SystemLib/Logging.h" #include "SystemLib/MemoryAllocation.h" #include "SystemLib/CheckedCast.h" #include <rapidjson/document.h> #include <rapidjson/prettywriter.h> #include <rapidjson/stringbuffer.h> namespace Selas { #define CurveModelNameSuffix_ "_generatedcurves" struct ElementDesc { FilePathString file; int32 lightSetIndex; }; struct LightSetDesc { CArray<FilePathString> lightFiles; }; //============================================================================================================================= struct SceneFileData { CArray<FilePathString> cameraFiles; FilePathString iblFile; CArray<LightSetDesc*> lightsets; CArray<ElementDesc> elements; }; //============================================================================================================================= struct CurveSegment { uint64 startIndex; uint64 controlPointCount; }; //============================================================================================================================= struct CurveData { float widthTip; float widthRoot; float degrees; bool faceCamera; CArray<float3> controlPoints; CArray<CurveSegment> segments; Hash32 name; }; //============================================================================================================================= static FixedString256 ContentRoot(BuildProcessorContext* context) { FixedString256 root; root.Copy(context->source.name.Ascii()); char* addr = StringUtil::FindLastChar(root.Ascii(), '~'); if(addr == nullptr) { root.Clear(); } else { *(addr + 1) = '\0'; } return root; } //============================================================================================================================= static Error ParseArchiveFile(BuildProcessorContext* context, const FixedString256& root, const FilePathString& sourceId, SubsceneResourceData* subscene) { FilePathString filepath; AssetFileUtils::ContentFilePath(sourceId.Ascii(), filepath); ReturnError_(context->AddFileDependency(filepath.Ascii())); rapidjson::Document document; ReturnError_(Json::OpenJsonDocument(filepath.Ascii(), document)); uint modelCount = 0; for(const auto& objFileKV : document.GetObject()) { modelCount += objFileKV.value.GetObject().MemberCount(); } subscene->modelInstances.Reserve(subscene->modelInstances.Count() + modelCount); for(const auto& objFileKV : document.GetObject()) { cpointer objFile = objFileKV.name.GetString(); FilePathString instanceObjFile; FixedStringSprintf(instanceObjFile, "%s%s", root.Ascii(), objFile); AssetFileUtils::IndependentPathSeperators(instanceObjFile); uint meshIndex = subscene->modelNames.Add(instanceObjFile); const auto& element = objFileKV.value; for(const auto& instanceKV : element.GetObject()) { cpointer instanceName = instanceKV.name.GetString(); Instance modelInstance; modelInstance.index = meshIndex; if(Json::ReadMatrix4x4(instanceKV.value, modelInstance.localToWorld) == false) { return Error_("Failed to parse transform from instance '%s' in primfile '%s'", instanceName, filepath.Ascii()); } subscene->modelInstances.Add(modelInstance); } } return Success_; } //============================================================================================================================= static Error ParseControlPointsFile(BuildProcessorContext* context, cpointer path, CurveData* importedCurve) { FilePathString filepath; AssetFileUtils::ContentFilePath(path, filepath); ReturnError_(context->AddFileDependency(filepath.Ascii())); rapidjson::Document document; ReturnError_(Json::OpenJsonDocument(filepath.Ascii(), document)); uint totalControlPoints = 0; // -- Do a prepass to count the total number of control points uint segmentCount = document.Size(); for(const auto& curveElement : document.GetArray()) { uint controlPointCount = curveElement.Size(); totalControlPoints += controlPointCount; } importedCurve->controlPoints.Resize(totalControlPoints); importedCurve->segments.Resize(segmentCount); uint segmentIndex = 0; uint cpIndex = 0; for(const auto& curveElement : document.GetArray()) { uint controlPointCount = curveElement.Size(); importedCurve->segments[segmentIndex].startIndex = cpIndex; importedCurve->segments[segmentIndex].controlPointCount = controlPointCount; ++segmentIndex; for(const auto& controlPointElement : curveElement.GetArray()) { float3& controlPoint = importedCurve->controlPoints[cpIndex]; ++cpIndex; controlPoint.x = controlPointElement[0].GetFloat(); controlPoint.y = controlPointElement[1].GetFloat(); controlPoint.z = controlPointElement[2].GetFloat(); } } return Success_; } //============================================================================================================================= static void BuildCurveModel(CurveData* importedCurve, cpointer curveName, BuiltModel& curveModel) { uint controlPointCount = importedCurve->controlPoints.Count(); uint curveCount = importedCurve->segments.Count(); MakeInvalid(&curveModel.aaBox); uint curveIndex = 0; uint64 indexOffset = 0; curveModel.curveModelNameHash = MurmurHash3_x86_32(curveName, StringUtil::Length(curveName)); curveModel.curves.Resize(curveCount); curveModel.curveIndices.Reserve(controlPointCount + curveCount * 3); curveModel.curveVertices.Reserve(controlPointCount + curveCount * 2); float widthRoot = importedCurve->widthRoot; float widthTip = importedCurve->widthTip; for(uint segIndex = 0, segCount = importedCurve->segments.Count(); segIndex < segCount; ++segIndex) { const CurveSegment& segment = importedCurve->segments[segIndex]; CurveMetaData& curve = curveModel.curves[curveIndex++]; curve.indexOffset = CheckedCast<uint32>(curveModel.curveIndices.Count()); curve.indexCount = CheckedCast<uint32>(segment.controlPointCount - 1); for(uint cpScan = 0; cpScan < segment.controlPointCount - 1; ++cpScan) { curveModel.curveIndices.Add(CheckedCast<uint32>(indexOffset)); ++indexOffset; } indexOffset += 3; curveModel.curveVertices.Add(float4(importedCurve->controlPoints[segment.startIndex], widthRoot)); for(uint cpScan = 0; cpScan < segment.controlPointCount; ++cpScan) { float w = Lerp(widthRoot, widthTip, (float)cpScan / (float)(segment.controlPointCount - 1)); float3 cpPosition = importedCurve->controlPoints[segment.startIndex + cpScan]; IncludePosition(&curveModel.aaBox, cpPosition); curveModel.curveVertices.Add(float4(cpPosition, w)); } curveModel.curveVertices.Add(float4(importedCurve->controlPoints[segment.startIndex + segment.controlPointCount - 1], widthTip)); } } //============================================================================================================================= static Error ParseCurveElement(BuildProcessorContext* context, cpointer curveName, const FixedString256& root, const rapidjson::Value& element, SubsceneResourceData* subscene) { FilePathString curveFile; if(Json::ReadFixedString(element, "jsonFile", curveFile) == false) { return Error_("`jsonFile ` parameter missing from instanced primitives section"); } AssetFileUtils::IndependentPathSeperators(curveFile); CurveData curve; Json::ReadFloat(element, "widthTip", curve.widthTip, 1.0f); Json::ReadFloat(element, "widthRoot", curve.widthRoot, 1.0f); Json::ReadFloat(element, "degrees", curve.degrees, 1.0f); Json::ReadBool(element, "faceCamera", curve.faceCamera, false); FilePathString controlPointsFile; FixedStringSprintf(controlPointsFile, "%s%s", root.Ascii(), curveFile.Ascii()); FilePathString curveModelName; FixedStringSprintf(curveModelName, "%s%s%s", root.Ascii(), curveFile.Ascii(), CurveModelNameSuffix_); ReturnError_(ParseControlPointsFile(context, controlPointsFile.Ascii(), &curve)); BuiltModel curveModel; BuildCurveModel(&curve, curveName, curveModel); ReturnError_(BakeModel(context, curveModelName.Ascii(), curveModel)); Instance curveInstance; curveInstance.index = subscene->modelNames.Add(curveModelName); curveInstance.localToWorld = Matrix4x4::Identity(); subscene->modelInstances.Add(curveInstance); return Success_; } //============================================================================================================================= static Error ParseInstancePrimitivesSection(BuildProcessorContext* context, const FixedString256& root, const rapidjson::Value& section, SubsceneResourceData* subscene) { uint controlPointCount = 0; uint curveCount = 0; for(const auto& keyvalue : section.GetObject()) { const auto& element = keyvalue.value; FixedString32 type; if(Json::ReadFixedString(element, "type", type) == false) { return Error_("'type' parameter missing from instanced primitives section."); } if(StringUtil::Equals(type.Ascii(), "archive")) { FilePathString primFile; if(Json::ReadFixedString(element, "jsonFile", primFile) == false) { return Error_("`jsonFile ` parameter missing from instanced primitives section"); } AssetFileUtils::IndependentPathSeperators(primFile); FilePathString sourceId; FixedStringSprintf(sourceId, "%s%s", root.Ascii(), primFile.Ascii()); ReturnError_(ParseArchiveFile(context, root, sourceId, subscene)); } else if(StringUtil::Equals(type.Ascii(), "curve")) { ReturnError_(ParseCurveElement(context, keyvalue.name.GetString(), root, element, subscene)); } } return Success_; } //============================================================================================================================= static Error ParseLightsFile(BuildProcessorContext* context, cpointer lightfile, CArray<SceneLight>& lights) { if(StringUtil::Length(lightfile) == 0) { return Success_; } FilePathString filepath; AssetFileUtils::ContentFilePath(lightfile, filepath); ReturnError_(context->AddFileDependency(filepath.Ascii())); rapidjson::Document document; ReturnError_(Json::OpenJsonDocument(filepath.Ascii(), document)); uint lightCount = document.MemberCount(); lights.Reserve(lights.Count() + lightCount); for(const auto& lightElementKV : document.GetObject()) { FixedString64 type; Json::ReadFixedString(lightElementKV.value, "type", type); if(StringUtil::Equals(type.Ascii(), "quad") == false) { continue; } float4 color; float exposure; Json::ReadFloat4(lightElementKV.value, "color", color, float4::Zero_); Json::ReadFloat(lightElementKV.value, "exposure", exposure, 0.0f); float width, height; Json::ReadFloat(lightElementKV.value, "width", width, 0.0f); Json::ReadFloat(lightElementKV.value, "height", height, 0.0f); float3 rgb = color.XYZ(); float3 radiance = Math::Powf(2.0f, exposure) * Pow(rgb, 2.2f); if(Dot(radiance, float3::One_) <= 0.0f) { continue; } SceneLight& light = lights.Add(); float4x4 matrix; Json::ReadMatrix4x4(lightElementKV.value, "translationMatrix", matrix); light.position = MatrixMultiplyPoint(float3::Zero_, matrix); light.direction = MatrixMultiplyVector(-float3::ZAxis_, matrix); light.x = MatrixMultiplyVector(width * float3::XAxis_, matrix); light.z = MatrixMultiplyVector(height * float3::YAxis_, matrix); light.radiance = radiance; light.type = QuadLight; } return Success_; } //============================================================================================================================= static Error ParseLightSets(BuildProcessorContext* context, const SceneFileData& sceneFile, SceneResourceData* scene) { scene->lightSetRanges.Resize((sceneFile.lightsets.Count())); for(uint setScan = 0, setCount = sceneFile.lightsets.Count(); setScan < setCount; ++setScan) { scene->lightSetRanges[setScan].start = (uint32)scene->lights.Count(); for(uint fileScan = 0, fileCount = sceneFile.lightsets[setScan]->lightFiles.Count(); fileScan < fileCount; ++fileScan) { cpointer filename = sceneFile.lightsets[setScan]->lightFiles[fileScan].Ascii(); ReturnError_(ParseLightsFile(context, filename, scene->lights)); } scene->lightSetRanges[setScan].count = (uint32)(scene->lights.Count() - scene->lightSetRanges[setScan].start); } return Success_; } //============================================================================================================================= static Error ImportDisneyMaterials(BuildProcessorContext* context, cpointer materialPath, cpointer prefix, SubsceneResourceData* subscene) { FilePathString filepath; AssetFileUtils::ContentFilePath(materialPath, filepath); ReturnError_(context->AddFileDependency(filepath.Ascii())); CArray<FixedString64> materialNames; CArray<ImportedMaterialData> importedMaterials; ReturnError_(ImportDisneyMaterials(filepath.Ascii(), materialNames, importedMaterials)); subscene->sceneMaterialNames.Reserve(importedMaterials.Count()); subscene->sceneMaterials.Reserve(importedMaterials.Count()); for(uint scan = 0, count = importedMaterials.Count(); scan < count; ++scan) { if(importedMaterials[scan].baseColorTexture.Length() > 0) { FilePathString temp; temp.Copy(importedMaterials[scan].baseColorTexture.Ascii()); FixedStringSprintf(importedMaterials[scan].baseColorTexture, "%s%s", prefix, temp.Ascii()); } Hash32 materialNameHash = MurmurHash3_x86_32(materialNames[scan].Ascii(), (int32)materialNames[scan].Length()); subscene->sceneMaterialNames.Add(materialNameHash); MaterialResourceData& material = subscene->sceneMaterials.Add(); BuildMaterial(importedMaterials[scan], material); } return Success_; } //============================================================================================================================= static Error ParseSceneFile(BuildProcessorContext* context, SceneFileData& output) { FilePathString filepath; AssetFileUtils::ContentFilePath(context->source.name.Ascii(), filepath); context->AddFileDependency(filepath.Ascii()); rapidjson::Document document; ReturnError_(Json::OpenJsonDocument(filepath.Ascii(), document)); if(document.HasMember("elements") == false) { return Error_("'elements' member not found in Disney scene '%s'", filepath.Ascii()); } for(const auto& elementJson : document["elements"].GetArray()) { ElementDesc& element = output.elements.Add(); Json::ReadFixedString(elementJson, "element", element.file); Json::ReadInt32(elementJson, "lightset", element.lightSetIndex, 0); } if(document.HasMember("cameras")) { for(const auto& cameraElement : document["cameras"].GetArray()) { FilePathString& cameraFile = output.cameraFiles.Add(); cameraFile.Copy(cameraElement.GetString()); } } Json::ReadFixedString(document, "ibl", output.iblFile); if(document.HasMember("lightsets")) { for(const auto& lightsetElement : document["lightsets"].GetArray()) { LightSetDesc* desc = New_(LightSetDesc); for(const auto& lightfiles : lightsetElement.GetArray()) { FilePathString& lightFile = desc->lightFiles.Add(); lightFile.Copy(lightfiles.GetString()); } output.lightsets.Add(desc); } } return Success_; } //============================================================================================================================= static Error AllocateSubscene(BuildProcessorContext* context, CArray<SubsceneResourceData*>& scenes, cpointer name, int32 lightSetIndex, const FilePathString& materialFile, const FixedString256& root, SubsceneResourceData*& scene) { scene = New_(SubsceneResourceData); scene->name.Copy(name); scene->lightSetIndex = lightSetIndex; ReturnError_(ImportDisneyMaterials(context, materialFile.Ascii(), root.Ascii(), scene)); scenes.Add(scene); return Success_; } //============================================================================================================================= static Error ParseElementFile(BuildProcessorContext* context, const FixedString256& root, const FilePathString& path, int32 lightSetIndex, SceneResourceData* rootScene, CArray<SubsceneResourceData*>& scenes) { FilePathString elementFilePath; AssetFileUtils::ContentFilePath(path.Ascii(), elementFilePath); ReturnError_(context->AddFileDependency(elementFilePath.Ascii())); rapidjson::Document document; ReturnError_(Json::OpenJsonDocument(elementFilePath.Ascii(), document)); // -- Prepare the materials json file path FilePathString materialFile; FixedStringSprintf(materialFile, "%s%s", root.Ascii(), document["matFile"].GetString()); FilePathString geomSceneName; FixedStringSprintf(geomSceneName, "%s_geometry", path.Ascii()); SubsceneResourceData* elementGeometryScene; ReturnError_(AllocateSubscene(context, scenes, geomSceneName.Ascii(), lightSetIndex, materialFile, root, elementGeometryScene)); uint geometrySceneIndex = rootScene->subsceneNames.Add(geomSceneName); Instance geometrySceneInstance; geometrySceneInstance.index = geometrySceneIndex; rootScene->subsceneInstances.Add(geometrySceneInstance); // -- Add the main geometry file FilePathString geomObjFile; FixedStringSprintf(geomObjFile, "%s%s", root.Ascii(), document["geomObjFile"].GetString()); AssetFileUtils::IndependentPathSeperators(geomObjFile); uint rootModelIndex = elementGeometryScene->modelNames.Add(geomObjFile); // -- create a child scene to contain the instanced primitives uint primitivesSceneIndex = InvalidIndex64; if(document.HasMember("instancedPrimitiveJsonFiles")) { SubsceneResourceData* primitivesScene; ReturnError_(AllocateSubscene(context, scenes, path.Ascii(), lightSetIndex, materialFile, root, primitivesScene)); primitivesSceneIndex = rootScene->subsceneNames.Add(primitivesScene->name); // -- read the instanced primitives section. ReturnError_(ParseInstancePrimitivesSection(context, root, document["instancedPrimitiveJsonFiles"], primitivesScene)); } { // -- Each element file will have a transform for the 'root level' object file... Instance rootInstance; Json::ReadMatrix4x4(document["transformMatrix"], rootInstance.localToWorld); rootInstance.index = rootModelIndex; elementGeometryScene->modelInstances.Add(rootInstance); if(primitivesSceneIndex != InvalidIndex64) { rootInstance.index = primitivesSceneIndex; rootScene->subsceneInstances.Add(rootInstance); } } // -- add instanced copies if(document.HasMember("instancedCopies")) { for(const auto& instancedCopyKV : document["instancedCopies"].GetObject()) { Instance copyInstance; if(Json::ReadMatrix4x4(instancedCopyKV.value["transformMatrix"], copyInstance.localToWorld) == false) { return Error_("Failed to read `transformMatrix` from instancedCopy '%s'", instancedCopyKV.name.GetString()); } uint modelIndex = rootModelIndex; if(instancedCopyKV.value.HasMember("geomObjFile")) { FilePathString altGeomObjFile; FixedStringSprintf(altGeomObjFile, "%s%s", root.Ascii(), instancedCopyKV.value["geomObjFile"].GetString()); AssetFileUtils::IndependentPathSeperators(altGeomObjFile); modelIndex = elementGeometryScene->modelNames.Add(altGeomObjFile); } copyInstance.index = modelIndex; elementGeometryScene->modelInstances.Add(copyInstance); uint sceneIndex = primitivesSceneIndex; if(instancedCopyKV.value.HasMember("instancedPrimitiveJsonFiles") && instancedCopyKV.value["instancedPrimitiveJsonFiles"].MemberCount() > 0) { SubsceneResourceData* altScene; ReturnError_(AllocateSubscene(context, scenes, instancedCopyKV.name.GetString(), lightSetIndex, materialFile, root, altScene)); sceneIndex = rootScene->subsceneNames.Add(altScene->name); // -- read the instanced primitives section. ReturnError_(ParseInstancePrimitivesSection(context, root, instancedCopyKV.value["instancedPrimitiveJsonFiles"], altScene)); } if(sceneIndex != InvalidIndex64) { copyInstance.index = sceneIndex; rootScene->subsceneInstances.Add(copyInstance); } } } return Success_; } //============================================================================================================================= static Error ParseCameraFile(BuildProcessorContext* context, cpointer path, CameraSettings& settings) { FilePathString fullPath; AssetFileUtils::ContentFilePath(path, fullPath); ReturnError_(context->AddFileDependency(fullPath.Ascii())); cpointer lastSep = StringUtil::FindLastChar(path, PlatformIndependentPathSep_) + 1; settings.name.Copy(lastSep); StringUtil::RemoveExtension(settings.name.Ascii()); rapidjson::Document document; ReturnError_(Json::OpenJsonDocument(fullPath.Ascii(), document)); Json::ReadFloat3(document, "eye", settings.position, float3(1.0f, 0.0f, 0.0f)); Json::ReadFloat(document, "fov", settings.fovDegrees, 70.0f); Json::ReadFloat3(document, "look", settings.lookAt, float3::Zero_); Json::ReadFloat3(document, "up", settings.up, float3::YAxis_); settings.znear = 0.1f; settings.zfar = 50000.0f; return Success_; } //============================================================================================================================= Error CDisneySceneBuildProcessor::Setup() { AssetFileUtils::EnsureAssetDirectory<SceneResource>(); AssetFileUtils::EnsureAssetDirectory<SubsceneResource>(); AssetFileUtils::EnsureAssetDirectory<ModelResource>(); return Success_; } //============================================================================================================================= cpointer CDisneySceneBuildProcessor::Type() { return "disneyscene"; } //============================================================================================================================= uint64 CDisneySceneBuildProcessor::Version() { return SceneResource::kDataVersion + SubsceneResource::kDataVersion + ModelResource::kDataVersion; } //============================================================================================================================= Error CDisneySceneBuildProcessor::Process(BuildProcessorContext* context) { FixedString256 contentRoot = ContentRoot(context); SceneFileData sceneFile; ReturnError_(ParseSceneFile(context, sceneFile)); CArray<SubsceneResourceData*> allScenes; SceneResourceData* rootScene = New_(SceneResourceData); rootScene->name.Copy(context->source.name.Ascii()); rootScene->backgroundIntensity = float4::One_; rootScene->iblName.Copy(sceneFile.iblFile.Ascii()); for(uint scan = 0, count = sceneFile.cameraFiles.Count(); scan < count; ++scan) { CameraSettings& settings = rootScene->cameras.Add(); ReturnError_(ParseCameraFile(context, sceneFile.cameraFiles[scan].Ascii(), settings)); } ReturnError_(ParseLightSets(context, sceneFile, rootScene)); for(uint scan = 0, count = sceneFile.elements.Count(); scan < count; ++scan) { const FilePathString& elementName = sceneFile.elements[scan].file; int32 lightSetIndex = sceneFile.elements[scan].lightSetIndex; ReturnError_(ParseElementFile(context, contentRoot, elementName, lightSetIndex, rootScene, allScenes)); } for(uint scan = 0, count = allScenes.Count(); scan < count; ++scan) { SubsceneResourceData* scene = allScenes[scan]; for(uint scan = 0, count = scene->modelNames.Count(); scan < count; ++scan) { if(!StringUtil::EndsWithIgnoreCase(scene->modelNames[scan].Ascii(), CurveModelNameSuffix_)) { context->AddProcessDependency("model", scene->modelNames[scan].Ascii()); } } ReturnError_(context->CreateOutput(SubsceneResource::kDataType, SubsceneResource::kDataVersion, scene->name.Ascii(), *scene)); Delete_(scene); } allScenes.Shutdown(); if(StringUtil::Length(sceneFile.iblFile.Ascii()) > 0) { context->AddProcessDependency("DualIbl", sceneFile.iblFile.Ascii()); } ReturnError_(context->CreateOutput(SceneResource::kDataType, SceneResource::kDataVersion, rootScene->name.Ascii(), *rootScene)); Delete_(rootScene); for(uint scan = 0, count = sceneFile.lightsets.Count(); scan < count; ++scan) { Delete_(sceneFile.lightsets[scan]); } return Success_; } }
43.700599
141
0.571047
5c7557362a73f40f51615910d3586efe130137ba
1,477
cpp
C++
DSA-450/02Matrix/10commonElements.cpp
vikkastiwari/cpp-coding-questions
020790e1a3b26c7b24991427004730b3f0785c71
[ "MIT" ]
null
null
null
DSA-450/02Matrix/10commonElements.cpp
vikkastiwari/cpp-coding-questions
020790e1a3b26c7b24991427004730b3f0785c71
[ "MIT" ]
null
null
null
DSA-450/02Matrix/10commonElements.cpp
vikkastiwari/cpp-coding-questions
020790e1a3b26c7b24991427004730b3f0785c71
[ "MIT" ]
null
null
null
// question link: https://www.geeksforgeeks.org/common-elements-in-all-rows-of-a-given-matrix/ #include <bits/stdc++.h> using namespace std; vector<int> findCommon(vector<vector<int>> &nums) { vector<int> common; unordered_map<int, int> map; // marking all row 0 elements as present for (int j = 0; j < nums[0].size(); j++) { map[nums[0][j]] = 1; } for (int i = 1; i < nums.size(); i++) { for (int j = 0; j < nums[0].size(); j++) { // we initialize first row with 1, here i=0 // then when i =1 we check in map if the count of that element is 1 // increment it by 1, now the count is 2 in map of that element // now in second row i=2 if the element is present then we compare the count of that element in map which is also now 2 with i. if (map[nums[i][j]] == i) { map[nums[i][j]] = i + 1; if ((i == nums.size() - 1) && map[nums[i][j]] == nums.size()) { common.push_back(nums[i][j]); } } } } return common; } int main() { vector<vector<int>> nums = { {1, 2, 1, 4, 8}, {3, 7, 8, 5, 1}, {8, 7, 7, 3, 1}, {8, 1, 2, 7, 9}, }; vector<int> result = findCommon(nums); for (int j = 0; j < result.size(); j++) { cout << result[j] << " "; } cout << endl; return 0; }
25.912281
139
0.477319
5c7610d0031114fd6ae16fbd1d44b0c1e1400667
622
cpp
C++
prob03/main.cpp
CSUF-CPSC120-2019F23-24/labex02-TommyLe3825
5d938242e9991e39c7138241e532475ed0705a48
[ "MIT" ]
null
null
null
prob03/main.cpp
CSUF-CPSC120-2019F23-24/labex02-TommyLe3825
5d938242e9991e39c7138241e532475ed0705a48
[ "MIT" ]
null
null
null
prob03/main.cpp
CSUF-CPSC120-2019F23-24/labex02-TommyLe3825
5d938242e9991e39c7138241e532475ed0705a48
[ "MIT" ]
null
null
null
// Name: Tommy Le // This program calculates the tax and tip on a restaurant bill. #include <iostream> int main() { double mealcost,tax,tip,totalbill; std::cout << "Welcome to the Restaurant Bill Calculator!\n"; //Input Meal Cost std::cout << "What is the total meal cost? "; std::cin >> mealcost; //Calculating Tax tax= mealcost * 0.0775; std::cout << "Tax: $" << tax << "\n"; //Calculating Tip tip= mealcost * 0.20; std::cout << "Tip: $" << tip << "\n"; //Calculating Total Bill totalbill=tip+tax+mealcost; std::cout << "Total Bill: $" << totalbill; return 0; }
22.214286
64
0.599678
f07bec174fb1b6798ea9e40cd591a2f6f74eec68
1,150
cpp
C++
Source/Kernels/vnImageNearest.cpp
Petercov/image-resampler
7897ed8a7b371a53011b7d850e510e7604d0de97
[ "BSD-2-Clause" ]
null
null
null
Source/Kernels/vnImageNearest.cpp
Petercov/image-resampler
7897ed8a7b371a53011b7d850e510e7604d0de97
[ "BSD-2-Clause" ]
null
null
null
Source/Kernels/vnImageNearest.cpp
Petercov/image-resampler
7897ed8a7b371a53011b7d850e510e7604d0de97
[ "BSD-2-Clause" ]
null
null
null
#include "Kernels/vnImageNearest.h" #include "Utilities/vnImageBlock.h" VN_STATUS vnNearestKernel( CONST CVImage & pSrcImage, FLOAT32 fX, FLOAT32 fY, UINT8 * pRawOutput ) { if ( VN_PARAM_CHECK ) { if ( !VN_IS_IMAGE_VALID(pSrcImage) || !pRawOutput ) { return vnPostError( VN_ERROR_INVALIDARG ); } } INT32 iX = (INT32) ( fX + 0.5f ); INT32 iY = (INT32) ( fY + 0.5f ); // // Floating point pixel coordinates are pixel-center based. Thus, a coordinate // of (0,0) refers to the center of the first pixel in an image, and a coordinate // of (0.5,0) refers to the border between the first and second pixels. // if ( iX < 0 ) iX = 0; if ( iX > pSrcImage.QueryWidth() - 1 ) iX = pSrcImage.QueryWidth() - 1; if ( iY < 0 ) iY = 0; if ( iY > pSrcImage.QueryHeight() - 1 ) iY = pSrcImage.QueryHeight() - 1; // // Sample our pixel and write it to the output buffer. // UINT8 * pSrcPixel = pSrcImage.QueryData() + pSrcImage.BlockOffset( iX, iY ); memcpy( pRawOutput, pSrcPixel, pSrcImage.QueryBitsPerPixel() >> 3 ); return VN_SUCCESS; }
28.75
98
0.616522
f07c4142ce407a400c9a397ea735499fd273c066
215
hpp
C++
src/modules/osg/generated_code/TriangleList.pypp.hpp
JaneliaSciComp/osgpyplusplus
a5ae3f69c7e9101a32d8cc95fe680dab292f75ac
[ "BSD-3-Clause" ]
17
2015-06-01T12:19:46.000Z
2022-02-12T02:37:48.000Z
src/modules/osg/generated_code/TriangleList.pypp.hpp
cmbruns/osgpyplusplus
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
[ "BSD-3-Clause" ]
7
2015-07-04T14:36:49.000Z
2015-07-23T18:09:49.000Z
src/modules/osg/generated_code/TriangleList.pypp.hpp
cmbruns/osgpyplusplus
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
[ "BSD-3-Clause" ]
7
2015-11-28T17:00:31.000Z
2020-01-08T07:00:59.000Z
// This file has been generated by Py++. #ifndef TriangleList_hpp__pyplusplus_wrapper #define TriangleList_hpp__pyplusplus_wrapper void register_TriangleList_class(); #endif//TriangleList_hpp__pyplusplus_wrapper
23.888889
44
0.855814
f07f84cdd2ba1c1e88458535c89ae66d4374b2e5
12,766
cpp
C++
Flash/src/flash.cpp
MuellerA/LonganNanoTest
ed71398e63ff318695552b665b42e762b401c61e
[ "MIT" ]
15
2019-12-15T21:57:27.000Z
2022-02-22T05:28:24.000Z
Flash/src/flash.cpp
MuellerA/LonganNanoTest
ed71398e63ff318695552b665b42e762b401c61e
[ "MIT" ]
null
null
null
Flash/src/flash.cpp
MuellerA/LonganNanoTest
ed71398e63ff318695552b665b42e762b401c61e
[ "MIT" ]
3
2020-07-28T17:19:39.000Z
2021-10-01T09:01:51.000Z
//////////////////////////////////////////////////////////////////////////////// // flash.cpp //////////////////////////////////////////////////////////////////////////////// extern "C" { #include "gd32vf103.h" } #include "GD32VF103/spi.h" #include "GD32VF103/gpio.h" #include "GD32VF103/time.h" #include "Longan/lcd.h" using ::RV::GD32VF103::Spi ; using ::RV::GD32VF103::Gpio ; using ::RV::GD32VF103::TickTimer ; using ::RV::Longan::Lcd ; using ::RV::Longan::LcdArea ; Gpio &button(Gpio::gpioA8()) ; Lcd &lcd(Lcd::lcd()) ; //////////////////////////////////////////////////////////////////////////////// class Flash { private: enum class Cmd { WriteEnable = 0x06, VolatileSrWriteEnable = 0x50, WriteDisable = 0x04, ReleasePowerDownId = 0xAB, // Dummy Dummy Dummy (ID7-ID0) ManufacturerDeviceId = 0x90, // Dummy Dummy 00h (MF7-MF0) (ID7-ID0) JedecId = 0x9F, // (MF7-MF0) (ID15-ID8) (ID7-ID0) UniqueId = 0x4B, // Dummy Dummy Dummy Dummy (UID63-0) ReadData = 0x03, // A23-A16 A15-A8 A7-A0 (D7-D0) FastRead = 0x0B, // A23-A16 A15-A8 A7-A0 Dummy (D7-D0) PageProgram = 0x02, // A23-A16 A15-A8 A7-A0 D7-D0 D7-D0 SectorErase = 0x20, // ( 4KB) A23-A16 A15-A8 A7-A0 BlockErase32 = 0x52, // (32KB) A23-A16 A15-A8 A7-A0 BlockErase64 = 0xD8, // (64KB) A23-A16 A15-A8 A7-A0 ChipErase = 0xC7, // 60h ReadStatusRegister1 = 0x05, // (S7-S0) WriteStatusRegister1 = 0x01, // (S7-S0) ReadStatusRegister2 = 0x35, // (S15-S8) WriteStatusRegister2 = 0x31, // (S15-S8) ReadStatusRegister3 = 0x15, // (S23-S16) WriteStatusRegister3 = 0x11, // (S23-S16) ReadSfdpRegister = 0x5A, // 00h 00h A7–A0 Dummy (D7-D0) EraseSecurityRegister = 0x44, // A23-A16 A15-A8 A7-A0 ProgramSecurityRegister = 0x42, // A23-A16 A15-A8 A7-A0 D7-D0 D7-D0 ReadSecurityRegister = 0x48, // A23-A16 A15-A8 A7-A0 Dummy (D7-D0) GlobalBlockLock = 0x7E, GlobalBlockUnlock = 0x98, ReadBlockLock = 0x3D, // A23-A16 A15-A8 A7-A0 (L7-L0) IndividualBlockLock = 0x36, // A23-A16 A15-A8 A7-A0 IndividualBlockUnlock = 0x39, // A23-A16 A15-A8 A7-A0 EraseProgramSuspend = 0x75, EraseProgramResume = 0x7A, PowerDown = 0xB9, EnableReset = 0x66, ResetDevice = 0x99, } ; public: Flash() : _spi(Spi::spi1()), _cs(Gpio::gpioB8()) { } void setup() { _spi.setup(Spi::Psc::_2) ; // SPI1: 54MHz/2 _cs.setup(Gpio::Mode::OUT_PP) ; _cs.high() ; } void getManufacturerDeviceId(uint8_t &mfid, uint8_t &did) { uint8_t dout[] = { 0x00, 0x00, 0x00 } ; uint8_t din[2] ; xch(Cmd::ManufacturerDeviceId, dout, sizeof(dout), din, sizeof(din)) ; mfid = din[0] ; did = din[1] ; } void getJedecId(uint8_t &mfid, uint8_t &memoryType, uint8_t &capacity) { uint8_t din[3] ; xch(Cmd::JedecId, nullptr, 0, din, sizeof(din)) ; mfid = din[0] ; memoryType = din[1] ; capacity = din[2] ; } void getUniqueId(uint64_t &uid) { uint8_t dout[] = { 0x00, 0x00, 0x00, 0x00 } ; uint8_t din[8] ; xch(Cmd::UniqueId, dout, sizeof(dout), din, sizeof(din)) ; uid = din[0] ; uid <<= 8 ; uid |= din[1] ; uid <<= 8 ; uid |= din[2] ; uid <<= 8 ; uid |= din[3] ; uid <<= 8 ; uid |= din[4] ; uid <<= 8 ; uid |= din[5] ; uid <<= 8 ; uid |= din[6] ; uid <<= 8 ; uid |= din[7] ; } void read(uint32_t addr, uint8_t *data, size_t size) { uint8_t dout[3] ; uint8_t *o = (uint8_t*)&addr ; dout[0] = o[2] ; dout[1] = o[1] ; dout[2] = o[0] ; xch(Cmd::ReadData, dout, sizeof(dout), data, size) ; } void write(uint32_t addr, uint8_t *data, size_t size) { if ((size == 0) || (size > 256)) return ; xch(Cmd::WriteEnable, nullptr, 0, nullptr, 0) ; uint8_t dout[3] ; uint8_t *o = (uint8_t*)&addr ; dout[0] = o[2] ; dout[1] = o[1] ; dout[2] = o[0] ; uint8_t cc = (uint8_t)Cmd::PageProgram ; _cs.low() ; _spi.xch(&cc, 1, 1) ; _spi.xch(dout, sizeof(dout), 1) ; _spi.xch(data, size, 1) ; _cs.high() ; } void erase(uint32_t addr) { xch(Cmd::WriteEnable, nullptr, 0, nullptr, 0) ; uint8_t dout[3] ; uint8_t *o = (uint8_t*)&addr ; dout[0] = o[2] ; dout[1] = o[1] ; dout[2] = o[0] ; xch(Cmd::SectorErase, dout, sizeof(dout), nullptr, 0) ; } void waitBusy() { uint8_t dout = (uint8_t) Cmd::ReadStatusRegister1 ; _cs.low() ; _spi.xch(&dout, sizeof(dout), 1) ; uint8_t status ; while (true) { _spi.xch(&status, sizeof(status), 2) ; if (!(status & 0x01)) break ; } _cs.high() ; } void getStatus1(uint8_t &status) { xch(Cmd::ReadStatusRegister1, nullptr, 0, &status, sizeof(status)) ; } void getStatus2(uint8_t &status) { xch(Cmd::ReadStatusRegister2, nullptr, 0, &status, sizeof(status)) ; } void getStatus3(uint8_t &status) { xch(Cmd::ReadStatusRegister3, nullptr, 0, &status, sizeof(status)) ; } bool getSize(uint32_t &size) { #pragma pack(push, 1) struct SfdpHeader { uint32_t _magic ; uint8_t _minor ; uint8_t _major ; uint8_t _count ; // n = _count+1 uint8_t _unused ; } ; struct SfdpParameterHeader { uint8_t _id ; uint8_t _minor ; uint8_t _major ; uint8_t _size ; // in 32 bit uint32_t _offset ; // clear MSByte / only lower 24 Bits used } ; struct SfdpParameter0 { uint32_t _1 ; uint32_t _flashMemoryDensity ; uint32_t _3 ; uint32_t _4 ; uint32_t _5 ; uint32_t _6 ; uint32_t _7 ; uint32_t _8 ; uint32_t _9 ; } ; #pragma pack(pop) SfdpHeader sfdpHdr ; SfdpParameterHeader sfdpParamHdr ; SfdpParameter0 sfdpParam0 ; uint8_t dout[] = { 0x00, 0x00, 0x00, 0x00 } ; xch(Cmd::ReadSfdpRegister, dout, sizeof(dout), (uint8_t*)&sfdpHdr , sizeof(sfdpHdr)) ; if (sfdpHdr._magic != 'PDFS') return false ; uint32_t offset ; uint8_t *o = (uint8_t*)&offset ; offset = sizeof(SfdpHeader) ; dout[0] = o[2] ; dout[1] = o[1] ; dout[2] = o[0] ; xch(Cmd::ReadSfdpRegister, dout, sizeof(dout), (uint8_t*)&sfdpParamHdr , sizeof(sfdpParamHdr)) ; sfdpParamHdr._offset &= 0xffffff ; if (sfdpParamHdr._id != 0) return false ; if (sfdpParamHdr._size < 9) return false ; offset = sfdpParamHdr._offset ; dout[0] = o[2] ; dout[1] = o[1] ; dout[2] = o[0] ; xch(Cmd::ReadSfdpRegister, dout, sizeof(dout), (uint8_t*)&sfdpParam0 , sizeof(sfdpParam0)) ; size = sfdpParam0._flashMemoryDensity ; return true ; } private: void xch(Cmd cmd, uint8_t *txData, size_t txSize, uint8_t *rxData, size_t rxSize) { uint8_t cc = (uint8_t)cmd ; _cs.low() ; _spi.xch(&cc, 1, 1) ; if (txSize) _spi.xch(txData, txSize, 1) ; if (rxSize) _spi.xch(rxData, rxSize, 2) ; _cs.high() ; } private: Spi &_spi ; Gpio &_cs ; } ; //////////////////////////////////////////////////////////////////////////////// uint8_t buttonPressed() { struct State { State() : _value{0x00}, _tick{TickTimer::now()} {} uint8_t _value ; uint64_t _tick ; } ; static State last ; static State current ; uint64_t now = TickTimer::now() ; if ((now - current._tick) < TickTimer::usToTick(2500)) return 0 ; current._tick = now ; current._value = (current._value << 1) | button.get() ; if ((current._value == last._value) || ((current._value != 0x00) && (current._value != 0xff))) return 0 ; uint32_t ms = TickTimer::tickToMs(current._tick - last._tick) ; last = current ; if (current._value) return 0 ; return (ms < 600) ? 1 : 2 ; } //////////////////////////////////////////////////////////////////////////////// int main() { Flash flash ; button.setup(Gpio::Mode::IN_FL) ; lcd.setup() ; flash.setup() ; lcd.clear() ; lcd.txtPos(0) ; lcd.put("Flash ") ; lcd.txtPos(4) ; lcd.put("press button to continue") ; LcdArea lcdWrk(lcd, 0, 160, 16, 48) ; while (true) { { uint8_t mfid ; uint8_t did ; flash.getManufacturerDeviceId(mfid, did) ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Manufacturer ID: ") ; lcdWrk.put(mfid, 2, '0', true) ; lcdWrk.txtPos(1) ; lcdWrk.put("Device ID: ") ; lcdWrk.put(did, 2, '0', true) ; } while (!buttonPressed()) ; { uint8_t mfid ; uint8_t memoryType ; uint8_t capacity ; flash.getJedecId(mfid, memoryType, capacity) ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Manufacturer ID: ") ; lcdWrk.put(mfid, 2, '0', true) ; lcdWrk.txtPos(1) ; lcdWrk.put("Memory Type: ") ; lcdWrk.put(memoryType, 2, '0', true) ; lcdWrk.txtPos(2) ; lcdWrk.put("Capacity: ") ; lcdWrk.put(capacity, 2, '0', true) ; } while (!buttonPressed()) ; { uint64_t uid ; flash.getUniqueId(uid) ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Unique ID: ") ; lcdWrk.txtPos(1) ; lcdWrk.put((uint32_t)(uid>>32), 8, '0', true) ; lcdWrk.put((uint32_t)(uid>> 0), 8, '0', true) ; } while (!buttonPressed()) ; { uint32_t size ; uint64_t size64 ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Size: ") ; if (flash.getSize(size)) { if (size & 0x80000000) size64 = 1LL << size ; else size64 = size + 1 ; size64 >>= 3 ; // bit to byte if (size64 > (1LL << 30)) { size64 >>= 30 ; lcdWrk.put((uint32_t)size64) ; lcdWrk.put("GByte") ; } else if (size64 > (1LL << 20)) { size64 >>= 20 ; lcdWrk.put((uint32_t)size64) ; lcdWrk.put("MByte") ; } else if (size64 > (1LL << 20)) { size64 >>= 10 ; lcdWrk.put((uint32_t)size64) ; lcdWrk.put("kByte") ; } else { lcdWrk.put((uint32_t)size64) ; lcdWrk.put("Byte") ; } } else lcdWrk.put('?') ; } while (!buttonPressed()) ; { uint8_t status1 ; uint8_t status2 ; uint8_t status3 ; flash.getStatus1(status1) ; flash.getStatus2(status2) ; flash.getStatus3(status3) ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Status1: ") ; lcdWrk.put(status1, 2, '0', true) ; lcdWrk.txtPos(1) ; lcdWrk.put("Status2: ") ; lcdWrk.put(status2, 2, '0', true) ; lcdWrk.txtPos(2) ; lcdWrk.put("Status3: ") ; lcdWrk.put(status3, 2, '0', true) ; } while (!buttonPressed()) ; { uint8_t data[16] ; flash.read(0x1000, data, sizeof(data)) ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Read") ; lcdWrk.txtPos(1) ; for (uint8_t b : data) { lcdWrk.put(b, 2, '0', true) ; lcdWrk.put(' ') ; } } while (!buttonPressed()) ; { const char *txt = "Hallo Welt?!" ; flash.write(0x1000, (uint8_t*)txt, 11) ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Write") ; lcdWrk.txtPos(1) ; lcdWrk.put("...") ; flash.waitBusy() ; lcdWrk.put(" done") ; } while (!buttonPressed()) ; { uint8_t data[16] ; flash.read(0x1000, data, sizeof(data)) ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Read") ; lcdWrk.txtPos(1) ; for (uint8_t b : data) { lcdWrk.put(b, 2, '0', true) ; lcdWrk.put(' ') ; } lcdWrk.clearEOL() ; } while (!buttonPressed()) ; { flash.erase(0x1000) ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Erase") ; lcdWrk.txtPos(1) ; lcdWrk.put("...") ; flash.waitBusy() ; lcdWrk.put(" done") ; } while (!buttonPressed()) ; { uint8_t data[16] ; flash.read(0x1000, data, sizeof(data)) ; lcdWrk.clear() ; lcdWrk.txtPos(0) ; lcdWrk.put("Read") ; lcdWrk.txtPos(1) ; for (uint8_t b : data) { lcdWrk.put(b, 2, '0', true) ; lcdWrk.put(' ') ; } lcdWrk.clearEOL() ; } while (!buttonPressed()) ; } } //////////////////////////////////////////////////////////////////////////////// // EOF ////////////////////////////////////////////////////////////////////////////////
24.933594
100
0.513943
f07fddd0d7e9745b75518d3d5266c40ab673b3d0
13,076
cpp
C++
chip8/src/cpu/opcodes.cpp
bryan-pakulski/emulators
599856760529cce7cc31be43d07617983e642dae
[ "MIT" ]
null
null
null
chip8/src/cpu/opcodes.cpp
bryan-pakulski/emulators
599856760529cce7cc31be43d07617983e642dae
[ "MIT" ]
null
null
null
chip8/src/cpu/opcodes.cpp
bryan-pakulski/emulators
599856760529cce7cc31be43d07617983e642dae
[ "MIT" ]
null
null
null
#include <iostream> #include <stdexcept> #include "../globals.hpp" #include "opcodes.hpp" using namespace std; opcodes::opcodes() { std::map<unsigned short, int> optable; } opcodes::~opcodes() { } /** * Gets function from the hashtable at a given index - If the function has not yet * been added to the lookup table it is inserted here with the key of the opcode * that has called it * * @param o opcode */ func_p opcodes::get(unsigned short o) { // Check if instruction already exists in opcode lookup table // If not then decode instruction based on HPP header and add to lookup int instruction = lookup(o); if ( instruction == -1 ) { instruction = decode( o ); if ( instruction != -1 ) { cerr << "Inserting new opcode: " << std::hex << o << " with key: " << std::hex << instruction << endl; optable.insert( std::pair<unsigned short, int>(o, instruction) ); } else { throw std::runtime_error("Invalid opcode: " + to_string(o)); } } // Run instruction from opcode lookup table, passes along current opcode operation return oplist[instruction]; } /** * Checks if an instruction already exists in the optable * If not it will be decoded and added for faster lookup next time * * @param o Opcode * * @return Returns the index location of function to call */ int opcodes::lookup(unsigned short o) { // Find in optable auto search = optable.find(o); if ( search != optable.end() ) return search->second; else return -1; } /** * Decodes a given opcode and returns an index * * @param o Opcode * * @return Returns the index location lookup key of the function to call */ int opcodes::decode(unsigned short o) { cerr << "Parsing new opcode: " << std::hex << o << endl; switch( o & 0xF000) { case 0x0000: switch( o & 0x0F00 ) { case 0x0000: switch( o & 0x000F ) { case 0x0000: return 1; break; case 0x000E: return 2; break; } break; default: return 0; } break; case 0x1000: return 3; break; case 0x2000: return 4; break; case 0x3000: return 5; break; case 0x4000: return 6; break; case 0x5000: return 7; break; case 0x6000: return 8; break; case 0x7000: return 9; break; case 0x8000: switch( o & 0x000F ) { case 0x0000: return 10; break; case 0x0001: return 11; break; case 0x0002: return 12; break; case 0x0003: return 13; break; case 0x0004: return 14; break; case 0x0005: return 15; break; case 0x0006: return 16; break; case 0x0007: return 17; break; case 0x000E: return 18; break; } break; case 0x9000: return 19; break; case 0xA000: return 20; break; case 0xB000: return 21; break; case 0xC000: return 22; break; case 0xD000: return 23; break; case 0xE000: switch( o & 0x00FF ) { case 0x009E: return 24; break; case 0x00A1: return 25; break; } break; case 0xF000: switch ( o & 0x00FF ) { case 0x0007: return 26; break; case 0x000A: return 27; break; case 0x0015: return 28; break; case 0x0018: return 29; break; case 0x001E: return 30; break; case 0x0029: return 31; break; case 0x0033: return 32; break; case 0x0055: return 33; break; case 0x0065: return 34; break; } break; } cerr << "Unknown opcode encountered: " << o << endl; return -1; } /** * @brief Calls RCA 1802 program at address NNN. * Not necessary for most ROMs */ void opcodes::op0NNN(cpu* proc) { } /** * @brief Clears the screen */ void opcodes::op00E0(cpu* proc) { proc->clearScreen = true; } /** * Returns from a subroutine */ void opcodes::op00EE(cpu* proc) { proc->setPC(proc->popStack()); } /** * Jumps to address NNN */ void opcodes::op1NNN(cpu* proc) { proc->setPC( proc->getOP() & 0x0FFF ); } /** * Calls subroutine at NNN */ void opcodes::op2NNN(cpu* proc) { proc->pushStack( proc->getPC() ); proc->setPC( proc->getOP() & 0x0FFF ); } /** * Skips the next instruction if VX equals NN */ void opcodes::op3XNN(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short n = (proc->getOP() & 0x00FF); if ( proc->getV( x ) == n ) { proc->stepPC(1); } } /** * Skips the next instruction if VX doesn't equal NN */ void opcodes::op4XNN(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short n = (proc->getOP() & 0x00FF); if ( proc->getV( x ) != n ) { proc->stepPC(1); } } /** * Skips the next instruction if VX equals VY */ void opcodes::op5XY0(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short y = (proc->getOP() & 0x00F0) >> 4; if ( proc->getV(x) == proc->getV(y) ) { proc->stepPC(1); } } /** * Sets VX to NN */ void opcodes::op6XNN(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short n = (proc->getOP() & 0x00FF); proc->setV(x, n); } /** * Adds NN to VX */ void opcodes::op7XNN(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short n = (proc->getOP() & 0x00FF); proc->setV(x, proc->getV(x) + n); } /** * Sets VX to the value of VY */ void opcodes::op8XY0(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short y = (proc->getOP() & 0x00F0) >> 4; proc->setV( x, proc->getV( y ) ); } /** * Sets VX to VX or VY */ void opcodes::op8XY1(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short y = (proc->getOP() & 0x00F0) >> 4; proc->setV(x, proc->getV(x) | proc->getV(y)); } /** * Sets VX to VX and VY */ void opcodes::op8XY2(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short y = (proc->getOP() & 0x00F0) >> 4; proc->setV(x, proc->getV(x) & proc->getV(y)); } /** * Sets VX to VX xor VY */ void opcodes::op8XY3(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short y = (proc->getOP() & 0x00F0) >> 4; proc->setV(x, proc->getV(x) ^ proc->getV(y)); } /** * Adds VY to VX. VF is set to 1 when there's a carry, * and to 0 when there isn't */ void opcodes::op8XY4(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short y = (proc->getOP() & 0x00F0) >> 4; short sum = proc->getV(x) + proc->getV(y); if (sum > 0xFF) { proc->setV(0xF, 1); sum -= 0x100; } proc->setV(x, sum); } /** * VY is subtracted from VX. VF is set to 0 when there's a * borrow, and 1 when there isn't */ void opcodes::op8XY5(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short y = (proc->getOP() & 0x00F0) >> 4; short diff = proc->getV(x) - proc->getV(y); proc->setV(0xF, 1); if (diff < 0) { proc->setV(0xF, 0); diff += 0x100; } proc->setV(x, diff); } /** * Shifts VX right by one. VF is set to the value * of the least significant bit of VX before the shift */ void opcodes::op8XY6(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; // Get least significant bit proc->setV(0xF, proc->getV(x) & 0x1); proc->setV(x, proc->getV(x) >> 1); } /** * Sets VX to VY minus VX. VF is set to 0 when there's a borrow, * and 1 when there isn't */ void opcodes::op8XY7(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short y = (proc->getOP() & 0x00F0) >> 4; short diff = proc->getV(y) - proc->getV(x); proc->setV(0xF, 1); if (diff < 0) { proc->setV(0xF, 0); diff += 0x100; } proc->setV(x, diff); } /** * Shifts VX left by one.VF is set to the value of the * most significant bit of VX before the shift */ void opcodes::op8XYE(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; proc->setV(0xF, proc->getV(x) >> 7); proc->setV(x, proc->getV(x) << 1); } /** * Skips the next instruction if VX doesn't equal VY */ void opcodes::op9XY0(cpu* proc) { unsigned short x = ( proc->getOP() & 0x0F00 ) >> 8; unsigned short y = ( proc->getOP() & 0x00F0 ) >> 4; if ( proc->getV(x) != proc->getV(y) ) { proc->stepPC(1); } } /** * Sets I to the address NNN */ void opcodes::opANNN(cpu* proc) { proc->setI( proc->getOP() & 0x0FFF ); } /** * Jumps to the address NNN plus V0 */ void opcodes::opBNNN(cpu* proc) { proc->setPC( (proc->getOP() & 0x0FFF) + proc->getV(0) ); } /** * Sets VX to the result of a bitwise and * operation on a random number and NN */ void opcodes::opCXNN(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short v_nn = proc->getOP() & 0x00FF; // TODO: generate random byte in the following format int r = ((rand() % (0xF + 1 - 0x0)) + 0x0); proc->setV(x, r & v_nn); } /** * Sprites stored in memory at location in index register (I), * 8bits wide. Wraps around the screen. If when * drawn, clears a pixel, register VF is set to 1 otherwise it is * zero. All drawing is XOR drawing (i.e. it toggles the screen pixels). * Sprites are drawn starting at position VX, VY. N is the number of 8bit * rows that need to be drawn. If N is greater than 1, * second line continues at position VX, VY+1, and so on */ void opcodes::opDXYN(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short y = (proc->getOP() & 0x00F0) >> 4; unsigned short nRows = (proc->getOP() & 0x000F); proc->setV(0xF, 0); // Normalized coordinates unsigned short xPos = proc->getV(x) % c8_display::INTERNAL_WIDTH; unsigned short yPos = proc->getV(y) % c8_display::INTERNAL_HEIGHT; // Iterate over display for (int row = 0; row < nRows; ++row) { unsigned short sprite = proc->mem->get(proc->getI() + row); for (int col = 0; col < 8; ++col) { if ((sprite & (0x80 >> col)) != 0) { unsigned short index = ((yPos + row) * c8_display::INTERNAL_WIDTH) + (xPos + col); index %= (c8_display::INTERNAL_WIDTH * c8_display::INTERNAL_HEIGHT); unsigned char gfxVal = proc->gfx->getPixel(index); if (gfxVal == 0xF) { proc->setV(0xF, 1); } gfxVal ^= 0xF; proc->gfx->setPixel(index, gfxVal); } } } proc->drawFlag = true; } /** * Skips the next instruction if the key stored in VX is pressed */ void opcodes::opEX9E(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short key = proc->getV(x); if (proc->keyPressed(key)) { proc->stepPC(1); } } /** * Skips the next instruction if the key stored in VX isn't pressed */ void opcodes::opEXA1(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short key = proc->getV(x); if (!proc->keyPressed(key)) { proc->stepPC(1); } } /** * Sets VX to the value of the delay timer */ void opcodes::opFX07(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; proc->setV(x, proc->delayTimer); } /** * A key press is awaited, and then stored in VX */ void opcodes::opFX0A(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; bool keyPressed = false; while (!keyPressed) { for (int i = 0; i < 0xF; i++) { if (proc->keyPressed(i)) { proc->setV(x, i); keyPressed = true; break; } } } } /** * Sets the delay timer to VX */ void opcodes::opFX15(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; proc->delayTimer = proc->getV(x); } /** * Sets the sound timer to VX */ void opcodes::opFX18(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; proc->soundTimer = proc->getV(x); } /** * Adds VX to I */ void opcodes::opFX1E(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; proc->setI(proc->getI() + proc->getV(x)); } /** * Sets I to the location of the sprite for the shortacter in VX. * shortacters 0-F (in hexadecimal) are represented by a 4x5 font */ void opcodes::opFX29(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; proc->setI(proc->getV(x) * 5); } /** * Stores the Binary-coded decimal representation of VX, * with the most significant of three digits at the address in I, * the middle digit at I plus 1, and the least significant digit at * I plus 2. (In other words, take the decimal representation of VX, * place the hundreds digit in memory at location in I, * the tens digit at location I+1, * and the ones digit at location I+2) */ void opcodes::opFX33(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; unsigned short vx = proc->getV(x); for (int i = 2; i >= 0; i--) { proc->mem->set(proc->getI() + i, vx % 10); vx /= 10; } } /** * Stores V0 to VX in memory starting at address I */ void opcodes::opFX55(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; for (int i = 0; i <= x; ++i) { proc->mem->set( proc->getI() + i, proc->getV(i) ); } } /** * Fills V0 to VX with values from memory starting at address I */ void opcodes::opFX65(cpu* proc) { unsigned short x = (proc->getOP() & 0x0F00) >> 8; for (int i = 0; i <= x; ++i) { proc->setV( i, proc->mem->get(proc->getI() + i) ); } }
19.229412
106
0.601101
f0844ff5707784bddf9aff38dcd89c3fded92da1
941
cpp
C++
Stack/postfixEvaluation.cpp
gaurav147-star/DSA-learning
52625953e2b1421fdd550004df893b970aac9308
[ "MIT" ]
1
2022-02-15T12:53:00.000Z
2022-02-15T12:53:00.000Z
Stack/postfixEvaluation.cpp
gaurav147-star/DSA-learning
52625953e2b1421fdd550004df893b970aac9308
[ "MIT" ]
null
null
null
Stack/postfixEvaluation.cpp
gaurav147-star/DSA-learning
52625953e2b1421fdd550004df893b970aac9308
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int postfixEvaluation(string s) { stack<double> st; for (int i = 0; i < s.length(); i++) { if (s[i] >= '0' && s[i] <= '9') { st.push(s[i] - '0'); } else { double op2 = st.top(); st.pop(); double op1 = st.top(); st.pop(); switch (s[i]) { case '+': st.push(op1 + op2); case '-': st.push(op1 - op2); case '*': st.push(op1 * op2); case '/': st.push(op1 / op2); break; case '^': st.push(pow(op1, op2)); break; default: break; } } } return st.top(); } int main() { cout << postfixEvaluation("46+2/5*7+") << endl; return 0; }
19.604167
51
0.336876
f084a7ccdba1a870071401028679bfbe7618d1f6
2,386
cpp
C++
phoenix/.test/test-listicons.cpp
vgmtool/vgm2pre
f4f917df35d531512292541234a5c1722b8af96f
[ "MIT" ]
21
2015-04-13T03:07:12.000Z
2021-11-20T00:27:00.000Z
phoenix/.test/test-listicons.cpp
apollolux/hello-phoenix
71510b5f329804c525a9576fb0367fe8ab2487cd
[ "MIT" ]
2
2015-10-06T14:59:48.000Z
2022-01-27T08:57:57.000Z
phoenix/.test/test-listicons.cpp
apollolux/hello-phoenix
71510b5f329804c525a9576fb0367fe8ab2487cd
[ "MIT" ]
2
2021-11-19T08:36:57.000Z
2022-03-04T16:03:16.000Z
#include "phoenix.hpp" using namespace nall; using namespace phoenix; struct TestWindow : Window { TestWindow() { setGeometry({64, 64, 480, 640}); setTitle("Test Window"); onClose = [&] { setVisible(false); }; } } *testWindow = nullptr; struct Application : Window { VerticalLayout layout; ListView listView; ListView test; ComboBox comboView; Button button; Label label; Menu file; Menu submenu; Item quit; Application() { setTitle("Main Window"); setGeometry({128, 128, 640, 480}); file.setText("File"); submenu.setText("Submenu"); submenu.setImage(image("folder.png")); quit.setText("Quit"); quit.setImage(image("image.png")); //submenu.setImage(); //quit.setImage(); setMenuVisible(); append(file); file.append(submenu); file.append(quit); listView.setHeaderText("Column 1", "Column 2", "Column 3"); listView.setHeaderVisible(); listView.setCheckable(); listView.append("A", "B", "C"); listView.append("D", "E", "F"); listView.append("G", "H", "I"); test.setHeaderText("Column 1", "Column 2"); test.setHeaderVisible(); test.append("A", "B"); test.append("C", "D"); test.append("E", "F"); listView.setImage(0, 0, image("image.png")); listView.setImage(1, 0, image("folder.png")); listView.setImage(2, 2, image("folder.png")); //listView.setImage(0, 0); //listView.setImage(1, 0); //button.setText("Hello"); button.setImage(image("image.png")); //button.setImage(); label.setText("Label"); append(layout); layout.setMargin(5); layout.append(listView, {~0, ~0}, 5); layout.append(test, {~0, ~0}, 5); layout.append(comboView, {~0, 0}, 5); layout.append(button, {~0, 0}, 5); layout.append(label, {~0, 0}); comboView.append("item1", "item2*", "item3", "item4", "item5", "item6", "item7", "item8"); button.onActivate = [&] { testWindow->setVisible(); //DialogWindow::folderSelect(*this, "c:/users/byuu/appdata/roaming/emulation"); //, "All files (*)"); //listView.remove(1); //comboView.modify(1, "item2"); //comboView.remove(2); }; setVisible(); onClose = &OS::quit; } } *application = nullptr; int main() { OS::setName("higan"); testWindow = new TestWindow; application = new Application; OS::main(); return 0; }
23.86
108
0.604359
f0868055168fed8680185c854b362c02ec1c1bce
8,161
cpp
C++
pocketpt.cpp
rpreiner/pocketpt
5575a1fea0695d50e96d26b8124ee21b63b928ac
[ "MIT" ]
null
null
null
pocketpt.cpp
rpreiner/pocketpt
5575a1fea0695d50e96d26b8124ee21b63b928ac
[ "MIT" ]
null
null
null
pocketpt.cpp
rpreiner/pocketpt
5575a1fea0695d50e96d26b8124ee21b63b928ac
[ "MIT" ]
null
null
null
#include <stdlib.h> // pocketpt, single-source GLSL path tracer by Reinhold Preiner, 2020 #include <stdio.h> // based on smallpt by Kevin Beason #include <windows.h> // Make: g++ -O3 pocketpt.cpp -o pocketpt -lopengl32 -lgdi32 #include <GL/GL.h> // Usage: ./pocketpt <samplesPerPixel> <y-resolution>, e.g.: ./pocketpt 10000 600 #define GLSL(...) "#version 460\n" #__VA_ARGS__ template<class R = void, class ... A> R glFunc (const char* n, A... a) { return ((R (__stdcall* )(A...)) ((void* (__stdcall*)(const char*)) GetProcAddress(LoadLibraryW(L"opengl32.dll"), "wglGetProcAddress"))(n)) (a...); }; float spheres[] = { // center.xyz, radius | emmission.xyz, 0 | color.rgb, refltype -1e5 - 2.6, 0, 0, 1e5, 0, 0, 0, 0, .75, .25, .25, 1, // Left (DIFFUSE) 1e5 + 2.6, 0, 0, 1e5, 0, 0, 0, 0, .25, .25, .75, 1, // Right 0, 1e5 + 2, 0, 1e5, 0, 0, 0, 0, .75, .75, .75, 1, // Top 0,-1e5 - 2, 0, 1e5, 0, 0, 0, 0, .75, .75, .75, 1, // Bottom 0, 0, -1e5 - 2.8, 1e5, 0, 0, 0, 0, .75, .75, .75, 1, // Back 0, 0, 1e5 + 7.9, 1e5, 0, 0, 0, 0, 0, 0, 0, 1, // Front -1.3, -1.2, -1.3, 0.8, 0, 0, 0, 0, .999,.999,.999, 2, // REFLECTIVE 1.3, -1.2, -0.2, 0.8, 0, 0, 0, 0, .999,.999,.999, 3, // REFRACTIVE 0, 11.96, 0, 10, 12,12,12,0, 0, 0, 0, 1, // Light }; int main(int argc, char *argv[]) { int spp = argc>1 ? atoi(argv[1]) : 1000, resy = argc>2 ? atoi(argv[2]) : 400, resx = resy*3/2; // image resolution HDC hdc = GetDC(0); static PIXELFORMATDESCRIPTOR pfd; SetPixelFormat(hdc, ChoosePixelFormat(hdc, &pfd), &pfd); wglMakeCurrent(hdc, wglCreateContext(hdc)); struct { int Sph, Rad; } buf; // GPU pixel buffer glFunc("glGenBuffers", 2, &buf); glFunc("glNamedBufferData", buf.Sph, sizeof(spheres), spheres, 0x88E4); // GL_STATIC_DRAW glFunc("glNamedBufferData", buf.Rad, 4*resx*resy*sizeof(float), 0, 0x88E4); glFunc("glBindBufferBase", 0x90D2, 0, buf.Sph); // GL_SHADER_STORAGE_BUFFER glFunc("glBindBufferBase", 0x90D2, 1, buf.Rad); int p=glFunc<int>("glCreateProgram"), s=glFunc<int>("glCreateShader", 0x91B9); // GL_COMPUTE_SHADER const char* src = GLSL( layout(local_size_x = 16, local_size_y = 16) in; struct Ray { vec3 o; vec3 d; }; struct Sphere { vec4 geo; vec3 e; vec4 c; } obj; layout(std430, binding = 0) buffer b0 { Sphere spheres[]; }; layout(std430, binding = 1) buffer b1 { vec4 accRad[]; }; uniform uvec2 imgdim, samps; // image dimensions and sample count vec3 rand01(uvec3 x){ for (int i=3; i-->0;) x = ((x>>8U)^x.yzx)*1103515245U; return vec3(x)*(1.0/float(0xffffffffU)); } void main() { uvec2 pix = gl_GlobalInvocationID.xy; if (pix.x >= imgdim.x || pix.y >= imgdim.y) return; uint gid = (imgdim.y - pix.y - 1) * imgdim.x + pix.x; if (samps.x == 0) accRad[gid] = vec4(0); // initialize radiance buffer Ray cam = Ray(vec3(0, 0.52, 7.4), normalize(vec3(0, -0.06, -1))); // define camera vec3 cx = normalize(cross(cam.d, abs(cam.d.y)<0.9 ? vec3(0,1,0) : vec3(0,0,1))), cy = cross(cx, cam.d); vec2 sdim = vec2(0.036, 0.024), rnd2 = 2*rand01(uvec3(pix, samps.x)).xy; // vvv tent filter sample vec2 tent = vec2(rnd2.x<1 ? sqrt(rnd2.x)-1 : 1-sqrt(2-rnd2.x), rnd2.y<1 ? sqrt(rnd2.y)-1 : 1-sqrt(2-rnd2.y)); vec2 s = ((pix + 0.5 * (0.5 + vec2((samps.x/2)%2, samps.x%2) + tent)) / vec2(imgdim) - 0.5)*sdim; vec3 spos = cam.o + cx*s.x + cy*s.y, lc = cam.o + cam.d * 0.035, accrad=vec3(0), accmat=vec3(1); Ray r = Ray(lc, normalize(lc - spos)); // construct ray for (int depth = 0; depth < 64; depth++) { // loop over ray bounces (max depth = 64) float d, inf = 1e20, t = inf, eps = 1e-4; // intersect ray with scene for (int i = spheres.length(); i-->0;) { Sphere s = spheres[i]; // perform intersection test in double precision dvec3 oc = dvec3(s.geo.xyz) - r.o; // Solve t^2*d.d + 2*t*(o-s).d + (o-s).(o-s)-r^2 = 0 double b=dot(oc,r.d), det=b*b-dot(oc,oc)+s.geo.w*s.geo.w; if (det < 0) continue; else det=sqrt(det); d = (d = float(b-det))>eps ? d : ((d=float(b+det))>eps ? d : inf); if(d < t) { t=d; obj = s; } } if (t < inf) { // object hit vec3 x = r.o + r.d*t, n = normalize(x-obj.geo.xyz), nl = dot(n,r.d)<0 ? n : -n; float p = max(max(obj.c.x, obj.c.y), obj.c.z); // max reflectance accrad += accmat*obj.e; accmat *= obj.c.xyz; vec3 rdir = reflect(r.d,n), rnd = rand01(uvec3(pix, samps.x*64 + depth)); if (depth > 5) if (rnd.z >= p) break; else accmat /= p; // Russian Roulette if (obj.c.w == 1) { // DIFFUSE float r1 = 2 * 3.141592653589793 * rnd.x, r2 = rnd.y, r2s = sqrt(r2); // cosine sampling vec3 w = nl, u = normalize((cross(abs(w.x)>0.1 ? vec3(0,1,0) : vec3(1,0,0), w))), v = cross(w,u); r = Ray(x, normalize(u*cos(r1)*r2s + v * sin(r1)*r2s + w * sqrt(1 - r2))); } else if (obj.c.w == 2) { // SPECULAR r = Ray(x, rdir); } else if (obj.c.w == 3) { // REFRACTIVE bool into = n==nl; float cos2t, nc=1, nt=1.5, nnt = into ? nc/nt : nt/nc, ddn = dot(r.d,nl); if ((cos2t = 1 - nnt * nnt*(1 - ddn * ddn)) >= 0) { // Fresnel reflection/refraction vec3 tdir = normalize(r.d*nnt - n * ((into ? 1 : -1)*(ddn*nnt + sqrt(cos2t)))); float a = nt - nc, b = nt + nc, R0 = a*a/(b*b), c = 1 - (into ? -ddn : dot(tdir,n)); float Re = R0 + (1 - R0)*c*c*c*c*c, Tr = 1 - Re, P = 0.25 + 0.5*Re, RP = Re/P, TP = Tr/(1-P); r = Ray(x, rnd.x < P ? rdir : tdir); // pick reflection with probability P accmat *= rnd.x < P ? RP : TP; // energy compensation } else r = Ray(x, rdir); // Total internal reflection } } } accRad[gid] += vec4(accrad / samps.y, 0); // <<< accumulate radiance vvv write 8bit rgb gamma encoded color if (samps.x == samps.y-1) accRad[gid].xyz = pow(vec3(clamp(accRad[gid].xyz, 0, 1)), vec3(0.45)) * 255 + 0.5; }); glFunc("glShaderSource", s, 1, &src, 0); glFunc("glCompileShader", s); glFunc("glAttachShader", p, s); glFunc("glLinkProgram", p); glFunc("glUseProgram", p); glFunc("glUniform2ui", glFunc<int>("glGetUniformLocation", p, "imgdim"), resx, resy); for (int pass = 0; pass < spp; pass++) { // sample rays glFunc("glUniform2ui", glFunc<int>("glGetUniformLocation", p, "samps"), pass, spp); glFunc("glDispatchCompute", (resx + 15) / 16, (resy + 15) / 16, 1); fprintf(stderr, "\rRendering (%d spp) %5.2f%%", spp, 100.0 * (pass+1) / spp); glFinish(); } float* pixels = new float[4*resx*resy]; // read back buffer and write inverse sensor image to file glFunc("glGetNamedBufferSubData", buf.Rad, 0, 4*resx*resy*sizeof(float), pixels); FILE *file = fopen("image.ppm", "w"); fprintf(file, "P3\n# spp: %d\n%d %d %d\n", spp, resx, resy, 255); for (int i = resx*resy; i-->0;) fprintf(file, "%d %d %d ", int(pixels[4*i]), int(pixels[4*i+1]), int(pixels[4*i+2])); }
72.866071
124
0.485357
f08869385b8bd0b0f20dd057ebc8fdbf6b9426c8
298
cpp
C++
AtCoder/ABC 162/C.cpp
igortakeo/Solutions-CF
d945f0ae21c691120b69db78ff3d240b7dedc0a7
[ "MIT" ]
1
2020-05-25T15:32:23.000Z
2020-05-25T15:32:23.000Z
AtCoder/ABC 162/C.cpp
igortakeo/Solutions-CF
d945f0ae21c691120b69db78ff3d240b7dedc0a7
[ "MIT" ]
null
null
null
AtCoder/ABC 162/C.cpp
igortakeo/Solutions-CF
d945f0ae21c691120b69db78ff3d240b7dedc0a7
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define ll long long using namespace std; int main(){ int k; ll sum = 0; cin >> k; for(int i=1; i<=k; i++){ for(int j=1; j<=k; j++){ int a = __gcd(i, j); for(int l=1; l<=k; l++){ sum+= __gcd(a, l); } } } cout << sum << endl; return 0; }
12.416667
27
0.47651
f08c2d61feb5de0e5929ee721e6e49d47a942450
53
cpp
C++
source/Allocators/DoubleStackAllocator.cpp
teemid/Capstan
35e37a41cdc4c471a4570916751e5f391693aef4
[ "MIT" ]
null
null
null
source/Allocators/DoubleStackAllocator.cpp
teemid/Capstan
35e37a41cdc4c471a4570916751e5f391693aef4
[ "MIT" ]
null
null
null
source/Allocators/DoubleStackAllocator.cpp
teemid/Capstan
35e37a41cdc4c471a4570916751e5f391693aef4
[ "MIT" ]
null
null
null
#include "Capstan/Allocators/DoubleStackAllocator.h"
26.5
52
0.849057
f0944e557457ef143775a29eda3792bb6760d37e
23,656
cpp
C++
firmware/src/Statemachine/Canopen.cpp
sprenger120/remote_control_device
c375ab12683c10fd2918ea8345bcb06a5d78b978
[ "MIT" ]
1
2021-01-27T12:23:43.000Z
2021-01-27T12:23:43.000Z
firmware/src/Statemachine/Canopen.cpp
sprenger120/remote_control_device
c375ab12683c10fd2918ea8345bcb06a5d78b978
[ "MIT" ]
null
null
null
firmware/src/Statemachine/Canopen.cpp
sprenger120/remote_control_device
c375ab12683c10fd2918ea8345bcb06a5d78b978
[ "MIT" ]
null
null
null
#include "Canopen.hpp" #include "ANSIEscapeCodes.hpp" #include "CanFestivalLocker.hpp" #include "Logging.hpp" #include "PeripheralDrivers/CanIO.hpp" #include "PeripheralDrivers/TerminalIO.hpp" #include <algorithm> namespace remote_control_device { Canopen *Canopen::_instance = nullptr; Message Canopen::RTD_StateBootupMessage = { Canopen::RPDO1_RTD_State, NOT_A_REQUEST, 1, {Canopen::RTD_State_Bootup, 0, 0, 0, 0, 0, 0, 0}}; Message Canopen::RTD_StateReadyMessage = { Canopen::RPDO1_RTD_State, NOT_A_REQUEST, 1, {Canopen::RTD_State_Ready, 0, 0, 0, 0, 0, 0, 0}}; Message Canopen::RTD_StateEmcyMessage = {Canopen::RPDO1_RTD_State, NOT_A_REQUEST, 1, {Canopen::RTD_State_Emergency, 0, 0, 0, 0, 0, 0, 0}}; Canopen::Canopen(CanIO &canio, Logging &log, bool bypass) : _canIO(canio), _log(log), _monitoredDevices{{MonitoredDevice(BusDevices::DriveMotorController), MonitoredDevice(BusDevices::BrakeActuator), MonitoredDevice(BusDevices::BrakePressureSensor), MonitoredDevice(BusDevices::SteeringActuator), MonitoredDevice(BusDevices::SteeringAngleSensor)}}, _stateControlledDevices{ {StateControlledDevice(BusDevices::DriveMotorController, CanDeviceState::Operational), StateControlledDevice(BusDevices::BrakeActuator, CanDeviceState::Operational), StateControlledDevice(BusDevices::SteeringActuator, CanDeviceState::Operational), StateControlledDevice(BusDevices::BrakePressureSensor, CanDeviceState::Operational)}}, _couplings{{Coupling(BusDevices::BrakeActuator, BrakeActuatorCoupling_IndexOD, BrakeActuatorCoupling_SubIndexOD, BrakeActuatorCoupling_EngagedValue, BrakeActuatorCoupling_DisEngagedValue), Coupling(BusDevices::SteeringActuator, SteeringActuatorCoupling_IndexOD, SteerinActuatorCoupling_SubIndexOD, SteerinActuatorCoupling_EngagedValue, SteerinActuatorCoupling_DisEngagedValue)}} { specialAssert(_instance == nullptr); _instance = this; if (bypass) { return; } { CFLocker locker; setNodeId(locker.getOD(), static_cast<UNS8>(BusDevices::RemoteControlDevice)); // fix for REPEAT_NMT_MAX_NODE_ID_TIMES not having enough repeats by default thus not // initializing the NMT table correctly which makes post_SlaveStateChange miss bootup // events for nodes with higher ids for (auto &e : locker.getOD()->NMTable) { e = Unknown_state; } // set zero values to not have canfestival send pure zeros 0 // which could cause damage setBrakeForce(0.0); setSteeringAngle(0.0); setWheelDriveTorque(0.0); setSelfState(StateId::Start); RTD_State = RTD_State_Bootup; setTPDO(TPDOIndex::SelfState, true); setActuatorPDOs(false); // setup callbacks locker.getOD()->heartbeatError = &cbHeartbeatError; locker.getOD()->post_SlaveStateChange = &cbSlaveStateChange; // avoids global reset sent out // preOperational callback is pre-programmed with // masterSendNMTstateChange (d, 0, NMT_Reset_Node) // by overwriting the callback we stop this from being sent locker.getOD()->preOperational = [](CO_Data *d) -> void {}; setState(locker.getOD(), Initialisation); setState(locker.getOD(), Operational); // RX timeout requires a timer table that can't be generated and is initialized with NULL // every time adding our own // also the stack has a bug in timeout registration (since fixed) // where it reads from the wrong memory address and uses garbage for the timeout value std::fill(_rpdoTimers.begin(), _rpdoTimers.end(), TIMER_NONE); locker.getOD()->RxPDO_EventTimers = _rpdoTimers.data(); // hack in rpdo timeout callback as it can't be registered anyhere locker.getOD()->RxPDO_EventTimers_Handler = [](CO_Data *d, UNS32 timerId) -> void { // remove reference to previously used timer // if not done, the next reception of this rpdo will clear the timer spot previously // used again even though it could be attributed to something completely different d->RxPDO_EventTimers[timerId] = TIMER_NONE; // NOLINT testHook_signalRTDTimeout(); _instance->signalRTDTimeout(); }; // when a rpdo is received, the OD entry where RTD_State resides is updated, every entry // can have a callback so we use this cb to reset the timeout flag set by the rpdo timeout RegisterSetODentryCallBack(locker.getOD(), RTD_State_ODIndex, RTD_State_ODSubIndex, [](CO_Data *d, const indextable *, UNS8 bSubindex) -> UNS32 { testHook_signalRTDRecovery(); _instance->signalRTDRecovery(); return OD_SUCCESSFUL; }); // rpdo timeout is a poorly supported feature in canopen // canfestival is also not capable to start the rpdo timeout unless at least // one message was received, so dispatch one fake message to get the timer going _canIO.addRXMessage(RTD_StateBootupMessage); } } Canopen::~Canopen() { _instance = nullptr; CFLocker locker; locker.getOD()->RxPDO_EventTimers = nullptr; } bool Canopen::isDeviceOnline(const BusDevices device) const { for (auto &dev : _monitoredDevices) { if (dev.device == device) { return !dev.disconnected; } } return false; } void Canopen::drawUIDevicesPart(TerminalIO &term) { term.write(ANSIEscapeCodes::ColorSection_WhiteText_GrayBackground); term.write("\r\nMonitored Devices:\r\n"); term.write(ANSIEscapeCodes::ColorSection_End); auto printMonitoredDevice = [&](const MonitoredDevice &dev) -> void { if (dev.disconnected) { term.write(ANSIEscapeCodes::ColorSection_WhiteText_RedBackground); } term.write(getBusDeviceName(dev.device)); if (dev.disconnected) { term.write(": Offline"); term.write(ANSIEscapeCodes::ColorSection_End); } else { term.write(": Online"); } term.write("\r\n"); }; for (auto &dev : _monitoredDevices) { printMonitoredDevice(dev); } MonitoredDevice rtd(BusDevices::RealTimeDevice); rtd.disconnected = _rtdTimeout; printMonitoredDevice(rtd); term.write(ANSIEscapeCodes::ColorSection_WhiteText_GrayBackground); term.write("\r\nState Controlled Devices:\r\n"); term.write(ANSIEscapeCodes::ColorSection_End); for (auto &scd : _stateControlledDevices) { if (scd.targetState != scd.currentState) { term.write(ANSIEscapeCodes::ColorSection_BlackText_YellowBackground); } term.write(getBusDeviceName(scd.device)); term.write(": "); term.write(getCanDeviceStateName(scd.currentState)); term.write(" (Target: "); term.write(getCanDeviceStateName(scd.targetState)); term.write(")"); if (scd.targetState != scd.currentState) { term.write(ANSIEscapeCodes::ColorSection_End); } term.write("\r\n"); } } void Canopen::kickstartPDOTranmission() { // setState(operational) calls sendPDOEvent which // causes the stack to register event timers for continous sending for all // enabled PDOs. As only self state is enabled by default // All other pdos get left behind and will not start transmitting // on their own until sendPDOEvent is called again. // Also: The stack has an oversight within pdo transmission in where there is no easy way // to force it to transmit a pdo with the same data continously. Every time a pdo tries to get // sent it is compared against the last one and if it is the same the function aborts. In this // case the event timers are not re-registered and the pdo is functionally broken You could do // something like this here below after every pdo transmission /*lock.getOD()->PDO_status[static_cast<size_t>(TPDOIndex::SelfState)].last_message.cob_id = 0; lock.getOD()->PDO_status[static_cast<size_t>(TPDOIndex::BrakeForce)].last_message.cob_id = 0; lock.getOD()->PDO_status[static_cast<size_t>(TPDOIndex::SteeringAngle)].last_message.cob_id = 0; lock.getOD()->PDO_status[static_cast<size_t>(TPDOIndex::MotorTorque)].last_message.cob_id = 0; lock.getOD()->PDO_status[static_cast<size_t>(TPDOIndex::TargetValues)].last_message.cob_id = 0;*/ // bus this is tedious as there is no callback to hook into after a pdo has fired. // So to avoid all this b.s. pdo.c was modified in line 539 to not compare at all. CFLocker lock; sendPDOevent(lock.getOD()); } void Canopen::setSelfState(const StateId state) { { CFLocker locker; SelfState = static_cast<UNS8>(state); } } void Canopen::setBrakeForce(float force) { { CFLocker locker; BrakeTargetForce = mapValue<float, INTEGER16>(0.0f, 1.0f, BrakeForceRaw_Min, BrakeForceRaw_Max, force); } } void Canopen::setWheelDriveTorque(float torque) { { CFLocker locker; WheelTargetTorque = mapValue<float, INTEGER16>(-1.0f, 1.0f, WheelDriveTorqueRaw_Min, WheelDriveTorqueRaw_Max, torque); } } void Canopen::setSteeringAngle(float angle) { // inverted due to hardware gearing angle *= -1.0f; { CFLocker locker; SteeringTargetAngle = mapValue<float, INTEGER32>(-1.0f, 1.0f, SteeringAngleRaw_Min, SteeringAngleRaw_Max, angle); } } void Canopen::setCouplingStates(bool brake, bool steering) { { CFLocker locker; _setCouplingState(_couplings[CouplingIndex_Brake], steering); _setCouplingState(_couplings[CouplingIndex_Steering], brake); } } void Canopen::setTPDO(const TPDOIndex index, bool enable) { { CFLocker locker; if (enable) { PDOEnable(locker.getOD(), static_cast<UNS8>(index)); } else { PDODisable(locker.getOD(), static_cast<UNS8>(index)); } } } void Canopen::setActuatorPDOs(bool enable) { setTPDO(TPDOIndex::BrakeForce, enable); setTPDO(TPDOIndex::SteeringAngle, enable); setTPDO(TPDOIndex::MotorTorque, enable); setTPDO(TPDOIndex::TargetValues, enable); if (enable) { kickstartPDOTranmission(); } } void Canopen::update(BusDevicesState &target) { { CFLocker locker; target.rtdEmergency = RTD_State == RTD_State_Emergency; target.rtdBootedUp = RTD_State != RTD_State_Bootup; } target.timeout = false; for (auto &e : _monitoredDevices) { target.timeout = target.timeout || e.disconnected; } target.timeout = target.timeout || _rtdTimeout; } void Canopen::cbSlaveStateChange(CO_Data *d, UNS8 heartbeatID, e_nodeState state) { const auto dev = static_cast<BusDevices>(heartbeatID); // state controlled devices int8_t index{0}; if ((index = _instance->findInStateControlledList(dev)) != -1) { { CFLocker lock; // interpret node state to check if device is in correct state CanDeviceState convertedState = CanDeviceState::Unknown; switch (state) { case e_nodeState::Operational: convertedState = CanDeviceState::Operational; break; case e_nodeState::Pre_operational: convertedState = CanDeviceState::Preoperational; break; case e_nodeState::Initialisation: /* fall through */ case e_nodeState::Disconnected: /* fall through */ case e_nodeState::Connecting: /* fall through */ // case Preparing: has same value as connecting /* fall through */ case e_nodeState::Stopped: /* fall through */ case e_nodeState::Unknown_state: /* fall through */ default: break; } _instance->_stateControlledDevices[index].currentState = convertedState; _instance->_log.logInfo(Logging::Origin::BusDevices, "%s changed state to %s", getBusDeviceName(dev), getCanDeviceStateName(convertedState)); if (convertedState != _instance->_stateControlledDevices[index].targetState) { _instance->setDeviceState( dev, _instance->_stateControlledDevices[index].targetState); } } } // reset disconnected state for (MonitoredDevice &e : _instance->_monitoredDevices) { if (e.device == dev && e.disconnected) { _instance->_log.logInfo(Logging::Origin::BusDevices, "%s is online", getBusDeviceName(dev)); e.disconnected = false; return; } } } void Canopen::cbHeartbeatError(CO_Data *d, UNS8 heartbeatID) { // Called when a node registered in the heartbeat consumer od index // didn't send a heartbeat within the timeout range // after timeout the node's state is changed to disconnected internally // when the timed out node recovers, slave state change callback is called const auto dev = static_cast<BusDevices>(heartbeatID); _instance->_log.logInfo(Logging::Origin::BusDevices, "%s timed out", getBusDeviceName(dev)); // Reset internal current state when device is state monitored // so UI doesn't show wrong information int8_t index = 0; if ((index = _instance->findInStateControlledList(dev)) != -1) { _instance->_stateControlledDevices[index].currentState = CanDeviceState::Unknown; } for (MonitoredDevice &e : _instance->_monitoredDevices) { if (e.device == dev) { e.disconnected = true; return; } } _instance->_log.logWarning(Logging::Origin::BusDevices, "Received heartbeat error callback for nodeId %d but it isn't registered as a " "monitored device", heartbeatID); } void Canopen::cbSDO(CO_Data *d, UNS8 nodeId) { // search for coupling with nodeid Coupling *coupling = nullptr; for (Coupling &e : _instance->_couplings) { if (e.device == static_cast<BusDevices>(nodeId)) { coupling = &e; break; } } if (coupling == nullptr) { _instance->_log.logDebug(Logging::Origin::BusDevices, "Unexpected SDO received from nodeId %d", nodeId); return; } bool restart = false; uint32_t abortCode = 0; if (getWriteResultNetworkDict(d, nodeId, &abortCode) != SDO_FINISHED) { // transfer failed // abortCode is 0 for timeout which isn't correct // but flow errors in the stack cause this to be 0 if (abortCode == 0) { // timeout, try again restart = true; } else { // serious error, most likely ill configured node // not attempting new transmission as these errors are more likely // to come from an active node which answers quickly (like we do) // causing risk of flooding _instance->_log.logWarning(Logging::Origin::BusDevices, "SDO to nodeId %d failed (%s)", nodeId, abortCodeToString(abortCode)); restart = false; } } else { // sucess but check if target changed mid request processing if (coupling->stateForThisRequest != coupling->targetState) { _instance->_log.logDebug(Logging::Origin::BusDevices, "SDO finished successfully but state changed mid transmission"); restart = true; } else { _instance->_log.logDebug(Logging::Origin::BusDevices, "SDO finished successfully"); } } // closing isn't necessary when the transfer is finished but this isn't always the case closeSDOtransfer(d, nodeId, SDO_CLIENT); if (restart) { // logDebug(Logging::Origin::BusDevices, "Repeating transmission"); _instance->_setCouplingState(*coupling, coupling->targetState); } } const char *Canopen::abortCodeToString(uint32_t abortCode) { switch (abortCode) { /* case OD_SUCCESSFUL: return "OD_SUCCESSFUL"; case OD_READ_NOT_ALLOWED: return "OD_READ_NOT_ALLOWED"; case OD_WRITE_NOT_ALLOWED: return "OD_WRITE_NOT_ALLOWED"; case OD_NO_SUCH_OBJECT: return "OD_NO_SUCH_OBJECT"; case OD_NOT_MAPPABLE: return "OD_NOT_MAPPABLE"; case OD_ACCES_FAILED: return "OD_ACCES_FAILED"; case OD_LENGTH_DATA_INVALID: return "OD_LENGTH_DATA_INVALID"; case OD_NO_SUCH_SUBINDEX: return "OD_NO_SUCH_SUBINDEX"; case OD_VALUE_RANGE_EXCEEDED: return "OD_VALUE_RANGE_EXCEEDED"; case OD_VALUE_TOO_LOW: return "OD_VALUE_TOO_LOW"; case OD_VALUE_TOO_HIGH: return "OD_VALUE_TOO_HIGH"; case SDOABT_TOGGLE_NOT_ALTERNED: return "SDOABT_TOGGLE_NOT_ALTERNED"; case SDOABT_TIMED_OUT: return "SDOABT_TIMED_OUT"; case SDOABT_CS_NOT_VALID: return "SDOABT_CS_NOT_VALID"; case SDOABT_INVALID_BLOCK_SIZE: return "SDOABT_INVALID_BLOCK_SIZE"; case SDOABT_OUT_OF_MEMORY: return "SDOABT_OUT_OF_MEMORY"; case SDOABT_GENERAL_ERROR: return "SDOABT_GENERAL_ERROR"; case SDOABT_LOCAL_CTRL_ERROR: return "SDOABT_LOCAL_CTRL_ERROR";*/ default: return "Error Unknown"; } } int8_t Canopen::findInStateControlledList(const BusDevices device) { for (uint8_t i = 0; i < _stateControlledDevices.size(); ++i) { if (_stateControlledDevices[i].device == device) { return i; } } return -1; } void Canopen::setDeviceState(const BusDevices device, CanDeviceState state) { // check if allowed to change state int8_t index = findInStateControlledList(device); if (index == -1) { _instance->_log.logWarning(Logging::Origin::BusDevices, "Denied request to change state of unlisted device with nodeId %d", static_cast<uint8_t>(device)); return; } uint8_t nmtCommand = 0; switch (state) { case CanDeviceState::Operational: nmtCommand = NMT_Start_Node; break; case CanDeviceState::Preoperational: nmtCommand = NMT_Enter_PreOperational; break; case CanDeviceState::Unknown: /* fall through */ default: return; } _instance->_log.logInfo(Logging::Origin::BusDevices, "Requesting %s to change status to %s", getBusDeviceName(device), getCanDeviceStateName(state)); _stateControlledDevices[index].targetState = state; { CFLocker locker; masterSendNMTstateChange(locker.getOD(), static_cast<uint8_t>(_stateControlledDevices[index].device), nmtCommand); // masterSendNMTstateChange is just blindly transmitting the state change request // when a node doesn't switch it isn't noticed as proceedNODE_GUARD which processes incoming // heartbeats compares the old state with the unchanged newly received one and finds no // difference // invalidating the local state of a node will force the change state callback to be fired // which allows confirming the state change or retrying locker.getOD()->NMTable[static_cast<UNS8>(_stateControlledDevices[index].device)] = Disconnected; } } const char *Canopen::getBusDeviceName(const BusDevices dev) { switch (dev) { case BusDevices::DriveMotorController: return "Drive Motor Controller (10h)"; case BusDevices::BrakeActuator: return "Brake Actuator (20h)"; case BusDevices::SteeringActuator: return "Steering Actuator (30h)"; case BusDevices::RemoteControlDevice: return "Remote Control Device (1h)"; case BusDevices::RealTimeDevice: return "Real Time Device (2h)"; case BusDevices::WheelSpeedSensor: return "Wheel Speed Sensor (11h)"; case BusDevices::BrakePressureSensor: return "Brake Pressure Sensor (21h)"; case BusDevices::SteeringAngleSensor: return "Steering Angle Sensor (31h)"; default: return "Unamed device"; } } Canopen::Coupling::Coupling(BusDevices device, uint16_t odIndex, uint8_t odSubIndex, uint32_t engagedValue, uint32_t disengagedValue) : device(device), odIndex(odIndex), odSubIndex(odSubIndex), engagedValue(engagedValue), disengagedValue(disengagedValue) { } void Canopen::_setCouplingState(Coupling &coupling, bool state) { coupling.targetState = state; // check if sdo is still in porgress { CFLocker locker; UNS32 abortCode = 0; if (getWriteResultNetworkDict(locker.getOD(), static_cast<UNS8>(coupling.device), &abortCode) == SDO_ABORTED_INTERNAL) { // nothing in progress, start write request coupling.stateForThisRequest = coupling.targetState; uint32_t couplingState = coupling.stateForThisRequest ? coupling.engagedValue : coupling.disengagedValue; writeNetworkDictCallBack(locker.getOD(), static_cast<UNS8>(coupling.device), coupling.odIndex, coupling.odSubIndex, 4, uint32, &couplingState, &Canopen::cbSDO, false); } else { _instance->_log.logInfo(Logging::Origin::BusDevices, "SDO transfer already in progress, repeating after this one finished"); } } } std::array<Canopen::BusDevices, Canopen::MonitoredDeviceCount> Canopen::getMonitoredDevices() const { std::array<Canopen::BusDevices, Canopen::MonitoredDeviceCount> list; for (uint8_t i = 0; i < _monitoredDevices.size(); ++i) { list[i] = _monitoredDevices[i].device; } return list; } std::array<Canopen::BusDevices, Canopen::StateControlledDeviceCount> Canopen::getStateControlledDevices() const { std::array<Canopen::BusDevices, Canopen::StateControlledDeviceCount> list; for (uint8_t i = 0; i < _stateControlledDevices.size(); ++i) { list[i] = _stateControlledDevices[i].device; } return list; } } // namespace remote_control_device
36.337942
113
0.625592
f096246210bf176cfe8d59ed7623c939fe2b7924
13,759
cpp
C++
my-cs/extern/loki-0.1.7/test/Checker/main.cpp
zaqwes8811/cs-courses
aa9cf5ad109c9cfcacaadc11bf2defb2188ddce2
[ "Apache-2.0" ]
24
2016-08-09T23:32:08.000Z
2022-02-08T02:24:34.000Z
my-cs/extern/loki-0.1.7/test/Checker/main.cpp
zaqwes8811/cs-courses
aa9cf5ad109c9cfcacaadc11bf2defb2188ddce2
[ "Apache-2.0" ]
15
2015-03-07T12:46:41.000Z
2015-04-11T09:08:36.000Z
extern/loki-0.1.7/test/Checker/main.cpp
zaqwes8811/micro-apps
7f63fdf613eff5d441a3c2c7b52d2a3d02d9736a
[ "MIT" ]
30
2015-04-22T16:10:43.000Z
2021-12-24T06:37:04.000Z
//////////////////////////////////////////////////////////////////////////////// // // Test program for The Loki Library // Copyright (c) 2008 Richard Sposato // The copyright on this file is protected under the terms of the MIT license. // // Permission to use, copy, modify, distribute and sell this software for any // purpose is hereby granted without fee, provided that the above copyright // notice appear in all copies and that both that copyright notice and this // permission notice appear in supporting documentation. // // The author makes no representations about the suitability of this software // for any purpose. It is provided "as is" without express or implied warranty. // //////////////////////////////////////////////////////////////////////////////// // $Id$ /// @file main.cpp This provides examples on how to use Loki's Checker facility. // ---------------------------------------------------------------------------- #include "../../include/loki/Checker.h" #include <stdexcept> #include <iostream> #include <vector> #if !defined( nullptr ) #define nullptr NULL #endif #if !defined( NULL ) #define NULL 0 #endif using namespace std; // ---------------------------------------------------------------------------- /* This class has 2 invariants. The this pointer may never equal NULL, and the value may not equal zero. */ class Thingy { public: static void ChangeThat( void ); static unsigned int GetThat( void ); explicit Thingy( unsigned int value ); Thingy( const Thingy & that ); Thingy & operator = ( const Thingy & that ); ~Thingy( void ); void Swap( Thingy & that ); bool operator == ( const Thingy & that ) const; void DoSomethingEvil( void ); unsigned int GetValue( void ) const; unsigned int DoSomething( bool doThrow ) const; void DoSomethingElse( void ) const; void AddCount( unsigned int count ); unsigned int GetCount( unsigned int index ) const; void ClearCounts( void ); private: /// This is a static validator. static bool StaticIsValid( void ); /// This is a per-instance validator. bool IsValid( void ) const; /// This can be used to validate pre-conditions and post-conditions. bool IsValidEmpty( void ) const; /// This can be used to validate pre-conditions and post-conditions. bool IsValidFull( void ) const; // These lines show how to declare checkers for non-static functions in a host class. typedef ::Loki::ContractChecker< Thingy, ::Loki::CheckForNoThrow > CheckForNoThrow; typedef ::Loki::ContractChecker< Thingy, ::Loki::CheckForNoChangeOrThrow > CheckForNoChangeOrThrow; typedef ::Loki::ContractChecker< Thingy, ::Loki::CheckForNoChange > CheckForNoChange; typedef ::Loki::ContractChecker< Thingy, ::Loki::CheckForEquality > CheckForEquality; typedef ::Loki::ContractChecker< Thingy, ::Loki::CheckForNothing > CheckInvariants; // These lines show how to declare checkers for static functions of a host class. typedef ::Loki::StaticChecker< ::Loki::CheckStaticForNoThrow > CheckStaticForNoThrow; typedef ::Loki::StaticChecker< ::Loki::CheckStaticForNothing > CheckStaticInvariants; typedef ::std::vector< unsigned int > IntBlock; static unsigned int s_value; unsigned int m_value; IntBlock m_counts; }; unsigned int Thingy::s_value = 10; // ---------------------------------------------------------------------------- // This example shows how static functions can use a no-throw checkers. void Thingy::ChangeThat( void ) { CheckStaticForNoThrow checker( &Thingy::StaticIsValid ); (void)checker; s_value--; } // ---------------------------------------------------------------------------- // This example shows how static functions can use an invariant checker. unsigned int Thingy::GetThat( void ) { CheckStaticInvariants checker( &Thingy::StaticIsValid ); (void)checker; return s_value; } // ---------------------------------------------------------------------------- // This example shows how ctors can use an invariant checker. Thingy::Thingy( unsigned int value ) : m_value( value ), m_counts() { CheckInvariants checker( this, &Thingy::IsValid ); (void)checker; } // ---------------------------------------------------------------------------- Thingy::Thingy( const Thingy & that ) : m_value( that.m_value ), m_counts( that.m_counts ) { CheckInvariants checker( this, &Thingy::IsValid ); (void)checker; } // ---------------------------------------------------------------------------- Thingy & Thingy::operator = ( const Thingy & that ) { CheckInvariants checker( this, &Thingy::IsValid ); (void)checker; if ( &that != this ) { Thingy temp( that ); temp.Swap( *this ); } return *this; } // ---------------------------------------------------------------------------- // A destructor really doesn't need a checker, but does need to confirm // the object is valid at the start of the destructor. Thingy::~Thingy( void ) { assert( IsValid() ); } // ---------------------------------------------------------------------------- // A swap function gets 2 checkers - one for this, and another for that. void Thingy::Swap( Thingy & that ) { CheckInvariants checker1( this, &Thingy::IsValid ); (void)checker1; CheckInvariants checker2( &that, &Thingy::IsValid ); (void)checker2; const IntBlock counts( m_counts ); m_counts = that.m_counts; that.m_counts = counts; const unsigned int value = m_value; m_value = that.m_value; that.m_value = value; } // ---------------------------------------------------------------------------- bool Thingy::operator == ( const Thingy & that ) const { return ( m_value == that.m_value ); } // ---------------------------------------------------------------------------- void Thingy::DoSomethingEvil( void ) { m_value = 0; } // ---------------------------------------------------------------------------- // This example shows how to use the no-throw checker. unsigned int Thingy::GetValue( void ) const { CheckForNoThrow checker( this, &Thingy::IsValid ); (void)checker; return m_value; } // ---------------------------------------------------------------------------- // This example shows how to use the equality checker. unsigned int Thingy::DoSomething( bool doThrow ) const { CheckForEquality checker( this, &Thingy::IsValid ); (void)checker; if ( doThrow ) throw ::std::logic_error( "Test Exception." ); return m_value; } // ---------------------------------------------------------------------------- // This example shows how to use the no-change checker. void Thingy::DoSomethingElse( void ) const { CheckForNoChange checker( this, &Thingy::IsValid ); (void)checker; } // ---------------------------------------------------------------------------- void Thingy::AddCount( unsigned int count ) { // This function's checker cares about class invariants and post-conditions, // but does not need to check pre-conditions, so it passes in a nullptr for // the pre-condition validator. Ths post-condition validator just makes sure // the container has at least 1 element. CheckInvariants checker( this, &Thingy::IsValid, nullptr, &Thingy::IsValidFull ); m_counts.push_back( count ); } // ---------------------------------------------------------------------------- unsigned int Thingy::GetCount( unsigned int index ) const { // This function's checker cares about class invariants and both the pre- and // post-conditions, so it passes in pointers for all 3 validators. The pre- // and post-conditions are both about making sure the container is not empty. CheckForNoChangeOrThrow checker( this, &Thingy::IsValid, &Thingy::IsValidFull, &Thingy::IsValidFull ); if ( m_counts.size() <= index ) return 0; const unsigned int count = m_counts[ index ]; return count; } // ---------------------------------------------------------------------------- void Thingy::ClearCounts( void ) { // This function's checker cares about class invariants and post-conditions, // but does not need to check pre-conditions, so it passes in a nullptr for // the pre-condition validator. Ths post-condition validator just makes sure // the container has no elements. CheckForNoThrow checker( this, &Thingy::IsValid, nullptr, &Thingy::IsValidEmpty ); m_counts.clear(); } // ---------------------------------------------------------------------------- // This is a static validator. bool Thingy::StaticIsValid( void ) { assert( s_value != 0 ); return true; } // ---------------------------------------------------------------------------- // This is a per-instance validator. bool Thingy::IsValid( void ) const { assert( nullptr != this ); assert( m_value != 0 ); return true; } // ---------------------------------------------------------------------------- bool Thingy::IsValidEmpty( void ) const { assert( nullptr != this ); assert( m_counts.size() == 0 ); return true; } // ---------------------------------------------------------------------------- bool Thingy::IsValidFull( void ) const { assert( nullptr != this ); assert( m_counts.size() != 0 ); return true; } // ---------------------------------------------------------------------------- // This is a validator function called by checkers inside standalone functions. bool AllIsValid( void ) { assert( Thingy::GetThat() != 0 ); return true; } // ---------------------------------------------------------------------------- // These lines show how to declare checkers for standalone functions. typedef ::Loki::StaticChecker< ::Loki::CheckStaticForNoThrow > CheckStaticForNoThrow; typedef ::Loki::StaticChecker< ::Loki::CheckStaticForNothing > CheckStaticInvariants; // ---------------------------------------------------------------------------- void DoSomething( void ) { // This example shows how to use a checker in a stand-alone function. CheckStaticForNoThrow checker( &AllIsValid ); (void)checker; Thingy::ChangeThat(); } // ---------------------------------------------------------------------------- void ThrowTest( void ) { Thingy thingy( 10 ); throw ::std::logic_error( "Will Thingy assert during an exception?" ); } // ---------------------------------------------------------------------------- int main( unsigned int argc, const char * const argv[] ) { try { cout << "Just before call to ThrowTest." << endl; ThrowTest(); cout << "Just after call to ThrowTest." << endl; } catch ( const ::std::logic_error & ex ) { cout << "Caught an exception! " << ex.what() << endl; } catch ( const ::std::exception & ex ) { cout << "Caught an exception! " << ex.what() << endl; } catch ( ... ) { cout << "Caught an exception!" << endl; } unsigned int count = 0; try { cout << "Running basic tests with Thingy." << endl; // First do some tests on class member functions. Thingy t1( 1 ); t1.DoSomething( false ); Thingy t2( 2 ); t2.DoSomething( true ); cout << "Done with basic tests with Thingy." << endl; } catch ( const ::std::logic_error & ex ) { cout << "Caught an exception! " << ex.what() << endl; } catch ( const ::std::exception & ex ) { cout << "Caught an exception! " << ex.what() << endl; } catch ( ... ) { cout << "Caught an exception!" << endl; } try { Thingy t1( 1 ); cout << "Now running tests with Thingy counts." << endl; // These lines will exercise the functions with pre- and post-conditions. t1.AddCount( 11 ); t1.AddCount( 13 ); t1.AddCount( 17 ); t1.AddCount( 19 ); count = t1.GetCount( 3 ); assert( count == 19 ); count = t1.GetCount( 0 ); assert( count == 11 ); t1.ClearCounts(); cout << "Done with tests with Thingy counts." << endl; } catch ( const ::std::logic_error & ex ) { cout << "Caught an exception! " << ex.what() << endl; } catch ( const ::std::exception & ex ) { cout << "Caught an exception! " << ex.what() << endl; } catch ( ... ) { cout << "Caught an exception!" << endl; } try { cout << "Now run tests on static member functions" << endl; // Next do some tests with static member functions. Thingy::ChangeThat(); const unsigned int value = Thingy::GetThat(); assert( value != 0 ); cout << "Done with tests on static member functions" << endl; } catch ( const ::std::logic_error & ex ) { cout << "Caught an exception! " << ex.what() << endl; } catch ( const ::std::exception & ex ) { cout << "Caught an exception! " << ex.what() << endl; } catch ( ... ) { cout << "Caught an exception!" << endl; } try { cout << "Now run test on a standalone function." << endl; // Then do a test with a standalone function. DoSomething(); cout << "Done with test on a standalone function." << endl; } catch ( const ::std::exception & ex ) { cout << "Caught an exception! " << ex.what() << endl; } catch ( ... ) { cout << "Caught an exception!" << endl; } cout << "All done!" << endl; return 0; } // ----------------------------------------------------------------------------
29.088795
106
0.529181
f09853d57b96f656cd589da1c25a2f02cc1897ea
1,524
hpp
C++
include/codegen/include/RootMotion/FinalIK/EditorIK.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/RootMotion/FinalIK/EditorIK.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/RootMotion/FinalIK/EditorIK.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:09:17 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes // Including type: UnityEngine.MonoBehaviour #include "UnityEngine/MonoBehaviour.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: RootMotion::FinalIK namespace RootMotion::FinalIK { // Forward declaring type: IK class IK; } // Completed forward declares // Type namespace: RootMotion.FinalIK namespace RootMotion::FinalIK { // Autogenerated type: RootMotion.FinalIK.EditorIK class EditorIK : public UnityEngine::MonoBehaviour { public: // private RootMotion.FinalIK.IK ik // Offset: 0x18 RootMotion::FinalIK::IK* ik; // private System.Void Start() // Offset: 0x1395670 void Start(); // private System.Void Update() // Offset: 0x1395718 void Update(); // public System.Void .ctor() // Offset: 0x13957E8 // Implemented from: UnityEngine.MonoBehaviour // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() static EditorIK* New_ctor(); }; // RootMotion.FinalIK.EditorIK } DEFINE_IL2CPP_ARG_TYPE(RootMotion::FinalIK::EditorIK*, "RootMotion.FinalIK", "EditorIK"); #pragma pack(pop)
33.866667
89
0.672572
f098e60a5ec2af63aaac74f9d576e9cfb39f56f5
11,089
cc
C++
parser/pub/tools/tools.cc
smartdata-x/MarketSys
b4f999fb80b8f2357b75694c2ca94d46190a55f7
[ "Apache-2.0" ]
null
null
null
parser/pub/tools/tools.cc
smartdata-x/MarketSys
b4f999fb80b8f2357b75694c2ca94d46190a55f7
[ "Apache-2.0" ]
null
null
null
parser/pub/tools/tools.cc
smartdata-x/MarketSys
b4f999fb80b8f2357b75694c2ca94d46190a55f7
[ "Apache-2.0" ]
3
2016-10-25T01:56:17.000Z
2019-06-24T04:45:06.000Z
// Copyright (c) 2015-2015 The restful Authors. All rights reserved. // Created on: 2015/11/24 Author: jiaoyongqing #include<malloc.h> #include<stdlib.h> #include<memory.h> #include <string> #include <sstream> #include <map> #include <list> #include <vector> #include "tools/tools.h" #include "tea/tea.h" #include "net/typedef.h" #include "base/logic/logic_comm.h" #include "db/db_comm.h" #include "logic/logic_unit.h" namespace tools { std::string GetTimeKey(int64 time) { struct tm timeTm; int64 s = time; localtime_r(&s, &timeTm); char s_char[32]; memset(s_char, '\0', sizeof(s_char)); snprintf(s_char, sizeof(s_char), "%4d-%02d-%02d %02d", timeTm.tm_year+1900, timeTm.tm_mon+1, timeTm.tm_mday, timeTm.tm_hour); std::string str_time = s_char; return str_time; } std::string GetProvinceString(int province) { switch (province) { case 1 : return "jsdx:"; case 2: return "shdx:"; case 3: return "zjdx:"; } return ""; } int64 StrToTime(const char *Data) { struct tm* tmp_time = (struct tm*)malloc(sizeof( struct tm )); strptime(Data, "%Y-%m-%d %H", tmp_time); tmp_time->tm_min = 0; tmp_time->tm_sec = 0; time_t t = mktime(tmp_time); free(tmp_time); return t; } int64 TodayStartTime() { return time(NULL) - (time(NULL) + 28800) % 86400; } int64 CurrentTime() { return time(NULL); } // 集合的形式为:a,b,c,d, std::string MergeSet(const std::string &set_one, \ const std::string &set_two, \ char separator) { if (set_one == "") return set_two; if (set_two == "") return set_one; std::string ret(set_two); if (ret[ret.length() - 1] != separator) { ret = ret + std::string(1, separator); } std::list<std::string> set_one_list; SeparatorStr(set_one, ',', &set_one_list); std::list<std::string>::iterator it = set_one_list.begin(); for (; it != set_one_list.end(); ++it) { if (set_two.find((*it).c_str()) == std::string::npos) { ret += *it; ret += std::string(","); } } return ret; } void ListGroup(const ContainerStr &l, \ int group_size, \ char separator, \ ContainerStr *const out) { ContainerStr::const_iterator it = l.begin(); int i = 0; std::string value(""); for (; it != l.end(); ++it) { value += *it; value += std::string(1, separator); ++i; if (i == group_size) { out->push_back(value); value = ""; i = 0; } } if (value != "") { out->push_back(value); } } bool IfSetOneIsInSetTwo(const std::string &set_one, \ const std::string &set_two, \ char separator) { if (set_one == "") return true; if (set_two == "") return false; std::list<std::string> set_one_list; SeparatorStr(set_one, ',', &set_one_list); std::list<std::string>::iterator it = set_one_list.begin(); for (; it != set_one_list.end(); ++it) { if (set_two.find((*it).c_str()) == std::string::npos) { return false; } } return true; } std::string DeleteSet(const std::string &set_one, \ const std::string &set_two, \ char separator) { if (set_one == "" || set_two == "") return set_two; std::string ret(""); std::list<std::string> set_two_list; SeparatorStr(set_two, ',', &set_two_list); std::list<std::string>::iterator it = set_two_list.begin(); for (; it != set_two_list.end(); ++it) { if (set_one.find((*it).c_str()) == std::string::npos) { ret += *it; ret += std::string(","); } } return ret; } std::string::size_type FindNth(const std::string &str, \ std::string::size_type start, \ int len, \ char ch, \ int num) { if (num == 0) return -1; std::string::size_type end = str.find(ch, start); int count = 0; int cur_len = end + 1 - start; while (true) { if (end == std::string::npos) break; if (cur_len > len) break; ++count; if (cur_len == len) break; if (count == num )break; start = end + 1; end = str.find(ch, start); cur_len = end + 1 - start; } if (count < num) { return -1; } return end; } void NumToChar(void *d, size_t l, std::string &token) { std::stringstream os; char *p = reinterpret_cast<char *>(d); int temp; for (int i = 0; i < l; ++i) { temp = p[i]; os << temp << ","; } token = os.str(); } size_t CharToNum(void **d, std::string &token) { ContainerStr out; tools::SeparatorStr<ContainerStr>(token, ',', &out, true); *d = reinterpret_cast<void *>(malloc(out.size())); char *p = reinterpret_cast<char*>(*d); for (int i = 0; i < out.size(); ++i) { p[i] = atoi(out[i].c_str()); } return out.size(); } std::string TeaEncode(const std::string src) { LOG_DEBUG2("encode before: %s", src.c_str()); int src_len = src.length(); int len = ((src.length() - 1) / 8 + 1) * 8; char *in = reinterpret_cast<char*>(malloc(len)); memset(in, 0, len); strcpy(in, src.c_str()); struct tea_data td; td.d = reinterpret_cast<void *>(in); td.l = len; StrEn(&td); std::string des; NumToChar(td.d, td.l, des); free(in); LOG_DEBUG2("encode after:%s", des.c_str()); return des; } std::string TeaDecode(const std::string src) { struct tea_data td; std::string temp_src(src); td.l = CharToNum(&td.d, temp_src); StrDe(&td); std::string temp(""); for (int i = 0; i < td.l; ++i) { temp.append(1, (reinterpret_cast<char*>(td.d))[i]); } temp.append(1, '\0'); LOG_DEBUG2("decode after:%s", temp.c_str()); free(td.d); return temp; } std::string GetToken(int64 user_id, std::string &token) { std::stringstream os; std::string cur_token; std::string temp; os.str(""); os << user_id; os << ","; os << time(NULL); cur_token = os.str(); LOG_DEBUG2("\n\norigin token: %s\n\n", cur_token.c_str()); int len = ((cur_token.length() - 1) / 8 + 1) * 8; char *in = reinterpret_cast<char*>(malloc(len)); memset(in, 0, len); strcpy(in, cur_token.c_str()); in[cur_token.length()] = 0; struct tea_data td; td.d = reinterpret_cast<void *>(in); td.l = len; StrEn(&td); NumToChar(td.d, td.l, token); free(in); return token; } bool CheckToken(int64 user_id, std::string &token) { struct tea_data td; td.l = CharToNum(&td.d, token); StrDe(&td); std::string origin_token(""); for (int i = 0; i < td.l; ++i) { origin_token.append(1, (reinterpret_cast<char*>(td.d))[i]); } origin_token.append(1, '\0'); std::string::size_type separator_pos = origin_token.find(',', 0); std::string origin_id = origin_token.substr(0, separator_pos); std::stringstream os; os.str(""); os << origin_token.substr(separator_pos + 1, origin_token.length()); int64 origin_time; os >> origin_time; os.str(""); os << user_id; std::string current_id = os.str(); LOG_DEBUG2("\n\norigin token: %s,%d\n\n", origin_id.c_str(), origin_time); int64 current_time = time(NULL); const int TOKEN_SURVIVE_TIME = 86400; if (origin_id == current_id && (current_time - origin_time <= 86400)) { return true; } return false; } void MapAdd(std::map<std::string, int64> *map, \ const std::string &key, int64 value) { std::map<std::string, int64>::iterator it; it = map->find(key); if (it == map->end()) { (*map)[key] = value; } else { (*map)[key] += value; } } std::string TimeFormat(int64 time, const char* format) { struct tm timeTm; localtime_r(&time, &timeTm); char s_char[32]; memset(s_char, '\0', sizeof(s_char)); snprintf(s_char, sizeof(s_char), format, timeTm.tm_year+1900, timeTm.tm_mon+1, timeTm.tm_mday, timeTm.tm_hour); std::string str_time = s_char; return str_time; } std::vector<std::string> Split(std::string str, std::string pattern) { std::string::size_type pos; std::vector<std::string> result; str += pattern; int size = str.size(); for (int i = 0; i < size; i++) { pos = str.find(pattern, i); if (pos < size) { std::string s = str.substr(i , pos - i); result.push_back(s); i = pos + pattern.size() - 1; } } return result; } void replace_all(std::string *str, \ const std::string &old_value, \ const std::string &new_value) { while (true) { std::string::size_type pos(0); if ((pos = str->find(old_value)) != std::string::npos) str->replace(pos, old_value.length(), new_value); else break; } } void replace_all_distinct(std::string *str, \ const std::string &old_value, \ const std::string &new_value) { for (std::string::size_type pos(0); \ pos != std::string::npos; pos += new_value.length()) { if ((pos = str->find(old_value, pos)) != std::string::npos) str->replace(pos, old_value.length(), new_value); else break; } } void ReplaceBlank(std::string *str) { // 去除空格 replace_all_distinct(str, " ", ""); // 去除\t replace_all_distinct(str, "\t", ""); // 去除\n replace_all_distinct(str, "\n", ""); } bool check_userid_if_in_sql(NetBase* value,const int socket) { bool r = false; bool flag = false; int64 user_id = 0; int error_code = 0; r = value->GetBigInteger(L"user_id", static_cast<int64*>(&user_id)); if (false == r) error_code = STRUCT_ERROR; if (user_id > 0) { db::DbSql sql; flag = sql.CheckUseridIfInSql(user_id); error_code = sql.get_error_info(); LOG_DEBUG2("\n\DbSql::check_id_token-------error_code: %d\n\n",error_code); if (error_code != 0) { send_error(error_code, socket); return false; } if (flag == false) { error_code = USER_ID_ISNOT_IN_SQL; LOG_DEBUG2("\n\DbSql::check_id_token-------error_code1: %d\n\n",error_code); send_error(error_code, socket); return false; LOG_DEBUG2("\n\DbSql::check_id_token-------error_code2: %d\n\n",error_code); } } return true; } bool check_id_token(NetBase* value,const int socket) { bool r = false; bool flag = false; int error_code = 0; std::string token = ""; int64 user_id = 0; r = value->GetString(L"token", &token); if (false == r) error_code = STRUCT_ERROR; r = value->GetBigInteger(L"user_id", static_cast<int64*>(&user_id)); if (false == r) error_code = STRUCT_ERROR; /*LOG_DEBUG2("\n\DbSql::check_id_token-------user_id: %d\n\n",user_id);*/ if (CheckToken(user_id, token)) { return true; } else { error_code = USER_ACCESS_NOT_ENOUGH; send_error(error_code, socket); return false; } return false; } bool CheckUserIdAndToken(NetBase* value,const int socket) { if (!tools::check_userid_if_in_sql(value, socket)) { return false; } if (!tools::check_id_token(value, socket)) { return false; } return true; } } // namespace tools
24.533186
93
0.584994
f09924a80a0e716a64c7699e1ed64931e559b292
228
hpp
C++
Rimfrost/src/Rimfrost/EventSystem/EventObserver.hpp
Cgunnar/Rimfrost
924f8bab51e42e6b0790eb46cc1064b6920333cf
[ "MIT" ]
null
null
null
Rimfrost/src/Rimfrost/EventSystem/EventObserver.hpp
Cgunnar/Rimfrost
924f8bab51e42e6b0790eb46cc1064b6920333cf
[ "MIT" ]
null
null
null
Rimfrost/src/Rimfrost/EventSystem/EventObserver.hpp
Cgunnar/Rimfrost
924f8bab51e42e6b0790eb46cc1064b6920333cf
[ "MIT" ]
null
null
null
#pragma once #include "Rimfrost\EventSystem\Event.hpp" namespace Rimfrost { class EventObserver { public: EventObserver() = default; virtual ~EventObserver() = default; virtual void onEvent(const Event& e) = 0; }; }
15.2
43
0.710526
f09a60960c8157f4cce0993e7a96946606567a9c
129
cpp
C++
dependencies/physx-4.1/source/geomutils/src/pcm/GuPCMContactPlaneConvex.cpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
dependencies/physx-4.1/source/geomutils/src/pcm/GuPCMContactPlaneConvex.cpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
dependencies/physx-4.1/source/geomutils/src/pcm/GuPCMContactPlaneConvex.cpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
version https://git-lfs.github.com/spec/v1 oid sha256:943d9f005beb984bd9d29ed487bf6adf30882f9fa79903c6092cbd91ecee3e90 size 6381
32.25
75
0.883721
f09f35100976469d13d4837b3b002ae69f7a61da
1,060
cpp
C++
cpp/0_check/modernes_cpp_source/source/lambdaAndAuto.cpp
shadialameddin/numerical_tools_and_friends
cc9f10f58886ee286ed89080e38ebd303d3c72a5
[ "Unlicense" ]
null
null
null
cpp/0_check/modernes_cpp_source/source/lambdaAndAuto.cpp
shadialameddin/numerical_tools_and_friends
cc9f10f58886ee286ed89080e38ebd303d3c72a5
[ "Unlicense" ]
null
null
null
cpp/0_check/modernes_cpp_source/source/lambdaAndAuto.cpp
shadialameddin/numerical_tools_and_friends
cc9f10f58886ee286ed89080e38ebd303d3c72a5
[ "Unlicense" ]
null
null
null
// lambdaAndAuto.cpp #include <functional> #include <iostream> double divMe(double a, double b){ return double(a/b); } using namespace std::placeholders; int main(){ std::cout << std::endl; // invoking the function object directly std::cout << "1/2.0= " << [](int a, int b){ return divMe(a, b); }(1, 2.0) << std::endl; // placeholders for both arguments auto myDivBindPlaceholder= [](int a, int b){ return divMe(a, b); }; std::cout << "1/2.0= " << myDivBindPlaceholder(1, 2.0) << std::endl; // placeholders for both arguments, swap the arguments auto myDivBindPlaceholderSwap= [](int a, int b){ return divMe(b, a); }; std::cout << "1/2.0= " << myDivBindPlaceholderSwap(2.0, 1) << std::endl; // placeholder for the first argument auto myDivBind1St= [](int a){ return divMe(a, 2.0); }; std::cout<< "1/2.0= " << myDivBind1St(1) << std::endl; // placeholder for the second argument auto myDivBind2Nd= [](int b){ return divMe(1, b); }; std::cout << "1/2.0= " << myDivBind2Nd(2.0) << std::endl; std::cout << std::endl; }
28.648649
89
0.626415
f09f8aea9ce08a9f95211f0e97a1b16ed177fd9e
12,063
cc
C++
whisperstreamlib/mts/mts_types.cc
cpopescu/whispercast
dd4ee1d4fa2e3436fc2387240eb3f5622749d944
[ "BSD-3-Clause" ]
null
null
null
whisperstreamlib/mts/mts_types.cc
cpopescu/whispercast
dd4ee1d4fa2e3436fc2387240eb3f5622749d944
[ "BSD-3-Clause" ]
null
null
null
whisperstreamlib/mts/mts_types.cc
cpopescu/whispercast
dd4ee1d4fa2e3436fc2387240eb3f5622749d944
[ "BSD-3-Clause" ]
null
null
null
#include <whisperstreamlib/mts/mts_types.h> #define CHECK_MARKER(bit_array, type, bit_size, expected_value) {\ type marker = bit_array.Read<type>(bit_size);\ if ( marker != expected_value ) {\ LOG_ERROR << "Invalid marker: " << (int)marker\ << ", expected: " << (int)expected_value;\ }\ } #define CHECK_MARKER_BIT(bit_array) CHECK_MARKER(bit_array, uint8, 1, 0x01); #define CHECK_ZERO_BIT(bit_array) CHECK_MARKER(bit_array, uint8, 1, 0x00); namespace streaming { namespace mts { const char* TSScramblingName(TSScrambling scrambling) { switch ( scrambling ) { CONSIDER(NOT_SCRAMBLED); CONSIDER(SCRAMBLED_RESERVED); CONSIDER(SCRAMBLED_EVEN_KEY); CONSIDER(SCRAMBLED_ODD_KEY); } LOG_FATAL << "Illegal TSScrambling: " << (int)scrambling; return "Unknown"; } DecodeStatus TSPacket::Decode(io::MemoryStream* in) { if ( in->Size() < kTSPacketSize ) { return DECODE_NO_DATA; } if ( io::NumStreamer::PeekByte(in) != kTSSyncByte ) { LOG_ERROR << "Cannot decode TSPacket, sync byte: " << strutil::ToHex(kTSSyncByte) << " not found in stream: " << in->DumpContentInline(16); return DECODE_ERROR; } in->Skip(1); // skip the sync byte io::BitArray h; h.PutMS(*in, 3); transport_error_indicator_ = h.Read<bool>(1); payload_unit_start_indicator_ = h.Read<bool>(1); transport_priority_ = h.Read<bool>(1); pid_ = h.Read<uint16>(13); scrambling_ = (TSScrambling)h.Read<uint8>(2); bool has_adaptation = h.Read<bool>(1); bool has_payload = h.Read<bool>(1); continuity_counter_ = h.Read<uint8>(4); if ( has_adaptation ) { adaptation_field_ = new AdaptationField(); DecodeStatus status = adaptation_field_->Decode(in); if ( status != DECODE_SUCCESS ) { LOG_ERROR << "Cannot decode TSPacket, failed to decode AdaptationField" ", result: " << DecodeStatusName(status); return status; } } if ( has_payload ) { payload_ = new io::MemoryStream(); // the header, before adaptation field, has 4 bytes. payload_->AppendStream(in, kTSPacketSize - 4 - (has_adaptation ? adaptation_field_->Size() : 0)); } return DECODE_SUCCESS; } string TSPacket::ToString() const { ostringstream oss; oss << "TSPacket{" "transport_error_indicator_: " << strutil::BoolToString(transport_error_indicator_) << ", payload_unit_start_indicator_: " << strutil::BoolToString(payload_unit_start_indicator_) << ", transport_priority_: " << strutil::BoolToString(transport_priority_) << ", pid_: " << pid_ << ", scrambling_: " << TSScramblingName(scrambling_) << ", continuity_counter_: " << (uint32)continuity_counter_; if ( adaptation_field_ == NULL ) { oss << ", adaptation_field_: NULL"; } else { oss << ", adaptation_field: " << adaptation_field_->ToString(); } if ( payload_ == NULL ) { oss << ", payload_: NULL"; } else { oss << ", payload_: " << payload_->Size() << " bytes"; } oss << "}"; return oss.str(); } //////////////////////////////////////////////////////////////////////// DecodeStatus ProgramAssociationTable::Decode(io::MemoryStream* in) { if ( in->Size() < 8 ) { return DECODE_NO_DATA; } io::BitArray data; data.PutMS(*in, 8); table_id_ = data.Read<uint8>(8); CHECK_MARKER_BIT(data); // 1 bit: section_syntax_indicator, must be 1 CHECK_ZERO_BIT(data); data.Skip(2); // 2 reserved bits uint16 section_length = data.Read<uint16>(12); ts_id_ = data.Read<uint16>(16); data.Skip(2); // 2 reserved bits version_number_ = data.Read<uint8>(5); currently_applicable_ = data.Read<bool>(1); section_number_ = data.Read<uint8>(8); last_section_number_ = data.Read<uint8>(8); // section_length is the length of the remaining section data // (starting with ts_id_ and including the last CRC). // So we've already decoded 5 bytes from this length. if ( section_length < 9 ) { LOG_ERROR << "Cannot decode ProgramAssociationTable, invalid section_length" ": " << section_length << " is too small"; return DECODE_ERROR; } if ( in->Size() < section_length - 5 ) { return DECODE_NO_DATA; } if ( (section_length - 5) % 4 ) { LOG_ERROR << "Cannot decode ProgramAssociationTable, invalid section_length" ": " << section_length << ", after the header there are: " << section_length - 5 << " bytes, which is not a multiple of 4"; return DECODE_ERROR; } for ( uint32 i = 5; i < section_length - 4; i += 4 ) { uint16 program_number = io::NumStreamer::ReadUInt16(in, common::BIGENDIAN); io::BitArray a; a.PutMS(*in, 16); a.Skip(3); uint16 pid = a.Read<uint16>(13); if ( program_number == 0 ) { network_pid_[program_number] = pid; } else { program_map_pid_[program_number] = pid; } } crc_ = io::NumStreamer::ReadUInt32(in, common::BIGENDIAN); return DECODE_SUCCESS; } string ProgramAssociationTable::ToString() const { ostringstream oss; oss << "ProgramAssociationTable{table_id_: " << (uint32)table_id_ << ", ts_id_: " << ts_id_ << ", version_number_: " << version_number_ << ", currently_applicable_: " << strutil::BoolToString(currently_applicable_) << ", section_number_: " << section_number_ << ", last_section_number_: " << last_section_number_ << ", network_pid_: " << strutil::ToString(network_pid_) << ", program_map_pid_: " << strutil::ToString(program_map_pid_) << ", crc_: " << crc_ << "}"; return oss.str(); } //////////////////////////////////////////////////////////////////////// DecodeStatus PESPacket::Header::Decode(io::MemoryStream* in) { if ( in->Size() < 2 ) { return DECODE_NO_DATA; } io::BitArray h; h.PutMS(*in, 1); uint8 mark = h.Read<uint8>(2); scrambling_ = (TSScrambling)h.Read<uint8>(2); is_priority_ = h.Read<bool>(1); is_data_aligned_ = h.Read<bool>(1); is_copyright_ = h.Read<bool>(1); is_original_ = h.Read<bool>(1); bool has_PTS = h.Read<bool>(1); bool has_DTS = h.Read<bool>(1); bool has_ESCR = h.Read<bool>(1); bool has_ES_rate = h.Read<bool>(1); bool has_DSM_trick_mode = h.Read<bool>(1); bool has_additional_copy_info = h.Read<bool>(1); bool has_CRC = h.Read<bool>(1); bool has_extension = h.Read<bool>(1); uint8 size = io::NumStreamer::ReadByte(in); uint32 start_size = in->Size(); if ( mark != 0b01 ) { LOG_ERROR << "Invalid marker before PES: " << strutil::ToBinary(mark); return DECODE_ERROR; } if ( has_PTS && !has_DTS ) { io::BitArray data; data.PutMS(*in, 5); pts_ = 0; // Note: 33 bit encoded! CHECK_MARKER(data, uint8, 4, 0b0010); pts_ = pts_ << 3 | data.Read<uint8>(3); CHECK_MARKER_BIT(data); pts_ = pts_ << 15 | data.Read<uint16>(15); CHECK_MARKER_BIT(data); pts_ = pts_ << 15 | data.Read<uint16>(15); CHECK_MARKER_BIT(data); } else if ( has_PTS && has_DTS ) { io::BitArray data; data.PutMS(*in, 10); pts_ = 0; // Note: 33 bit encoded! dts_ = 0; // Note: 33 bit encoded! CHECK_MARKER(data, uint8, 4, 0b0011); pts_ = pts_ << 3 | data.Read<uint8>(3); CHECK_MARKER_BIT(data); pts_ = pts_ << 15 | data.Read<uint16>(15); CHECK_MARKER_BIT(data); pts_ = pts_ << 15 | data.Read<uint16>(15); CHECK_MARKER_BIT(data); CHECK_MARKER(data, uint8, 4, 0b0001); dts_ = dts_ << 3 | data.Read<uint8>(3); CHECK_MARKER_BIT(data); dts_ = dts_ << 15 | data.Read<uint16>(15); CHECK_MARKER_BIT(data); dts_ = dts_ << 15 | data.Read<uint16>(15); CHECK_MARKER_BIT(data); } else if ( !has_PTS && has_DTS ) { LOG_ERROR << "Found Decoding Timestamp without Presentation Timestamp"; return DECODE_ERROR; } if ( has_ESCR ) { io::BitArray data; data.PutMS(*in, 6); escr_base_ = 0; data.Skip(2); // reserved escr_base_ = escr_base_ << 3 | data.Read<uint8>(3); CHECK_MARKER_BIT(data); escr_base_ = escr_base_ << 15 | data.Read<uint16>(15); CHECK_MARKER_BIT(data); escr_base_ = escr_base_ << 15 | data.Read<uint16>(15); CHECK_MARKER_BIT(data); escr_extension_ = data.Read<uint16>(9); CHECK_MARKER_BIT(data); } if ( has_ES_rate ) { io::BitArray data; data.PutMS(*in, 3); CHECK_MARKER_BIT(data); es_rate_ = data.Read<uint32>(22); CHECK_MARKER_BIT(data); } if ( has_DSM_trick_mode ) { // trick mode is encoded on 8 bits. // TODO(cosmin): decode DSM trick mode trick_mode_ = io::NumStreamer::ReadByte(in); } if ( has_additional_copy_info ) { // additional copy info is encoded on 8 bits. Ignore it for now. // TODO(cosmin): decode additional copy info additional_copy_info_ = io::NumStreamer::ReadByte(in); } if ( has_CRC ) { previous_pes_packet_crc_ = io::NumStreamer::ReadUInt16(in, common::BIGENDIAN); } if ( has_extension ) { // TODO(cosmin): decode extension } // skip the rest of the header (extension + stuffing bytes) uint32 decoded_size = start_size - in->Size(); in->Skip(size - decoded_size); return DECODE_SUCCESS; } string PESPacket::Header::ToString() const { ostringstream oss; oss << "{scrambling_: " << TSScramblingName(scrambling_) << ", is_priority_: " << strutil::BoolToString(is_priority_) << ", is_data_aligned_: " << strutil::BoolToString(is_data_aligned_) << ", is_copyright_: " << strutil::BoolToString(is_copyright_) << ", is_original_: " << strutil::BoolToString(is_original_) << ", pts_: " << pts_ << ", dts_: " << dts_ << ", escr_base_: " << escr_base_ << ", escr_extension_: " << escr_extension_ << ", es_rate_: " << es_rate_ << ", trick_mode_: " << strutil::ToHex(trick_mode_) << ", add_info: " << strutil::ToHex(additional_copy_info_) << ", prev_crc: " << previous_pes_packet_crc_ << "}"; return oss.str(); } DecodeStatus PESPacket::Decode(io::MemoryStream* in) { if ( in->Size() < 6 ) { return DECODE_NO_DATA; } in->MarkerSet(); uint32 mark = io::NumStreamer::ReadUInt24(in, common::BIGENDIAN); if ( mark != kPESMarker ) { in->MarkerRestore(); LOG_ERROR << "PES Marker not found." " Expected: " << strutil::ToHex(kPESMarker, 3) << ", found: " << strutil::ToHex(mark, 3) << ", in stream: " << in->DumpContentInline(16); return DECODE_ERROR; } uint8 stream_id = io::NumStreamer::ReadByte(in); uint16 size = io::NumStreamer::ReadUInt16(in, common::BIGENDIAN); if ( in->Size() < size ) { in->MarkerRestore(); return DECODE_NO_DATA; } if ( stream_id == kPESStreamIdPadding ) { in->Skip(size); in->MarkerClear(); return DECODE_SUCCESS; } if ( stream_id == kPESStreamIdProgramMap || stream_id == kPESStreamIdProgramDirectory || stream_id == kPESStreamIdECM || stream_id == kPESStreamIdEMM || stream_id == kPESStreamIdPrivate2 ) { // decode body (no header) data_.AppendStream(in, size); in->MarkerClear(); return DECODE_SUCCESS; } if ( (stream_id >= kPESStreamIdAudioStart && stream_id <= kPESStreamIdAudioEnd) || (stream_id >= kPESStreamIdVideoStart && stream_id <= kPESStreamIdVideoEnd) ) { // decode header const uint32 start_size = in->Size(); DecodeStatus status = header_.Decode(in); if ( status != DECODE_SUCCESS ) { in->MarkerRestore(); return status; } const uint32 header_encoding_size = start_size - in->Size(); CHECK_GE(size, header_encoding_size); // decode body data_.AppendStream(in, size - header_encoding_size); in->MarkerClear(); return DECODE_SUCCESS; } LOG_ERROR << "Unknown stream ID: " << strutil::StringPrintf("%02x", stream_id); in->Skip(size); in->MarkerClear(); return DECODE_SUCCESS; } string PESPacket::ToString() const { ostringstream oss; oss << "PESPacket{stream_id_: " << PESStreamIdName(stream_id_) << ", header_: " << header_.ToString() << ", data_: #" << data_.Size() << " bytes}"; return oss.str(); } } }
34.269886
96
0.631186
f0a3986dff053570d226301f52321899ed5ba9bd
8,948
cpp
C++
example-ExtendsSprite/src/DocumentRoot.cpp
selflash/ofxSelflash
087a263b2d4de970edd75ecab2c2a48b7b58e62d
[ "MIT" ]
19
2015-05-14T09:57:38.000Z
2022-01-10T23:32:28.000Z
example-ExtendsSprite/src/DocumentRoot.cpp
selflash/ofxSelflash
087a263b2d4de970edd75ecab2c2a48b7b58e62d
[ "MIT" ]
3
2015-08-04T09:07:26.000Z
2018-01-18T07:14:35.000Z
example-ExtendsSprite/src/DocumentRoot.cpp
selflash/ofxSelflash
087a263b2d4de970edd75ecab2c2a48b7b58e62d
[ "MIT" ]
1
2015-08-04T09:05:22.000Z
2015-08-04T09:05:22.000Z
#include "DocumentRoot.h" //static const double pi = std::acos(-1.0); // お手軽に π を得る。 //============================================================== // Constructor / Destructor //============================================================== //-------------------------------------------------------------- // //-------------------------------------------------------------- DocumentRoot::DocumentRoot() { cout << "[DocumentRoot]DocumentRoot()" << endl; _target = this; name("DocumentRoot"); useHandCursor(true); } //-------------------------------------------------------------- // //-------------------------------------------------------------- DocumentRoot::~DocumentRoot() { cout << "[DocumentRoot]~DocumentRoot()" << endl; } //============================================================== // Setup / Update / Draw //============================================================== //-------------------------------------------------------------- // //-------------------------------------------------------------- void DocumentRoot::_setup() { cout << "[DocumentRoot]_setup()" << endl; //-------------------------------------- //ステージに追加された時にキーボードイベントを監視する addEventListener(flEvent::ADDED_TO_STAGE, this, &DocumentRoot::_eventHandler); addEventListener(flMouseEvent::MOUSE_DOWN, this, &DocumentRoot::_mouseEventHandler); addEventListener(flMouseEvent::MOUSE_UP, this, &DocumentRoot::_mouseEventHandler); flGraphics* g; g = graphics(); g->clear(); g->beginFill(0x888888, 0.1); g->drawRect(0, 0, ofGetWidth(), ofGetHeight()); g->endFill(); //----------------------------------- //----------------------------------- //copy from examples/graphics/graphicsExample //graphicsExampleのコードを書き写し counter = 0; ofSetCircleResolution(50); ofBackground(255,255,255); bSmooth = false; // ofSetWindowTitle("graphics example"); ofSetFrameRate(60); // if vertical sync is off, we can go a bit fast... this caps the framerate at 60fps. //----------------------------------- } //-------------------------------------------------------------- void DocumentRoot::_update() { //-------------------------------------- if(!isMouseDown()){ _forceX *= 0.95; _forceY *= 0.95; float temp; temp = x(); temp += _forceX; x(temp); temp = y(); temp += _forceY; y(temp); } else { _preX = x(); _preY = y(); } //-------------------------------------- //-------------------------------------- flGraphics* g; g = graphics(); g->clear(); //背景色 g->beginFill(0x888888, 0.1); g->drawRect(0, 0, ofGetWidth(), ofGetHeight()); g->endFill(); //透明のヒットエリア g->beginFill(0x0000cc, 0); g->drawRect(-x(), -y(), ofGetWidth(), ofGetHeight()); g->endFill(); //-------------------------------------- //----------------------------------- //copy from examples/graphics/graphicsExample //graphicsExampleのコードを書き写し counter = counter + 0.033f; //----------------------------------- } //-------------------------------------------------------------- void DocumentRoot::_draw() { //----------------------------------- //copy from examples/graphics/graphicsExample //graphicsExampleのコードを書き写し //--------------------------- circles //let's draw a circle: ofSetColor(255,130,0); float radius = 50 + 10 * sin(counter); ofFill(); // draw "filled shapes" ofDrawCircle(100,400,radius); // now just an outline ofNoFill(); ofSetHexColor(0xCCCCCC); ofDrawCircle(100,400,80); // use the bitMap type // note, this can be slow on some graphics cards // because it is using glDrawPixels which varies in // speed from system to system. try using ofTrueTypeFont // if this bitMap type slows you down. ofSetHexColor(0x000000); ofDrawBitmapString("circle", 75,500); //--------------------------- rectangles ofFill(); for (int i = 0; i < 200; i++){ ofSetColor((int)ofRandom(0,255),(int)ofRandom(0,255),(int)ofRandom(0,255)); ofDrawRectangle(ofRandom(250,350),ofRandom(350,450),ofRandom(10,20),ofRandom(10,20)); } ofSetHexColor(0x000000); ofDrawBitmapString("rectangles", 275,500); //--------------------------- transparency ofSetHexColor(0x00FF33); ofDrawRectangle(400,350,100,100); // alpha is usually turned off - for speed puposes. let's turn it on! ofEnableAlphaBlending(); ofSetColor(255,0,0,127); // red, 50% transparent ofDrawRectangle(450,430,100,33); ofSetColor(255,0,0,(int)(counter * 10.0f) % 255); // red, variable transparent ofDrawRectangle(450,370,100,33); ofDisableAlphaBlending(); ofSetHexColor(0x000000); ofDrawBitmapString("transparency", 410,500); //--------------------------- lines // a bunch of red lines, make them smooth if the flag is set ofSetHexColor(0xFF0000); for (int i = 0; i < 20; i++){ ofDrawLine(600,300 + (i*5),800, 250 + (i*10)); } ofSetHexColor(0x000000); ofDrawBitmapString("lines\npress 's' to toggle smoothness", 600,500); //----------------------------------- } //============================================================== // Public Method //============================================================== //============================================================== // Protected / Private Method //============================================================== //============================================================== // Private Event Handler //============================================================== //-------------------------------------------------------------- void DocumentRoot::_eventHandler(flEvent& event) { cout << "[DocumentRoot]_eventHandler(" + event.type() + ")"; if(event.type() == flEvent::ADDED_TO_STAGE) { removeEventListener(flEvent::ADDED_TO_STAGE, this, &DocumentRoot::_eventHandler); stage()->addEventListener(flKeyboardEvent::KEY_PRESS, this, &DocumentRoot::_keyboardEventHandler); stage()->addEventListener(flKeyboardEvent::KEY_RELEASE, this, &DocumentRoot::_keyboardEventHandler); } } //-------------------------------------------------------------- void DocumentRoot::_keyboardEventHandler(flEvent& event) { // cout << "[DocumentRoot]_keyboardEventHandler(" + event.type() + ")"; flKeyboardEvent* keyboardEvent = dynamic_cast<flKeyboardEvent*>(&event); int key = keyboardEvent->keyCode(); if(event.type() == flKeyboardEvent::KEY_PRESS) { //----------------------------------- //copy from examples/graphics/graphicsExample //graphicsExampleのコードを書き写し if (key == 's') { bSmooth = !bSmooth; if (bSmooth){ ofEnableAntiAliasing(); }else{ ofDisableAntiAliasing(); } } //----------------------------------- } if(event.type() == flKeyboardEvent::KEY_RELEASE) { } } //-------------------------------------------------------------- void DocumentRoot::_moveEventHandler(flEvent& event) { //cout << "[DocumentRoot]_moveEventHandler(" << event.type() << ")" << endl; // cout << "mouse is moving" << endl; } //-------------------------------------------------------------- void DocumentRoot::_mouseEventHandler(flEvent& event) { // cout << "[DocumentRoot]_mouseEventHandler(" << event.type() << ")" << endl; // cout << "[PrentBox]this = " << this << endl; // cout << "[ParetBox]currentTarget = " << event.currentTarget() << endl; // cout << "[ParetBox]target = " << event.target() << endl; if(event.type() == flMouseEvent::MOUSE_OVER) { if(event.target() == this) { } } if(event.type() == flMouseEvent::MOUSE_OUT) { if(event.target() == this) { } } if(event.type() == flMouseEvent::MOUSE_DOWN) { if(event.target() == this) { startDrag(); stage()->addEventListener(flMouseEvent::MOUSE_UP, this, &DocumentRoot::_mouseEventHandler); stage()->addEventListener(flMouseEvent::MOUSE_MOVE, this, &DocumentRoot::_moveEventHandler); } } if(event.type() == flMouseEvent::MOUSE_UP) { if(event.currentTarget() == stage()) { stopDrag(); stage()->removeEventListener(flMouseEvent::MOUSE_UP, this, &DocumentRoot::_mouseEventHandler); stage()->removeEventListener(flMouseEvent::MOUSE_MOVE, this, &DocumentRoot::_moveEventHandler); _forceX = (x() - _preX) * 0.5; _forceY = (y() - _preY) * 0.5; } } }
34.022814
109
0.456638
f0a6282ef467cbb597f6376aa9e36c7f9759eb46
3,508
cpp
C++
src/SQLite.cpp
nianfh/beebox
a2c68847a442f1d4bcb80d9eefb7c0c7682f748a
[ "MIT" ]
1
2018-07-11T03:47:41.000Z
2018-07-11T03:47:41.000Z
src/SQLite.cpp
nianfh/beebox
a2c68847a442f1d4bcb80d9eefb7c0c7682f748a
[ "MIT" ]
null
null
null
src/SQLite.cpp
nianfh/beebox
a2c68847a442f1d4bcb80d9eefb7c0c7682f748a
[ "MIT" ]
null
null
null
#include "SQLite.h" #include <sqlite3/sqlite3.h> #include <stdio.h> #include <vector> namespace beebox { CSQLite::CSQLite() { m_db = NULL; } CSQLite::~CSQLite() { close(); } bool CSQLite::open(string filePath) { if (m_db) { close(); } return sqlite3_open_v2(filePath.c_str(), &m_db, SQLITE_OPEN_READWRITE, NULL) == SQLITE_OK ? true : false; } void CSQLite::close() { sqlite3_close(m_db); } bool CSQLite::create(string filePath) { return sqlite3_open_v2(filePath.c_str(), &m_db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL) == SQLITE_OK ? true : false; } bool CSQLite::select(string sql, string& recordInJson) { sqlite3_stmt* res = NULL; const char* unused = NULL; recordInJson.clear(); int rc = sqlite3_prepare_v2(m_db, sql.c_str(), sql.size(), &res, &unused); if (rc != SQLITE_OK) { return false; } int columnCount = sqlite3_column_count(res); vector<string> fieldNameList; for (int i=0; i<columnCount; ++i) { const char* name = sqlite3_column_name(res, i); string _name = "\"" ; _name += name; _name += "\":"; fieldNameList.push_back(_name); } recordInJson += "["; rc = sqlite3_step(res); while(rc == SQLITE_ROW) { for(int i=0; i<columnCount; i++) { if (i == 0) { recordInJson += "{"; } string val = getValue(res, i); recordInJson += fieldNameList[i]; recordInJson += val.empty() ? "null" : val; if (i < columnCount - 1) { recordInJson += ","; } else { recordInJson += "}"; } } rc = sqlite3_step(res); if (rc == SQLITE_ROW) { recordInJson += ","; } } recordInJson += "]"; sqlite3_finalize(res); if (recordInJson.size() < 3) { recordInJson.clear(); } return true; } bool CSQLite::execute(string sql) { printf("########## sql: %s\n", sql.c_str()); char* errMsg = NULL; int rc = sqlite3_exec(m_db, sql.c_str(), 0, 0, &errMsg); if (rc != SQLITE_OK) { printf("SQL error:%s\n", errMsg); return false; } else { printf("SQL Execute OK!\n"); } return true; } string CSQLite::getError() { return sqlite3_errmsg(m_db); } string CSQLite::getValue(sqlite3_stmt* res, int columnIndex) { const unsigned char* pStr = NULL; int type = sqlite3_column_type(res, columnIndex); string out; char buffer[256] = {0}; switch(type) { case SQLITE_INTEGER: sprintf(buffer, "%d", sqlite3_column_int(res, columnIndex)); out = buffer; break; case SQLITE_FLOAT: sprintf(buffer, "%f", sqlite3_column_double(res, columnIndex)); out = buffer; break; case SQLITE3_TEXT: pStr = sqlite3_column_text(res, columnIndex); if (pStr) { out = "\""; out += (char*)pStr; out += "\""; } break; case SQLITE_BLOB: //sqlite3_column_bytes(res, 0); //(void*) sqlite3_column_blob(res, 0); out = "blob"; break; case SQLITE_NULL: out = ""; break; default: out = ""; break; }; return out; } } // namespace beebox
19.381215
80
0.517104
f0a6567ff64ee8caa5ac52d811f47b9e0bea8794
1,246
cpp
C++
Dynamic Programming/Coin Change/SolutionbyPooja.cpp
Mdanish777/Programmers-Community
b5ca9582fc1cd4337baa7077ff62130a1052583f
[ "MIT" ]
261
2019-09-30T19:47:29.000Z
2022-03-29T18:20:07.000Z
Dynamic Programming/Coin Change/SolutionbyPooja.cpp
Mdanish777/Programmers-Community
b5ca9582fc1cd4337baa7077ff62130a1052583f
[ "MIT" ]
647
2019-10-01T16:51:29.000Z
2021-12-16T20:39:44.000Z
Dynamic Programming/Coin Change/SolutionbyPooja.cpp
Mdanish777/Programmers-Community
b5ca9582fc1cd4337baa7077ff62130a1052583f
[ "MIT" ]
383
2019-09-30T19:32:07.000Z
2022-03-24T16:18:26.000Z
/* Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, How many ways can we make the change? The order of coins doesn’t matter. input: N = 4 S = [ 1, 2, 3 ] Output = 4 There are four solutions: [ 1, 1, 1, 1 ], [ 1, 1, 2 ], [ 2, 2 ], [ 1, 3 ]. */ #include <iostream> using namespace std; int coin_change(int* arr, int N, int n) { int t[n + 1][N + 1]; for (int i = 0; i < N + 1; i++) t[0][i] = 0; for (int i = 0; i < n + 1; i++) t[i][0] = 1; for (int i = 1; i < n + 1; i++) { for (int j = 1; j < N + 1; j++) { if (arr[i - 1] <= j) t[i][j] = t[i - 1][j] + t[i][j - arr[i - 1]]; else t[i][j] = t[i - 1][j]; } } return t[n][N]; } int main() { int size, N; cout << "Array Size "; cin >> size; int* arr = new int[size]; cout << "\nEnter coins "; for (int i = 0; i < size; i++) cin >> *(arr + i); cout << "Enter sum "; cin >> N; cout << "\nNo. of ways : " << coin_change(arr, N, size); }
21.859649
161
0.399679
f0ad631f8a4cc60d71b0bedeeead556dbc107356
542
cpp
C++
8 Hashing/03.hard/10.indexpairs.cpp
markpairdha/DataStructures
cf002e5a982543bd91e4a06ab22e76c40095786e
[ "MIT" ]
null
null
null
8 Hashing/03.hard/10.indexpairs.cpp
markpairdha/DataStructures
cf002e5a982543bd91e4a06ab22e76c40095786e
[ "MIT" ]
null
null
null
8 Hashing/03.hard/10.indexpairs.cpp
markpairdha/DataStructures
cf002e5a982543bd91e4a06ab22e76c40095786e
[ "MIT" ]
null
null
null
#include<iostream> #include<bits/stdc++.h> #include<unordered_map> using namespace std; int countindexpairs(int arr[],int n) { unordered_map<int,int> mp; for(int i=0;i<n;i++) mp[arr[i]]++; int ans=0; unordered_map<int,int> ::iterator it; for(it = mp.begin();it != mp.end();it++) { int freq = it->second; ans += (freq*(freq-1))/2; } return ans; } int main() { int arr[] = {1,1,1,1,1,2,2,2,2}; int size = sizeof(arr)/sizeof(arr[0]); cout << countindexpairs(arr,size) << endl; return 0; }
20.074074
44
0.577491
f0ae115e5186c11bf9fd48e719659cc0cace4643
8,946
cpp
C++
Source/Gui3D-master/examples/build/EnvironmentDemo.cpp
shanefarris/CoreGameEngine
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
[ "MIT" ]
3
2019-04-12T15:22:53.000Z
2022-01-05T02:59:56.000Z
Source/Gui3D-master/examples/build/EnvironmentDemo.cpp
shanefarris/CoreGameEngine
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
[ "MIT" ]
null
null
null
Source/Gui3D-master/examples/build/EnvironmentDemo.cpp
shanefarris/CoreGameEngine
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
[ "MIT" ]
2
2019-04-10T22:46:21.000Z
2020-05-27T16:21:37.000Z
#include <iostream> #include <sstream> #include <vector> #include <OGRE/Ogre.h> #include <OIS/OIS.h> #include "Gui3D.h" #include "Gui3DPanel.h" #include "MyEnvironmentDemoPanelColors.h" typedef struct PanelAndDirection { Gui3D::Panel* panel; Ogre::Vector3 cameraDirection; int yaw; } PanelAndDirection; class EnvironmentDemo : public Ogre::FrameListener, public OIS::KeyListener, public OIS::MouseListener { public: // Gui3D main object Gui3D::Gui3D* mGui3D; // Keep track of some captions to modify their contents on callback Gui3D::Caption* captionButton; Gui3D::Caption* captionChecked; Gui3D::Caption* captionCombobox; Ogre::SceneNode* tvNode; Ogre::Vector3 originalTvNodePos; Ogre::Entity* entSinbad; Ogre::AnimationState* a, *a2; Gui3D::Panel* mPanel; MyEnvironmentDemoPanelColors mMyEnvironmentDemoPanelColors; EnvironmentDemo() { originalTvNodePos = Ogre::Vector3(0, 1, 10); _makeOgre(); _makeOIS(); _makeScene(); mGui3D = new Gui3D::Gui3D(&mMyEnvironmentDemoPanelColors); mGui3D->createScreen(mViewport, "environmentDemo", "mainScreen"); mPanel = _createPanel(Ogre::Vector3(0, 5.3, -2.5), 180); mCamera->setPosition(0, 6.f, -8); mCamera->setDirection(Ogre::Vector3(0, 0, 1)); } Gui3D::Panel* _createPanel(Ogre::Vector3 pos, int yaw) { Gui3D::Panel* panel = new Gui3D::Panel( mGui3D, mSceneMgr, Ogre::Vector2(400, 400), 15, "environmentDemo", "kikoo"); panel->mNode->setPosition(pos); panel->mNode->yaw(Ogre::Degree(yaw)); panel->makeCaption(10, 10, 380, 30, "Move the TV please...", Gorilla::TextAlign_Centre); panel->makeCaption(10, 100, 90, 100, "Left", Gorilla::TextAlign_Centre, Gorilla::VerticalAlign_Middle); panel->makeCaption(310, 100, 90, 100, "Right", Gorilla::TextAlign_Centre, Gorilla::VerticalAlign_Middle); Gui3D::ScrollBar* s = panel->makeScrollBar(100, 100, 200, 100, 0, 15); s->setValueChangedCallback(this, &EnvironmentDemo::decalValueChanged); s->setStep(0.1); s->setDisplayedPrecision(0, false); s->setCallCallbackOnSelectingValue(true); s->setDisplayValue(false); return panel; } bool decalValueChanged(Gui3D::PanelElement* e) { Ogre::Vector3 pos = originalTvNodePos; pos.x -= ((Gui3D::ScrollBar*)e)->getValue(); tvNode->setPosition(pos); return true; } ~EnvironmentDemo() { delete mGui3D; std::ostringstream s; s << "\n** Average FPS (with FSAA to 1) is " << mWindow->getAverageFPS() << "\n\n"; Ogre::LogManager::getSingleton().logMessage(s.str()); delete mRoot; } bool frameStarted(const Ogre::FrameEvent& evt) { if (mWindow->isClosed()) return false; Ogre::Vector3 trans(0,0,0); if (mKeyboard->isKeyDown(OIS::KC_W)) trans.z = -1; else if (mKeyboard->isKeyDown(OIS::KC_S)) trans.z = 1; if (mKeyboard->isKeyDown(OIS::KC_A)) trans.x = -1; else if (mKeyboard->isKeyDown(OIS::KC_D)) trans.x = 1; if (trans.isZeroLength() == false) { Ogre::Vector3 pos = mCamera->getPosition(); pos += mCamera->getOrientation() * (trans * 10.0f) * evt.timeSinceLastFrame; pos.y = 6.0f; mCamera->setPosition(pos); } a->addTime(evt.timeSinceLastFrame); a2->addTime(evt.timeSinceLastFrame); mPanel->injectMouseMoved(mCamera->getCameraToViewportRay(0.5f, 0.5f)); mPanel->injectTime(evt.timeSinceLastFrame); mMouse->capture(); // Quit on ESCAPE Keyboard mKeyboard->capture(); if (mKeyboard->isKeyDown(OIS::KC_ESCAPE)) return false; return true; } bool keyPressed(const OIS::KeyEvent &e) { mPanel->injectKeyPressed(e); return true; } bool keyReleased(const OIS::KeyEvent &e) { mPanel->injectKeyReleased(e); return true; } bool mousePressed(const OIS::MouseEvent &evt, OIS::MouseButtonID id) { mPanel->injectMousePressed(evt, id); return true; } bool mouseReleased(const OIS::MouseEvent &evt, OIS::MouseButtonID id) { mPanel->injectMouseReleased(evt, id); return true; } bool mouseMoved(const OIS::MouseEvent &arg) { Ogre::Real pitch = Ogre::Real(arg.state.Y.rel) * -0.005f; Ogre::Real yaw = Ogre::Real(arg.state.X.rel) * -0.005f; mCamera->pitch(Ogre::Radian(pitch)); mCamera->yaw(Ogre::Radian(yaw)); return true; } void _makeOgre() { mRoot = new Ogre::Root("", ""); mRoot->addFrameListener(this); #if OGRE_PLATFORM == OGRE_PLATFORM_LINUX mRoot->loadPlugin(OGRE_RENDERER); #else #if 1 #ifdef _DEBUG mRoot->loadPlugin("RenderSystem_Direct3D9_d"); #else mRoot->loadPlugin("RenderSystem_Direct3D9"); #endif #else #ifdef _DEBUG mRoot->loadPlugin("RenderSystem_GL_d.dll"); #else mRoot->loadPlugin("RenderSystem_GL.dll"); #endif #endif #endif mRoot->setRenderSystem(mRoot->getAvailableRenderers()[0]); Ogre::ResourceGroupManager* rgm = Ogre::ResourceGroupManager::getSingletonPtr(); rgm->addResourceLocation(".", "FileSystem"); rgm->addResourceLocation("sinbad.zip", "Zip"); mRoot->initialise(false); Ogre::NameValuePairList misc; misc["FSAA"] = "1"; mWindow = mRoot->createRenderWindow("Gorilla", 800, 600, false, &misc); mSceneMgr = mRoot->createSceneManager(Ogre::ST_EXTERIOR_CLOSE); mCamera = mSceneMgr->createCamera("Camera"); mViewport = mWindow->addViewport(mCamera); mViewport->setBackgroundColour(Ogre::ColourValue(0./255, 80./255, 160./255, .5f)); rgm->initialiseAllResourceGroups(); tvNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); tvNode->setPosition(originalTvNodePos); tvNode->setScale(2, 2, 2); Ogre::Entity* entTV = mSceneMgr->createEntity("TV.mesh"); tvNode->attachObject(entTV); Ogre::SceneNode* sinbadNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); sinbadNode->setPosition(0, 2, -2.2); sinbadNode->setScale(0.4, 0.4, 0.4); sinbadNode->yaw(Ogre::Degree(180)); entSinbad = mSceneMgr->createEntity("sinbad.mesh"); sinbadNode->attachObject(entSinbad); entSinbad->getSkeleton()->setBlendMode(Ogre::ANIMBLEND_CUMULATIVE); a = entSinbad->getAnimationState("IdleBase"); a->setEnabled(true); a->setLoop(true); a2 = entSinbad->getAnimationState("IdleTop"); a2->setEnabled(true); a2->setLoop(true); //mCameraNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); //mCameraNode->attachObject(mCamera); mCamera->setNearClipDistance(0.05f); mCamera->setFarClipDistance(1000); } void _makeOIS() { // Initialise OIS OIS::ParamList pl; size_t windowHnd = 0; std::ostringstream windowHndStr; mWindow->getCustomAttribute("WINDOW", &windowHnd); windowHndStr << windowHnd; pl.insert(std::make_pair(Ogre::String("WINDOW"), windowHndStr.str())); mInputManager = OIS::InputManager::createInputSystem(pl); mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject(OIS::OISKeyboard, true)); mKeyboard->setEventCallback(this); mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject(OIS::OISMouse, true)); mMouse->setEventCallback(this); mMouse->getMouseState().width = mViewport->getActualWidth(); mMouse->getMouseState().height = mViewport->getActualHeight(); } void _makeScene() { Ogre::Plane plane(Ogre::Vector3::UNIT_Y, 0); Ogre::MeshManager::getSingleton().createPlane("ground", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, plane, 1500, 1500, 20, 20, true, 1, 150, 150, Ogre::Vector3::UNIT_Z); Ogre::Entity* entGround = mSceneMgr->createEntity("GroundEntity", "ground"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(entGround); entGround->setMaterialName("Gui3DExample/Ground"); entGround->setCastShadows(false); } Ogre::Root* mRoot; Ogre::RenderWindow* mWindow; Ogre::Viewport* mViewport; Ogre::SceneManager* mSceneMgr; Ogre::Camera* mCamera; OIS::InputManager* mInputManager; OIS::Keyboard* mKeyboard; OIS::Mouse* mMouse; }; int main() { EnvironmentDemo* demo = new EnvironmentDemo(); demo->mRoot->startRendering(); delete demo; return 0; }
30.848276
120
0.625755
f0ae79a162cee6343a9cc5bdc989da19c7e0c60c
1,923
cpp
C++
scripts/project_euler/euler_problem_37.cpp
cannontwo/cannon
4be79f3a6200d1a3cd26c28c8f2250dbdf08f267
[ "MIT" ]
null
null
null
scripts/project_euler/euler_problem_37.cpp
cannontwo/cannon
4be79f3a6200d1a3cd26c28c8f2250dbdf08f267
[ "MIT" ]
46
2021-01-12T23:03:52.000Z
2021-10-01T17:29:01.000Z
scripts/project_euler/euler_problem_37.cpp
cannontwo/cannon
4be79f3a6200d1a3cd26c28c8f2250dbdf08f267
[ "MIT" ]
null
null
null
#include <iostream> #include <cassert> #include <cmath> #include <algorithm> #include <cannon/log/registry.hpp> #include <cannon/math/primes.hpp> #include <cannon/math/digits.hpp> using namespace cannon::log; using namespace cannon::math; /*! * The number 3797 has an interesting property. Being prime itself, it is * possible to continuously remove digits from left o right, and remain prime at * each stage: 3797, 797, 97, and 7. Similarly, we can work from right to left: * 3797, 379, 37, and 3. * * Find the sum of the only eleven primes that are both truncatable from left to * right and right to left. * * Note: 2, 3, 5, and 7 are not considered to be truncatable primes. */ bool is_right_truncatable(unsigned int x) { if (!is_prime(x)) return false; while (x != 0) { if (!is_prime(x)) return false; x /= 10; } return true; } bool is_left_truncatable(unsigned int x) { while (x != 0) { if (!is_prime(x)) return false; unsigned int first_digit_pow = std::floor(std::log10(x)); unsigned int first_digit = x / std::pow(10, first_digit_pow); x -= first_digit * std::pow(10, first_digit_pow); } return true; } bool is_truncatable(unsigned int x) { return is_left_truncatable(x) && is_right_truncatable(x); } unsigned int compute_truncatable_primes_sum() { unsigned int sum = 0; unsigned int num_truncatable = 0; unsigned int upper = 1000; auto primes = get_primes_up_to(upper); // Skipping 2-7 unsigned int i = 4; while (num_truncatable < 11) { for (; i < primes.size(); ++i) { if (is_truncatable(primes[i])) { log_info("Found truncatable prime:", primes[i]); sum += primes[i]; ++num_truncatable; } } upper *= 2; primes = get_primes_up_to(upper); } return sum; } int main(int argc, char** argv) { std::cout << compute_truncatable_primes_sum() << std::endl; }
22.360465
80
0.656786
f0af743f6522a91956e542645b9de037882c3874
1,901
cpp
C++
src/main.cpp
vieiraa/ray_tracer
75665fd5b15f486ad52f3c5b61521fb394d40fe1
[ "MIT" ]
null
null
null
src/main.cpp
vieiraa/ray_tracer
75665fd5b15f486ad52f3c5b61521fb394d40fe1
[ "MIT" ]
null
null
null
src/main.cpp
vieiraa/ray_tracer
75665fd5b15f486ad52f3c5b61521fb394d40fe1
[ "MIT" ]
null
null
null
#include <chrono> #include <glm/geometric.hpp> #include "camera.h" #include "orthographic_camera.h" #include "pinhole_camera.h" #include "scene.h" #include "buffer.h" #include "raytracer.h" #include "path_tracer.h" #include "bvh.h" int main() { unsigned int width = 256; unsigned int height = 256; PinholeCamera camera(-2.5f, 2.5f, -2.5f, 2.5f, 5.0f, glm::ivec2(width, height), glm::vec3(0.0f, 0.0f, 6.0f), // position glm::vec3(0.0f, -1.0f, 0.0f), // up glm::vec3(0.0f, 0.0f, -1.0f)); // look at Scene scene; scene.load(); //Primitives number std::cout << "\nNumber of primitives: " << scene.primitives_.size(); // acceleration structure construction time auto start1 = std::chrono::high_resolution_clock::now(); scene.acc_ = std::make_unique<BVH_SAH>(scene.primitives_); auto duration1 = std::chrono:: duration_cast<std::chrono::seconds>(std::chrono::high_resolution_clock::now() - start1); std::cout << "\nBVH construction time: " << duration1.count() << "s" << std::endl; Buffer rendering_buffer(width, height); glm::vec3 background_color(1.0f, 1.0f, 1.0f); // Set up the renderer. PathTracer rt(camera, scene, background_color, rendering_buffer); auto start2 = std::chrono::high_resolution_clock::now(); rt.integrate(); // Renders the final image. auto duration2 = std::chrono:: duration_cast<std::chrono::seconds>(std::chrono::high_resolution_clock::now() - start2); std::cout << "\nElapsed time: " << duration2.count() << "s" << std::endl; // Save the rendered image to a .ppm file. rendering_buffer.save("teste.ppm"); return 0; }
30.174603
89
0.571804
f0af752401c2358f7c738dff258fa6e5bb7e7176
2,477
hpp
C++
include/clotho/utility/linear_bit_block_iterator.hpp
putnampp/clotho
6dbfd82ef37b4265381cd78888cd6da8c61c68c2
[ "ECL-2.0", "Apache-2.0" ]
3
2015-06-16T21:27:57.000Z
2022-01-25T23:26:54.000Z
include/clotho/utility/linear_bit_block_iterator.hpp
putnampp/clotho
6dbfd82ef37b4265381cd78888cd6da8c61c68c2
[ "ECL-2.0", "Apache-2.0" ]
3
2015-06-16T21:12:42.000Z
2015-06-23T12:41:00.000Z
include/clotho/utility/linear_bit_block_iterator.hpp
putnampp/clotho
6dbfd82ef37b4265381cd78888cd6da8c61c68c2
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
// Copyright 2015 Patrick Putnam // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef LINEAR_BIT_BLOCK_ITERATOR_HPP_ #define LINEAR_BIT_BLOCK_ITERATOR_HPP_ #include "clotho/utility/bit_block_iterator_def.hpp" namespace clotho { namespace utility { namespace tag { struct linear_iterator_tag {}; } // namespace tag } // namespace utility } // namespace clotho namespace clotho { namespace utility { template < class Block > class bit_block_iterator < Block, clotho::utility::tag::linear_iterator_tag, typename std::enable_if< std::is_integral< Block >::value >::type > { public: typedef bit_block_iterator< Block, clotho::utility::tag::linear_iterator_tag, void > self_type; typedef Block block_type; bit_block_iterator( block_type b = (block_type)0) : m_val(b) , m_index(0) { if( (m_val & (block_type)1) == 0) next(); } bit_block_iterator( const self_type & rhs ) : m_val( rhs.m_val ) , m_index( rhs.m_index ) { } bit_block_iterator & operator++() { if( m_val ) next(); return *this; } bit_block_iterator operator++(int) { bit_block_iterator res(*this); this->operator++(); return res; } inline bool done() const { return (m_val == 0); } unsigned int operator*() const { return m_index; } bool operator==( const self_type & rhs ) const { return (this->m_val == rhs.m_val); } bool operator!=(const self_type & rhs ) const { return (this->m_val != rhs.m_val); } virtual ~bit_block_iterator() {} protected: inline void next() { do { m_val >>= 1; ++m_index; } while( (m_val != 0) && (m_val & (block_type)1) == 0 ); } block_type m_val; unsigned int m_index; }; } // namespace utility { } // namespace clotho { #endif // LINEAR_BIT_BLOCK_ITERATOR_HPP_
25.802083
146
0.634639
f0b0a5d96d62348b136ca0edc7e881fd7b6cea60
7,451
cpp
C++
SuperBigNum.cpp
W-YXN/MyNOIPProjects
0269a8385a6c8d87511236146f374f39dcdd2b82
[ "Apache-2.0" ]
null
null
null
SuperBigNum.cpp
W-YXN/MyNOIPProjects
0269a8385a6c8d87511236146f374f39dcdd2b82
[ "Apache-2.0" ]
null
null
null
SuperBigNum.cpp
W-YXN/MyNOIPProjects
0269a8385a6c8d87511236146f374f39dcdd2b82
[ "Apache-2.0" ]
1
2019-01-19T01:05:07.000Z
2019-01-19T01:05:07.000Z
#define max(a, b) a > b ? a : b #define min(a, b) a < b ? a : b class bign { public: int len, s[MAX_L]; bign(); bign(const char *); bign(int); bool sign; string toStr() const; friend istream &operator>>(istream &, bign &); friend ostream &operator<<(ostream &, bign &); bign operator=(const char *); bign operator=(int); bign operator=(const string); bool operator>(const bign &) const; bool operator>=(const bign &) const; bool operator<(const bign &) const; bool operator<=(const bign &) const; bool operator==(const bign &) const; bool operator!=(const bign &) const; bign operator+(const bign &) const; bign operator++(); bign operator++(int); bign operator+=(const bign &); bign operator-(const bign &) const; bign operator--(); bign operator--(int); bign operator-=(const bign &); bign operator*(const bign &)const; bign operator*(const int num) const; bign operator*=(const bign &); bign operator/(const bign &) const; bign operator/=(const bign &); bign operator%(const bign &) const; bign bign::operator%=(const bign &); bign factorial() const; bign Sqrt() const; bign pow(const bign &) const; void clean(); ~bign(); }; bign::bign() { memset(s, 0, sizeof(s)); len = 1; sign = 1; } bign::bign(const char *num) { *this = num; } bign::bign(int num) { *this = num; } string bign::toStr() const { string res; res = ""; for (int i = 0; i < len; i++) res = (char)(s[i] + '0') + res; if (res == "") res = "0"; if (!sign && res != "0") res = "-" + res; return res; } istream &operator>>(istream &in, bign &num) { string str; in >> str; num = str; return in; } ostream &operator<<(ostream &out, bign &num) { out << num.toStr(); return out; } bign bign::operator=(const char *num) { memset(s, 0, sizeof(s)); char a[MAX_L] = ""; if (num[0] != '-') strcpy(a, num); else for (int i = 1; i < strlen(num); i++) a[i - 1] = num[i]; sign = !(num[0] == '-'); len = strlen(a); for (int i = 0; i < strlen(a); i++) s[i] = a[len - i - 1] - 48; return *this; } bign bign::operator=(int num) { char temp[MAX_L]; sprintf(temp, "%d", num); *this = temp; return *this; } bign bign::operator=(const string num) { const char *tmp; tmp = num.c_str(); *this = tmp; return *this; } bool bign::operator<(const bign &num) const { if (sign ^ num.sign) return num.sign; if (len != num.len) return len < num.len; for (int i = len - 1; i >= 0; i--) if (s[i] != num.s[i]) return sign ? (s[i] < num.s[i]) : (!(s[i] < num.s[i])); return !sign; } bool bign::operator>(const bign &num) const { return num < *this; } bool bign::operator<=(const bign &num) const { return !(*this > num); } bool bign::operator>=(const bign &num) const { return !(*this < num); } bool bign::operator!=(const bign &num) const { return *this > num || *this < num; } bool bign::operator==(const bign &num) const { return !(num != *this); } bign bign::operator+(const bign &num) const { if (sign ^ num.sign) { bign tmp = sign ? num : *this; tmp.sign = 1; return sign ? *this - tmp : num - tmp; } bign result; result.len = 0; int temp = 0; for (int i = 0; temp || i < (max(len, num.len)); i++) { int t = s[i] + num.s[i] + temp; result.s[result.len++] = t % 10; temp = t / 10; } result.sign = sign; return result; } bign bign::operator++() { *this = *this + 1; return *this; } bign bign::operator++(int) { bign old = *this; ++(*this); return old; } bign bign::operator+=(const bign &num) { *this = *this + num; return *this; } bign bign::operator-(const bign &num) const { bign b = num, a = *this; if (!num.sign && !sign) { b.sign = 1; a.sign = 1; return b - a; } if (!b.sign) { b.sign = 1; return a + b; } if (!a.sign) { a.sign = 1; b = bign(0) - (a + b); return b; } if (a < b) { bign c = (b - a); c.sign = false; return c; } bign result; result.len = 0; for (int i = 0, g = 0; i < a.len; i++) { int x = a.s[i] - g; if (i < b.len) x -= b.s[i]; if (x >= 0) g = 0; else { g = 1; x += 10; } result.s[result.len++] = x; } result.clean(); return result; } bign bign::operator*(const bign &num) const { bign result; result.len = len + num.len; for (int i = 0; i < len; i++) for (int j = 0; j < num.len; j++) result.s[i + j] += s[i] * num.s[j]; for (int i = 0; i < result.len; i++) { result.s[i + 1] += result.s[i] / 10; result.s[i] %= 10; } result.clean(); result.sign = !(sign ^ num.sign); return result; } bign bign::operator*(const int num) const { bign x = num; bign z = *this; return x * z; } bign bign::operator*=(const bign &num) { *this = *this * num; return *this; } bign bign::operator/(const bign &num) const { bign ans; ans.len = len - num.len + 1; if (ans.len < 0) { ans.len = 1; return ans; } bign divisor = *this, divid = num; divisor.sign = divid.sign = 1; int k = ans.len - 1; int j = len - 1; while (k >= 0) { while (divisor.s[j] == 0) j--; if (k > j) k = j; char z[MAX_L]; memset(z, 0, sizeof(z)); for (int i = j; i >= k; i--) z[j - i] = divisor.s[i] + '0'; bign dividend = z; if (dividend < divid) { k--; continue; } int key = 0; while (divid * key <= dividend) key++; key--; ans.s[k] = key; bign temp = divid * key; for (int i = 0; i < k; i++) temp = temp * 10; divisor = divisor - temp; k--; } ans.clean(); ans.sign = !(sign ^ num.sign); return ans; } bign bign::operator/=(const bign &num) { *this = *this / num; return *this; } bign bign::operator%(const bign &num) const { bign a = *this, b = num; a.sign = b.sign = 1; bign result, temp = a / b * b; result = a - temp; result.sign = sign; return result; } bign bign::operator%=(const bign &num) { *this = *this % num; return *this; } bign bign::pow(const bign &num) const { bign result = 1; for (bign i = 0; i < num; i++) result = result * (*this); return result; } bign bign::factorial() const { bign result = 1; for (bign i = 1; i <= *this; i++) result *= i; return result; } void bign::clean() { if (len == 0) len++; while (len > 1 && s[len - 1] == '\0') len--; } bign bign::Sqrt() const { if (*this < 0) return -1; if (*this <= 1) return *this; bign l = 0, r = *this, mid; while (r - l > 1) { mid = (l + r) / 2; if (mid * mid > *this) r = mid; else l = mid; } return l; } bign::~bign() { //Nothing to do. }
18.911168
67
0.476715
f0b193b1898fab2aabee86a2b7a9cf98b7551b35
14,729
cpp
C++
source/smoothmethod.cpp
TianSHH/Picop
200fffde41eaf3fa5e041eaface306053f291056
[ "BSD-3-Clause" ]
1
2019-11-22T12:03:44.000Z
2019-11-22T12:03:44.000Z
source/smoothmethod.cpp
TianSHH/Picop
200fffde41eaf3fa5e041eaface306053f291056
[ "BSD-3-Clause" ]
null
null
null
source/smoothmethod.cpp
TianSHH/Picop
200fffde41eaf3fa5e041eaface306053f291056
[ "BSD-3-Clause" ]
null
null
null
#include "smoothmethod.h" SmoothMethod::SmoothMethod() { } SmoothMethod::~SmoothMethod() { } QImage SmoothMethod::averageFiltering(QImage *originImage) { bool ok; int filterRadius = QInputDialog::getInt(nullptr, QObject::tr("均值滤波"), "输入滤波器大小(1~30)", 3, 1, 30, 1, &ok); if (ok) { if (filterRadius % 2 == 0) filterRadius += 1; qDebug().noquote() << "[Debug]" << QDateTime::currentDateTimeUtc().toString("yyyy-MM-dd hh:mm:ss.zzz") << ":" << "图像平滑, 方式, 均值滤波" << "滤波器大小" << filterRadius; int kernel[filterRadius][filterRadius]; for (int i = 0; i < filterRadius; i++) for (int j = 0; j < filterRadius; j++) kernel[i][j] = 1; int len = filterRadius / 2; int originWidth = originImage->width(); int originHeight = originImage->height(); QImage targetImage = QImage(originWidth + 2 * len, originHeight + 2 * len, QImage::Format_RGB32); // 添加边框 for (int i = 0; i < targetImage.width(); i++) for (int j = 0; j < targetImage.height(); j++) if (i >= len && i < targetImage.width() - len && j >= len && j < targetImage.height() - len) { // 不在边框中 QColor originImageColor = QColor(originImage->pixel(i - len, j - len)); targetImage.setPixelColor(i, j, originImageColor); } else // 在边框中 targetImage.setPixel(i, j, Qt::white); // 将边框中颜色设置为白色 for (int i = len; i < targetImage.width() - len; i++) for (int j = len; j < targetImage.height() - len; j++) { int r = 0; int g = 0; int b = 0; for (int p = -len; p <= len; p++) for (int q = -len; q <= len; q++) { r = targetImage.pixelColor(i + p, j + q).red() * kernel[len + p][len + q] + r; g = targetImage.pixelColor(i + p, j + q).green() * kernel[len + p][len + q] + g; b = targetImage.pixelColor(i + p, j + q).blue() * kernel[len + p][len + q] + b; } r /= (filterRadius * filterRadius); g /= (filterRadius * filterRadius); b /= (filterRadius * filterRadius); if (((i - len) >= 0) && ((i - len) < originWidth) && ((j - len) >= 0) && ((j - len) < originHeight)) originImage->setPixel(i - len, j - len, qRgb(r, g, b)); } } return (*originImage); } // averageFiltering QImage SmoothMethod::medianFiltering(QImage *originImage) { // originImage 格式为 Format_RGB32 bool ok; int filterRadius = QInputDialog::getInt(nullptr, QObject::tr("中值滤波"), "输入滤波器大小(1~30)", 3, 1, 30, 1, &ok); if (ok) { if (filterRadius % 2 == 0) filterRadius += 1; qDebug().noquote() << "[Debug]" << QDateTime::currentDateTimeUtc().toString("yyyy-MM-dd hh:mm:ss.zzz") << ":" << "图像平滑, 方式, 中值滤波" << "滤波器大小" << filterRadius; int len = filterRadius / 2; int threshold = filterRadius * filterRadius / 2 + 1; int originWidth = originImage->width(); int originHeight = originImage->height(); QImage middleImage = QImage(originWidth + 2 * len, originHeight + 2 * len, QImage::Format_RGB32); QImage targetImage = QImage(originWidth, originHeight, QImage::Format_RGB32); // 初始化 middleImage for (int i = 0; i < middleImage.width(); i++) { for (int j = 0; j < middleImage.height(); j++) { if ((i >= len) && (i < (middleImage.width() - len)) && (j >= len) && (j < (middleImage.height() - len))) { // 像素点不在边框中 middleImage.setPixelColor(i, j, QColor(originImage->pixel(i - len, j - len))); } else { // 像素点在边框中 middleImage.setPixelColor(i, j, Qt::white); } } } // 使用直方图记录窗口中出现的像素的出现次数 int redHist[256] = {0}; int greenHist[256] = {0}; int blueHist[256] = {0}; int grayHist[256] = {0}; for (int i = len; i < middleImage.width() - len; i++) { for (int j = len; j < middleImage.height() - len; j++) { // 设置窗口 if (j == len) { // 每到新的一列, 初始化直方图 memset(redHist, 0, sizeof(redHist)); memset(greenHist, 0, sizeof(greenHist)); memset(blueHist, 0, sizeof(blueHist)); memset(grayHist, 0, sizeof(grayHist)); for (int p = -len; p <= len; p++) { for (int q = -len; q <= len; q++) { int red = qRed(middleImage.pixel(i + p, j + q)); int green = qGreen(middleImage.pixel(i + p, j + q)); int blue = qBlue(middleImage.pixel(i + p, j + q)); int gray = qGray(middleImage.pixel(i + p, j + q)); redHist[red]++; greenHist[green]++; blueHist[blue]++; grayHist[gray]++; } } } else { // 列数增加, 窗口按列向下移动, 为窗口新添加一行像素值, 并删去一行像素值 int oldWindowStartCol = j - len - 1; int newWindowEndCol = j + len; for (int p = -len; p <= len; p++) { // 要减去的列的像素值, 从窗口上到窗口下, 即 [j-len,j+len] int red = qRed(middleImage.pixel(i + p, oldWindowStartCol)); int green = qGreen(middleImage.pixel(i + p, oldWindowStartCol)); int blue = qBlue(middleImage.pixel(i + p, oldWindowStartCol)); int gray = qGray(middleImage.pixel(i + p, oldWindowStartCol)); redHist[red]--; greenHist[green]--; blueHist[blue]--; grayHist[gray]--; red = qRed(middleImage.pixel(i + p, newWindowEndCol)); green = qGreen(middleImage.pixel(i + p, newWindowEndCol)); blue = qBlue(middleImage.pixel(i + p, newWindowEndCol)); gray = qGray(middleImage.pixel(i + p, newWindowEndCol)); redHist[red]++; greenHist[green]++; blueHist[blue]++; grayHist[gray]++; } } // 获取窗口内像素中值 int r = getMedianValue(redHist, threshold); int g = getMedianValue(greenHist, threshold); int b = getMedianValue(blueHist, threshold); targetImage.setPixel(i - len, j - len, qRgb(r, g, b)); } } return targetImage; } } // medianFiltering // 获取窗口中像素的中值 int SmoothMethod::getMedianValue(const int *histogram, int threshold) { int sum = 0; for (int i = 0; i < 256; i++) { sum += histogram[i]; if (sum >= threshold) return i; } return 255; } // getMedianValue QImage SmoothMethod::KNNF(QImage originImage) { bool ok1; bool ok2; int filterRadius = QInputDialog::getInt(nullptr, QObject::tr("K近邻均值滤波"), "输入滤波器大小(1~30)", 3, 1, 30, 1, &ok1); int K = QInputDialog::getInt(nullptr, QObject::tr("K近邻均值平滑"), "输入K值", 1, 1, 30, 1, &ok2); if (ok1 & ok2) { if (filterRadius % 2 == 0) filterRadius += 1; qDebug().noquote().nospace() << "[Debug] " << QDateTime::currentDateTimeUtc().toString("yyyy-MM-dd hh:mm:ss.zzz") << ": " << "图像平滑, 方式, K近邻均值滤波, " << "滤波器大小, " << filterRadius << ", " << "K值, " << K; // int kernel[filterRadius][filterRadius]; // for (int i = 0; i < filterRadius; i++) // for (int j = 0; j < filterRadius; j++) // kernel[i][j] = 1; int len = filterRadius / 2; int originWidth = originImage.width(); int originHeight = originImage.height(); QImage middleImage = QImage(originWidth + 2 * len, originHeight + 2 * len, QImage::Format_RGB32); QImage targetImage = QImage(originWidth, originHeight, QImage::Format_RGB32); // 添加边框 for (int i = 0; i < middleImage.width(); i++) for (int j = 0; j < middleImage.height(); j++) if (i >= len && i < middleImage.width() - len && j >= len && j < middleImage.height() - len) { // 不在边框中 middleImage.setPixelColor(i, j, QColor(originImage.pixel(i - len, j - len))); } else { // 在边框中 middleImage.setPixel(i, j, Qt::white); // 将边框中颜色设置为白色 } int redHist[256] = {0}; int greenHist[256] = {0}; int blueHist[256] = {0}; for (int i = len; i < middleImage.width() - len; i++) for (int j = len; j < middleImage.height() - len; j++) { // 设置窗口 if (j == len) { // 每到新的一列, 初始化直方图 memset(redHist, 0, sizeof(redHist)); memset(greenHist, 0, sizeof(greenHist)); memset(blueHist, 0, sizeof(blueHist)); for (int p = -len; p <= len; p++) { for (int q = -len; q <= len; q++) { int red = qRed(middleImage.pixel(i + p, j + q)); int green = qGreen(middleImage.pixel(i + p, j + q)); int blue = qBlue(middleImage.pixel(i + p, j + q)); redHist[red]++; greenHist[green]++; blueHist[blue]++; } } } else { // 列数增加, 窗口按列向下移动, 为窗口新添加一行像素值, 并删去一行像素值 int oldWindowStartCol = j - len - 1; int newWindowEndCol = j + len; for (int p = -len; p <= len; p++) { // 要减去的列的像素值, 从窗口上到窗口下, 即 [j-len,j+len] int red = qRed(middleImage.pixel(i + p, oldWindowStartCol)); int green = qGreen(middleImage.pixel(i + p, oldWindowStartCol)); int blue = qBlue(middleImage.pixel(i + p, oldWindowStartCol)); redHist[red]--; greenHist[green]--; blueHist[blue]--; red = qRed(middleImage.pixel(i + p, newWindowEndCol)); green = qGreen(middleImage.pixel(i + p, newWindowEndCol)); blue = qBlue(middleImage.pixel(i + p, newWindowEndCol)); redHist[red]++; greenHist[green]++; blueHist[blue]++; } } int r = getKValue(redHist, qRed(middleImage.pixel(i, j)), K); int g = getKValue(greenHist, qGreen(middleImage.pixel(i, j)), K); int b = getKValue(blueHist, qBlue(middleImage.pixel(i, j)), K); // int r = getAverage(rKNNValue); // int g = getAverage(gKNNValue); // int b = getAverage(bKNNValue); targetImage.setPixel(i - len, j - len, qRgb(r, g, b)); } return targetImage; } return originImage; } // KNNF int SmoothMethod::getKValue(const int *histogram, int key, int K) { // 计算距离 key 的 K 近邻的方法也是桶排序 // 记录各点到 key 距离的数组长度不超过 255-key // bucket[255-key][0] => 像素值大于 key 的点其像素值与 key 的差值 // bucket[255-key][1] => 像素值小于 key 的点其像素值与 key 的差值 int bucket[255][2]; for (int i = 0; i <= 255; i++) { bucket[i][0] = 0; bucket[i][1] = 0; } for (int i = 0; i <= 255; i++) { if (histogram[i] > 0) { if (i - key >= 0) { bucket[i - key][0] = histogram[i]; } else { bucket[key - i][1] = histogram[i]; } } } int max = K + 1; int KNNValue[max] = {0}; K = K - 1; // 所有的 K 近邻点中 key 本身是第一个 KNNValue[0] = key; bucket[0][0]--; if (K <= 0) return key; // j 是 KNNValue 索引 for (int i = 0, j = 1; i <= 255; i++) { if (bucket[i][0] > 0) { // TODO 可优化 // 大于 key 的像素值 qDebug() << ">"; if (bucket[i][0] >= K) { for (int k = 0; k < K; j++, k++) { KNNValue[j] = i + key; } K = 0; } else { for (int k = 0; k < bucket[i][0]; j++, k++) { // 将所有像素值为 i 的点全部加入 KNNValue[j] = i + key; // 还原原始像素值 } K -= bucket[i][0]; } } if (K <= 0) break; if (bucket[i][1] > 0) { // 小于 key 的像素值 qDebug() << "<"; if (bucket[i][1] >= K) { for (int k = 0; k < K; j++, k++) { KNNValue[j] = key - i; } K = 0; } else { for (int k = 0; k < bucket[i][1]; j++, k++) { // 将所有像素值为 i 的点全部加入 KNNValue[j] = key - i; // 还原原始像素值 } K -= bucket[i][1]; } } if (K <= 0) break; } for (int i = 0; i < max - 1; i++) qDebug() << KNNValue[i]; // return KNNValue; int res = getAverage(KNNValue, max - 1); return res; } // getKValue int SmoothMethod::getAverage(const int *arr, int len) { int average = 0; for (int i = 0; i < len; i++) average += arr[i]; int res = average / len; return res; } // getAverage
34.494145
129
0.42345
f0b19e8ef7819f07395c7199e2a6c9f000b5a0ec
2,548
cpp
C++
gen_desc/kitti_gen.cpp
lilin-hitcrt/RINet
0e28c26e015c50385816b2cbe6549583486fd486
[ "MIT" ]
5
2022-03-01T13:56:47.000Z
2022-03-09T02:57:15.000Z
gen_desc/kitti_gen.cpp
lilin-hitcrt/RINet
0e28c26e015c50385816b2cbe6549583486fd486
[ "MIT" ]
null
null
null
gen_desc/kitti_gen.cpp
lilin-hitcrt/RINet
0e28c26e015c50385816b2cbe6549583486fd486
[ "MIT" ]
1
2022-03-06T07:59:51.000Z
2022-03-06T07:59:51.000Z
#include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/visualization/cloud_viewer.h> #include <opencv2/opencv.hpp> #include "semanticConf.hpp" #include "genData.hpp" int main(int argc,char** argv){ if(argc<4){ std::cout<<"Usage: ./kitti_gen cloud_folder label_folder output_file"<<std::endl; exit(0); } std::string cloud_path=argv[1]; std::string label_path=argv[2]; bool label_valid[20]={0,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1}; bool use_min[20]={1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1}; int label_map[20]={-1,0,-1,-1,-1,-1,-1,-1,-1,1,2,3,4,5,6,7,8,9,10,11}; std::shared_ptr<semConf> semconf(new semConf("../conf/sem_config.yaml")); genData gener(cloud_path,label_path, semconf); CloudLPtr cloud(new CloudL); int totaldata = gener.totaldata; int num=0; pcl::visualization::CloudViewer viewer("cloud"); std::ofstream fout(argv[3],ios::binary); while (gener.getData(cloud)){ std::cout<<num<<"/"<<totaldata<<std::endl; CloudLPtr cloud_out(new CloudL); std::vector<float> dis_list; cloud_out->resize((label_map[19]+1)*360); dis_list.resize(cloud_out->size(),0.f); for(auto p:cloud->points){ if(label_valid[p.label]){ int angle=std::floor((std::atan2(p.y,p.x)+M_PI)*180./M_PI); if(angle<0||angle>359){ continue; } float dis=std::sqrt(p.x*p.x+p.y*p.y); if(dis>50){ continue; } auto& q=cloud_out->at(360*label_map[p.label]+angle); if(q.label>0){ float dis_temp=std::sqrt(q.x*q.x+q.y*q.y); if(use_min[p.label]){ if(dis<dis_temp){ q=p; dis_list[360*label_map[p.label]+angle]=dis; } }else{ if(dis>dis_temp){ q=p; dis_list[360*label_map[p.label]+angle]=dis; } } }else{ q=p; dis_list[360*label_map[p.label]+angle]=dis; } } } for(auto dis:dis_list){ fout.write((char*)(&dis),sizeof(dis)); } auto ccloud=semconf->getColorCloud(cloud_out); viewer.showCloud(ccloud); ++num; } fout.close(); return 0; }
36.4
89
0.494505
f0b3482342d0c26c556d88ebc899d2d825d10dd1
760
cpp
C++
KDF/src/Platform/OpenGL/OpenGLContext.cpp
Kuenlun/DynamicFlowchart
54f0863f204298c31d68690d695fc81667d0fde6
[ "MIT" ]
null
null
null
KDF/src/Platform/OpenGL/OpenGLContext.cpp
Kuenlun/DynamicFlowchart
54f0863f204298c31d68690d695fc81667d0fde6
[ "MIT" ]
null
null
null
KDF/src/Platform/OpenGL/OpenGLContext.cpp
Kuenlun/DynamicFlowchart
54f0863f204298c31d68690d695fc81667d0fde6
[ "MIT" ]
null
null
null
#include "KDFpch.h" #include "OpenGLContext.h" #include <GLFW/glfw3.h> #include <Glad/glad.h> namespace KDF { OpenGLContext::OpenGLContext(GLFWwindow* windowHandle) : m_windowHandle(windowHandle) { KDF_CORE_ASSERT(windowHandle, "Window handle is null!"); } void OpenGLContext::Init() { glfwMakeContextCurrent(m_windowHandle); int status = gladLoadGLLoader((GLADloadproc)glfwGetProcAddress); KDF_CORE_ASSERT(status, "Failed to initialize Glad"); CORE_LOG_INFO("OpenGL Info:"); CORE_LOG_INFO("\tVendor {0}", glGetString(GL_VENDOR)); CORE_LOG_INFO("\tRenderer {0}", glGetString(GL_RENDERER)); CORE_LOG_INFO("\tVersion {0}", glGetString(GL_VERSION)); } void OpenGLContext::SwapBuffers() { glfwSwapBuffers(m_windowHandle); } }
21.714286
66
0.740789
f0b9afdee429081c137cbabb2df8b2a312396ec3
1,221
cpp
C++
BAC_2nd/ch5/UVa12096.cpp
Anyrainel/aoapc-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
3
2017-08-15T06:00:01.000Z
2018-12-10T09:05:53.000Z
BAC_2nd/ch5/UVa12096.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
null
null
null
BAC_2nd/ch5/UVa12096.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
2
2017-09-16T18:46:27.000Z
2018-05-22T05:42:03.000Z
// UVa12096 The SetStack Computer // Rujia Liu #include<iostream> #include<string> #include<set> #include<map> #include<stack> #include<vector> #include<algorithm> using namespace std; #define ALL(x) x.begin(),x.end() #define INS(x) inserter(x,x.begin()) typedef set<int> Set; map<Set,int> IDcache; // 把集合映射成ID vector<Set> Setcache; // 根据ID取集合 // 查找给定集合x的ID。如果找不到,分配一个新ID int ID (Set x) { if (IDcache.count(x)) return IDcache[x]; Setcache.push_back(x); // 添加新集合 return IDcache[x] = Setcache.size() - 1; } int main () { int T; cin >> T; while(T--) { stack<int> s; // 题目中的栈 int n; cin >> n; for(int i = 0; i < n; i++) { string op; cin >> op; if (op[0] == 'P') s.push(ID(Set())); else if (op[0] == 'D') s.push(s.top()); else { Set x1 = Setcache[s.top()]; s.pop(); Set x2 = Setcache[s.top()]; s.pop(); Set x; if (op[0] == 'U') set_union (ALL(x1), ALL(x2), INS(x)); if (op[0] == 'I') set_intersection (ALL(x1), ALL(x2), INS(x)); if (op[0] == 'A') { x = x2; x.insert(ID(x1)); } s.push(ID(x)); } cout << Setcache[s.top()].size() << endl; } cout << "***" << endl; } return 0; }
23.037736
70
0.527437
f0bfeb13d9f891159be59bd3a9018602f94a5beb
5,432
cc
C++
base/test/scoped_feature_list.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
base/test/scoped_feature_list.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
base/test/scoped_feature_list.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/test/scoped_feature_list.h" #include <algorithm> #include <string> #include <utility> #include <vector> #include "base/stl_util.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" namespace base { namespace test { namespace { std::vector<StringPiece> GetFeatureVector( const std::initializer_list<Feature>& features) { std::vector<StringPiece> output; for (const Feature& feature : features) { output.push_back(feature.name); } return output; } // Extracts a feature name from a feature state string. For example, given // the input "*MyLovelyFeature<SomeFieldTrial", returns "MyLovelyFeature". StringPiece GetFeatureName(StringPiece feature) { StringPiece feature_name = feature; // Remove default info. if (feature_name.starts_with("*")) feature_name = feature_name.substr(1); // Remove field_trial info. std::size_t index = feature_name.find("<"); if (index != std::string::npos) feature_name = feature_name.substr(0, index); return feature_name; } struct Features { std::vector<StringPiece> enabled_feature_list; std::vector<StringPiece> disabled_feature_list; }; // Merges previously-specified feature overrides with those passed into one of // the Init() methods. |features| should be a list of features previously // overridden to be in the |override_state|. |merged_features| should contain // the enabled and disabled features passed into the Init() method, plus any // overrides merged as a result of previous calls to this function. void OverrideFeatures(const std::string& features, FeatureList::OverrideState override_state, Features* merged_features) { std::vector<StringPiece> features_list = SplitStringPiece(features, ",", TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY); for (StringPiece feature : features_list) { StringPiece feature_name = GetFeatureName(feature); if (ContainsValue(merged_features->enabled_feature_list, feature_name) || ContainsValue(merged_features->disabled_feature_list, feature_name)) continue; if (override_state == FeatureList::OverrideState::OVERRIDE_ENABLE_FEATURE) { merged_features->enabled_feature_list.push_back(feature); } else { DCHECK_EQ(override_state, FeatureList::OverrideState::OVERRIDE_DISABLE_FEATURE); merged_features->disabled_feature_list.push_back(feature); } } } } // namespace ScopedFeatureList::ScopedFeatureList() {} ScopedFeatureList::~ScopedFeatureList() { if (original_feature_list_) { FeatureList::ClearInstanceForTesting(); FeatureList::RestoreInstanceForTesting(std::move(original_feature_list_)); } } void ScopedFeatureList::Init() { std::unique_ptr<FeatureList> feature_list(new FeatureList); feature_list->InitializeFromCommandLine(std::string(), std::string()); InitWithFeatureList(std::move(feature_list)); } void ScopedFeatureList::InitWithFeatureList( std::unique_ptr<FeatureList> feature_list) { DCHECK(!original_feature_list_); original_feature_list_ = FeatureList::ClearInstanceForTesting(); FeatureList::SetInstance(std::move(feature_list)); } void ScopedFeatureList::InitFromCommandLine( const std::string& enable_features, const std::string& disable_features) { std::unique_ptr<FeatureList> feature_list(new FeatureList); feature_list->InitializeFromCommandLine(enable_features, disable_features); InitWithFeatureList(std::move(feature_list)); } void ScopedFeatureList::InitWithFeatures( const std::initializer_list<Feature>& enabled_features, const std::initializer_list<Feature>& disabled_features) { Features merged_features; merged_features.enabled_feature_list = GetFeatureVector(enabled_features); merged_features.disabled_feature_list = GetFeatureVector(disabled_features); FeatureList* feature_list = FeatureList::GetInstance(); // |current_enabled_features| and |current_disabled_features| must declare out // of if scope to avoid them out of scope before JoinString calls because // |merged_features| may contains StringPiece which holding pointer points to // |current_enabled_features| and |current_disabled_features|. std::string current_enabled_features; std::string current_disabled_features; if (feature_list) { FeatureList::GetInstance()->GetFeatureOverrides(&current_enabled_features, &current_disabled_features); OverrideFeatures(current_enabled_features, FeatureList::OverrideState::OVERRIDE_ENABLE_FEATURE, &merged_features); OverrideFeatures(current_disabled_features, FeatureList::OverrideState::OVERRIDE_DISABLE_FEATURE, &merged_features); } std::string enabled = JoinString(merged_features.enabled_feature_list, ","); std::string disabled = JoinString(merged_features.disabled_feature_list, ","); InitFromCommandLine(enabled, disabled); } void ScopedFeatureList::InitAndEnableFeature(const Feature& feature) { InitWithFeatures({feature}, {}); } void ScopedFeatureList::InitAndDisableFeature(const Feature& feature) { InitWithFeatures({}, {feature}); } } // namespace test } // namespace base
35.272727
80
0.745398
f0c266afdbbcaeb1c0628f623cfc342ab307f85c
5,958
hh
C++
Kaskade/fem/diffops/mooneyRivlin.hh
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
3
2019-07-03T14:03:31.000Z
2021-12-19T10:18:49.000Z
Kaskade/fem/diffops/mooneyRivlin.hh
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
6
2020-02-17T12:01:30.000Z
2021-12-09T22:02:33.000Z
Kaskade/fem/diffops/mooneyRivlin.hh
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
2
2020-12-03T04:41:18.000Z
2021-01-11T21:44:42.000Z
#ifndef MOONEY_RIVLIN_HH #define MOONEY_RIVLIN_HH #include "linalg/invariants.hh" #include "utilities/functionTools.hh" namespace Kaskade { template <int dim, class VolumetricPenalty = void, Invariant i = Invariant::Principal, class Direction = void> class MooneyRivlin; /** * \param lambda first Lame constant * \param mu second Lame constant */ template <class VolumetricPenalty, int dim, Invariant i = Invariant::Principal, class Direction = void> MooneyRivlin<dim,VolumetricPenalty,i,Direction> createMooneyRivlinFromLameConstants(double lambda, double mu) { static_assert(!std::is_same<VolumetricPenalty,void>::value,"not implemented"); VolumetricPenalty g; // std::cout << "g': " << g.d1(1) << ", g'': " << g.d2(1) << std::endl; //double c = (lambda + 2*mu)/(g.d2(1)-g.d1(1)); //double b = -0.5*mu - 0.5*c*g.d1(1); //double a = mu + 0.5*c*g.d1(1); double rho = g.d1(1)/(-g.d2(1)+g.d1(1)); double d = (lambda+2.0*mu)/(g.d2(1)-g.d1(1)); double c = (0.5*rho-0.25)*mu+0.25*rho*lambda; if(c > 0.25*mu) c = (rho-0.75)*mu+0.5*rho*lambda; double b = -mu + rho*(lambda+2.*mu)-2.*c; double a = b + mu; double alpha = 0.5*a - b; double beta = 0.5*b; // std::cout << "alpha: " << alpha << ", beta: " << beta << ", c: " << c << ", d: " << d << std::endl; if(a<0 || b<0 || c<0) { std::cout << "computed parameters: " << a << ", " << b << ", " << c << ", " << d << std::endl; std::cout << "alpha=" << alpha << ", beta=" << beta << std::endl; std::cout << "material law is not polyconvex" << std::endl; exit(1); } return MooneyRivlin<dim,VolumetricPenalty,i,Direction>(alpha,beta,c,d); } /** * \param E Young's modulus * \param nu Poisson ratio */ template <class VolumetricPenalty, int dim, Invariant i = Invariant::Principal, class Direction = void> MooneyRivlin<dim,VolumetricPenalty,i,Direction> createMooneyRivlinFromMaterialConstants(double E, double nu) { static_assert(!std::is_same<VolumetricPenalty,void>::value,"not implemented"); double lambda = E*nu/((1+nu)*(1-2*nu)); double mu = E/(2*(1+nu)); return createMooneyRivlinFromLameConstants<VolumetricPenalty,dim,i,Direction>(lambda,mu); } template <int dim, class VolumetricPenalty, Invariant i, class Direction> class MooneyRivlin : public StrainBase<double,dim>, public Sum<Scaled<ShiftedInvariant<typename ChooseInvariant<1,dim,i,CauchyGreenTensor<double,dim>,Direction>::type> >, Scaled<ShiftedInvariant<typename ChooseInvariant<2,dim,i,CauchyGreenTensor<double,dim>,Direction>::type> >, MatrixToScalarFunction<VolumetricPenalty,Determinant<dim> > > { typedef typename ChooseInvariant<1,dim,i,CauchyGreenTensor<double,dim>,Direction>::type Inv1; typedef ShiftedInvariant<Inv1> SInv1; typedef typename ChooseInvariant<2,dim,i,CauchyGreenTensor<double,dim>,Direction>::type Inv2; typedef ShiftedInvariant<Inv2> SInv2; typedef Determinant<dim> Det; typedef MatrixToScalarFunction<VolumetricPenalty,Det>Penalty; typedef Sum<Scaled<SInv1>,Scaled<SInv2>,Penalty> Base; using StrainBase<double,dim>::F; using StrainBase<double,dim>::S; public: typedef double Scalar; MooneyRivlin(double lambda, double mu) : MooneyRivlin(createMooneyRivlinFromLameConstants<VolumetricPenalty,dim>(lambda,mu)) {} // template <class Scalar, class enable = typename std::enable_if<std::is_same<Scalar,double>::value && std::is_same<Direction,void>::value,void>::type> MooneyRivlin(double c0, double c1, double c2, double c3) : StrainBase<double,dim>(), Base(Scaled<SInv1>(c0,SInv1(Inv1(S),dim)), Scaled<SInv2>(c1,SInv2(Inv2(S),dim)), Penalty(Det(F),VolumetricPenalty(c2,c3))) { assert(c0>0 && c1>0 && c2>0); } template <class Dir, class enable = typename std::enable_if< std::is_same<Direction,Dir>::value && !std::is_same<void,Direction>::value,void>::type> MooneyRivlin(double c0, double c1, double c2, double c3, Dir d) : StrainBase<double,dim>(), Base(Scaled<SInv1>(c0,SInv1(Inv1(S,d),dim)), Scaled<SInv2>(c1,SInv2(Inv2(S,d),dim)), Penalty(Det(F),VolumetricPenalty(c2,c3))) { assert(c0>0 && c1>0 && c2>0); } MooneyRivlin(MooneyRivlin const&) = default; MooneyRivlin& operator=(MooneyRivlin const&) = default; }; template <int dim, Invariant i,class Direction> class MooneyRivlin<dim,void,i,Direction> : public StrainBase<double,dim>, public Sum<Scaled<ShiftedInvariant<typename ChooseInvariant<1,dim,i,CauchyGreenTensor<double,dim>,Direction>::type> >, Scaled<ShiftedInvariant<typename ChooseInvariant<2,dim,i,CauchyGreenTensor<double,dim>,Direction>::type> > > { typedef typename ChooseInvariant<1,dim,i,CauchyGreenTensor<double,dim>,Direction>::type Inv1; typedef typename ChooseInvariant<2,dim,i,CauchyGreenTensor<double,dim>,Direction>::type Inv2; typedef ShiftedInvariant<Inv1> SInv1; typedef ShiftedInvariant<Inv2> SInv2; typedef Sum<Scaled<SInv1>,Scaled<SInv2> > Base; using StrainBase<double,dim>::S; public: typedef double Scalar; template <class Scalar, class enable = typename std::enable_if<std::is_same<Scalar,double>::value && std::is_same<Direction,void>::value,void>::type> MooneyRivlin(double c0, double c1) : StrainBase<double,dim>(), Base(Scaled<SInv1>(c0,SInv1(Inv1(S),dim)),Scaled<SInv2>(c1,SInv2(Inv2(S),dim))) { assert(c0>0 && c1>0); } template <class Scalar, class enable = typename std::enable_if<std::is_same<Scalar,double>::value && !std::is_same<Direction,void>::value,void>::type> MooneyRivlin(double c0, double c1, Direction const& d) : StrainBase<double,dim>(), Base(Scaled<SInv1>(c0,SInv1(Inv1(S,d),dim)),Scaled<SInv2>(c1,SInv2(Inv2(S,d),dim))) { assert(c0>0 && c1>0); } MooneyRivlin(MooneyRivlin const&) = default; MooneyRivlin& operator=(MooneyRivlin const&) = default; }; } #endif
46.546875
158
0.678583
f0c33de0a5f5bbb2cedc3d33d337a78916f422b7
1,117
cpp
C++
hand.cpp
youdymoo/blackjack
de3890aae667718e9386eae39d777d942b05fe91
[ "MIT" ]
null
null
null
hand.cpp
youdymoo/blackjack
de3890aae667718e9386eae39d777d942b05fe91
[ "MIT" ]
null
null
null
hand.cpp
youdymoo/blackjack
de3890aae667718e9386eae39d777d942b05fe91
[ "MIT" ]
null
null
null
#include "hand.h" Hand::Hand() { discardAll(); } void Hand::discardAll() { curValue.count = 0; curValue.soft = false; } void Hand::addCard(Card c) { int countCard; if (c.spot != ACE) { if (c.spot <= NINE) { countCard = c.spot + 2; curValue.count += countCard; } else if (c.spot >= TEN && c.spot <= KING) { countCard = 10; curValue.count += countCard; } if (curValue.count > 21 && curValue.soft) { curValue.count -= 10; curValue.soft = false; } return; } else { countCard = 11; curValue.count += countCard; if (curValue.count > 21) { if (curValue.soft) { curValue.count -= 10; return; } else { curValue.count -= 10; curValue.soft = false; return; } } else { curValue.soft = true; return; } } } HandValue Hand::handValue() const { return curValue; }
21.075472
51
0.438675
f0c422605b8c43b5b392f5f57e418a229c356f8d
970
hpp
C++
include/defines.hpp
Yao-Chung/Sokoban-Agent
7135a51ee8a912fe8a636ccfeecbcd3551e6720c
[ "BSD-3-Clause" ]
null
null
null
include/defines.hpp
Yao-Chung/Sokoban-Agent
7135a51ee8a912fe8a636ccfeecbcd3551e6720c
[ "BSD-3-Clause" ]
null
null
null
include/defines.hpp
Yao-Chung/Sokoban-Agent
7135a51ee8a912fe8a636ccfeecbcd3551e6720c
[ "BSD-3-Clause" ]
null
null
null
#ifndef SOKOBAN_AGENT_DEFINES #define SOKOBAN_AGENT_DEFINES #include <vector> #include <string> #include <iostream> enum MoveDirection{ Left = 0, Right = 1, Up = 2, Down = 3, Unspecified = -1, }; using Map = std::vector<std::string>; using Position = std::pair<int, int>; using Decimal = float; std::string getKey(const Map map); std::string getKey(const Position manPos, const std::vector<Position> boxPos); std::pair< Position, std::vector<Position> > getPositions(const Map map); Map move(const Map& map, const MoveDirection direction, const Map& level); void write_solution(const std::string filename, const Map& map, const std::vector<MoveDirection>& policy); std::vector< std::pair<Map, std::vector<MoveDirection>> > read_solutions(std::string filename); Map readMap(std::istream &stream); std::vector< std::pair<Map, std::vector<MoveDirection>> > clean_solutions(std::vector< std::pair<Map, std::vector<MoveDirection>> > solutions); #endif
34.642857
143
0.727835
f0c83d8b974fd845985527c413970c06730c5cc1
1,561
hpp
C++
apps/src/videostitch-live-gui/src/configurations/rigconfigurationwidget.hpp
tlalexander/stitchEm
cdff821ad2c500703e6cb237ec61139fce7bf11c
[ "MIT" ]
182
2019-04-19T12:38:30.000Z
2022-03-20T16:48:20.000Z
apps/src/videostitch-live-gui/src/configurations/rigconfigurationwidget.hpp
doymcc/stitchEm
20693a55fa522d7a196b92635e7a82df9917c2e2
[ "MIT" ]
107
2019-04-23T10:49:35.000Z
2022-03-02T18:12:28.000Z
apps/src/videostitch-live-gui/src/configurations/rigconfigurationwidget.hpp
doymcc/stitchEm
20693a55fa522d7a196b92635e7a82df9917c2e2
[ "MIT" ]
59
2019-06-04T11:27:25.000Z
2022-03-17T23:49:49.000Z
// Copyright (c) 2012-2017 VideoStitch SAS // Copyright (c) 2018 stitchEm #ifndef RIGCONFIGURATIONWIDGET_HPP #define RIGCONFIGURATIONWIDGET_HPP #include <QWidget> #include "ui_rigconfigurationwidget.h" #include "libvideostitch/stereoRigDef.hpp" class RigConfigurationWidget : public QFrame, public Ui::RigConfigurationWidgetClass { Q_OBJECT public: explicit RigConfigurationWidget(QWidget* const parent = nullptr); ~RigConfigurationWidget(); void loadConfiguration(const QStringList inputNames, const VideoStitch::Core::StereoRigDefinition::Orientation orientation, const VideoStitch::Core::StereoRigDefinition::Geometry geometry, const double diameter, const double ipd, const QVector<int> leftInputs, const QVector<int> rightInputs); signals: void notifyRigConfigured(const VideoStitch::Core::StereoRigDefinition::Orientation orientation, const VideoStitch::Core::StereoRigDefinition::Geometry geometry, const double diameter, const double ipd, const QVector<int> leftInputs, const QVector<int> rightInputs); public slots: void onButtonAcceptClicked(); void onButtonCircularChecked(); void onButtonPolygonalChecked(); void onOrientationChanged(const QString& orientation); private: void addInputsToList(const QVector<int> left, const QVector<int> right); QVector<int> getLeftInputs() const; QVector<int> getRightInputs() const; QStringList inputNames; }; #endif // RIGCONFIGURATIONWIDGET_HPP
39.025
114
0.73991
f0c9ea61afd241f3c72bd16e62d22587e4d0f3d9
53,605
hh
C++
apps/rosetta/rif_dock_test.hh
willsheffler/rifdock
291d05112d52318bb07d499ce6da3e0fb9fbf9cf
[ "Apache-2.0" ]
2
2020-01-28T07:59:26.000Z
2020-09-17T06:32:14.000Z
apps/rosetta/rif_dock_test.hh
willsheffler/rifdock
291d05112d52318bb07d499ce6da3e0fb9fbf9cf
[ "Apache-2.0" ]
null
null
null
apps/rosetta/rif_dock_test.hh
willsheffler/rifdock
291d05112d52318bb07d499ce6da3e0fb9fbf9cf
[ "Apache-2.0" ]
null
null
null
#include <basic/options/option_macros.hh> #include <basic/options/keys/corrections.OptionKeys.gen.hh> #include <riflib/scaffold/nineA_util.hh> #include <vector> #ifdef GLOBAL_VARIABLES_ARE_BAD #ifndef INCLUDED_rif_dock_test_hh_1 #define INCLUDED_rif_dock_test_hh_1 OPT_1GRP_KEY( StringVector , rif_dock, scaffolds ) OPT_1GRP_KEY( StringVector, rif_dock, scaffold_res ) OPT_1GRP_KEY( StringVector, rif_dock, scaffold_res_fixed ) OPT_1GRP_KEY( Boolean , rif_dock, scaffold_res_use_best_guess ) OPT_1GRP_KEY( Boolean , rif_dock, scaffold_to_ala ) OPT_1GRP_KEY( Boolean , rif_dock, scaffold_to_ala_selonly ) OPT_1GRP_KEY( Boolean , rif_dock, replace_orig_scaffold_res ) OPT_1GRP_KEY( Boolean , rif_dock, replace_all_with_ala_1bre ) OPT_1GRP_KEY( Boolean , rif_dock, random_perturb_scaffold ) OPT_1GRP_KEY( StringVector, rif_dock, target_bounding_xmaps ) OPT_1GRP_KEY( String , rif_dock, target_pdb ) OPT_1GRP_KEY( String , rif_dock, target_res ) OPT_1GRP_KEY( String , rif_dock, target_rif ) OPT_1GRP_KEY( Real , rif_dock, target_rf_resl ) OPT_1GRP_KEY( Integer , rif_dock, target_rf_oversample ) OPT_1GRP_KEY( String , rif_dock, target_rf_cache ) OPT_1GRP_KEY( String , rif_dock, target_donors ) OPT_1GRP_KEY( String , rif_dock, target_acceptors ) OPT_1GRP_KEY( Boolean , rif_dock, only_load_highest_resl ) OPT_1GRP_KEY( Boolean , rif_dock, use_rosetta_grid_energies ) OPT_1GRP_KEY( Boolean , rif_dock, soft_rosetta_grid_energies ) OPT_1GRP_KEY( StringVector, rif_dock, data_cache_dir ) OPT_1GRP_KEY( Real , rif_dock, beam_size_M ) OPT_1GRP_KEY( Real , rif_dock, max_beam_multiplier ) OPT_1GRP_KEY( Boolean , rif_dock, multiply_beam_by_seeding_positions ) OPT_1GRP_KEY( Boolean , rif_dock, multiply_beam_by_scaffolds ) OPT_1GRP_KEY( Real , rif_dock, search_diameter ) OPT_1GRP_KEY( Real , rif_dock, hsearch_scale_factor ) OPT_1GRP_KEY( Real , rif_dock, max_rf_bounding_ratio ) OPT_1GRP_KEY( Boolean , rif_dock, make_bounding_plot_data ) OPT_1GRP_KEY( Boolean , rif_dock, align_output_to_scaffold ) OPT_1GRP_KEY( Boolean , rif_dock, output_scaffold_only ) OPT_1GRP_KEY( Boolean , rif_dock, output_full_scaffold_only ) OPT_1GRP_KEY( Boolean , rif_dock, output_full_scaffold ) OPT_1GRP_KEY( Integer , rif_dock, n_pdb_out ) OPT_1GRP_KEY( Real , rif_dock, rf_resl ) OPT_1GRP_KEY( Integer , rif_dock, rf_oversample ) OPT_1GRP_KEY( Boolean , rif_dock, downscale_atr_by_hierarchy ) OPT_1GRP_KEY( Real , rif_dock, favorable_1body_multiplier ) OPT_1GRP_KEY( Real , rif_dock, favorable_1body_multiplier_cutoff ) OPT_1GRP_KEY( Real , rif_dock, favorable_2body_multiplier ) OPT_1GRP_KEY( Integer , rif_dock, rotrf_oversample ) OPT_1GRP_KEY( Real , rif_dock, rotrf_resl ) OPT_1GRP_KEY( Real , rif_dock, rotrf_spread ) OPT_1GRP_KEY( Real , rif_dock, rotrf_scale_atr ) OPT_1GRP_KEY( String , rif_dock, rotrf_cache_dir ) OPT_1GRP_KEY( Boolean , rif_dock, hack_pack ) OPT_1GRP_KEY( Boolean , rif_dock, hack_pack_during_hsearch ) OPT_1GRP_KEY( Real , rif_dock, hack_pack_frac ) OPT_1GRP_KEY( Real , rif_dock, pack_iter_mult ) OPT_1GRP_KEY( Integer , rif_dock, pack_n_iters ) OPT_1GRP_KEY( Real , rif_dock, hbond_weight ) OPT_1GRP_KEY( Real , rif_dock, upweight_multi_hbond ) OPT_1GRP_KEY( Real , rif_dock, min_hb_quality_for_satisfaction ) OPT_1GRP_KEY( Real , rif_dock, long_hbond_fudge_distance ) OPT_1GRP_KEY( Real , rif_dock, global_score_cut ) OPT_1GRP_KEY( Real , rif_dock, redundancy_filter_mag ) OPT_1GRP_KEY( Boolean , rif_dock, filter_seeding_positions_separately ) OPT_1GRP_KEY( Boolean , rif_dock, filter_scaffolds_separately ) OPT_1GRP_KEY( Real , rif_dock, force_output_if_close_to_input ) OPT_1GRP_KEY( Integer , rif_dock, force_output_if_close_to_input_num ) OPT_1GRP_KEY( Real , rif_dock, upweight_iface ) OPT_1GRP_KEY( Boolean , rif_dock, use_scaffold_bounding_grids ) OPT_1GRP_KEY( Boolean , rif_dock, restrict_to_native_scaffold_res ) OPT_1GRP_KEY( Real , rif_dock, bonus_to_native_scaffold_res ) OPT_1GRP_KEY( Boolean , rif_dock, add_native_scaffold_rots_when_packing ) OPT_1GRP_KEY( Boolean , rif_dock, dump_all_rif_rots ) OPT_1GRP_KEY( Boolean , rif_dock, dump_all_rif_rots_into_output ) OPT_1GRP_KEY( Boolean , rif_dock, rif_rots_as_chains ) OPT_1GRP_KEY( String , rif_dock, dump_rifgen_near_pdb ) OPT_1GRP_KEY( Real , rif_dock, dump_rifgen_near_pdb_dist ) OPT_1GRP_KEY( Real , rif_dock, dump_rifgen_near_pdb_frac ) OPT_1GRP_KEY( Boolean , rif_dock, dump_rifgen_text ) OPT_1GRP_KEY( String , rif_dock, score_this_pdb ) OPT_1GRP_KEY( String , rif_dock, dump_pdb_at_bin_center ) OPT_1GRP_KEY( String , rif_dock, dokfile ) OPT_1GRP_KEY( String , rif_dock, outdir ) OPT_1GRP_KEY( String , rif_dock, output_tag ) OPT_1GRP_KEY( Boolean , rif_dock, dont_use_scaffold_loops ) OPT_1GRP_KEY( Boolean , rif_dock, dump_resfile ) OPT_1GRP_KEY( Boolean , rif_dock, pdb_info_pikaa ) OPT_1GRP_KEY( Boolean , rif_dock, cache_scaffold_data ) OPT_1GRP_KEY( Real , rif_dock, tether_to_input_position ) OPT_1GRP_KEY( Boolean , rif_dock, lowres_sterics_cbonly ) OPT_1GRP_KEY( Integer , rif_dock, require_satisfaction ) OPT_1GRP_KEY( Integer , rif_dock, num_hotspots ) OPT_1GRP_KEY( Integer , rif_dock, require_n_rifres ) OPT_1GRP_KEY( Boolean , rif_dock, use_dl_mix_bb ) OPT_1GRP_KEY( Real , rif_dock, rosetta_score_fraction ) OPT_1GRP_KEY( Real , rif_dock, rosetta_score_then_min_below_thresh ) OPT_1GRP_KEY( Integer , rif_dock, rosetta_score_at_least ) OPT_1GRP_KEY( Integer , rif_dock, rosetta_score_at_most ) OPT_1GRP_KEY( Real , rif_dock, rosetta_min_fraction ) OPT_1GRP_KEY( Integer , rif_dock, rosetta_min_at_least ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_min_fix_target ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_min_targetbb ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_min_scaffoldbb ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_min_allbb ) OPT_1GRP_KEY( Real , rif_dock, rosetta_score_cut ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_hard_min ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_score_total ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_score_ddg_only ) OPT_1GRP_KEY( Real , rif_dock, rosetta_score_rifres_rifres_weight ) OPT_1GRP_KEY( Real , rif_dock, rosetta_score_rifres_scaffold_weight ) OPT_1GRP_KEY( String , rif_dock, rosetta_soft_score ) OPT_1GRP_KEY( String , rif_dock, rosetta_hard_score ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_filter_before ) OPT_1GRP_KEY( Integer , rif_dock, rosetta_filter_n_per_scaffold ) OPT_1GRP_KEY( Real , rif_dock, rosetta_filter_redundancy_mag ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_filter_even_if_no_score ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_debug_dump_scores ) OPT_1GRP_KEY( Boolean , rif_dock, rosetta_score_select_random ) OPT_1GRP_KEY( Boolean , rif_dock, extra_rotamers ) OPT_1GRP_KEY( Boolean , rif_dock, extra_rif_rotamers ) OPT_1GRP_KEY( Integer , rif_dock, always_available_rotamers_level ) OPT_1GRP_KEY( Boolean , rif_dock, packing_use_rif_rotamers ) OPT_1GRP_KEY( Integer , rif_dock, nfold_symmetry ) OPT_1GRP_KEY( RealVector , rif_dock, symmetry_axis ) OPT_1GRP_KEY( Real , rif_dock, user_rotamer_bonus_constant ) OPT_1GRP_KEY( Real , rif_dock, user_rotamer_bonus_per_chi ) OPT_1GRP_KEY( Real , rif_dock, resl0 ) OPT_1GRP_KEY( Integer , rif_dock, dump_x_frames_per_resl ) OPT_1GRP_KEY( Boolean , rif_dock, dump_only_best_frames ) OPT_1GRP_KEY( Integer , rif_dock, dump_only_best_stride ) OPT_1GRP_KEY( String , rif_dock, dump_prefix ) OPT_1GRP_KEY( String , rif_dock, scaff_search_mode ) OPT_1GRP_KEY( String , rif_dock, nineA_cluster_path ) OPT_1GRP_KEY( String , rif_dock, nineA_baseline_range ) OPT_1GRP_KEY( Integer , rif_dock, low_cut_site ) OPT_1GRP_KEY( Integer , rif_dock, high_cut_site ) OPT_1GRP_KEY( Integer , rif_dock, max_insertion ) OPT_1GRP_KEY( Integer , rif_dock, max_deletion ) OPT_1GRP_KEY( Real , rif_dock, fragment_cluster_tolerance ) OPT_1GRP_KEY( Real , rif_dock, fragment_max_rmsd ) OPT_1GRP_KEY( Integer , rif_dock, max_fragments ) OPT_1GRP_KEY( StringVector, rif_dock, morph_rules_files ) OPT_1GRP_KEY( String , rif_dock, morph_silent_file ) OPT_1GRP_KEY( String , rif_dock, morph_silent_archetype ) OPT_1GRP_KEY( Real , rif_dock, morph_silent_max_structures ) OPT_1GRP_KEY( Boolean , rif_dock, morph_silent_random_selection ) OPT_1GRP_KEY( Real , rif_dock, morph_silent_cluster_use_frac ) OPT_1GRP_KEY( Boolean , rif_dock, include_parent ) OPT_1GRP_KEY( Boolean , rif_dock, use_parent_body_energies ) OPT_1GRP_KEY( Integer , rif_dock, dive_resl ) OPT_1GRP_KEY( Integer , rif_dock, pop_resl ) OPT_1GRP_KEY( String , rif_dock, match_this_pdb ) OPT_1GRP_KEY( Real , rif_dock, match_this_rmsd ) OPT_1GRP_KEY( String , rif_dock, rot_spec_fname ) // constrain file OPT_1GRP_KEY( StringVector, rif_dock, cst_files ) OPT_1GRP_KEY( StringVector, rif_dock, seed_with_these_pdbs ) OPT_1GRP_KEY( Boolean , rif_dock, seed_include_input ) OPT_1GRP_KEY( StringVector, rif_dock, seeding_pos ) OPT_1GRP_KEY( Boolean , rif_dock, seeding_by_patchdock ) OPT_1GRP_KEY( String , rif_dock, xform_pos ) OPT_1GRP_KEY( Integer , rif_dock, rosetta_score_each_seeding_at_least ) OPT_1GRP_KEY( Real , rif_dock, cluster_score_cut ) OPT_1GRP_KEY( Real , rif_dock, keep_top_clusters_frac ) OPT_1GRP_KEY( Real , rif_dock, unsat_orbital_penalty ) OPT_1GRP_KEY( Real , rif_dock, neighbor_distance_cutoff ) OPT_1GRP_KEY( Integer , rif_dock, unsat_neighbor_cutoff ) OPT_1GRP_KEY( Boolean , rif_dock, unsat_debug ) OPT_1GRP_KEY( Boolean , rif_dock, test_hackpack ) OPT_1GRP_KEY( String , rif_dock, unsat_helper ) OPT_1GRP_KEY( Real , rif_dock, unsat_score_offset ) OPT_1GRP_KEY( Integer , rif_dock, unsat_require_burial ) OPT_1GRP_KEY( Boolean , rif_dock, report_common_unsats ) OPT_1GRP_KEY( Boolean , rif_dock, dump_presatisfied_donors_acceptors ) OPT_1GRP_KEY( IntegerVector, rif_dock, requirements ) void register_options() { using namespace basic::options; using namespace basic::options::OptionKeys; NEW_OPT( rif_dock::scaffolds, "" , utility::vector1<std::string>() ); NEW_OPT( rif_dock::scaffold_res, "" , utility::vector1<std::string>() ); NEW_OPT( rif_dock::scaffold_res_fixed, "" , utility::vector1<std::string>() ); NEW_OPT( rif_dock::scaffold_res_use_best_guess, "" , false ); NEW_OPT( rif_dock::scaffold_to_ala, "" , false ); NEW_OPT( rif_dock::scaffold_to_ala_selonly, "" , true ); NEW_OPT( rif_dock::replace_orig_scaffold_res, "", true ); NEW_OPT( rif_dock::replace_all_with_ala_1bre, "" , false ); NEW_OPT( rif_dock::random_perturb_scaffold, "" , false ); NEW_OPT( rif_dock::target_bounding_xmaps, "" , utility::vector1<std::string>() ); NEW_OPT( rif_dock::target_pdb, "" , "" ); NEW_OPT( rif_dock::target_res, "" , "" ); NEW_OPT( rif_dock::target_rif, "" , "" ); NEW_OPT( rif_dock::target_rf_resl, "" , 0.25 ); NEW_OPT( rif_dock::target_rf_oversample, "" , 2 ); NEW_OPT( rif_dock::downscale_atr_by_hierarchy, "" , true ); NEW_OPT( rif_dock::favorable_1body_multiplier, "Anything with a one-body energy less than favorable_1body_cutoff gets multiplied by this", 1 ); NEW_OPT( rif_dock::favorable_1body_multiplier_cutoff, "Anything with a one-body energy less than this gets multiplied by favorable_1body_multiplier", 0 ); NEW_OPT( rif_dock::favorable_2body_multiplier, "Anything with a two-body energy less than 0 gets multiplied by this", 1 ); NEW_OPT( rif_dock::target_rf_cache, "" , "NO_CACHE_SPECIFIED_ON_COMMAND_LINE" ); NEW_OPT( rif_dock::target_donors, "", "" ); NEW_OPT( rif_dock::target_acceptors, "", "" ); NEW_OPT( rif_dock::only_load_highest_resl, "Only read in the highest resolution rif", false ); NEW_OPT( rif_dock::use_rosetta_grid_energies, "Use Frank's grid energies for scoring", false ); NEW_OPT( rif_dock::soft_rosetta_grid_energies, "Use soft option for grid energies", false ); NEW_OPT( rif_dock::data_cache_dir, "" , utility::vector1<std::string>(1,"./") ); NEW_OPT( rif_dock::beam_size_M, "" , 10.000000 ); NEW_OPT( rif_dock::max_beam_multiplier, "Maximum beam multiplier", 1 ); NEW_OPT( rif_dock::multiply_beam_by_seeding_positions, "Multiply beam size by number of seeding positions", false); NEW_OPT( rif_dock::multiply_beam_by_scaffolds, "Multiply beam size by number of scaffolds", true); NEW_OPT( rif_dock::max_rf_bounding_ratio, "" , 4 ); NEW_OPT( rif_dock::make_bounding_plot_data, "" , false ); NEW_OPT( rif_dock::align_output_to_scaffold, "" , false ); NEW_OPT( rif_dock::output_scaffold_only, "" , false ); NEW_OPT( rif_dock::output_full_scaffold_only, "" , false ); NEW_OPT( rif_dock::output_full_scaffold, "", false ); NEW_OPT( rif_dock::n_pdb_out, "" , 10 ); NEW_OPT( rif_dock::rf_resl, "" , 0.25 ); NEW_OPT( rif_dock::rf_oversample, "" , 2 ); NEW_OPT( rif_dock::rotrf_oversample, "" , 2 ); NEW_OPT( rif_dock::rotrf_resl, "" , 0.3 ); NEW_OPT( rif_dock::rotrf_spread, "" , 0.0 ); NEW_OPT( rif_dock::rotrf_scale_atr, "" , 1.0 ); NEW_OPT( rif_dock::rotrf_cache_dir, "" , "./" ); NEW_OPT( rif_dock::hack_pack, "" , true ); NEW_OPT( rif_dock::hack_pack_during_hsearch, "hackpack during hsearch", false ); NEW_OPT( rif_dock::hack_pack_frac, "" , 0.2 ); NEW_OPT( rif_dock::pack_iter_mult, "" , 2.0 ); NEW_OPT( rif_dock::pack_n_iters, "" , 1 ); NEW_OPT( rif_dock::hbond_weight, "" , 2.0 ); NEW_OPT( rif_dock::upweight_multi_hbond, "" , 0.0 ); NEW_OPT( rif_dock::min_hb_quality_for_satisfaction, "Minimum fraction of total hbond energy required for satisfaction. Scale -1 to 0", -0.6 ); NEW_OPT( rif_dock::long_hbond_fudge_distance, "Any hbond longer than 2A gets moved closer to 2A by this amount for scoring", 0.0 ); NEW_OPT( rif_dock::global_score_cut, "" , 0.0 ); NEW_OPT( rif_dock::redundancy_filter_mag, "" , 1.0 ); NEW_OPT( rif_dock::filter_seeding_positions_separately, "Redundancy filter each seeding position separately", true ); NEW_OPT( rif_dock::filter_scaffolds_separately, "Redundancy filter each scaffold separately", true ); NEW_OPT( rif_dock::force_output_if_close_to_input, "" , 1.0 ); NEW_OPT( rif_dock::force_output_if_close_to_input_num, "" , 0 ); NEW_OPT( rif_dock::upweight_iface, "", 1.2 ); NEW_OPT( rif_dock::use_scaffold_bounding_grids, "", false ); NEW_OPT( rif_dock::search_diameter, "", 150.0 ); NEW_OPT( rif_dock::hsearch_scale_factor, "global scaling of rotation/translation search grid", 1.0 ); NEW_OPT( rif_dock::restrict_to_native_scaffold_res, "aka structure prediction CHEAT", false ); NEW_OPT( rif_dock::bonus_to_native_scaffold_res, "aka favor native CHEAT", -0.3 ); NEW_OPT( rif_dock::add_native_scaffold_rots_when_packing, "CHEAT", false ); NEW_OPT( rif_dock::dump_all_rif_rots, "", false ); NEW_OPT( rif_dock::dump_all_rif_rots_into_output, "dump all rif rots into output", false); NEW_OPT( rif_dock::rif_rots_as_chains, "dump rif rots as chains instead of models, loses resnum if true", false ); NEW_OPT( rif_dock::dump_rifgen_near_pdb, "dump rifgen rotamers with same AA type near this single residue", ""); NEW_OPT( rif_dock::dump_rifgen_near_pdb_dist, "", 1 ); NEW_OPT( rif_dock::dump_rifgen_near_pdb_frac, "", 1 ); NEW_OPT( rif_dock::dump_rifgen_text, "Dump the rifgen tables within dump_rifgen_near_pdb_dist", false ); NEW_OPT( rif_dock::score_this_pdb, "Score every residue of this pdb using the rif scoring machinery", "" ); NEW_OPT( rif_dock::dump_pdb_at_bin_center, "Dump each residue of this pdb at the rotamer's bin center", "" ); NEW_OPT( rif_dock::dokfile, "", "default.dok" ); NEW_OPT( rif_dock::outdir, "", "./" ); NEW_OPT( rif_dock::output_tag, "", "" ); NEW_OPT( rif_dock::dont_use_scaffold_loops, "", false ); NEW_OPT( rif_dock::dump_resfile, "", false ); NEW_OPT( rif_dock::pdb_info_pikaa, "", false ); NEW_OPT( rif_dock::cache_scaffold_data, "", false ); NEW_OPT( rif_dock::tether_to_input_position, "", -1.0 ); NEW_OPT( rif_dock::lowres_sterics_cbonly, "", true ); NEW_OPT( rif_dock::require_satisfaction, "", 0 ); NEW_OPT( rif_dock::num_hotspots, "Number of hotspots found in Rifdock hotspots. If in doubt, set this to 1000", 0 ); NEW_OPT( rif_dock::require_n_rifres, "This doesn't work during HackPack", 0 ); NEW_OPT( rif_dock::use_dl_mix_bb, "use phi to decide where d is allow", false ); NEW_OPT( rif_dock::rosetta_score_fraction , "", 0.00 ); NEW_OPT( rif_dock::rosetta_score_then_min_below_thresh, "", -9e9 ); NEW_OPT( rif_dock::rosetta_score_at_least, "", -1 ); NEW_OPT( rif_dock::rosetta_score_at_most, "", 999999999 ); NEW_OPT( rif_dock::rosetta_min_fraction , "", 0.1 ); NEW_OPT( rif_dock::rosetta_min_at_least, "", -1 ); NEW_OPT( rif_dock::rosetta_min_targetbb , "", false ); NEW_OPT( rif_dock::rosetta_min_scaffoldbb , "", false ); NEW_OPT( rif_dock::rosetta_min_allbb , "", false ); NEW_OPT( rif_dock::rosetta_min_fix_target, "", false ); NEW_OPT( rif_dock::rosetta_score_cut , "", -10.0 ); NEW_OPT( rif_dock::rosetta_hard_min , "", false ); NEW_OPT( rif_dock::rosetta_score_total , "", false ); NEW_OPT( rif_dock::rosetta_score_ddg_only , "", false ); NEW_OPT( rif_dock::rosetta_score_rifres_rifres_weight, "", 0.75 ); NEW_OPT( rif_dock::rosetta_score_rifres_scaffold_weight, "", 0.5 ); NEW_OPT( rif_dock::rosetta_soft_score, "", "beta_soft" ); NEW_OPT( rif_dock::rosetta_hard_score, "", "beta" ); NEW_OPT( rif_dock::rosetta_filter_before, "redundancy filter results before rosetta score", false ); NEW_OPT( rif_dock::rosetta_filter_n_per_scaffold, "use with rosetta_filter_before, num to save per scaffold", 300); NEW_OPT( rif_dock::rosetta_filter_redundancy_mag, "use with rosetta_filter_before, redundancy mag on the clustering", 0.5); NEW_OPT( rif_dock::rosetta_filter_even_if_no_score, "Do the filtering for rosetta score and min even if you don't actually score/min", false ); NEW_OPT( rif_dock::rosetta_debug_dump_scores, "dump lists of scores around the rosetta score and min", false); NEW_OPT( rif_dock::rosetta_score_select_random, "Select random positions to score rather than best", false); NEW_OPT( rif_dock::extra_rotamers, "", true ); NEW_OPT( rif_dock::extra_rif_rotamers, "", true ); NEW_OPT( rif_dock::always_available_rotamers_level, "", 0 ); NEW_OPT( rif_dock::packing_use_rif_rotamers, "", true ); NEW_OPT( rif_dock::nfold_symmetry, "", 1 ); NEW_OPT( rif_dock::symmetry_axis, "", utility::vector1<double>() ); NEW_OPT( rif_dock::user_rotamer_bonus_constant, "", 0 ); NEW_OPT( rif_dock::user_rotamer_bonus_per_chi, "", 0 ); NEW_OPT( rif_dock::resl0, "", 16 ); NEW_OPT( rif_dock::dump_x_frames_per_resl, "Use this to make a movie", 0 ); NEW_OPT( rif_dock::dump_only_best_frames, "Only dump the best frames for the movie", false ); NEW_OPT( rif_dock::dump_only_best_stride, "When doing dump_only_best_frames, dump every Xth element of the best", 1 ); NEW_OPT( rif_dock::dump_prefix, "Convince Brian to make this autocreate the folder", "hsearch" ); NEW_OPT( rif_dock::scaff_search_mode, "Which scaffold mode and HSearch do you want? Options: default, morph_dive_pop, nineA_baseline", "default"); NEW_OPT( rif_dock::nineA_cluster_path, "Path to cluster database for nineA_baseline.", "" ); NEW_OPT( rif_dock::nineA_baseline_range, "format cdindex:low-high (python range style)", ""); NEW_OPT( rif_dock::low_cut_site, "The low cut point for fragment insertion, this res and the previous get minimized.", 0 ); NEW_OPT( rif_dock::high_cut_site, "The high cut point for fragment insertion, this res and the next get minimized.", 0 ); NEW_OPT( rif_dock::max_insertion, "Maximum number of residues to lengthen protein by.", 0 ); NEW_OPT( rif_dock::max_deletion, "Maximum number of residues to shorten protein by.", 0 ); NEW_OPT( rif_dock::fragment_cluster_tolerance, "RMSD cluster tolerance for fragments.", 0.5 ); NEW_OPT( rif_dock::fragment_max_rmsd , "Max RMSD to starting fragment.", 10000 ); NEW_OPT( rif_dock::max_fragments, "Maximum number of fragments to find.", 10000000 ); NEW_OPT( rif_dock::morph_rules_files, "List of files for each scaffold to specify morph regions", utility::vector1<std::string>() ); NEW_OPT( rif_dock::morph_silent_file, "Silent file containing pre-morphed structures. Overrides other options", "" ); NEW_OPT( rif_dock::morph_silent_archetype, "PDB to calculate transform difference between input position and silent file", "" ); NEW_OPT( rif_dock::morph_silent_max_structures, "Cluster silent file into this many cluster centers", 1000000000 ); NEW_OPT( rif_dock::morph_silent_random_selection, "Use random picks instead of clustering to limit silent file", false ); NEW_OPT( rif_dock::morph_silent_cluster_use_frac, "Cluster and take the top clusters that make up this frac of total", 1 ); NEW_OPT( rif_dock::include_parent, "Include parent fragment in diversified scaffolds.", false ); NEW_OPT( rif_dock::use_parent_body_energies, "Don't recalculate 1-/2-body energies for fragment insertions", false ); NEW_OPT( rif_dock::dive_resl , "Dive to this depth before diversifying", 5 ); NEW_OPT( rif_dock::pop_resl , "Return to this depth after diversifying", 4 ); NEW_OPT( rif_dock::match_this_pdb, "Like tether to input position but applied at diversification time.", "" ); NEW_OPT( rif_dock::match_this_rmsd, "RMSD for match_this_pdb", 7 ); NEW_OPT( rif_dock::rot_spec_fname,"rot_spec_fname","NOT SPECIFIED"); // constrain file names NEW_OPT( rif_dock::cst_files, "" , utility::vector1<std::string>() ); NEW_OPT( rif_dock::seed_with_these_pdbs, "Use these pdbs as seeding positions, use this with tether_to_input_position", utility::vector1<std::string>() ); NEW_OPT( rif_dock::seed_include_input, "Include the input scaffold as a seeding position in seed_with_these_pdbs", true ); NEW_OPT( rif_dock::seeding_pos, "" , utility::vector1<std::string>() ); NEW_OPT( rif_dock::seeding_by_patchdock, "The format of seeding file can be either Rosetta Xform or raw patchdock outputs", true ); NEW_OPT( rif_dock::xform_pos, "" , "" ); NEW_OPT( rif_dock::rosetta_score_each_seeding_at_least, "", -1 ); NEW_OPT( rif_dock::cluster_score_cut, "", 0); NEW_OPT( rif_dock::keep_top_clusters_frac, "", 0.5); NEW_OPT( rif_dock::unsat_orbital_penalty, "temp", 0 ); NEW_OPT( rif_dock::neighbor_distance_cutoff, "temp", 6.0 ); NEW_OPT( rif_dock::unsat_neighbor_cutoff, "temp", 6 ); NEW_OPT( rif_dock::unsat_debug, "Dump debug info from unsat calculations", false ); NEW_OPT( rif_dock::test_hackpack, "Test the packing objective in the original position too", false ); NEW_OPT( rif_dock::unsat_helper, "Helper file for use with unsats", "" ); NEW_OPT( rif_dock::unsat_score_offset, "This gets added to the score of all designs", 0.0 ); NEW_OPT( rif_dock::unsat_require_burial, "Require at least this many polar atoms be buried", 0 ); NEW_OPT( rif_dock::report_common_unsats, "Show probability of burying every unsat", false ); NEW_OPT( rif_dock::dump_presatisfied_donors_acceptors, "Dump the presatisifed donors and acceptors", false ); NEW_OPT( rif_dock::requirements, "which rif residue should be in the final output", utility::vector1< int >()); } #endif #endif #ifndef INCLUDED_rif_dock_test_hh_3 #define INCLUDED_rif_dock_test_hh_3 struct RifDockOpt { std::vector<std::string> scaffold_fnames; std::vector<std::string> scaffold_res_fnames; std::vector<std::string> data_cache_path; std::vector<std::string> rif_files; bool VERBOSE ; double resl0 ; int64_t DIM ; int64_t DIMPOW2 ; int64_t beam_size ; float max_beam_multiplier ; bool multiply_beam_by_seeding_positions ; bool multiply_beam_by_scaffolds ; bool replace_all_with_ala_1bre ; bool lowres_sterics_cbonly ; float tether_to_input_position_cut ; bool tether_to_input_position ; float global_score_cut ; std::string target_pdb ; std::string outdir ; std::string output_tag ; std::string dokfile_fname ; bool dump_all_rif_rots ; bool dump_all_rif_rots_into_output ; bool rif_rots_as_chains ; std::string dump_rifgen_near_pdb ; float dump_rifgen_near_pdb_dist ; float dump_rifgen_near_pdb_frac ; bool dump_rifgen_text ; std::string score_this_pdb ; std::string dump_pdb_at_bin_center ; bool add_native_scaffold_rots_when_packing; bool restrict_to_native_scaffold_res ; float bonus_to_native_scaffold_res ; float hack_pack_frac ; float hsearch_scale_factor ; float search_diameter ; bool use_scaffold_bounding_grids ; bool scaffold_res_use_best_guess ; bool scaff2ala ; bool scaff2alaselonly ; bool replace_orig_scaffold_res ; int require_satisfaction ; int num_hotspots ; int require_n_rifres ; bool use_dl_mix_bb ; float target_rf_resl ; bool align_to_scaffold ; bool output_scaffold_only ; bool output_full_scaffold_only ; bool output_full_scaffold ; bool pdb_info_pikaa ; bool dump_resfile ; std::string target_res_fname ; int target_rf_oversample ; float max_rf_bounding_ratio ; std::string target_rf_cache ; std::string target_donors ; std::string target_acceptors ; bool only_load_highest_resl ; bool use_rosetta_grid_energies ; bool soft_rosetta_grid_energies ; bool downscale_atr_by_hierarchy ; float favorable_1body_multiplier ; float favorable_1body_multiplier_cutoff ; float favorable_2body_multiplier ; bool random_perturb_scaffold ; bool dont_use_scaffold_loops ; bool cache_scaffold_data ; float rf_resl ; bool hack_pack ; bool hack_pack_during_hsearch ; int rf_oversample ; int rotrf_oversample ; float rotrf_resl ; float rotrf_spread ; std::string rotrf_cache_dir ; float rotrf_scale_atr ; float pack_iter_mult ; int pack_n_iters ; float hbond_weight ; float upweight_iface ; float upweight_multi_hbond ; float min_hb_quality_for_satisfaction ; float long_hbond_fudge_distance ; float redundancy_filter_mag ; bool filter_seeding_positions_separately ; bool filter_scaffolds_separately ; int force_output_if_close_to_input_num ; float force_output_if_close_to_input ; int n_pdb_out ; bool extra_rotamers ; bool extra_rif_rotamers ; int always_available_rotamers_level ; int packing_use_rif_rotamers ; float rosetta_score_fraction ; float rosetta_score_then_min_below_thresh ; float rosetta_score_at_least ; float rosetta_score_at_most ; float rosetta_min_fraction ; int rosetta_min_at_least ; bool rosetta_min_fix_target ; bool rosetta_min_targetbb ; bool rosetta_min_scaffoldbb ; bool rosetta_min_allbb ; float rosetta_score_cut ; float rosetta_hard_min ; bool rosetta_score_total ; bool rosetta_score_ddg_only ; float rosetta_score_rifres_rifres_weight ; float rosetta_score_rifres_scaffold_weight ; bool rosetta_beta ; std::string rosetta_soft_score ; std::string rosetta_hard_score ; bool rosetta_filter_before ; int rosetta_filter_n_per_scaffold ; float rosetta_filter_redundancy_mag ; bool rosetta_filter_even_if_no_score ; bool rosetta_debug_dump_scores ; bool rosetta_score_select_random ; int nfold_symmetry ; std::vector<float> symmetry_axis ; float user_rotamer_bonus_constant ; float user_rotamer_bonus_per_chi ; int dump_x_frames_per_resl ; bool dump_only_best_frames ; int dump_only_best_stride ; std::string dump_prefix ; std::string scaff_search_mode ; std::string nineA_cluster_path ; std::string nineA_baseline_range ; int low_cut_site ; int high_cut_site ; int max_insertion ; int max_deletion ; float fragment_cluster_tolerance ; float fragment_max_rmsd ; int max_fragments ; std::vector<std::string> morph_rules_fnames ; std::string morph_silent_file ; std::string morph_silent_archetype ; int morph_silent_max_structures ; bool morph_silent_random_selection ; float morph_silent_cluster_use_frac ; bool include_parent ; bool use_parent_body_energies ; int dive_resl ; int pop_resl ; std::string match_this_pdb ; float match_this_rmsd ; std::string rot_spec_fname ; // constrain file names std::vector<std::string> cst_fnames ; std::vector<std::string> seed_with_these_pdbs ; bool seed_include_input ; std::vector<std::string> seeding_fnames ; std::string xform_fname ; float rosetta_score_each_seeding_at_least ; float cluster_score_cut ; float keep_top_clusters_frac ; bool seeding_by_patchdock ; float unsat_orbital_penalty ; float neighbor_distance_cutoff ; int unsat_neighbor_cutoff ; bool unsat_debug ; bool test_hackpack ; std::string unsat_helper ; float unsat_score_offset ; int unsat_require_burial ; bool report_common_unsats ; bool dump_presatisfied_donors_acceptors ; std::vector<int> requirements; void init_from_cli(); }; #endif #ifdef GLOBAL_VARIABLES_ARE_BAD #ifndef INCLUDED_rif_dock_test_hh_4 #define INCLUDED_rif_dock_test_hh_4 void RifDockOpt::init_from_cli() { using basic::options::option; using namespace basic::options::OptionKeys; runtime_assert( option[rif_dock::target_rif].user() ); VERBOSE = false; resl0 = option[rif_dock::resl0 ](); DIM = 6; DIMPOW2 = 1<<DIM; beam_size = int64_t( option[rif_dock::beam_size_M]() * 1000000.0 / DIMPOW2 ) * DIMPOW2; max_beam_multiplier = option[rif_dock::max_beam_multiplier ](); multiply_beam_by_seeding_positions = option[rif_dock::multiply_beam_by_seeding_positions ](); multiply_beam_by_scaffolds = option[rif_dock::multiply_beam_by_scaffolds ](); replace_all_with_ala_1bre = option[rif_dock::replace_all_with_ala_1bre ](); target_pdb = option[rif_dock::target_pdb ](); lowres_sterics_cbonly = option[rif_dock::lowres_sterics_cbonly ](); tether_to_input_position_cut = option[rif_dock::tether_to_input_position ](); tether_to_input_position = tether_to_input_position_cut > 0.0; global_score_cut = option[rif_dock::global_score_cut ](); outdir = option[rif_dock::outdir ](); output_tag = option[rif_dock::output_tag ](); dokfile_fname = outdir + "/" + option[rif_dock::dokfile ](); dump_all_rif_rots = option[rif_dock::dump_all_rif_rots ](); dump_all_rif_rots_into_output = option[rif_dock::dump_all_rif_rots_into_output ](); rif_rots_as_chains = option[rif_dock::rif_rots_as_chains ](); dump_rifgen_near_pdb = option[rif_dock::dump_rifgen_near_pdb ](); dump_rifgen_near_pdb_dist = option[rif_dock::dump_rifgen_near_pdb_dist ](); dump_rifgen_near_pdb_frac = option[rif_dock::dump_rifgen_near_pdb_frac ](); dump_rifgen_text = option[rif_dock::dump_rifgen_text ](); score_this_pdb = option[rif_dock::score_this_pdb ](); dump_pdb_at_bin_center = option[rif_dock::dump_pdb_at_bin_center ](); add_native_scaffold_rots_when_packing = option[rif_dock::add_native_scaffold_rots_when_packing ](); restrict_to_native_scaffold_res = option[rif_dock::restrict_to_native_scaffold_res ](); bonus_to_native_scaffold_res = option[rif_dock::bonus_to_native_scaffold_res ](); hack_pack_frac = option[rif_dock::hack_pack_frac ](); hsearch_scale_factor = option[rif_dock::hsearch_scale_factor ](); search_diameter = option[rif_dock::search_diameter ](); use_scaffold_bounding_grids = option[rif_dock::use_scaffold_bounding_grids ](); scaffold_res_use_best_guess = option[rif_dock::scaffold_res_use_best_guess ](); scaff2ala = option[rif_dock::scaffold_to_ala ](); scaff2alaselonly = option[rif_dock::scaffold_to_ala_selonly ](); replace_orig_scaffold_res = option[rif_dock::replace_orig_scaffold_res ](); require_satisfaction = option[rif_dock::require_satisfaction ](); num_hotspots = option[rif_dock::num_hotspots ](); require_n_rifres = option[rif_dock::require_n_rifres ](); use_dl_mix_bb = option[rif_dock::use_dl_mix_bb ](); target_rf_resl = option[rif_dock::target_rf_resl ](); align_to_scaffold = option[rif_dock::align_output_to_scaffold ](); output_scaffold_only = option[rif_dock::output_scaffold_only ](); output_full_scaffold_only = option[rif_dock::output_full_scaffold_only ](); output_full_scaffold = option[rif_dock::output_full_scaffold ](); pdb_info_pikaa = option[rif_dock::pdb_info_pikaa ](); dump_resfile = option[rif_dock::dump_resfile ](); target_res_fname = option[rif_dock::target_res ](); target_rf_oversample = option[rif_dock::target_rf_oversample ](); max_rf_bounding_ratio = option[rif_dock::max_rf_bounding_ratio ](); target_rf_cache = option[rif_dock::target_rf_cache ](); target_donors = option[rif_dock::target_donors ](); target_acceptors = option[rif_dock::target_acceptors ](); only_load_highest_resl = option[rif_dock::only_load_highest_resl ](); use_rosetta_grid_energies = option[rif_dock::use_rosetta_grid_energies ](); soft_rosetta_grid_energies = option[rif_dock::soft_rosetta_grid_energies ](); downscale_atr_by_hierarchy = option[rif_dock::downscale_atr_by_hierarchy ](); favorable_1body_multiplier = option[rif_dock::favorable_1body_multiplier ](); favorable_1body_multiplier_cutoff = option[rif_dock::favorable_1body_multiplier_cutoff ](); favorable_2body_multiplier = option[rif_dock::favorable_2body_multiplier ](); random_perturb_scaffold = option[rif_dock::random_perturb_scaffold ](); dont_use_scaffold_loops = option[rif_dock::dont_use_scaffold_loops ](); cache_scaffold_data = option[rif_dock::cache_scaffold_data ](); rf_resl = option[rif_dock::rf_resl ](); hack_pack = option[rif_dock::hack_pack ](); hack_pack_during_hsearch = option[rif_dock::hack_pack_during_hsearch ](); rf_oversample = option[rif_dock::rf_oversample ](); redundancy_filter_mag = option[rif_dock::redundancy_filter_mag ](); filter_seeding_positions_separately = option[rif_dock::filter_seeding_positions_separately ](); filter_scaffolds_separately = option[rif_dock::filter_scaffolds_separately ](); rotrf_oversample = option[rif_dock::rotrf_oversample ](); rotrf_resl = option[rif_dock::rotrf_resl ](); rotrf_spread = option[rif_dock::rotrf_spread ](); rotrf_cache_dir = option[rif_dock::rotrf_cache_dir ](); rotrf_scale_atr = option[rif_dock::rotrf_scale_atr ](); pack_iter_mult = option[rif_dock::pack_iter_mult ](); pack_n_iters = option[rif_dock::pack_n_iters ](); hbond_weight = option[rif_dock::hbond_weight ](); upweight_iface = option[rif_dock::upweight_iface ](); upweight_multi_hbond = option[rif_dock::upweight_multi_hbond ](); min_hb_quality_for_satisfaction = option[rif_dock::min_hb_quality_for_satisfaction ](); long_hbond_fudge_distance = option[rif_dock::long_hbond_fudge_distance ](); redundancy_filter_mag = option[rif_dock::redundancy_filter_mag ](); force_output_if_close_to_input_num = option[rif_dock::force_output_if_close_to_input_num ](); force_output_if_close_to_input = option[rif_dock::force_output_if_close_to_input ](); n_pdb_out = option[rif_dock::n_pdb_out ](); extra_rotamers = option[rif_dock::extra_rotamers ](); extra_rif_rotamers = option[rif_dock::extra_rif_rotamers ](); always_available_rotamers_level = option[rif_dock::always_available_rotamers_level ](); packing_use_rif_rotamers = option[rif_dock::packing_use_rif_rotamers ](); rosetta_score_fraction = option[rif_dock::rosetta_score_fraction ](); rosetta_score_then_min_below_thresh = option[rif_dock::rosetta_score_then_min_below_thresh ](); rosetta_score_at_least = option[rif_dock::rosetta_score_at_least ](); rosetta_score_at_most = option[rif_dock::rosetta_score_at_most ](); rosetta_min_fraction = option[rif_dock::rosetta_min_fraction ](); rosetta_min_at_least = option[rif_dock::rosetta_min_at_least ](); rosetta_min_fix_target = option[rif_dock::rosetta_min_fix_target ](); rosetta_min_targetbb = option[rif_dock::rosetta_min_targetbb ](); rosetta_min_scaffoldbb = option[rif_dock::rosetta_min_scaffoldbb ](); rosetta_min_allbb = option[rif_dock::rosetta_min_allbb ](); rosetta_score_cut = option[rif_dock::rosetta_score_cut ](); rosetta_hard_min = option[rif_dock::rosetta_hard_min ](); rosetta_score_total = option[rif_dock::rosetta_score_total ](); rosetta_score_ddg_only = option[rif_dock::rosetta_score_ddg_only ](); rosetta_score_rifres_rifres_weight = option[rif_dock::rosetta_score_rifres_rifres_weight ](); rosetta_score_rifres_scaffold_weight = option[rif_dock::rosetta_score_rifres_scaffold_weight ](); rosetta_soft_score = option[rif_dock::rosetta_soft_score ](); rosetta_hard_score = option[rif_dock::rosetta_hard_score ](); rosetta_beta = option[corrections::beta ](); rosetta_filter_before = option[rif_dock::rosetta_filter_before ](); rosetta_filter_n_per_scaffold = option[rif_dock::rosetta_filter_n_per_scaffold ](); rosetta_filter_redundancy_mag = option[rif_dock::rosetta_filter_redundancy_mag ](); rosetta_filter_even_if_no_score = option[rif_dock::rosetta_filter_even_if_no_score ](); user_rotamer_bonus_constant = option[rif_dock::user_rotamer_bonus_constant ](); user_rotamer_bonus_per_chi = option[rif_dock::user_rotamer_bonus_per_chi ](); rosetta_debug_dump_scores = option[rif_dock::rosetta_debug_dump_scores ](); rosetta_score_select_random = option[rif_dock::rosetta_score_select_random ](); dump_x_frames_per_resl = option[rif_dock::dump_x_frames_per_resl ](); dump_only_best_frames = option[rif_dock::dump_only_best_frames ](); dump_only_best_stride = option[rif_dock::dump_only_best_stride ](); dump_prefix = option[rif_dock::dump_prefix ](); scaff_search_mode = option[rif_dock::scaff_search_mode ](); nineA_cluster_path = option[rif_dock::nineA_cluster_path ](); nineA_baseline_range = option[rif_dock::nineA_baseline_range ](); low_cut_site = option[rif_dock::low_cut_site ](); high_cut_site = option[rif_dock::high_cut_site ](); max_insertion = option[rif_dock::max_insertion ](); max_deletion = option[rif_dock::max_deletion ](); fragment_cluster_tolerance = option[rif_dock::fragment_cluster_tolerance ](); fragment_max_rmsd = option[rif_dock::fragment_max_rmsd ](); max_fragments = option[rif_dock::max_fragments ](); morph_silent_file = option[rif_dock::morph_silent_file ](); morph_silent_archetype = option[rif_dock::morph_silent_archetype ](); morph_silent_max_structures = option[rif_dock::morph_silent_max_structures ](); morph_silent_random_selection = option[rif_dock::morph_silent_random_selection ](); morph_silent_cluster_use_frac = option[rif_dock::morph_silent_cluster_use_frac ](); include_parent = option[rif_dock::include_parent ](); use_parent_body_energies = option[rif_dock::use_parent_body_energies ](); dive_resl = option[rif_dock::dive_resl ](); pop_resl = option[rif_dock::pop_resl ](); match_this_pdb = option[rif_dock::match_this_pdb ](); match_this_rmsd = option[rif_dock::match_this_rmsd ](); rot_spec_fname = option[rif_dock::rot_spec_fname ](); seed_include_input = option[rif_dock::seed_include_input ](); seeding_by_patchdock = option[rif_dock::seeding_by_patchdock ](); xform_fname = option[rif_dock::xform_pos ](); rosetta_score_each_seeding_at_least = option[rif_dock::rosetta_score_each_seeding_at_least ](); cluster_score_cut = option[rif_dock::cluster_score_cut ](); keep_top_clusters_frac = option[rif_dock::keep_top_clusters_frac ](); unsat_orbital_penalty = option[rif_dock::unsat_orbital_penalty ](); neighbor_distance_cutoff = option[rif_dock::neighbor_distance_cutoff ](); unsat_neighbor_cutoff = option[rif_dock::unsat_neighbor_cutoff ](); unsat_debug = option[rif_dock::unsat_debug ](); test_hackpack = option[rif_dock::test_hackpack ](); unsat_helper = option[rif_dock::unsat_helper ](); unsat_score_offset = option[rif_dock::unsat_score_offset ](); unsat_require_burial = option[rif_dock::unsat_require_burial ](); report_common_unsats = option[rif_dock::report_common_unsats ](); dump_presatisfied_donors_acceptors = option[rif_dock::dump_presatisfied_donors_acceptors ](); for( std::string s : option[rif_dock::scaffolds ]() ) scaffold_fnames.push_back(s); for( std::string s : option[rif_dock::scaffold_res ]() ) scaffold_res_fnames.push_back(s); for( std::string s : option[rif_dock::data_cache_dir]() ) data_cache_path.push_back(s); for( std::string fn : option[rif_dock::target_bounding_xmaps]() ) rif_files.push_back(fn); rif_files.push_back( option[rif_dock::target_rif]() ); if( scaff2ala && scaff2alaselonly && option[rif_dock::scaffold_to_ala_selonly].user() ){ std::cout << "WARNING: -scaffold_to_ala overrides -scaffold_to_ala_selonly!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << std::endl; } if( rosetta_score_total && rosetta_score_ddg_only ){ std::cout << "WARNING: rosetta_score_total overrives rosetta_score_ddg_only" << std::endl; rosetta_score_ddg_only = false; } runtime_assert_msg( min_hb_quality_for_satisfaction < 0 && min_hb_quality_for_satisfaction > -1, "-min_hb_quality_for_satisfaction must be between -1 and 0"); nfold_symmetry = option[rif_dock::nfold_symmetry](); symmetry_axis.clear(); if( option[rif_dock::symmetry_axis]().size() == 3 ){ symmetry_axis.push_back( option[rif_dock::symmetry_axis]()[1] ); symmetry_axis.push_back( option[rif_dock::symmetry_axis]()[2] ); symmetry_axis.push_back( option[rif_dock::symmetry_axis]()[3] ); } else if( option[rif_dock::symmetry_axis]().size() == 0 ){ symmetry_axis.push_back(0); symmetry_axis.push_back(0); symmetry_axis.push_back(1); } else { std::cout << "bad rif_dock::symmetry_axis option" << std::endl; std::exit(-1); } // Brian if (option[rif_dock::use_scaffold_bounding_grids]()) { std::cout << "ERROR: use_scaffold_bounding_grids no longer supported. Email bcov@uw.edu" << std::endl; std::exit(-1); } if (option[rif_dock::nfold_symmetry]() > 1) { std::cout << "ERROR: nfold_symmetry not currently supported. Email bcov@uw.edu" << std::endl; std::exit(-1); } if ( scaff_search_mode == "nineA_baseline" ) { if ( scaffold_fnames.size() > 0 ) { std::cout << "ERROR: can't use -scaffolds with nineA_baseline." << std::endl; std::exit(-1); } std::vector<uint64_t> cdindex_then_clusts = devel::scheme::parse_nineA_baseline_range( nineA_baseline_range ); uint64_t num_scaffolds = cdindex_then_clusts.size() - 1; runtime_assert( num_scaffolds > 0 ); scaffold_fnames.resize(num_scaffolds); } for( std::string s : option[rif_dock::morph_rules_files ]() ) morph_rules_fnames.push_back(s); // constrain file names for( std::string s : option[rif_dock::cst_files ]() ) cst_fnames.push_back(s); for( std::string s : option[rif_dock::seed_with_these_pdbs ]() ) seed_with_these_pdbs.push_back(s); for( std::string s : option[rif_dock::seeding_pos ]() ) seeding_fnames.push_back(s); for( int req : option[rif_dock::requirements]() ) requirements.push_back(req); } #endif #endif
58.648796
158
0.612406
f0cb289aca4dd19d69e868efc9e4137c98d0b056
1,771
cpp
C++
matlab/panoContext_code/Toolbox/segmentation/segmentGraphMex_edge.cpp
imamik/LayoutNet
f68eb214e793b9786f2582f9244bac4f8f98a816
[ "MIT" ]
380
2018-02-23T02:58:35.000Z
2022-03-21T06:34:33.000Z
matlab/panoContext_code/Toolbox/segmentation/segmentGraphMex_edge.cpp
imamik/LayoutNet
f68eb214e793b9786f2582f9244bac4f8f98a816
[ "MIT" ]
36
2018-04-11T03:49:42.000Z
2021-01-21T01:25:47.000Z
matlab/panoContext_code/Toolbox/segmentation/segmentGraphMex_edge.cpp
imamik/LayoutNet
f68eb214e793b9786f2582f9244bac4f8f98a816
[ "MIT" ]
94
2018-02-25T05:23:51.000Z
2022-02-11T02:00:47.000Z
#include <cstdio> #include <cstdlib> #include <image.h> #include <misc.h> #include <pnmfile.h> #include "mex.h" #include "segment-image.h" void mexFunction(int nlhs,mxArray* plhs[],int nrhs,const mxArray* prhs[]) { // check arguments if (nrhs != 5) { mexPrintf("Usage: [seg] = segmentGraphMex_edge(maxID, numEdge, edges, threshold, minSize);\n"); return; } // convert edges memory from matlab to c++ int maxID = (int)mxGetScalar(prhs[0]); int numEdge = (int)mxGetScalar(prhs[1]); double* edgeMat = (double*)mxGetData(prhs[2]); double c = mxGetScalar(prhs[3]); int min_size = (int)mxGetScalar(prhs[4]); printf("maxID: %d, numEdge: %d, c: %f, min_size: %d\n", maxID, numEdge, c, min_size); edge *edges = new edge[numEdge]; for( int i = 0; i<numEdge; i++) { edges[i].a = edgeMat[i*3+0]; edges[i].b = edgeMat[i*3+1]; edges[i].w = edgeMat[i*3+2]; } printf("a: %d, b: %d, w: %f\n", edges[0].a, edges[0].b, edges[0].w); printf("Loading finished!\n"); universe *u = segment_graph( maxID, numEdge, edges, c); printf("get out of segment_graph\n"); // post process for (int i = 0; i < numEdge; i++) { int a = u->find(edges[i].a); int b = u->find(edges[i].b); if ((a != b) && ((u->size(a) < min_size) || (u->size(b) < min_size))) u->join(a, b); } printf("finish post process\n"); // pass result to matlab plhs[0] = mxCreateNumericMatrix((mwSize)maxID, 1, mxDOUBLE_CLASS, mxREAL); double* output = (double *)mxGetData(plhs[0]); for (int i = 0; i<maxID; i++) { output[i] = (double)(u->find(i+1)); } printf("packed up output\n"); delete[] edges; printf("delete edges\n"); //delete u; printf("memory released\n"); }
29.516667
98
0.585545
f0cd16803c3887c2e9fc46e5b45ea987f4b0c6b2
8,806
cpp
C++
src/main.cpp
russellklenk/gwbase
eb4094b4cea29cd24612e88298efbdfbec1d59aa
[ "Unlicense" ]
3
2018-03-24T12:28:05.000Z
2021-07-29T02:00:16.000Z
src/main.cpp
russellklenk/gwbase
eb4094b4cea29cd24612e88298efbdfbec1d59aa
[ "Unlicense" ]
null
null
null
src/main.cpp
russellklenk/gwbase
eb4094b4cea29cd24612e88298efbdfbec1d59aa
[ "Unlicense" ]
1
2018-05-13T12:59:01.000Z
2018-05-13T12:59:01.000Z
/*///////////////////////////////////////////////////////////////////////////// /// @summary Implements the entry point of the application. This handles the /// setup of our third party libraries and the creation of our main window and /// rendering context, along with implementing the game loop. /// @author Russell Klenk (contact@russellklenk.com) ///////////////////////////////////////////////////////////////////////////80*/ /*//////////////// // Includes // ////////////////*/ #include <stdio.h> #include <stdlib.h> #include "math.hpp" #include "input.hpp" #include "display.hpp" #include "entity.hpp" #include "player.hpp" #include "ll_sprite.hpp" #include "ll_shader.hpp" /*///////////////// // Constants // /////////////////*/ #define GW_WINDOW_WIDTH 800 #define GW_WINDOW_HEIGHT 600 #define GW_WINDOW_TITLE "Geometry Wars" #define GW_MIN_TIMESTEP 0.000001 #define GW_MAX_TIMESTEP 0.25 #define GW_SIM_TIMESTEP 1.0 / 120.0 /*/////////////// // Globals // ///////////////*/ static EntityManager *gEntityManager = NULL; static DisplayManager *gDisplayManager = NULL; static InputManager *gInputManager = NULL; /*/////////////////////// // Local Functions // ///////////////////////*/ /// @summary Callback to handle a GLFW error. Prints the error information to stderr. /// @param error_code The internal GLFW error code. /// @param error_desc A textual description of the error. static void glfw_error(int error_code, char const *error_desc) { fprintf(stderr, "ERROR: (GLFW code 0x%08X): %s\n", error_code, error_desc); } #if GL_DEBUG_ENABLE /// @summary Callback to handle output from the GL_ARB_debug_output extension, /// which is of course not supported on OSX as of 10.9. /// @param source /// @param type /// @param id /// @param severity /// @param length /// @param message /// @param context static void gl_arb_debug( GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, char const *message, void *context) { UNUSED_ARG(source); UNUSED_ARG(type); UNUSED_ARG(id); UNUSED_ARG(severity); UNUSED_ARG(length); UNUSED_ARG(context); fprintf(stdout, "ARB_debug: %s\n", message); } #endif /// @summary Executes all of the logic associated with game user input. This /// is also where we would run user interface logic. Runs once per application tick. /// @param currentTime The current absolute time, in seconds. This represents /// the time at which the current tick started. /// @param elapsedTime The time elapsed since the previous tick, in seconds. static void input(double currentTime, double elapsedTime) { gInputManager->Update(currentTime, elapsedTime); gEntityManager->Input(currentTime, elapsedTime, gInputManager); } /// @summary Executes a single game simulation tick to move all game entities. /// Runs zero or more times per application tick at a fixed timestep. /// @param currentTime The current absolute simulation time, in seconds. This /// represents the time at which the current simulation tick started. /// @param elapsedTime The time elapsed since the previous tick, in seconds. static void simulate(double currentTime, double elapsedTime) { gEntityManager->Update(currentTime, elapsedTime); } /// @summary Submits a single frame to the GPU for rendering. Runs once per /// application tick at a variable timestep. /// @param currentTime The current absolute time, in seconds. This represents /// the time at which the current tick started. /// @param elapsedTime The time elapsed since the previous tick, in seconds. /// @param t A value in [0, 1] indicating how far into the current simulation /// step we are at the time the frame is generated. /// @param width The width of the default framebuffer, in pixels. /// @param height The height of the default framebuffer, in pixels. static void render(double currentTime, double elapsedTime, double t, int width, int height) { UNUSED_ARG(currentTime); UNUSED_ARG(elapsedTime); UNUSED_ARG(t); DisplayManager *dm = gDisplayManager; SpriteBatch *batch = dm->GetBatch(); SpriteFont *font = dm->GetFont(); float rgba[]= {1.0f, 0.0f, 0.0f, 1.0f}; dm->SetViewport(width, height); dm->Clear(0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0); dm->BeginFrame(); batch->SetBlendModeAlpha(); font->Draw("Hello, world!", 0, 0, 1, rgba, 5.0f, 5.0f, batch); gEntityManager->Draw(currentTime, elapsedTime, dm); dm->EndFrame(); } /*/////////////////////// // Public Functions // ///////////////////////*/ int main(int argc, char **argv) { GLFWwindow *window = NULL; UNUSED_ARG(argc); UNUSED_ARG(argv); // initialize GLFW, our platform abstraction library. glfwSetErrorCallback(glfw_error); if (!glfwInit()) { exit(EXIT_FAILURE); } glfwWindowHint(GLFW_VISIBLE, GL_TRUE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #if GL_DEBUG_ENABLE glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); #endif // create the main application window and OpenGL context. window = glfwCreateWindow(GW_WINDOW_WIDTH, GW_WINDOW_HEIGHT, GW_WINDOW_TITLE, NULL, NULL); if (window == NULL) { fprintf(stderr, "ERROR: Cannot create primary GLFW window.\n"); glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); // now that we have an OpenGL context, load extensions provided by the platform. // note that glewExperimental is defined by the GLEW library and is required on // OSX or the glGenVertexArrays() call will cause a fault. glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { fprintf(stderr, "ERROR: Cannot initialize GLEW for the primary context.\n"); glfwTerminate(); exit(EXIT_FAILURE); } // clear any OpenGL error status and configure debug output. glGetError(); #if GL_DEBUG_ENABLE if (GLEW_ARB_debug_output) { glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB); glDebugMessageCallbackARB(gl_arb_debug, NULL); } #endif // initialize global managers: gDisplayManager = new DisplayManager(); gDisplayManager->Init(window); gInputManager = new InputManager(); gInputManager->Init(window); Player *player = new Player(0); player->Init(gDisplayManager); gEntityManager = new EntityManager(); gEntityManager->AddEntity(player); // game loop setup and run: const double Step = GW_SIM_TIMESTEP; double previousTime = glfwGetTime(); double currentTime = previousTime; double elapsedTime = 0.0; double accumulator = 0.0; double simTime = 0.0; double t = 0.0; int width = 0; int height = 0; while (!glfwWindowShouldClose(window)) { // retrieve the current framebuffer size, which // may be different from the current window size. glfwGetFramebufferSize(window, &width, &height); // update the main game clock. previousTime = currentTime; currentTime = glfwGetTime(); elapsedTime = currentTime - previousTime; if (elapsedTime > GW_MAX_TIMESTEP) { elapsedTime = GW_MAX_TIMESTEP; } if (elapsedTime < GW_MIN_TIMESTEP) { elapsedTime = GW_MIN_TIMESTEP; } accumulator += elapsedTime; // process user input at the start of the frame. input(currentTime, elapsedTime); // execute the simulation zero or more times per-frame. // the simulation runs at a fixed timestep. while (accumulator >= Step) { // @todo: swap game state buffers here. // pass the current game state to simulate. simulate(simTime, Step); accumulator -= Step; simTime += Step; } // interpolate display state. t = accumulator / Step; // state = currentState * t + previousState * (1.0 - t); render(currentTime, elapsedTime, t, width, height); // now present the current frame and process OS events. glfwSwapBuffers(window); glfwPollEvents(); } // teardown global managers. delete gEntityManager; delete gDisplayManager; delete gInputManager; // perform any top-level cleanup. glfwTerminate(); exit(EXIT_SUCCESS); }
33.356061
94
0.650693
f0da524a8ee5f41b5b255973c45add652ae74843
473
cc
C++
src/core/logging_event.cc
pragkent/logbox
15274be0726cd3f0d71266a0ce4755106c8bdd1f
[ "MIT" ]
2
2015-02-14T04:24:07.000Z
2015-02-28T11:23:48.000Z
src/core/logging_event.cc
pragkent/logbox
15274be0726cd3f0d71266a0ce4755106c8bdd1f
[ "MIT" ]
null
null
null
src/core/logging_event.cc
pragkent/logbox
15274be0726cd3f0d71266a0ce4755106c8bdd1f
[ "MIT" ]
null
null
null
#include "core/logging_event.h" #include <errno.h> #include "util/environment.h" namespace logbox { LoggingEvent::LoggingEvent( LogSeverity severity, const char* file, int line, const char* function) : severity_(severity), file_fullname_(file), file_basename_(Environment::GetBasename(file)), line_no_(line), function_(function), preserved_errno_(errno), timestamp_(Environment::Now()) { } } // namespace logbox
20.565217
53
0.676533
f0da74da343d1e48921fbefea6fe4b456427bae7
1,197
cpp
C++
Code/System/Core/Time/Time.cpp
JuanluMorales/KRG
f3a11de469586a4ef0db835af4bc4589e6b70779
[ "MIT" ]
419
2022-01-27T19:37:43.000Z
2022-03-31T06:14:22.000Z
Code/System/Core/Time/Time.cpp
jagt/KRG
ba20cd8798997b0450491b0cc04dc817c4a4bc76
[ "MIT" ]
2
2022-01-28T20:35:33.000Z
2022-03-13T17:42:52.000Z
Code/System/Core/Time/Time.cpp
jagt/KRG
ba20cd8798997b0450491b0cc04dc817c4a4bc76
[ "MIT" ]
20
2022-01-27T20:41:02.000Z
2022-03-26T16:16:57.000Z
#include "Time.h" #include <chrono> //------------------------------------------------------------------------- namespace KRG { KRG::Nanoseconds EngineClock::CurrentTime = 0; //------------------------------------------------------------------------- Nanoseconds::operator Microseconds() const { auto const duration = std::chrono::duration<uint64, std::chrono::steady_clock::period>( m_value ); uint64 const numMicroseconds = std::chrono::duration_cast<std::chrono::microseconds>( duration ).count(); return float( numMicroseconds ); } //------------------------------------------------------------------------- Nanoseconds PlatformClock::GetTime() { auto const time = std::chrono::high_resolution_clock::now(); uint64 const numNanosecondsSinceEpoch = time.time_since_epoch().count(); return Nanoseconds( numNanosecondsSinceEpoch ); } //------------------------------------------------------------------------- void EngineClock::Update( Milliseconds deltaTime ) { KRG_ASSERT( deltaTime >= 0 ); CurrentTime += deltaTime.ToNanoseconds(); } }
34.2
114
0.472013
f0db14785a36f33ca7d2e246eff7183b9b3bb82d
215
cpp
C++
src/sysGCU/appThread.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
33
2021-12-08T11:10:59.000Z
2022-03-26T19:59:37.000Z
src/sysGCU/appThread.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
6
2021-12-22T17:54:31.000Z
2022-01-07T21:43:18.000Z
src/sysGCU/appThread.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
2
2022-01-04T06:00:49.000Z
2022-01-26T07:27:28.000Z
#include "types.h" #include "AppThread.h" /* * --INFO-- * Address: 80424E18 * Size: 00003C */ AppThread::AppThread(u32 stackSize, int msgCount, int priority) : JKRThread(stackSize, msgCount, priority) { }
15.357143
63
0.674419
f0ddf37d5a08322fefec7ff12c8b80b255fc02f5
370
cpp
C++
LeetCode/Problems/Algorithms/#762_PrimeNumberOfSetBitsInBinaryRepresentation_sol1_builtin_popcount_and_unordered_set_O(R-L)_time_O(1)_extra_space_40ms_6.5MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#762_PrimeNumberOfSetBitsInBinaryRepresentation_sol1_builtin_popcount_and_unordered_set_O(R-L)_time_O(1)_extra_space_40ms_6.5MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#762_PrimeNumberOfSetBitsInBinaryRepresentation_sol1_builtin_popcount_and_unordered_set_O(R-L)_time_O(1)_extra_space_40ms_6.5MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class Solution { public: int countPrimeSetBits(int L, int R) { const unordered_set<int> PRIMES = {2,3,5,7,11,13,17,19}; int answer = 0; for(int num = L; num <= R; ++num){ int setBitsCnt = __builtin_popcount(num); answer += (PRIMES.find(setBitsCnt) != PRIMES.end()); } return answer; } };
30.833333
65
0.524324
f0e175d7937cf22938a778b3d6a68b2e534d5321
44,217
hpp
C++
src/libraries/surfMesh/MeshedSurface/MeshedSurface.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/surfMesh/MeshedSurface/MeshedSurface.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/surfMesh/MeshedSurface/MeshedSurface.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2011-2015 OpenFOAM Foundation Copyright (C) 2015 Applied CCM ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CAELUS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CAELUS. If not, see <http://www.gnu.org/licenses/>. Class CML::MeshedSurface Description A surface geometry mesh with zone information, not to be confused with the similarly named surfaceMesh, which actually refers to the cell faces of a volume mesh. A MeshedSurface can have zero or more surface zones (roughly equivalent to faceZones for a polyMesh). If surface zones are defined, they must be contiguous and cover all of the faces. The MeshedSurface is intended for surfaces from a variety of sources. - A set of points and faces without any surface zone information. - A set of points and faces with randomly ordered zone information. This could arise, for example, from reading external file formats such as STL, etc. \*---------------------------------------------------------------------------*/ #ifndef MeshedSurface_H #define MeshedSurface_H #include "PrimitivePatch_.hpp" #include "PatchTools.hpp" #include "pointField.hpp" #include "face.hpp" #include "triFace.hpp" #include "surfZoneList.hpp" #include "surfaceFormatsCore.hpp" #include "runTimeSelectionTables.hpp" #include "memberFunctionSelectionTables.hpp" #include "HashSet.hpp" #include "boundBox.hpp" #include "Ostream.hpp" #include "UnsortedMeshedSurface.hpp" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace CML { // Forward declaration of friend functions and operators class Time; class surfMesh; class polyBoundaryMesh; template<class Face> class MeshedSurface; template<class Face> class MeshedSurfaceProxy; template<class Face> class UnsortedMeshedSurface; /*---------------------------------------------------------------------------*\ Class MeshedSurface Declaration \*---------------------------------------------------------------------------*/ template<class Face> class MeshedSurface : public PrimitivePatch<Face, ::CML::List, pointField, point>, public fileFormats::surfaceFormatsCore { // friends - despite different face representationsx template<class Face2> friend class MeshedSurface; template<class Face2> friend class UnsortedMeshedSurface; friend class surfMesh; private: // Private typedefs for convenience typedef PrimitivePatch < Face, ::CML::List, pointField, point > ParentType; typedef UnsortedMeshedSurface<Face> FriendType; typedef MeshedSurfaceProxy<Face> ProxyType; // Private Member Data //- Zone information // (face ordering nFaces/startFace only used during reading/writing) List<surfZone> zones_; protected: // Protected Member functions //- Transfer points/zones and transcribe face -> triFace void transcribe(MeshedSurface<face>&); //- basic sanity check on zones void checkZones(); //- Non-const access to global points pointField& storedPoints() { return const_cast<pointField&>(ParentType::points()); } //- Non-const access to the faces List<Face>& storedFaces() { return static_cast<List<Face> &>(*this); } //- Non-const access to the zones surfZoneList& storedZones() { return zones_; } //- sort faces by zones and store sorted faces void sortFacesAndStore ( const Xfer<List<Face> >& unsortedFaces, const Xfer<List<label> >& zoneIds, const bool sorted ); //- Set new zones from faceMap virtual void remapFaces(const labelUList& faceMap); public: // Public typedefs //- Face type used typedef Face FaceType; //- Runtime type information ClassName("MeshedSurface"); // Static //- Face storage only handles triangulated faces inline static bool isTri(); //- Can we read this file format? static bool canRead(const fileName&, const bool verbose=false); //- Can we read this file format? static bool canReadType(const word& ext, const bool verbose=false); //- Can we write this file format? static bool canWriteType(const word& ext, const bool verbose=false); static wordHashSet readTypes(); static wordHashSet writeTypes(); // Constructors //- Construct null MeshedSurface(); //- Construct by transferring components (points, faces, zones). MeshedSurface ( const Xfer<pointField>&, const Xfer<List<Face> >&, const Xfer<surfZoneList>& ); //- Construct by transferring components (points, faces). // Use zone information if available MeshedSurface ( const Xfer<pointField>&, const Xfer<List<Face> >&, const labelUList& zoneSizes = labelUList(), const UList<word>& zoneNames = UList<word>() ); //- Construct as copy MeshedSurface(const MeshedSurface&); //- Construct from a UnsortedMeshedSurface MeshedSurface(const UnsortedMeshedSurface<Face>&); //- Construct from a boundary mesh with local points/faces MeshedSurface ( const polyBoundaryMesh&, const bool globalPoints=false ); //- Construct from a surfMesh MeshedSurface(const surfMesh&); //- Construct by transferring the contents from a UnsortedMeshedSurface MeshedSurface(const Xfer<UnsortedMeshedSurface<Face> >&); //- Construct by transferring the contents from a MeshedSurface MeshedSurface(const Xfer<MeshedSurface<Face> >&); //- Construct from file name (uses extension to determine type) MeshedSurface(const fileName&); //- Construct from file name (uses extension to determine type) MeshedSurface(const fileName&, const word& ext); //- Construct from database MeshedSurface(const Time&, const word& surfName=""); // Declare run-time constructor selection table declareRunTimeSelectionTable ( autoPtr, MeshedSurface, fileExtension, ( const fileName& name ), (name) ); // Selectors //- Select constructed from filename (explicit extension) static autoPtr<MeshedSurface> New ( const fileName&, const word& ext ); //- Select constructed from filename (implicit extension) static autoPtr<MeshedSurface> New(const fileName&); //- Destructor virtual ~MeshedSurface(); // Member Function Selectors declareMemberFunctionSelectionTable ( void, UnsortedMeshedSurface, write, fileExtension, ( const fileName& name, const MeshedSurface<Face>& surf ), (name, surf) ); //- Write to file static void write(const fileName&, const MeshedSurface<Face>&); // Member Functions // Access //- The surface size is the number of faces label size() const { return ParentType::size(); } //- Return const access to the faces inline const List<Face>& faces() const { return static_cast<const List<Face> &>(*this); } //- Const access to the surface zones. // If zones are defined, they must be contiguous and cover the // entire surface const List<surfZone>& surfZones() const { return zones_; } //- Add surface zones virtual void addZones ( const UList<surfZone>&, const bool cullEmpty=false ); //- Add surface zones virtual void addZones ( const labelUList& sizes, const UList<word>& names, const bool cullEmpty=false ); //- Add surface zones virtual void addZones ( const labelUList& sizes, const bool cullEmpty=false ); //- Remove surface zones virtual void removeZones(); // Edit //- Clear all storage virtual void clear(); //- Move points virtual void movePoints(const pointField&); //- Scale points. A non-positive factor is ignored virtual void scalePoints(const scalar); //- Reset primitive data (points, faces and zones) // Note, optimized to avoid overwriting data (with Xfer::null) virtual void reset ( const Xfer<pointField >& points, const Xfer<List<Face> >& faces, const Xfer<surfZoneList>& zones ); //- Reset primitive data (points, faces and zones) // Note, optimized to avoid overwriting data (with Xfer::null) virtual void reset ( const Xfer<List<point> >& points, const Xfer<List<Face> >& faces, const Xfer<surfZoneList >& zones ); //- Remove invalid faces virtual void cleanup(const bool verbose); virtual bool stitchFaces ( const scalar tol=SMALL, const bool verbose=false ); virtual bool checkFaces ( const bool verbose=false ); //- Triangulate in-place, returning the number of triangles added virtual label triangulate(); //- Triangulate in-place, returning the number of triangles added // and setting a map of original face Ids. // The faceMap is zero-sized when no triangulation was done. virtual label triangulate(List<label>& faceMap); //- Return new surface. // Returns return pointMap, faceMap from subsetMeshMap MeshedSurface subsetMesh ( const labelHashSet& include, labelList& pointMap, labelList& faceMap ) const; //- Return new surface. MeshedSurface subsetMesh ( const labelHashSet& include ) const; //- Transfer the contents of the argument and annul the argument void transfer(MeshedSurface<Face>&); //- Transfer the contents of the argument and annul the argument void transfer(UnsortedMeshedSurface<Face>&); //- Transfer contents to the Xfer container Xfer<MeshedSurface<Face> > xfer(); // Read //- Read from file. Chooses reader based on explicit extension bool read(const fileName&, const word& ext); //- Read from file. Chooses reader based on detected extension virtual bool read(const fileName&); // Write void writeStats(Ostream& os) const; //- Generic write routine. Chooses writer based on extension. virtual void write(const fileName& name) const { write(name, *this); } //- Write to database void write(const Time&, const word& surfName="") const; // Member operators void operator=(const MeshedSurface<Face>&); //- Conversion operator to MeshedSurfaceProxy operator MeshedSurfaceProxy<Face>() const; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // //- Specialization for holding triangulated information template<> inline bool MeshedSurface<triFace>::isTri() { return true; } //- Specialization for holding triangulated information template<> inline label MeshedSurface<triFace>::triangulate() { return 0; } //- Specialization for holding triangulated information template<> inline label MeshedSurface<triFace>::triangulate(List<label>& faceMap) { if (notNull(faceMap)) { faceMap.clear(); } return 0; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace CML #include "UnsortedMeshedSurface.hpp" #include "MeshedSurfaceProxy.hpp" #include "mergePoints.hpp" #include "Time.hpp" #include "ListOps.hpp" #include "polyBoundaryMesh.hpp" #include "polyMesh.hpp" #include "surfMesh.hpp" #include "primitivePatch.hpp" #include "addToRunTimeSelectionTable.hpp" // * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * // template<class Face> inline bool CML::MeshedSurface<Face>::isTri() { return false; } template<class Face> CML::wordHashSet CML::MeshedSurface<Face>::readTypes() { return wordHashSet(*fileExtensionConstructorTablePtr_); } template<class Face> CML::wordHashSet CML::MeshedSurface<Face>::writeTypes() { return wordHashSet(*writefileExtensionMemberFunctionTablePtr_); } // * * * * * * * * * * * * * Static Member Functions * * * * * * * * * * * * // template<class Face> bool CML::MeshedSurface<Face>::canReadType ( const word& ext, const bool verbose ) { return fileFormats::surfaceFormatsCore::checkSupport ( readTypes() | FriendType::readTypes(), ext, verbose, "reading" ); } template<class Face> bool CML::MeshedSurface<Face>::canWriteType ( const word& ext, const bool verbose ) { return fileFormats::surfaceFormatsCore::checkSupport ( writeTypes() | ProxyType::writeTypes(), ext, verbose, "writing" ); } template<class Face> bool CML::MeshedSurface<Face>::canRead ( const fileName& name, const bool verbose ) { word ext = name.ext(); if (ext == "gz") { ext = name.lessExt().ext(); } return canReadType(ext, verbose); } template<class Face> void CML::MeshedSurface<Face>::write ( const fileName& name, const MeshedSurface<Face>& surf ) { if (debug) { Info<< "MeshedSurface::write" "(const fileName&, const MeshedSurface&) : " "writing to " << name << endl; } const word ext = name.ext(); typename writefileExtensionMemberFunctionTable::iterator mfIter = writefileExtensionMemberFunctionTablePtr_->find(ext); if (mfIter == writefileExtensionMemberFunctionTablePtr_->end()) { // no direct writer, delegate to proxy if possible wordHashSet supported = ProxyType::writeTypes(); if (supported.found(ext)) { MeshedSurfaceProxy<Face>(surf).write(name); } else { FatalErrorInFunction << "Unknown file extension " << ext << nl << nl << "Valid types are :" << endl << (supported | writeTypes()) << exit(FatalError); } } else { mfIter()(name, surf); } } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // template<class Face> CML::MeshedSurface<Face>::MeshedSurface() : ParentType(List<Face>(), pointField()) {} template<class Face> CML::MeshedSurface<Face>::MeshedSurface ( const Xfer<pointField>& pointLst, const Xfer<List<Face> >& faceLst, const Xfer<surfZoneList>& zoneLst ) : ParentType(List<Face>(), pointField()), zones_() { reset(pointLst, faceLst, zoneLst); } template<class Face> CML::MeshedSurface<Face>::MeshedSurface ( const Xfer<pointField>& pointLst, const Xfer<List<Face> >& faceLst, const labelUList& zoneSizes, const UList<word>& zoneNames ) : ParentType(List<Face>(), pointField()) { reset(pointLst, faceLst, Xfer<surfZoneList>()); if (zoneSizes.size()) { if (zoneNames.size()) { addZones(zoneSizes, zoneNames); } else { addZones(zoneSizes); } } } template<class Face> CML::MeshedSurface<Face>::MeshedSurface ( const MeshedSurface<Face>& surf ) : ParentType(surf.faces(), surf.points()), zones_(surf.surfZones()) {} template<class Face> CML::MeshedSurface<Face>::MeshedSurface ( const UnsortedMeshedSurface<Face>& surf ) : ParentType(List<Face>(), surf.points()) { labelList faceMap; this->storedZones().transfer(surf.sortedZones(faceMap)); const List<Face>& origFaces = surf.faces(); List<Face> newFaces(origFaces.size()); // this is somewhat like ListOps reorder and/or IndirectList forAll(newFaces, faceI) { newFaces[faceI] = origFaces[faceMap[faceI]]; } this->storedFaces().transfer(newFaces); } template<class Face> CML::MeshedSurface<Face>::MeshedSurface(const surfMesh& mesh) : ParentType(List<Face>(), pointField()) { // same face type as surfMesh MeshedSurface<face> surf ( xferCopy(mesh.points()), xferCopy(mesh.faces()), xferCopy(mesh.surfZones()) ); this->transcribe(surf); } template<class Face> CML::MeshedSurface<Face>::MeshedSurface ( const polyBoundaryMesh& bMesh, const bool useGlobalPoints ) : ParentType(List<Face>(), pointField()) { const polyMesh& mesh = bMesh.mesh(); const polyPatchList& bPatches = bMesh; // Get a single patch for all boundaries primitivePatch allBoundary ( SubList<face> ( mesh.faces(), mesh.nFaces() - mesh.nInternalFaces(), mesh.nInternalFaces() ), mesh.points() ); // use global/local points: const pointField& bPoints = ( useGlobalPoints ? mesh.points() : allBoundary.localPoints() ); // global/local face addressing: const List<Face>& bFaces = ( useGlobalPoints ? allBoundary : allBoundary.localFaces() ); // create zone list surfZoneList newZones(bPatches.size()); label startFaceI = 0; label nZone = 0; forAll(bPatches, patchI) { const polyPatch& p = bPatches[patchI]; if (p.size()) { newZones[nZone] = surfZone ( p.name(), p.size(), startFaceI, nZone ); nZone++; startFaceI += p.size(); } } newZones.setSize(nZone); // same face type as the polyBoundaryMesh MeshedSurface<face> surf ( xferCopy(bPoints), xferCopy(bFaces), xferMove(newZones) ); this->transcribe(surf); } template<class Face> CML::MeshedSurface<Face>::MeshedSurface ( const fileName& name, const word& ext ) : ParentType(List<Face>(), pointField()) { read(name, ext); } template<class Face> CML::MeshedSurface<Face>::MeshedSurface(const fileName& name) : ParentType(List<Face>(), pointField()) { read(name); } template<class Face> CML::MeshedSurface<Face>::MeshedSurface ( const Time& t, const word& surfName ) : ParentType(List<Face>(), pointField()) { surfMesh mesh ( IOobject ( "dummyName", t.timeName(), t, IOobject::MUST_READ_IF_MODIFIED, IOobject::NO_WRITE, false ), surfName ); // same face type as surfMesh MeshedSurface<face> surf ( xferMove(mesh.storedPoints()), xferMove(mesh.storedFaces()), xferMove(mesh.storedZones()) ); this->transcribe(surf); } template<class Face> CML::MeshedSurface<Face>::MeshedSurface ( const Xfer<UnsortedMeshedSurface<Face> >& surf ) : ParentType(List<Face>(), pointField()) { transfer(surf()); } template<class Face> CML::MeshedSurface<Face>::MeshedSurface ( const Xfer<MeshedSurface<Face> >& surf ) : ParentType(List<Face>(), pointField()) { transfer(surf()); } // * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * // template<class Face> CML::MeshedSurface<Face>::~MeshedSurface() {} // * * * * * * * * * * * * Protected Member Functions * * * * * * * * * * * // template<class Face> void CML::MeshedSurface<Face>::remapFaces ( const labelUList& faceMap ) { // recalculate the zone start/size if (notNull(faceMap) && faceMap.size()) { surfZoneList& zones = storedZones(); if (zones.size() == 1) { // optimized for single zone case zones[0].size() = faceMap.size(); } else if (zones.size()) { label newFaceI = 0; label origEndI = 0; forAll(zones, zoneI) { surfZone& zone = zones[zoneI]; // adjust zone start zone.start() = newFaceI; origEndI += zone.size(); for (label faceI = newFaceI; faceI < faceMap.size(); ++faceI) { if (faceMap[faceI] < origEndI) { ++newFaceI; } else { break; } } // adjust zone size zone.size() = newFaceI - zone.start(); } } } } // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // template<class Face> void CML::MeshedSurface<Face>::clear() { ParentType::clearOut(); storedPoints().clear(); storedFaces().clear(); storedZones().clear(); } template<class Face> void CML::MeshedSurface<Face>::movePoints(const pointField& newPoints) { // Adapt for new point position ParentType::movePoints(newPoints); // Copy new points storedPoints() = newPoints; } template<class Face> void CML::MeshedSurface<Face>::scalePoints(const scalar scaleFactor) { // avoid bad scaling if (scaleFactor > 0 && scaleFactor != 1.0) { pointField newPoints(scaleFactor*this->points()); // Adapt for new point position ParentType::movePoints(newPoints); storedPoints() = newPoints; } } template<class Face> void CML::MeshedSurface<Face>::reset ( const Xfer<pointField>& pointLst, const Xfer<List<Face> >& faceLst, const Xfer<surfZoneList>& zoneLst ) { ParentType::clearOut(); // Take over new primitive data. // Optimized to avoid overwriting data at all if (notNull(pointLst)) { storedPoints().transfer(pointLst()); } if (notNull(faceLst)) { storedFaces().transfer(faceLst()); } if (notNull(zoneLst)) { storedZones().transfer(zoneLst()); } } template<class Face> void CML::MeshedSurface<Face>::reset ( const Xfer<List<point> >& pointLst, const Xfer<List<Face> >& faceLst, const Xfer<surfZoneList>& zoneLst ) { ParentType::clearOut(); // Take over new primitive data. // Optimized to avoid overwriting data at all if (notNull(pointLst)) { storedPoints().transfer(pointLst()); } if (notNull(faceLst)) { storedFaces().transfer(faceLst()); } if (notNull(zoneLst)) { storedZones().transfer(zoneLst()); } } // Remove badly degenerate faces, double faces. template<class Face> void CML::MeshedSurface<Face>::cleanup(const bool verbose) { // merge points (already done for STL, TRI) stitchFaces(SMALL, verbose); checkFaces(verbose); this->checkTopology(verbose); } template<class Face> bool CML::MeshedSurface<Face>::stitchFaces ( const scalar tol, const bool verbose ) { pointField& pointLst = this->storedPoints(); // Merge points labelList pointMap(pointLst.size()); pointField newPoints(pointLst.size()); bool hasMerged = mergePoints(pointLst, tol, verbose, pointMap, newPoints); if (!hasMerged) { return false; } if (verbose) { Info<< "MeshedSurface::stitchFaces : Renumbering all faces" << endl; } // Set the coordinates to the merged ones pointLst.transfer(newPoints); List<Face>& faceLst = this->storedFaces(); List<label> faceMap(faceLst.size()); // Reset the point labels to the unique points array label newFaceI = 0; forAll(faceLst, faceI) { Face& f = faceLst[faceI]; forAll(f, fp) { f[fp] = pointMap[f[fp]]; } // for extra safety: collapse face as well if (f.collapse() >= 3) { if (newFaceI != faceI) { faceLst[newFaceI] = f; } faceMap[newFaceI] = faceI; newFaceI++; } else if (verbose) { Pout<< "MeshedSurface::stitchFaces : " << "Removing collapsed face " << faceI << endl << " vertices :" << f << endl; } } pointMap.clear(); if (newFaceI != faceLst.size()) { if (verbose) { Pout<< "MeshedSurface::stitchFaces : " << "Removed " << faceLst.size() - newFaceI << " faces" << endl; } faceLst.setSize(newFaceI); faceMap.setSize(newFaceI); remapFaces(faceMap); } faceMap.clear(); // Merging points might have changed geometric factors ParentType::clearOut(); return true; } // Remove badly degenerate faces and double faces. template<class Face> bool CML::MeshedSurface<Face>::checkFaces ( const bool verbose ) { bool changed = false; List<Face>& faceLst = this->storedFaces(); List<label> faceMap(faceLst.size()); label newFaceI = 0; // Detect badly labelled faces and mark degenerate faces const label maxPointI = this->points().size() - 1; forAll(faceLst, faceI) { Face& f = faceLst[faceI]; // avoid degenerate faces if (f.collapse() >= 3) { forAll(f, fp) { if (f[fp] < 0 || f[fp] > maxPointI) { FatalErrorInFunction << "face " << f << " uses point indices outside point range 0.." << maxPointI << exit(FatalError); } } faceMap[faceI] = faceI; newFaceI++; } else { // mark as bad face faceMap[faceI] = -1; changed = true; if (verbose) { WarningInFunction << "face[" << faceI << "] = " << f << " does not have three unique vertices" << endl; } } } // Detect doubled faces // do not touch the faces const labelListList& fFaces = this->faceFaces(); newFaceI = 0; forAll(faceLst, faceI) { // skip already collapsed faces: if (faceMap[faceI] < 0) { continue; } const Face& f = faceLst[faceI]; // duplicate face check bool okay = true; const labelList& neighbours = fFaces[faceI]; // Check if faceNeighbours use same points as this face. // Note: discards normal information - sides of baffle are merged. forAll(neighbours, neighI) { const label neiFaceI = neighbours[neighI]; if (neiFaceI <= faceI || faceMap[neiFaceI] < 0) { // lower numbered faces already checked // skip neighbours that are themselves collapsed continue; } const Face& nei = faceLst[neiFaceI]; if (f == nei) { okay = false; if (verbose) { WarningInFunction << "faces share the same vertices:" << nl << " face[" << faceI << "] : " << f << nl << " face[" << neiFaceI << "] : " << nei << endl; // printFace(Warning, " ", f, points()); // printFace(Warning, " ", nei, points()); } break; } } if (okay) { faceMap[faceI] = faceI; newFaceI++; } else { faceMap[faceI] = -1; } } // Phase 1: pack // Done to keep numbering constant in phase 1 if (changed || newFaceI < faceLst.size()) { changed = true; if (verbose) { WarningInFunction << "Removed " << faceLst.size() - newFaceI << " illegal faces." << endl; } // compress the face list newFaceI = 0; forAll(faceLst, faceI) { if (faceMap[faceI] >= 0) { if (newFaceI != faceI) { faceLst[newFaceI] = faceLst[faceI]; } faceMap[newFaceI] = faceI; newFaceI++; } } faceLst.setSize(newFaceI); remapFaces(faceMap); } faceMap.clear(); // Topology can change because of renumbering ParentType::clearOut(); return changed; } template<class Face> CML::label CML::MeshedSurface<Face>::triangulate() { return triangulate ( const_cast<List<label>&>(List<label>::null()) ); } template<class Face> CML::label CML::MeshedSurface<Face>::triangulate ( List<label>& faceMapOut ) { label nTri = 0; label maxTri = 0; // the maximum number of triangles for any single face List<Face>& faceLst = this->storedFaces(); // determine how many triangles will be needed forAll(faceLst, faceI) { const label n = faceLst[faceI].nTriangles(); if (maxTri < n) { maxTri = n; } nTri += n; } // nothing to do if (nTri <= faceLst.size()) { if (notNull(faceMapOut)) { faceMapOut.clear(); } return 0; } List<Face> newFaces(nTri); List<label> faceMap; // reuse storage from optional faceMap if (notNull(faceMapOut)) { faceMap.transfer(faceMapOut); } faceMap.setSize(nTri); // remember the number of *additional* faces nTri -= faceLst.size(); if (this->points().empty()) { // triangulate without points // simple face triangulation around f[0] label newFaceI = 0; forAll(faceLst, faceI) { const Face& f = faceLst[faceI]; for (label fp = 1; fp < f.size() - 1; ++fp) { label fp1 = f.fcIndex(fp); newFaces[newFaceI] = triFace(f[0], f[fp], f[fp1]); faceMap[newFaceI] = faceI; newFaceI++; } } } else { // triangulate with points List<face> tmpTri(maxTri); label newFaceI = 0; forAll(faceLst, faceI) { // 'face' not '<Face>' const face& f = faceLst[faceI]; label nTmp = 0; f.triangles(this->points(), nTmp, tmpTri); for (label triI = 0; triI < nTmp; triI++) { newFaces[newFaceI] = Face ( static_cast<labelUList&>(tmpTri[triI]) ); faceMap[newFaceI] = faceI; newFaceI++; } } } faceLst.transfer(newFaces); remapFaces(faceMap); // optionally return the faceMap if (notNull(faceMapOut)) { faceMapOut.transfer(faceMap); } faceMap.clear(); // Topology can change because of renumbering ParentType::clearOut(); return nTri; } template<class Face> CML::MeshedSurface<Face> CML::MeshedSurface<Face>::subsetMesh ( const labelHashSet& include, labelList& pointMap, labelList& faceMap ) const { const pointField& locPoints = this->localPoints(); const List<Face>& locFaces = this->localFaces(); // Fill pointMap, faceMap PatchTools::subsetMap(*this, include, pointMap, faceMap); // Create compact coordinate list and forward mapping array pointField newPoints(pointMap.size()); labelList oldToNew(locPoints.size()); forAll(pointMap, pointI) { newPoints[pointI] = locPoints[pointMap[pointI]]; oldToNew[pointMap[pointI]] = pointI; } // create/copy a new zones list, each zone with zero size surfZoneList newZones(this->surfZones()); forAll(newZones, zoneI) { newZones[zoneI].size() = 0; } // Renumber face node labels List<Face> newFaces(faceMap.size()); forAll(faceMap, faceI) { const label origFaceI = faceMap[faceI]; newFaces[faceI] = Face(locFaces[origFaceI]); // Renumber labels for face Face& f = newFaces[faceI]; forAll(f, fp) { f[fp] = oldToNew[f[fp]]; } } oldToNew.clear(); // recalculate the zones start/size label newFaceI = 0; label origEndI = 0; // adjust zone sizes forAll(newZones, zoneI) { surfZone& zone = newZones[zoneI]; // adjust zone start zone.start() = newFaceI; origEndI += zone.size(); for (label faceI = newFaceI; faceI < faceMap.size(); ++faceI) { if (faceMap[faceI] < origEndI) { ++newFaceI; } else { break; } } // adjust zone size zone.size() = newFaceI - zone.start(); } // construct a sub-surface return MeshedSurface ( xferMove(newPoints), xferMove(newFaces), xferMove(newZones) ); } template<class Face> CML::MeshedSurface<Face> CML::MeshedSurface<Face>::subsetMesh ( const labelHashSet& include ) const { labelList pointMap, faceMap; return subsetMesh(include, pointMap, faceMap); } template<class Face> void CML::MeshedSurface<Face>::transfer ( MeshedSurface<Face>& surf ) { reset ( xferMove(surf.storedPoints()), xferMove(surf.storedFaces()), xferMove(surf.storedZones()) ); } template<class Face> void CML::MeshedSurface<Face>::transfer ( UnsortedMeshedSurface<Face>& surf ) { clear(); labelList faceMap; surfZoneList zoneLst = surf.sortedZones(faceMap); if (zoneLst.size() <= 1) { reset ( xferMove(surf.storedPoints()), xferMove(surf.storedFaces()), Xfer<surfZoneList>() ); } else { List<Face>& oldFaces = surf.storedFaces(); List<Face> newFaces(faceMap.size()); forAll(faceMap, faceI) { newFaces[faceI].transfer(oldFaces[faceMap[faceI]]); } reset ( xferMove(surf.storedPoints()), xferMove(newFaces), xferMove(zoneLst) ); } faceMap.clear(); surf.clear(); } template<class Face> CML::Xfer<CML::MeshedSurface<Face> > CML::MeshedSurface<Face>::xfer() { return xferMove(*this); } // Read from file, determine format from extension template<class Face> bool CML::MeshedSurface<Face>::read(const fileName& name) { word ext = name.ext(); if (ext == "gz") { fileName unzipName = name.lessExt(); return read(unzipName, unzipName.ext()); } else { return read(name, ext); } } // Read from file in given format template<class Face> bool CML::MeshedSurface<Face>::read ( const fileName& name, const word& ext ) { clear(); // read via selector mechanism transfer(New(name, ext)()); return true; } template<class Face> void CML::MeshedSurface<Face>::write ( const Time& t, const word& surfName ) const { MeshedSurfaceProxy<Face>(*this).write(t, surfName); } // * * * * * * * * * * * * * * * Member Operators * * * * * * * * * * * * * // template<class Face> void CML::MeshedSurface<Face>::operator=(const MeshedSurface& surf) { clear(); this->storedPoints() = surf.points(); this->storedFaces() = surf.faces(); this->storedZones() = surf.surfZones(); } template<class Face> CML::MeshedSurface<Face>::operator CML::MeshedSurfaceProxy<Face>() const { return MeshedSurfaceProxy<Face> ( this->points(), this->faces(), this->surfZones() ); } // * * * * * * * * * * * * Protected Member Functions * * * * * * * * * * * // template<class Face> void CML::MeshedSurface<Face>::checkZones() { // extra safety, ensure we have at some zones // and they cover all the faces - fix start silently surfZoneList& zones = this->storedZones(); if (zones.size()) { label count = 0; forAll(zones, zoneI) { zones[zoneI].start() = count; count += zones[zoneI].size(); } if (count < this->size()) { WarningInFunction << "more faces " << this->size() << " than zones " << count << " ... extending final zone" << endl; zones.last().size() += count - this->size(); } else if (count > this->size()) { FatalErrorInFunction << "more zones " << count << " than faces " << this->size() << exit(FatalError); } } } template<class Face> void CML::MeshedSurface<Face>::sortFacesAndStore ( const Xfer<List<Face> >& unsortedFaces, const Xfer<List<label> >& zoneIds, const bool sorted ) { List<Face> oldFaces(unsortedFaces); List<label> zones(zoneIds); if (sorted) { // already sorted - simply transfer faces this->storedFaces().transfer(oldFaces); } else { // unsorted - determine the sorted order: // avoid SortableList since we discard the main list anyhow List<label> faceMap; sortedOrder(zones, faceMap); zones.clear(); // sorted faces List<Face> newFaces(faceMap.size()); forAll(faceMap, faceI) { // use transfer to recover memory where possible newFaces[faceI].transfer(oldFaces[faceMap[faceI]]); } this->storedFaces().transfer(newFaces); } zones.clear(); } // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // template<class Face> void CML::MeshedSurface<Face>::addZones ( const UList<surfZone>& srfZones, const bool cullEmpty ) { label nZone = 0; surfZoneList& zones = this->storedZones(); zones.setSize(zones.size()); forAll(zones, zoneI) { if (srfZones[zoneI].size() || !cullEmpty) { zones[nZone] = surfZone(srfZones[zoneI], nZone); nZone++; } } zones.setSize(nZone); } template<class Face> void CML::MeshedSurface<Face>::addZones ( const labelUList& sizes, const UList<word>& names, const bool cullEmpty ) { label start = 0; label nZone = 0; surfZoneList& zones = this->storedZones(); zones.setSize(sizes.size()); forAll(zones, zoneI) { if (sizes[zoneI] || !cullEmpty) { zones[nZone] = surfZone ( names[zoneI], sizes[zoneI], start, nZone ); start += sizes[zoneI]; nZone++; } } zones.setSize(nZone); } template<class Face> void CML::MeshedSurface<Face>::addZones ( const labelUList& sizes, const bool cullEmpty ) { label start = 0; label nZone = 0; surfZoneList& zones = this->storedZones(); zones.setSize(sizes.size()); forAll(zones, zoneI) { if (sizes[zoneI] || !cullEmpty) { zones[nZone] = surfZone ( word("zone") + ::CML::name(nZone), sizes[zoneI], start, nZone ); start += sizes[zoneI]; nZone++; } } zones.setSize(nZone); } template<class Face> void CML::MeshedSurface<Face>::removeZones() { this->storedZones().clear(); } // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // template<class Face> void CML::MeshedSurface<Face>::writeStats(Ostream& os) const { os << "points : " << this->points().size() << nl; if (MeshedSurface<Face>::isTri()) { os << "triangles : " << this->size() << nl; } else { label nTri = 0; label nQuad = 0; forAll(*this, i) { const label n = this->operator[](i).size(); if (n == 3) { nTri++; } else if (n == 4) { nQuad++; } } os << "faces : " << this->size() << " (tri:" << nTri << " quad:" << nQuad << " poly:" << (this->size() - nTri - nQuad ) << ")" << nl; } os << "boundingBox : " << boundBox(this->points()) << endl; } // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // template<class Face> CML::autoPtr< CML::MeshedSurface<Face> > CML::MeshedSurface<Face>::New(const fileName& name, const word& ext) { if (debug) { Info<< "MeshedSurface::New(const fileName&, const word&) : " "constructing MeshedSurface" << endl; } typename fileExtensionConstructorTable::iterator cstrIter = fileExtensionConstructorTablePtr_->find(ext); if (cstrIter == fileExtensionConstructorTablePtr_->end()) { // no direct reader, delegate if possible wordHashSet supported = FriendType::readTypes(); if (supported.found(ext)) { // create indirectly autoPtr< MeshedSurface<Face> > surf(new MeshedSurface<Face>); surf().transfer(FriendType::New(name, ext)()); return surf; } // nothing left to try, issue error supported += readTypes(); FatalErrorInFunction << "Unknown file extension " << ext << nl << nl << "Valid types are :" << nl << supported << exit(FatalError); } return autoPtr< MeshedSurface<Face> >(cstrIter()(name)); } template<class Face> CML::autoPtr< CML::MeshedSurface<Face> > CML::MeshedSurface<Face>::New(const fileName& name) { word ext = name.ext(); if (ext == "gz") { ext = name.lessExt().ext(); } return New(name, ext); } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
23.358162
79
0.542099
f0e3176656a2486c5b034523bacc31885375ef30
1,525
cpp
C++
networkit/cpp/auxiliary/ParallelTimings.cpp
ArminWiebigke/networkit
713320a5961f6324d62df2ea7a32675fa053dfac
[ "MIT" ]
null
null
null
networkit/cpp/auxiliary/ParallelTimings.cpp
ArminWiebigke/networkit
713320a5961f6324d62df2ea7a32675fa053dfac
[ "MIT" ]
null
null
null
networkit/cpp/auxiliary/ParallelTimings.cpp
ArminWiebigke/networkit
713320a5961f6324d62df2ea7a32675fa053dfac
[ "MIT" ]
null
null
null
/* * ParallelTimings.cpp * * Created on: 2019-11-05 * Author: Armin Wiebigke */ #include <map> #include "ParallelTimings.h" namespace NetworKit { void ParallelTimings::addTime(Aux::Timer &timer, const std::string &name) const { timer.stop(); double elapsed = timer.elapsedNanoseconds(); auto tid = omp_get_thread_num(); timings[tid][name] += elapsed; timer.start(); } ParallelTimings::ParallelTimings() : timings(omp_get_max_threads()) { } void ParallelTimings::addTimings(const std::unordered_map<std::string, double> &ts, const std::string &prefix) const { auto tid = omp_get_thread_num(); for (auto &t : ts) { timings[tid][prefix + t.first] += t.second; } } std::unordered_map<std::string, double> ParallelTimings::getTimings() const { std::unordered_map<std::string, double> timingsSum; for (const auto& threadTimings : timings) { for (const auto& it : threadTimings) { timingsSum[it.first] += it.second; } } return timingsSum; } bool ParallelTimings::timingsEmpty() const { for (const auto& threadTimings : timings) { if (!threadTimings.empty()) return false; } return true; } std::string ParallelTimings::timingsAsString() const { std::map<std::string, double> timingsSum; for (const auto& threadTimings : timings) { for (const auto& it : threadTimings) { timingsSum[it.first] += it.second; } } std::stringstream str; for (const auto& t : timingsSum) { str << t.first + ": " << t.second / 1e6 << "ms" << "\n"; } return str.str(); } } // namespace NetworKit
23.106061
118
0.683934
f0e719c6ea86f83338f9e8745890360cae78d634
6,370
cpp
C++
texture.cpp
CaptainDreamcast/prism
a6b0f5c3e86d7b37d14c9139862775e7768998ce
[ "MIT" ]
7
2018-04-08T15:01:59.000Z
2022-02-27T12:13:19.000Z
texture.cpp
CaptainDreamcast/prism
a6b0f5c3e86d7b37d14c9139862775e7768998ce
[ "MIT" ]
1
2017-04-23T15:27:37.000Z
2017-04-24T05:38:18.000Z
texture.cpp
CaptainDreamcast/libtari
a6b0f5c3e86d7b37d14c9139862775e7768998ce
[ "MIT" ]
1
2020-04-24T04:21:00.000Z
2020-04-24T04:21:00.000Z
#include "prism/texture.h" #include<algorithm> #ifdef DREAMCAST #include <png/png.h> #else #include <png.h> #endif #include "prism/file.h" #include "prism/log.h" #include "prism/system.h" #include "prism/math.h" using namespace std; #define FONT_CHARACTER_AMOUNT 91 static int isFontDataLoaded; static TextureData gFont; static FontCharacterData gFontCharacterData[FONT_CHARACTER_AMOUNT]; void unloadFont() { if (!isFontDataLoaded) return; unloadTexture(gFont); memset(gFontCharacterData, 0, sizeof gFontCharacterData); isFontDataLoaded = 0; } static void loadFontHeader(const char* tFileDir) { FileHandler file; file = fileOpen(tFileDir, O_RDONLY); if (file == FILEHND_INVALID) { logError("Cannot open font header."); logErrorString(tFileDir); recoverFromError(); } fileSeek(file, 0, 0); int i; for (i = 0; i < FONT_CHARACTER_AMOUNT; i++) { fileRead(file, &gFontCharacterData[i], sizeof gFontCharacterData[i]); } fileClose(file); } static void loadFontTexture(const char* tFileDir) { gFont = loadTexturePKG(tFileDir); } void setFont(const char* tFileDirHeader, const char* tFileDirTexture) { if (isFontDataLoaded) { unloadFont(); } if (!isFile(tFileDirHeader)) { return; } loadFontHeader(tFileDirHeader); loadFontTexture(tFileDirTexture); isFontDataLoaded = 1; } void loadConsecutiveTextures(TextureData * tDst, const char * tBaseFileDir, int tAmount) { int i; for (i = 0; i < tAmount; i++) { char path[1024]; getPathWithNumberAffixedFromAssetPath(path, tBaseFileDir, i); tDst[i] = loadTexture(path); } } TextureData getFontTexture() { return gFont; } FontCharacterData getFontCharacterData(char tChar) { int i; if (tChar < ' ' || tChar > 'z') i = 0; else i = tChar - ' '; return gFontCharacterData[i]; } TextureSize makeTextureSize(int x, int y) { TextureSize ret; ret.x = x; ret.y = y; return ret; } TextureData createWhiteTexture() { int length = 16 * 16 * 4; uint8_t* data = (uint8_t*)allocMemory(length); memset(data, 0xFF, length); TextureData ret = loadTextureFromARGB32Buffer(makeBuffer(data, length), 16, 16); freeMemory(data); return ret; } TextureData createWhiteCircleTexture() { int length = 16 * 16 * 4; uint8_t* data = (uint8_t*)allocMemory(length); memset(data, 0xFF, length); const std::vector<int> LINE_EMPTY_AMOUNT = {5, 3, 2, 1, 1}; for (size_t y = 0; y < LINE_EMPTY_AMOUNT.size(); y++) { const auto width = LINE_EMPTY_AMOUNT[y]; for (int x = 0; x < width; x++) { data[(y * 16 + x) * 4 + 3] = 0; data[(y * 16 + (15 - x)) * 4 + 3] = 0; data[((15 - y) * 16 + x) * 4 + 3] = 0; data[((15 - y) * 16 + (15 - x)) * 4 + 3] = 0; } } TextureData ret = loadTextureFromARGB32Buffer(makeBuffer(data, length), 16, 16); freeMemory(data); return ret; } Buffer turnARGB32BufferIntoARGB16Buffer(const Buffer& tSrc) { int dstSize = tSrc.mLength / 2; char* dst = (char*)allocMemory(dstSize); char* src = (char*)tSrc.mData; int n = dstSize / 2; int i; for(i = 0; i < n; i++) { int srcPos = 4*i; int dstPos = 2*i; uint8_t a = ((uint8_t)src[srcPos + 3]) >> 4; uint8_t r = ((uint8_t)src[srcPos + 2]) >> 4; uint8_t g = ((uint8_t)src[srcPos + 1]) >> 4; uint8_t b = ((uint8_t)src[srcPos + 0]) >> 4; dst[dstPos + 0] = (g << 4) | b; dst[dstPos + 1] = (a << 4) | r; } return makeBufferOwned(dst, dstSize); } /* Linear/iterative twiddling algorithm from Marcus' tatest */ #define TWIDTAB(x) ( (x&1)|((x&2)<<1)|((x&4)<<2)|((x&8)<<3)|((x&16)<<4)| \ ((x&32)<<5)|((x&64)<<6)|((x&128)<<7)|((x&256)<<8)|((x&512)<<9) ) #define TWIDOUT(x, y) ( TWIDTAB((y)) | (TWIDTAB((x)) << 1) ) #define MIN(a, b) ( (a)<(b)? (a):(b) ) /* This twiddling code is copied from pvr_texture.c, and the original algorithm was written by Vincent Penne. */ Buffer twiddleTextureBuffer8(const Buffer& tBuffer, int tWidth, int tHeight) { int w = tWidth; int h = tHeight; int mini = min(w, h); int mask = mini - 1; uint8_t * pixels = (uint8_t *)tBuffer.mData; uint8_t * vtex = (uint8_t*)allocMemory(tBuffer.mLength); int x, y, yout; for(y = 0; y < h; y++) { yout = y; for(x = 0; x < w; x++) { vtex[TWIDOUT(x & mask, yout & mask) + (x / mini + yout / mini)*mini * mini] = pixels[y * w + x]; } } return makeBufferOwned(vtex, tBuffer.mLength); } Buffer twiddleTextureBuffer16(const Buffer& tBuffer, int tWidth, int tHeight) { int w = tWidth; int h = tHeight; int mini = min(w, h); int mask = mini - 1; uint16_t * pixels = (uint16_t *)tBuffer.mData; uint16_t * vtex = (uint16_t*)allocMemory(tBuffer.mLength); int x, y, yout; for (y = 0; y < h; y++) { yout = y; for (x = 0; x < w; x++) { vtex[TWIDOUT(x & mask, yout & mask) + (x / mini + yout / mini)*mini * mini] = pixels[y * w + x]; } } return makeBufferOwned(vtex, tBuffer.mLength); } #ifdef DREAMCAST #pragma GCC diagnostic ignored "-Wclobbered" #endif #ifdef _WIN32 #pragma warning(push) #pragma warning(disable: 4611) #endif void saveRGB32ToPNG(const Buffer& b, int tWidth, int tHeight, const char* tFileDir) { char fullPath[1024]; getFullPath(fullPath, tFileDir); FILE *fp = fopen(fullPath, "wb"); if (!fp) { logErrorFormat("Unable to open file %s", tFileDir); return; } auto png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) { logError("Unable to create png struct."); return; } auto info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { logError("Unable to create png info struct."); return; } if (setjmp(png_jmpbuf(png_ptr))) { logError("Exception writing png."); return; } png_init_io(png_ptr, fp); if (setjmp(png_jmpbuf(png_ptr))) { logError("Exception writing png."); return; } png_set_IHDR(png_ptr, info_ptr, tWidth, tHeight, 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_write_info(png_ptr, info_ptr); if (setjmp(png_jmpbuf(png_ptr))) { logError("Exception writing png."); return; } for (int y = tHeight - 1; y >= 0; y--) { png_bytep bytes = ((png_bytep)b.mData) + tWidth * 3 * y; png_write_rows(png_ptr, &bytes, 1); } if (setjmp(png_jmpbuf(png_ptr))) { logError("Exception writing png."); return; } png_write_end(png_ptr, NULL); fclose(fp); } #ifdef _WIN32 #pragma warning(pop) #endif
22.75
88
0.649137
f0e933ed100092fe5cf143ddcb9558b9fc32c21d
267
hpp
C++
pythran/pythonic/include/__builtin__/ReferenceError.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
1
2018-03-24T00:33:03.000Z
2018-03-24T00:33:03.000Z
pythran/pythonic/include/__builtin__/ReferenceError.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/include/__builtin__/ReferenceError.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
null
null
null
#ifndef PYTHONIC_INCLUDE_BUILTIN_REFERENCEERROR_HPP #define PYTHONIC_INCLUDE_BUILTIN_REFERENCEERROR_HPP #include "pythonic/include/types/exceptions.hpp" PYTHONIC_NS_BEGIN namespace __builtin__ { PYTHONIC_EXCEPTION_DECL(ReferenceError) } PYTHONIC_NS_END #endif
16.6875
51
0.868914
f0ea469a07225cc24c6b92a7cb30c43024a6108f
5,692
cpp
C++
c++/src/corelib/ncbi_safe_static.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
31
2016-12-09T04:56:59.000Z
2021-12-31T17:19:10.000Z
c++/src/corelib/ncbi_safe_static.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
6
2017-03-10T17:25:13.000Z
2021-09-22T15:49:49.000Z
c++/src/corelib/ncbi_safe_static.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
20
2015-01-04T02:15:17.000Z
2021-12-03T02:31:43.000Z
/* $Id: ncbi_safe_static.cpp 177027 2009-11-24 19:19:28Z grichenk $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Aleksey Grichenko * * File Description: * Static variables safety - create on demand, destroy on termination * * CSafeStaticGuard:: -- guarantee for CSafePtr<> and CSafeRef<> * destruction and cleanup * */ #include <ncbi_pch.hpp> #include <corelib/ncbi_safe_static.hpp> #include <corelib/ncbistd.hpp> #include <corelib/ncbithr.hpp> #include <corelib/ncbimtx.hpp> #include <corelib/error_codes.hpp> #include <memory> #include <assert.h> #define NCBI_USE_ERRCODE_X Corelib_Static BEGIN_NCBI_SCOPE CSafeStaticLifeSpan::CSafeStaticLifeSpan(ELifeSpan span, int adjust) : m_LifeSpan(int(span) + adjust) { if (span == eLifeSpan_Min) { m_LifeSpan = int(span); // ignore adjustments adjust = 0; } if (adjust >= 5000 || adjust <= -5000) { ERR_POST_X(1, Warning << "CSafeStaticLifeSpan level adjustment out of range: " << adjust); } _ASSERT(adjust > -5000 && adjust < 5000); } CSafeStaticLifeSpan& CSafeStaticLifeSpan::GetDefault(void) { static CSafeStaticLifeSpan s_DefaultSpan(eLifeSpan_Min); return s_DefaultSpan; } ///////////////////////////////////////////////////////////////////////////// // // CSafeStaticPtr_Base:: // // Protective mutex and the owner thread ID to avoid // multiple initializations and deadlocks DEFINE_STATIC_MUTEX(s_Mutex); static CThreadSystemID s_MutexOwner; // true if s_MutexOwner has been set (while the mutex is locked) static bool s_MutexLocked; bool CSafeStaticPtr_Base::Init_Lock(bool* mutex_locked) { // Check if already locked by the same thread to avoid deadlock // in case of nested calls to Get() by T constructor // Lock only if unlocked or locked by another thread // to prevent initialization by another thread CThreadSystemID id = CThreadSystemID::GetCurrent(); if (!s_MutexLocked || s_MutexOwner != id) { s_Mutex.Lock(); s_MutexLocked = true; *mutex_locked = true; s_MutexOwner = id; } return m_Ptr == 0; } void CSafeStaticPtr_Base::Init_Unlock(bool mutex_locked) { // Unlock the mutex only if it was locked by the same call to Get() if ( mutex_locked ) { s_MutexLocked = false; s_Mutex.Unlock(); } } int CSafeStaticPtr_Base::x_GetCreationOrder(void) { static CAtomicCounter s_CreationOrder; return s_CreationOrder.Add(1); } CSafeStaticPtr_Base::~CSafeStaticPtr_Base(void) { bool mutex_locked = false; if ( x_IsStdStatic() && !Init_Lock(&mutex_locked) ) { x_Cleanup(); } Init_Unlock(mutex_locked); } ///////////////////////////////////////////////////////////////////////////// // // CSafeStaticGuard:: // // Cleanup stack to keep all on-demand variables CSafeStaticGuard::TStack* CSafeStaticGuard::sm_Stack; // CSafeStaticGuard reference counter int CSafeStaticGuard::sm_RefCount; CSafeStaticGuard::CSafeStaticGuard(void) { // Initialize the guard only once if (sm_RefCount == 0) { CSafeStaticGuard::sm_Stack = new CSafeStaticGuard::TStack; } sm_RefCount++; } static CSafeStaticGuard* sh_CleanupGuard; CSafeStaticGuard::~CSafeStaticGuard(void) { CMutexGuard guard(s_Mutex); // Protect CSafeStaticGuard destruction if ( sh_CleanupGuard ) { CSafeStaticGuard* tmp = sh_CleanupGuard; sh_CleanupGuard = 0; delete tmp; } // If this is not the last reference, then do not destroy stack if (--sm_RefCount > 0) { return; } assert(sm_RefCount == 0); // Call Cleanup() for all variables registered NON_CONST_ITERATE(TStack, it, *sm_Stack) { (*it)->x_Cleanup(); } delete sm_Stack; sm_Stack = 0; } // Global guard - to prevent premature destruction by e.g. GNU compiler // (it destroys all local static variables before any global one) static CSafeStaticGuard sg_CleanupGuard; // Initialization of the guard CSafeStaticGuard* CSafeStaticGuard::x_Get(void) { // Local static variable - to initialize the guard // as soon as the function is called (global static // variable may be still uninitialized at this moment) static CSafeStaticGuard sl_CleanupGuard; if ( !sh_CleanupGuard ) sh_CleanupGuard = new CSafeStaticGuard; return &sl_CleanupGuard; } END_NCBI_SCOPE
27.765854
78
0.655657
f0ed6acb33e0b41499306ec4590b306a0280924d
5,808
cpp
C++
libs/geometry/src/matrix.cpp
blagodarin/yttrium
534289c3082355e5537a03c0b5855b60f0c344ad
[ "Apache-2.0" ]
null
null
null
libs/geometry/src/matrix.cpp
blagodarin/yttrium
534289c3082355e5537a03c0b5855b60f0c344ad
[ "Apache-2.0" ]
null
null
null
libs/geometry/src/matrix.cpp
blagodarin/yttrium
534289c3082355e5537a03c0b5855b60f0c344ad
[ "Apache-2.0" ]
null
null
null
// This file is part of the Yttrium toolkit. // Copyright (C) Sergei Blagodarin. // SPDX-License-Identifier: Apache-2.0 #include <yttrium/geometry/matrix.h> #include <yttrium/geometry/euler.h> #include <yttrium/geometry/size.h> #include <cmath> #include <numbers> namespace Yt { Matrix4::Matrix4(const Euler& e) noexcept { const auto yaw = e._yaw / 180 * std::numbers::pi_v<float>; const auto pitch = e._pitch / 180 * std::numbers::pi_v<float>; const auto roll = e._roll / 180 * std::numbers::pi_v<float>; const auto cy = std::cos(yaw); const auto sy = std::sin(yaw); const auto cp = std::cos(pitch); const auto sp = std::sin(pitch); const auto cr = std::cos(roll); const auto sr = std::sin(roll); x = { sy * sp * sr + cy * cr, cy * sp * sr - sy * cr, -cp * sr, 0 }; y = { sy * cp, cy * cp, sp, 0 }; z = { cy * sr - sy * sp * cr, -cy * sp * cr - sy * sr, cp * cr, 0 }; t = { 0, 0, 0, 1 }; } Matrix4 Matrix4::camera(const Vector3& position, const Euler& orientation) noexcept { const Matrix4 r{ orientation }; return { r.x.x, r.x.y, r.x.z, -dot_product(position, { r.x.x, r.x.y, r.x.z }), r.y.x, r.y.y, r.y.z, -dot_product(position, { r.y.x, r.y.y, r.y.z }), r.z.x, r.z.y, r.z.z, -dot_product(position, { r.z.x, r.z.y, r.z.z }), 0, 0, 0, 1 }; } Matrix4 Matrix4::perspective(const SizeF& size, float vertical_fov, float near_plane, float far_plane) noexcept { const auto aspect = size._width / size._height; const auto f = 1 / std::tan(vertical_fov / 360 * std::numbers::pi_v<float>); const auto xx = f / aspect; const auto yy = f; const auto zz = (near_plane + far_plane) / (near_plane - far_plane); const auto tz = 2 * near_plane * far_plane / (near_plane - far_plane); const auto zw = -1.f; return { xx, 0, 0, 0, 0, yy, 0, 0, 0, 0, zz, tz, 0, 0, zw, 0 }; } Matrix4 Matrix4::projection_2d(const SizeF& size, float near_plane, float far_plane) noexcept { const auto xx = 2 / size._width; const auto yy = -2 / size._height; const auto zz = -2 / (far_plane - near_plane); const auto tx = -1.f; const auto ty = 1.f; const auto tz = (far_plane + near_plane) / (far_plane - near_plane); return { xx, 0, 0, tx, 0, yy, 0, ty, 0, 0, zz, tz, 0, 0, 0, 1 }; } Matrix4 Matrix4::rotation(float degrees, const Vector3& axis) noexcept { const auto v = normalize(axis); const auto radians = degrees / 180 * std::numbers::pi_v<float>; const auto c = std::cos(radians); const auto s = std::sin(radians); return { v.x * v.x * (1 - c) + c, v.y * v.x * (1 - c) - s * v.z, v.z * v.x * (1 - c) + s * v.y, 0, v.x * v.y * (1 - c) + s * v.z, v.y * v.y * (1 - c) + c, v.z * v.y * (1 - c) - s * v.x, 0, v.x * v.z * (1 - c) - s * v.y, v.y * v.z * (1 - c) + s * v.x, v.z * v.z * (1 - c) + c, 0, 0, 0, 0, 1 }; } float det(const Matrix4& m) noexcept { const auto xy = m.x.z * m.y.w - m.x.w * m.y.z; const auto xz = m.x.z * m.z.w - m.x.w * m.z.z; const auto xt = m.x.z * m.t.w - m.x.w * m.t.z; const auto yz = m.y.z * m.z.w - m.y.w * m.z.z; const auto yt = m.y.z * m.t.w - m.y.w * m.t.z; const auto zt = m.z.z * m.t.w - m.z.w * m.t.z; const auto yzt = m.y.y * zt - m.z.y * yt + m.t.y * yz; const auto xzt = m.x.y * zt - m.z.y * xt + m.t.y * xz; const auto xyt = m.x.y * yt - m.y.y * xt + m.t.y * xy; const auto xyz = m.x.y * yz - m.y.y * xz + m.z.y * xy; return m.x.x * yzt - m.y.x * xzt + m.z.x * xyt - m.t.x * xyz; } Matrix4 inverse(const Matrix4& m) noexcept { // Z and W rows. auto det01 = m.x.z * m.y.w - m.x.w * m.y.z; auto det02 = m.x.z * m.z.w - m.x.w * m.z.z; auto det03 = m.x.z * m.t.w - m.x.w * m.t.z; auto det12 = m.y.z * m.z.w - m.y.w * m.z.z; auto det13 = m.y.z * m.t.w - m.y.w * m.t.z; auto det23 = m.z.z * m.t.w - m.z.w * m.t.z; // Y, Z and W rows. const auto det123 = m.y.y * det23 - m.z.y * det13 + m.t.y * det12; const auto det023 = m.x.y * det23 - m.z.y * det03 + m.t.y * det02; const auto det013 = m.x.y * det13 - m.y.y * det03 + m.t.y * det01; const auto det012 = m.x.y * det12 - m.y.y * det02 + m.z.y * det01; const auto d = 1 / (m.x.x * det123 - m.y.x * det023 + m.z.x * det013 - m.t.x * det012); const auto xx = d * det123; const auto xy = d * -det023; const auto xz = d * det013; const auto xw = d * -det012; const auto yx = d * -(m.y.x * det23 - m.z.x * det13 + m.t.x * det12); const auto yy = d * (m.x.x * det23 - m.z.x * det03 + m.t.x * det02); const auto yz = d * -(m.x.x * det13 - m.y.x * det03 + m.t.x * det01); const auto yw = d * (m.x.x * det12 - m.y.x * det02 + m.z.x * det01); // Y and W rows. det01 = m.x.y * m.y.w - m.y.y * m.x.w; det02 = m.x.y * m.z.w - m.z.y * m.x.w; det03 = m.x.y * m.t.w - m.t.y * m.x.w; det12 = m.y.y * m.z.w - m.z.y * m.y.w; det13 = m.y.y * m.t.w - m.t.y * m.y.w; det23 = m.z.y * m.t.w - m.t.y * m.z.w; const auto zx = d * (m.y.x * det23 - m.z.x * det13 + m.t.x * det12); const auto zy = d * -(m.x.x * det23 - m.z.x * det03 + m.t.x * det02); const auto zz = d * (m.x.x * det13 - m.y.x * det03 + m.t.x * det01); const auto zw = d * -(m.x.x * det12 - m.y.x * det02 + m.z.x * det01); // Y and Z rows. det01 = m.y.z * m.x.y - m.x.z * m.y.y; det02 = m.z.z * m.x.y - m.x.z * m.z.y; det03 = m.t.z * m.x.y - m.x.z * m.t.y; det12 = m.z.z * m.y.y - m.y.z * m.z.y; det13 = m.t.z * m.y.y - m.y.z * m.t.y; det23 = m.t.z * m.z.y - m.z.z * m.t.y; const auto tx = d * -(m.y.x * det23 - m.z.x * det13 + m.t.x * det12); const auto ty = d * (m.x.x * det23 - m.z.x * det03 + m.t.x * det02); const auto tz = d * -(m.x.x * det13 - m.y.x * det03 + m.t.x * det01); const auto tw = d * (m.x.x * det12 - m.y.x * det02 + m.z.x * det01); return { xx, yx, zx, tx, xy, yy, zy, ty, xz, yz, zz, tz, xw, yw, zw, tw }; } }
34.366864
112
0.532369
f0ef45f838db55c49ad28fb6f393909025c8e1d6
7,054
hpp
C++
packages/Search/src/details/DTK_DetailsTreeTraversal.hpp
flyingcat007/DTK_Test
ef8e0e791b76f138045354715a8ce23436ea0edf
[ "BSD-3-Clause" ]
null
null
null
packages/Search/src/details/DTK_DetailsTreeTraversal.hpp
flyingcat007/DTK_Test
ef8e0e791b76f138045354715a8ce23436ea0edf
[ "BSD-3-Clause" ]
null
null
null
packages/Search/src/details/DTK_DetailsTreeTraversal.hpp
flyingcat007/DTK_Test
ef8e0e791b76f138045354715a8ce23436ea0edf
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** * Copyright (c) 2012-2017 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * ****************************************************************************/ #ifndef DTK_DETAILS_TREE_TRAVERSAL_HPP #define DTK_DETAILS_TREE_TRAVERSAL_HPP #include <DTK_DBC.hpp> #include <DTK_DetailsAlgorithms.hpp> #include <DTK_DetailsNode.hpp> #include <DTK_DetailsPredicate.hpp> #include <DTK_DetailsPriorityQueue.hpp> #include <DTK_DetailsStack.hpp> namespace DataTransferKit { template <typename DeviceType> class BVH; namespace Details { template <typename DeviceType> struct TreeTraversal { public: using ExecutionSpace = typename DeviceType::execution_space; template <typename Predicate, typename Insert> KOKKOS_INLINE_FUNCTION static int query( BVH<DeviceType> const bvh, Predicate const &pred, Insert const &insert ) { using Tag = typename Predicate::Tag; return queryDispatch( bvh, pred, insert, Tag{} ); } /** * Return true if the node is a leaf. */ KOKKOS_INLINE_FUNCTION static bool isLeaf( BVH<DeviceType> bvh, Node const *node ) { // COMMENT: could also check that pointer is in the range [leaf_nodes, // leaf_nodes+n] (void)bvh; return ( node->children.first == nullptr ) && ( node->children.second == nullptr ); } /** * Return the index of the leaf node. */ KOKKOS_INLINE_FUNCTION static int getIndex( BVH<DeviceType> bvh, Node const *leaf ) { return bvh._indices[leaf - bvh._leaf_nodes.data()]; } /** * Return the root node of the BVH. */ KOKKOS_INLINE_FUNCTION static Node const *getRoot( BVH<DeviceType> bvh ) { if ( bvh.empty() ) return nullptr; return ( bvh.size() > 1 ? bvh._internal_nodes : bvh._leaf_nodes ) .data(); } }; // There are two (related) families of search: one using a spatial predicate and // one using nearest neighbours query (see boost::geometry::queries // documentation). template <typename DeviceType, typename Predicate, typename Insert> KOKKOS_FUNCTION int spatial_query( BVH<DeviceType> const bvh, Predicate const &predicate, Insert const &insert ) { if ( bvh.empty() ) return 0; if ( bvh.size() == 1 ) { Node const *leaf = TreeTraversal<DeviceType>::getRoot( bvh ); if ( predicate( leaf ) ) { int const leaf_index = TreeTraversal<DeviceType>::getIndex( bvh, leaf ); insert( leaf_index ); return 1; } else return 0; } Stack<Node const *> stack; Node const *root = TreeTraversal<DeviceType>::getRoot( bvh ); stack.push( root ); int count = 0; while ( !stack.empty() ) { Node const *node = stack.top(); stack.pop(); if ( TreeTraversal<DeviceType>::isLeaf( bvh, node ) ) { insert( TreeTraversal<DeviceType>::getIndex( bvh, node ) ); count++; } else { for ( Node const *child : {node->children.first, node->children.second} ) { if ( predicate( child ) ) { stack.push( child ); } } } } return count; } // query k nearest neighbours template <typename DeviceType, typename Insert> KOKKOS_FUNCTION int nearestQuery( BVH<DeviceType> const bvh, Point const &query_point, int k, Insert const &insert ) { if ( bvh.empty() || k < 1 ) return 0; if ( bvh.size() == 1 ) { Node const *leaf = TreeTraversal<DeviceType>::getRoot( bvh ); int const leaf_index = TreeTraversal<DeviceType>::getIndex( bvh, leaf ); double const leaf_distance = distance( query_point, leaf->bounding_box ); insert( leaf_index, leaf_distance ); return 1; } using PairNodePtrDistance = Kokkos::pair<Node const *, double>; struct CompareDistance { KOKKOS_INLINE_FUNCTION bool operator()( PairNodePtrDistance const &lhs, PairNodePtrDistance const &rhs ) { // reverse order (larger distance means lower priority) return lhs.second > rhs.second; } }; PriorityQueue<PairNodePtrDistance, CompareDistance> queue; // priority does not matter for the root since the node will be // processed directly and removed from the priority queue we don't even // bother computing the distance to it. Node const *root = TreeTraversal<DeviceType>::getRoot( bvh ); queue.push( root, 0. ); int count = 0; while ( !queue.empty() && count < k ) { // get the node that is on top of the priority list (i.e. is the // closest to the query point) Node const *node = queue.top().first; double const node_distance = queue.top().second; // NOTE: it would be nice to be able to do something like // tie( node, node_distance = queue.top(); queue.pop(); if ( TreeTraversal<DeviceType>::isLeaf( bvh, node ) ) { insert( TreeTraversal<DeviceType>::getIndex( bvh, node ), node_distance ); count++; } else { // insert children of the node in the priority list for ( Node const *child : {node->children.first, node->children.second} ) { double child_distance = distance( query_point, child->bounding_box ); queue.push( child, child_distance ); } } } return count; } template <typename DeviceType, typename Predicate, typename Insert> KOKKOS_INLINE_FUNCTION int queryDispatch( BVH<DeviceType> const bvh, Predicate const &pred, Insert const &insert, SpatialPredicateTag ) { return spatial_query( bvh, pred, insert ); } template <typename DeviceType, typename Predicate, typename Insert> KOKKOS_INLINE_FUNCTION int queryDispatch( BVH<DeviceType> const bvh, Predicate const &pred, Insert const &insert, NearestPredicateTag ) { return nearestQuery( bvh, pred._query_point, pred._k, insert ); } } // end namespace Details } // end namespace DataTransferKit #endif
31.632287
80
0.561242
f0f058c70d3c3c2b34e72acbf78be9b844e025bb
788
cpp
C++
client/include/game/CColDisk.cpp
MayconFelipeA/sampvoiceatt
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
[ "MIT" ]
368
2015-01-01T21:42:00.000Z
2022-03-29T06:22:22.000Z
client/include/game/CColDisk.cpp
MayconFelipeA/sampvoiceatt
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
[ "MIT" ]
92
2019-01-23T23:02:31.000Z
2022-03-23T19:59:40.000Z
client/include/game/CColDisk.cpp
MayconFelipeA/sampvoiceatt
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
[ "MIT" ]
179
2015-02-03T23:41:17.000Z
2022-03-26T08:27:16.000Z
/* Plugin-SDK (Grand Theft Auto San Andreas) source file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #include "CColDisk.h" // Converted from thiscall void CColDisk::Set(float startRadius,CVector const&start,CVector const&end,float endRadius,uchar material,uchar pieceType,uchar lighting) 0x40FD50 void CColDisk::Set(float startRadius, CVector const& start, CVector const& end, float endRadius, unsigned char material, unsigned char pieceType, unsigned char lighting) { plugin::CallMethod<0x40FD50, CColDisk *, float, CVector const&, CVector const&, float, unsigned char, unsigned char, unsigned char>(this, startRadius, start, end, endRadius, material, pieceType, lighting); }
65.666667
209
0.769036
f0f3e273807c03960248ad61cc8e678f24cf06dc
78
hpp
C++
include/Pulsejet/Pulsejet.hpp
logicomacorp/pulsejet
ec73d19ccb71ff05b2122e258fe4b7b16e55fb53
[ "MIT" ]
30
2021-06-07T20:25:48.000Z
2022-03-30T00:52:38.000Z
include/Pulsejet/Pulsejet.hpp
going-digital/pulsejet
8452a0311645867d64c038cef7fdf751b26717ee
[ "MIT" ]
null
null
null
include/Pulsejet/Pulsejet.hpp
going-digital/pulsejet
8452a0311645867d64c038cef7fdf751b26717ee
[ "MIT" ]
1
2021-09-21T11:17:45.000Z
2021-09-21T11:17:45.000Z
#pragma once #include "Decode.hpp" #include "Encode.hpp" #include "Meta.hpp"
13
21
0.717949