hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
5299f4c2c7f8c7d0d4b4190516bd2e2e1209ddb5
13,960
cpp
C++
native/cocos/platform/java/jni/JniHelper.cpp
SteveLau-GameDeveloper/engine
159e5acd0f5115a878d59ed59f924ce7627a5466
[ "Apache-2.0", "MIT" ]
null
null
null
native/cocos/platform/java/jni/JniHelper.cpp
SteveLau-GameDeveloper/engine
159e5acd0f5115a878d59ed59f924ce7627a5466
[ "Apache-2.0", "MIT" ]
null
null
null
native/cocos/platform/java/jni/JniHelper.cpp
SteveLau-GameDeveloper/engine
159e5acd0f5115a878d59ed59f924ce7627a5466
[ "Apache-2.0", "MIT" ]
null
null
null
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2022 Xiamen Yaji Software Co., Ltd. http://www.cocos.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated engine source code (the "Software"), a limited, worldwide, royalty-free, non-assignable, revocable and non-exclusive license to use Cocos Creator solely to develop games on your target platforms. You shall not use Cocos Creator software for developing other software or tools that's used for developing games. You are not granted to publish, distribute, sublicense, and/or sell copies of Cocos Creator. The software or tools in this License Agreement are licensed, not sold. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "platform/java/jni/JniHelper.h" #if ANDROID #include <android/log.h> #else #include "cocos/base/Log.h" #endif #include <pthread.h> #include <cstring> #include "base/UTF8.h" #define CC_CACHE_CLASS_ID 0 #if ANDROID #define LOG_TAG "JniHelper" #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) #else #define LOGD(...) CC_LOG_DEBUG(__VA_ARGS__) #define LOGE(...) CC_LOG_ERROR(__VA_ARGS__) #endif namespace { pthread_key_t g_key; // NOLINT(readability-identifier-naming) class JClassWrapper final { public: explicit JClassWrapper(jclass kls) { if (kls) { _globalKls = static_cast<jclass>(cc::JniHelper::getEnv()->NewGlobalRef(static_cast<jobject>(kls))); } } ~JClassWrapper() { if (_globalKls) { cc::JniHelper::getEnv()->DeleteGlobalRef(_globalKls); } _globalKls = nullptr; } jclass operator*() const { return _globalKls; } private: jclass _globalKls = {}; }; #if CC_CACHE_CLASS_ID ccstd::unordered_map<const char *, JClassWrapper> _cachedJClasses; #endif }; // namespace jclass _getClassID(const char *className) { // NOLINT if (nullptr == className) { return nullptr; } #if CC_CACHE_CLASS_ID auto it = _cachedJClasses.find(className); if (it != _cachedJClasses.end()) { return *it->second; } #endif JNIEnv *env = cc::JniHelper::getEnv(); jstring jstrClassName = env->NewStringUTF(className); auto *klassObj = static_cast<jclass>(env->CallObjectMethod(cc::JniHelper::classloader, cc::JniHelper::loadclassMethodMethodId, jstrClassName)); if (nullptr == klassObj || env->ExceptionCheck()) { LOGE("Classloader failed to find class of %s", className); if (env->ExceptionCheck()) { env->ExceptionDescribe(); } env->ExceptionClear(); klassObj = nullptr; } ccDeleteLocalRef(env, jstrClassName); // LOGE("1. delete 0x%p", jstrClassName); #if CC_CACHE_CLASS_ID if (klassObj) { _cachedJClasses.emplace(className, klassObj); } #endif return klassObj; } void cbDetachCurrentThread(void * /*a*/) { cc::JniHelper::getJavaVM()->DetachCurrentThread(); } namespace cc { jmethodID JniHelper::loadclassMethodMethodId = nullptr; jobject JniHelper::classloader = nullptr; std::function<void()> JniHelper::classloaderCallback = nullptr; jobject JniHelper::sActivity = nullptr; JavaVM * JniHelper::sJavaVM = nullptr; JavaVM *JniHelper::getJavaVM() { pthread_t thisthread = pthread_self(); LOGD("JniHelper::getJavaVM(), pthread_self() = %ld", thisthread); return JniHelper::sJavaVM; } void JniHelper::init(JNIEnv *env, jobject activity) { env->GetJavaVM(&JniHelper::sJavaVM); JniHelper::sActivity = activity; pthread_key_create(&g_key, cbDetachCurrentThread); auto ok = JniHelper::setClassLoaderFrom(activity); CC_ASSERT(ok); } JNIEnv *JniHelper::cacheEnv() { JavaVM *jvm = JniHelper::sJavaVM; JNIEnv *env = nullptr; // get jni environment jint ret = jvm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_4); switch (ret) { case JNI_OK: // Success! pthread_setspecific(g_key, env); return env; case JNI_EDETACHED: // Thread not attached #if CC_PLATFORM == CC_PLATFORM_ANDROID if (jvm->AttachCurrentThread(&env, nullptr) < 0) { #else if (jvm->AttachCurrentThread(reinterpret_cast<void **>(&env), nullptr) < 0) { #endif LOGE("Failed to get the environment using AttachCurrentThread()"); return nullptr; } else { // Success : Attached and obtained JNIEnv! pthread_setspecific(g_key, env); return env; } case JNI_EVERSION: // Cannot recover from this error LOGE("JNI interface version 1.4 not supported"); default: LOGE("Failed to get the environment using GetEnv()"); return nullptr; } } JNIEnv *JniHelper::getEnv() { auto *env = static_cast<JNIEnv *>(pthread_getspecific(g_key)); if (env == nullptr) { env = JniHelper::cacheEnv(); } return env; } jobject JniHelper::getActivity() { return sActivity; } #if CC_PLATFORM == CC_PLATFORM_OHOS bool JniHelper::setClassLoaderFrom(jobject activityinstance) { JniMethodInfo getclassloaderMethod; if (!JniHelper::getMethodInfoDefaultClassLoader(getclassloaderMethod, "ohos/app/AbilityContext", "getClassloader", // typo ? "()Ljava/lang/ClassLoader;")) { return false; } jobject klassLoader = cc::JniHelper::getEnv()->CallObjectMethod(activityinstance, getclassloaderMethod.methodID); if (nullptr == klassLoader) { return false; } JniMethodInfo loadClass; if (!JniHelper::getMethodInfoDefaultClassLoader(loadClass, "java/lang/ClassLoader", "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;")) { return false; } JniHelper::classloader = cc::JniHelper::getEnv()->NewGlobalRef(klassLoader); JniHelper::loadclassMethodMethodId = loadClass.methodID; JniHelper::sActivity = cc::JniHelper::getEnv()->NewGlobalRef(activityinstance); if (JniHelper::classloaderCallback != nullptr) { JniHelper::classloaderCallback(); } return true; } #elif CC_PLATFORM == CC_PLATFORM_ANDROID bool JniHelper::setClassLoaderFrom(jobject activityinstance) { JniMethodInfo getClassloaderMethod; if (!JniHelper::getMethodInfoDefaultClassLoader(getClassloaderMethod, "android/content/Context", "getClassLoader", "()Ljava/lang/ClassLoader;")) { return false; } jobject classLoader = cc::JniHelper::getEnv()->CallObjectMethod(activityinstance, getClassloaderMethod.methodID); if (nullptr == classLoader) { return false; } JniMethodInfo loadClass; if (!JniHelper::getMethodInfoDefaultClassLoader(loadClass, "java/lang/ClassLoader", "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;")) { return false; } JniHelper::classloader = cc::JniHelper::getEnv()->NewGlobalRef(classLoader); JniHelper::loadclassMethodMethodId = loadClass.methodID; JniHelper::sActivity = cc::JniHelper::getEnv()->NewGlobalRef(activityinstance); if (JniHelper::classloaderCallback != nullptr) { JniHelper::classloaderCallback(); } return true; } #endif bool JniHelper::getStaticMethodInfo(JniMethodInfo &methodinfo, const char * className, const char * methodName, const char * paramCode) { if ((nullptr == className) || (nullptr == methodName) || (nullptr == paramCode)) { return false; } JNIEnv *env = JniHelper::getEnv(); if (!env) { LOGE("Failed to get JNIEnv"); return false; } jclass classID = _getClassID(className); if (!classID) { LOGE("Failed to find class %s", className); env->ExceptionClear(); return false; } jmethodID methodID = env->GetStaticMethodID(classID, methodName, paramCode); if (!methodID) { LOGE("Failed to find static method id of %s", methodName); env->ExceptionClear(); return false; } methodinfo.classID = classID; methodinfo.env = env; methodinfo.methodID = methodID; return true; } //NOLINTNEXTLINE bool JniHelper::getMethodInfoDefaultClassLoader(JniMethodInfo &methodinfo, const char * className, const char * methodName, const char * paramCode) { if ((nullptr == className) || (nullptr == methodName) || (nullptr == paramCode)) { return false; } JNIEnv *env = JniHelper::getEnv(); if (!env) { return false; } jclass classID = env->FindClass(className); if (!classID) { LOGE("Failed to find class %s", className); env->ExceptionClear(); return false; } jmethodID methodID = env->GetMethodID(classID, methodName, paramCode); if (!methodID) { LOGE("Failed to find method id of %s", methodName); env->ExceptionClear(); return false; } methodinfo.classID = classID; methodinfo.env = env; methodinfo.methodID = methodID; return true; } bool JniHelper::getMethodInfo(JniMethodInfo &methodinfo, const char * className, const char * methodName, const char * paramCode) { if ((nullptr == className) || (nullptr == methodName) || (nullptr == paramCode)) { return false; } JNIEnv *env = JniHelper::getEnv(); if (!env) { return false; } jclass classID = _getClassID(className); if (!classID) { LOGE("Failed to find class %s", className); env->ExceptionClear(); return false; } jmethodID methodID = env->GetMethodID(classID, methodName, paramCode); if (!methodID) { LOGE("Failed to find method id of %s", methodName); env->ExceptionClear(); return false; } methodinfo.classID = classID; methodinfo.env = env; methodinfo.methodID = methodID; return true; } ccstd::string JniHelper::jstring2string(jstring jstr) { if (jstr == nullptr) { return ""; } JNIEnv *env = JniHelper::getEnv(); if (!env) { return ""; } ccstd::string strValue = cc::StringUtils::getStringUTFCharsJNI(env, jstr); return strValue; } jstring JniHelper::convert(JniHelper::LocalRefMapType *localRefs, cc::JniMethodInfo *t, const char *x) { jstring ret = nullptr; if (x) { ret = cc::StringUtils::newStringUTFJNI(t->env, x); } (*localRefs)[t->env].push_back(ret); return ret; } jstring JniHelper::convert(JniHelper::LocalRefMapType *localRefs, cc::JniMethodInfo *t, const ccstd::string &x) { return convert(localRefs, t, x.c_str()); } jobject JniHelper::convert(JniHelper::LocalRefMapType *localRefs, cc::JniMethodInfo *t, const std::vector<std::string> &x) { jclass stringClass = _getClassID("java/lang/String"); jobjectArray ret = t->env->NewObjectArray(x.size(), stringClass, nullptr); for (auto i = 0; i < x.size(); i++) { jstring jstr = cc::StringUtils::newStringUTFJNI(t->env, x[i]); t->env->SetObjectArrayElement(ret, i, jstr); t->env->DeleteLocalRef(jstr); } (*localRefs)[t->env].push_back(ret); return ret; } void JniHelper::deleteLocalRefs(JNIEnv *env, JniHelper::LocalRefMapType *localRefs) { if (!env) { return; } for (const auto &ref : (*localRefs)[env]) { ccDeleteLocalRef(env, ref); // LOGE("2. delete 0x%p", ref); } (*localRefs)[env].clear(); } void JniHelper::reportError(const ccstd::string &className, const ccstd::string &methodName, const ccstd::string &signature) { LOGE("Failed to find static java method. Class name: %s, method name: %s, signature: %s ", className.c_str(), methodName.c_str(), signature.c_str()); } } //namespace cc
32.693208
153
0.588467
[ "vector" ]
529bc6283091296c25ae1f59e2ec6c7bb22d481a
6,592
cpp
C++
src/TerrainTilesCursor.cpp
codenamecpp/GrimLandsKeeper
a2207e2a459a254cbc703306ef92a09ecf714090
[ "MIT" ]
14
2020-06-27T18:51:41.000Z
2022-03-30T18:20:02.000Z
src/TerrainTilesCursor.cpp
codenamecpp/GLKeeper
a2207e2a459a254cbc703306ef92a09ecf714090
[ "MIT" ]
1
2020-06-07T09:48:11.000Z
2020-06-07T09:48:11.000Z
src/TerrainTilesCursor.cpp
codenamecpp/GrimLandsKeeper
a2207e2a459a254cbc703306ef92a09ecf714090
[ "MIT" ]
2
2020-08-27T09:38:10.000Z
2021-08-12T01:17:30.000Z
#include "pch.h" #include "TerrainTilesCursor.h" #include "SceneObject.h" #include "RenderableProcMesh.h" #include "TexturesManager.h" #include "TimeManager.h" void TerrainTilesCursor::EnterWorld() { debug_assert(mMeshObject == nullptr); mMeshObject = new RenderableProcMesh; mMeshObject->mDebugColor.mA = 0; // hide debug box SetupCursorMeshMaterial(mMeshObject); } void TerrainTilesCursor::ClearWorld() { if (mMeshObject) { mMeshObject->DestroyObject(); mMeshObject = nullptr; } mSelectionRect.w = 0; mSelectionRect.h = 0; } void TerrainTilesCursor::UpdateFrame() { float deltaTime = (float) gTimeManager.GetRealtimeFrameDelta(); mCursorEffectTime += deltaTime; if (mMeshObject) { MeshMaterial* material = mMeshObject->GetMeshMaterial(); debug_assert(material); float translucency = cxx::ping_pong(mCursorEffectTime, 0.3f); material->mMaterialColor.mR = 20 + (unsigned char)(235 * translucency); material->mMaterialColor.mG = material->mMaterialColor.mR; material->mMaterialColor.mB = material->mMaterialColor.mR; } } void TerrainTilesCursor::UpdateCursor(const Rectangle& selectionRect) { if (selectionRect == mSelectionRect) return; mSelectionRect = selectionRect; SetupCursorMesh(); } void TerrainTilesCursor::UpdateCursor(const Point& selectionPoint) { Rectangle rcSelection; rcSelection.x = selectionPoint.x; rcSelection.y = selectionPoint.y; rcSelection.w = 1; rcSelection.h = 1; UpdateCursor(rcSelection); } void TerrainTilesCursor::ClearCursor() { mSelectionRect.w = 0; mSelectionRect.h = 0; SetupCursorMesh(); } void TerrainTilesCursor::SetupCursorMesh() { if (mMeshObject == nullptr) { debug_assert(false); return; } // it is possible to cache mesh component if (mMeshObject == nullptr) { debug_assert(false); return; } mMeshObject->ClearMesh(); if (mSelectionRect.w == 0 || mSelectionRect.h == 0) { mMeshObject->UpdateBounds(); return; } cxx::aabbox areaBounds; GetTerrainAreaBounds(mSelectionRect, areaBounds); // setup selection trimesh mMeshObject->mTriMeshParts.resize(1); Vertex3D_TriMesh& triMesh = mMeshObject->mTriMeshParts[0]; /* /1--------/3 / | / | / | / | 5---------7 | | 0- - -| -2 | / | / |/ | / 4---------6/ */ glm::vec3 edges[8]; areaBounds.get_edges(edges); float displacement = 0.03f; // offset glm::vec3 center = areaBounds.get_center(); for (glm::vec3& curr_edge: edges) { curr_edge.x += (curr_edge.x > center.x) ? displacement : -displacement; curr_edge.y += displacement; curr_edge.z += (curr_edge.z > center.z) ? displacement : -displacement; } auto PushSelectionLine = [&center](Vertex3D_TriMesh& trimesh, const glm::vec3& point_start, const glm::vec3& point_end, bool isDiagonal) { float lineWidth = 0.03f; glm::vec3 direction = isDiagonal ? (point_start - center) : (point_end - point_start); glm::vec3 sides[2] = { isDiagonal ? glm::vec3(direction.y, 0.0f, -direction.x) : glm::vec3( direction.z, 0.0f, -direction.x), isDiagonal ? glm::vec3(direction.x, 0.0f, direction.y) : glm::vec3( 0.0f, direction.z, direction.x) }; for (const glm::vec3& currSide: sides) { glm::vec3 side_cw = glm::normalize(currSide) * lineWidth; glm::vec3 side_ccw = glm::normalize(currSide * -1.0f) * lineWidth; Color32 verticesColor = Color32_Blue; verticesColor.mA = 0; // setup vertices Vertex3D quad_vertices[4]; quad_vertices[0].mPosition = point_start + side_cw; quad_vertices[0].mColor = verticesColor; quad_vertices[0].mTexcoord = {0.0f, 1.0f}; quad_vertices[1].mPosition = point_end + side_cw; quad_vertices[1].mColor = verticesColor; quad_vertices[1].mTexcoord = {1.0f, 1.0f}; quad_vertices[2].mPosition = point_start + side_ccw; quad_vertices[2].mColor = verticesColor; quad_vertices[2].mTexcoord = {0.0f, 0.0f}; quad_vertices[3].mPosition = point_end + side_ccw; quad_vertices[3].mColor = verticesColor; quad_vertices[3].mTexcoord = {1.0f, 0.0f}; // setup triangles int indexStart = (int) trimesh.mVertices.size(); glm::ivec3 quad_triangles[2] = { glm::ivec3(indexStart + 2, indexStart + 0, indexStart + 1), glm::ivec3(indexStart + 1, indexStart + 3, indexStart + 2), }; trimesh.AppendVertices(quad_vertices, 4); trimesh.AppendTriangles(quad_triangles, 2); } }; PushSelectionLine(triMesh, edges[5], edges[7], false); PushSelectionLine(triMesh, edges[5], edges[1], false); PushSelectionLine(triMesh, edges[1], edges[3], false); PushSelectionLine(triMesh, edges[7], edges[3], false); PushSelectionLine(triMesh, edges[0], edges[2], false); PushSelectionLine(triMesh, edges[0], edges[4], false); PushSelectionLine(triMesh, edges[4], edges[6], false); PushSelectionLine(triMesh, edges[2], edges[6], false); // diagonals PushSelectionLine(triMesh, edges[1], edges[0], true); PushSelectionLine(triMesh, edges[5], edges[4], true); PushSelectionLine(triMesh, edges[7], edges[6], true); PushSelectionLine(triMesh, edges[3], edges[2], true); mMeshObject->InvalidateMesh(); mMeshObject->UpdateBounds(); } void TerrainTilesCursor::SetupCursorMeshMaterial(RenderableProcMesh* component) { debug_assert(mMeshObject); debug_assert(component); component->SetMeshMaterialsCount(1); MeshMaterial* material = component->GetMeshMaterial(); debug_assert(material); material->mRenderStates.mIsDepthWriteEnabled = false; material->mRenderStates.mIsAlphaBlendEnabled = true; material->mRenderStates.mIsFaceCullingEnabled = false; material->mRenderStates.mBlendingMode = eBlendingMode_Additive; material->mDiffuseTexture = gTexturesManager.mCursorTexture; material->mMaterialColor = Color32_NULL; }
33.125628
149
0.616808
[ "mesh" ]
52a3612b633648085a0547e684026bbdf57d7df1
7,916
cpp
C++
catflow/cpp/test/JsonObjectTest.cpp
PancakeSoftware/openHabAI
362846055d0bea0bbbe56ba96806de0303de53c1
[ "MIT" ]
7
2018-05-24T15:08:48.000Z
2020-07-09T05:38:01.000Z
catflow/cpp/test/JsonObjectTest.cpp
PancakeSoftware/openHabAI
362846055d0bea0bbbe56ba96806de0303de53c1
[ "MIT" ]
3
2018-05-10T17:49:39.000Z
2022-02-26T03:22:54.000Z
catflow/cpp/test/JsonObjectTest.cpp
PancakeSoftware/openHabAI
362846055d0bea0bbbe56ba96806de0303de53c1
[ "MIT" ]
2
2018-07-21T17:45:28.000Z
2020-02-20T14:19:30.000Z
/* * File: Test * Author: Joshua Johannson * */ #include <gtest/gtest.h> #include "TestHelper.hpp" #include <ApiJsonObject.h> #include <server/ApiServer.h> class MyObject : public ApiJsonObject { public: int i = 10; string s = ""; bool b = false; string pNonSave = ""; string pReadonly = "keep this value"; string pHidden = "hidden value"; bool iChanged = false, sChanged = false, bChanged = false; void params() override {JsonObject::params(); param("i", i).onChanged([this]() {iChanged = true;} ); param("s", s); param("b", b); param("nonSave", pNonSave).nonSave(); param("readOnly", pReadonly).readOnly(); param("hidden", pHidden).hidden(); } void onParamsChanged(vector<string> params) override { if (find(params.begin(), params.end(), "s") != params.end()) sChanged = true; if (find(params.begin(), params.end(), "b") != params.end()) bChanged = true; } }; TEST(JsonObjectTest, fromToJson) { Json valIn{ {"i", 20}, {"s", "string"}, {"b", true}, {"dontHave", "error"}, {"nonSave", "nonSave me"}, {"readOnly", "no write me"}, {"hidden", "new hiddenValue"} }; Json valOut{ {"i", 20}, {"s", "string"}, {"b", true}, {"nonSave", "nonSave me"}, {"readOnly", "keep this value"}, }; MyObject myObject; myObject.fromJson(valIn, true /*catch all exceptions*/); EXPECT_EQ(20, myObject.i); EXPECT_EQ("string", myObject.s); EXPECT_EQ(true, myObject.b); EXPECT_TRUE(testCompareJson( Json{ {"s", "string"}, {"b", true}, }, myObject.toJson({"s", "b"}))); EXPECT_TRUE(testCompareJson(valOut, myObject.toJson())); // toJson with hidden valOut["hidden"] = "new hiddenValue"; EXPECT_TRUE(testCompareJson(valOut, myObject.toJson(false, false))); } TEST(JsonObjectTest, saveLoad) { Json val{ {"i", 20}, {"s", "string"}, {"b", true}, {"dontHave", "error"}, {"nonSave", "nonSave me"}, {"readOnly", "not write me"} }; MyObject myObject; myObject.fromJson(val, true /*catch all exceptions*/); myObject.save("./test/", "testJsonObject.json"); cout << "save finish" << endl; MyObject myObjectNew; cout << "now load" << endl; myObjectNew.load("./test/", "testJsonObject.json"); // non save should have changed val["nonSave"] = ""; val["readOnly"] = "keep this value"; val.erase("dontHave"); EXPECT_EQ(20, myObjectNew.i); EXPECT_EQ("string", myObjectNew.s); EXPECT_EQ(true, myObjectNew.b); EXPECT_TRUE(testCompareJson(val, myObjectNew.toJson())); } TEST(JsonObjectTest, exceptions) { Json val{ {"i", false}, {"s", 100}, {"b", true} }; MyObject myObject; try { myObject = val; cout << myObject.toJson().dump(2) << endl; //FAIL(); } catch (exception &e) { SUCCEED(); } } class SimpleObj: public ApiJsonObject{ public: float from; float to; int id; string name = "--"; vector<int> vec; vector<SimpleObj> objVec; SimpleObj(){ cout << endl << "[SimpleObj] '"<< name <<"' create" << endl; cout << "pointer from: " << static_cast<void*>(&from) << endl; cout << "pointer name: " << static_cast<void*>(&name) << endl; } void params() override { JsonObject::params(); cout << "[SimpleObj] defineParams() " << endl; param("from", from); param("to", to); param("id", id); param("name", name); param("vec", vec); param("objVec", objVec); } }; class As { public: string name = "--"; As(string name) { this->name = name; cout << "Constructor " << name << endl; } As(const As& old) { cout << "Copy "<< name << " other: " << old.name << endl; //*this = old; } As& operator=(As const &r) { cout << "Copy assign "<< name << " other: " << r.name << endl; //*this = r; return *this; } ~As() { cout << "delete "<< name << endl; } }; TEST(JsonObjectTest, simpleJsonObject) { { As a("a"); As b("b"); b = a; cout << "Name: " << b.name << endl; As c = a; } Json json{ {"from", 1.0}, {"to", 4.0}, {"id",2}, {"name", "outer"}, {"vec", {1,2,3,4}}, {"objVec", {{ {"from", 99.0}, {"to", 999.0}, {"id",222}, {"name", "inner"}, {"vec", {122,222,322,422}}, {"objVec", Json::array()} }} } }; SimpleObj obj; obj.params(); obj.name = "OLD"; cout << endl << "======= fromJson ==" << endl; obj = json; //vector<string> a; //a = json.get<vector<string>>(); cout << endl << "======= toJson ==" << endl; cout << "from: " << obj.from << " name:" << obj.name << endl; Json out = obj; EXPECT_TRUE(testCompareJson(json, out)); cout << "Json: " << out.dump(2) << endl; } TEST(JsonObjectTest, notifyParamsChanged) { // check send package queue EXPECT_EQ(0, Catflow::requestsToSend.size()); MyObject obj; obj.setStorePath("./test/jsonObjectTest"); ApiRequest sub("", "subscribe"); sub.client = new VoidClient(); obj.processApi(sub); obj.s = "test"; obj.i = 12345; obj.pHidden = "some other hidden value"; obj.notifyParamsChanged({"i", "s", "not-a-param", "hidden"}); // check send package queue EXPECT_TRUE(1 <= Catflow::requestsToSend.size()); EXPECT_TRUE(testCompareJson( ApiRequest("", "update", Json{ {"s", "test"}, {"i", 12345}, {"hidden", "some other hidden value"} }).toJson(), Catflow::requestsToSend.back().second.toJson())); // cleanup Catflow::requestsToSend.clear(); } class ObjWithFunction: public JsonObject { public: string text; map<int, string> idMap; //@TODO somehow map<K, V> can only be set if K = string void params() override { JsonObject::params(); paramWithFunction("text", [this](Json j) {text = j;}, [](){ return "set from lambda!";}); paramWithFunction("idMap", [this](Json j) { idMap.clear(); for (auto it=j.begin(); it!=j.end(); it++) idMap.insert(make_pair(it.value().begin().value(), next(it.value().begin()).value().get<string>())); }, [this] () { return idMap;} ); } }; TEST(JsonObjectTest, paramWithFunction) { ObjWithFunction objWithFunction; Json setJ{ {"text", "hello"}, {"idMap", { {1, "first"}, {2, "second"}, }} }; /* * setJ = * { * "text": "hello", * "idMap": [ * [ * 1, * "first" * ], * [ * 2, * "second" * ] * ], * } */ objWithFunction = setJ; map<int, string> idMap = { {1, "first"}, {2, "second"} }; EXPECT_EQ("hello", objWithFunction.text); EXPECT_EQ(idMap, objWithFunction.idMap); EXPECT_TRUE(testCompareJson( Json{ {"text", "set from lambda!"}, {"idMap", { {1, "first"}, {2, "second"}, }} }, objWithFunction.toJson())); } TEST(JsonObjectTest, onParamChanged) { MyObject myObject; EXPECT_EQ(myObject.sChanged, false); EXPECT_EQ(myObject.iChanged, false); EXPECT_EQ(myObject.bChanged, false); myObject.fromJson( Json{ {"i", 20}, {"b", true}, }); EXPECT_EQ(myObject.sChanged, false); EXPECT_EQ(myObject.iChanged, true); EXPECT_EQ(myObject.bChanged, true); myObject.fromJson( Json{ {"s", "lol"} }); EXPECT_EQ(myObject.sChanged, true); EXPECT_EQ(myObject.iChanged, true); EXPECT_EQ(myObject.bChanged, true); }
22.298592
100
0.52476
[ "vector" ]
52a9f7e204e872f39980e7cdf9e400b7f627c949
10,903
cpp
C++
src/ArduinoOcpp/Core/OcppOperation.cpp
othorne-public/ArduinoOcpp
7e63351917a12707bc0b9cd8d3a8680306661f49
[ "MIT" ]
null
null
null
src/ArduinoOcpp/Core/OcppOperation.cpp
othorne-public/ArduinoOcpp
7e63351917a12707bc0b9cd8d3a8680306661f49
[ "MIT" ]
null
null
null
src/ArduinoOcpp/Core/OcppOperation.cpp
othorne-public/ArduinoOcpp
7e63351917a12707bc0b9cd8d3a8680306661f49
[ "MIT" ]
null
null
null
// matth-x/ArduinoOcpp // Copyright Matthias Akstaller 2019 - 2022 // MIT License #include <ArduinoOcpp/Core/OcppOperation.h> #include <ArduinoOcpp/Core/OcppMessage.h> #include <ArduinoOcpp/Core/OcppModel.h> #include <ArduinoOcpp/Core/OcppSocket.h> #include <ArduinoOcpp/Platform.h> #include <ArduinoOcpp/Debug.h> int unique_id_counter = 1000000; using namespace ArduinoOcpp; OcppOperation::OcppOperation(std::unique_ptr<OcppMessage> msg) : ocppMessage(std::move(msg)) { } OcppOperation::OcppOperation() { } OcppOperation::~OcppOperation(){ } void OcppOperation::setOcppMessage(std::unique_ptr<OcppMessage> msg){ ocppMessage = std::move(msg); } void OcppOperation::setOcppModel(std::shared_ptr<OcppModel> oModel) { if (!ocppMessage) { AO_DBG_ERR("Must be called after setOcppMessage(). Abort"); return; } if (!oModel) { AO_DBG_ERR("Passed nullptr. Ignore"); return; } ocppMessage->setOcppModel(oModel); } void OcppOperation::setTimeout(std::unique_ptr<Timeout> to){ if (!to){ AO_DBG_ERR("Passed nullptr! Ignore"); return; } timeout = std::move(to); timeout->setOnTimeoutListener(onTimeoutListener); timeout->setOnAbortListener(onAbortListener); } Timeout *OcppOperation::getTimeout() { return timeout.get(); } void OcppOperation::setMessageID(const std::string &id){ if (!messageID.empty()){ AO_DBG_WARN("MessageID is set twice or is set after first usage!"); } messageID = id; } const std::string *OcppOperation::getMessageID() { if (messageID.empty()) { char id_str [16] = {'\0'}; sprintf(id_str, "%d", unique_id_counter++); messageID = std::string {id_str}; //messageID = std::to_string(unique_id_counter++); } return &messageID; } boolean OcppOperation::sendReq(OcppSocket& ocppSocket){ /* * timeout behaviour * * if timeout, print out error message and treat this operation as completed (-> return true) */ if (timeout->isExceeded()) { //cancel this operation AO_DBG_INFO("%s has timed out! Discard operation", ocppMessage->getOcppOperationType()); return true; } /* * retry behaviour * * if retry, run the rest of this function, i.e. resend the message. If not, just return false */ if (ao_tick_ms() <= retry_start + RETRY_INTERVAL * retry_interval_mult) { //NO retry return false; } // Do retry. Increase timer by factor 2 if (RETRY_INTERVAL * retry_interval_mult * 2 <= RETRY_INTERVAL_MAX) retry_interval_mult *= 2; /* * Create the OCPP message */ auto requestPayload = ocppMessage->createReq(); if (!requestPayload) { onAbortListener(); return true; } /* * Create OCPP-J Remote Procedure Call header */ size_t json_buffsize = JSON_ARRAY_SIZE(4) + (getMessageID()->length() + 1) + requestPayload->capacity(); DynamicJsonDocument requestJson(json_buffsize); requestJson.add(MESSAGE_TYPE_CALL); //MessageType requestJson.add(*getMessageID()); //Unique message ID requestJson.add(ocppMessage->getOcppOperationType()); //Action requestJson.add(*requestPayload); //Payload /* * Serialize and send. Destroy serialization and JSON object. * * If sending was successful, start timer * * Return that this function must be called again (-> false) */ std::string out {}; serializeJson(requestJson, out); if (printReqCounter > 5000) { printReqCounter = 0; AO_DBG_DEBUG("Try to send request: %s", out.c_str()); } printReqCounter++; bool success = ocppSocket.sendTXT(out); timeout->tick(success); if (success) { AO_DBG_TRAFFIC_OUT(out.c_str()); retry_start = ao_tick_ms(); } else { //ocppSocket is not able to put any data on TCP stack. Maybe because we're offline retry_start = 0; retry_interval_mult = 1; } return false; } boolean OcppOperation::receiveConf(JsonDocument& confJson){ /* * check if messageIDs match. If yes, continue with this function. If not, return false for message not consumed */ if (*getMessageID() != confJson[1].as<std::string>()){ return false; } /* * Hand the payload over to the OcppMessage object */ JsonObject payload = confJson[2]; ocppMessage->processConf(payload); /* * Hand the payload over to the onReceiveConf Callback */ onReceiveConfListener(payload); /* * return true as this message has been consumed */ return true; } boolean OcppOperation::receiveError(JsonDocument& confJson){ /* * check if messageIDs match. If yes, continue with this function. If not, return false for message not consumed */ if (*getMessageID() != confJson[1].as<std::string>()){ return false; } /* * Hand the error over to the OcppMessage object */ const char *errorCode = confJson[2]; const char *errorDescription = confJson[3]; JsonObject errorDetails = confJson[4]; bool abortOperation = ocppMessage->processErr(errorCode, errorDescription, errorDetails); if (abortOperation) { onReceiveErrorListener(errorCode, errorDescription, errorDetails); onAbortListener(); } else { //restart operation timeout->restart(); retry_start = 0; retry_interval_mult = 1; } return abortOperation; } boolean OcppOperation::receiveReq(JsonDocument& reqJson){ std::string reqId = reqJson[1]; setMessageID(reqId); //TODO What if client receives requests two times? Can happen if previous conf is lost. In the Smart Charging Profile // it probably doesn't matter to repeat an operation on the EVSE. Change in future? /* * Hand the payload over to the OcppOperation object */ JsonObject payload = reqJson[3]; ocppMessage->processReq(payload); /* * Hand the payload over to the first Callback. It is a callback that notifies the client that request has been processed in the OCPP-library */ onReceiveReqListener(payload); reqExecuted = true; //ensure that the conf is only sent after the req has been executed return true; //true because everything was successful. If there will be an error check in future, this value becomes more reasonable } boolean OcppOperation::sendConf(OcppSocket& ocppSocket){ if (!reqExecuted) { //wait until req has been executed return false; } /* * Create the OCPP message */ std::unique_ptr<DynamicJsonDocument> confJson = nullptr; std::unique_ptr<DynamicJsonDocument> confPayload = std::unique_ptr<DynamicJsonDocument>(ocppMessage->createConf()); std::unique_ptr<DynamicJsonDocument> errorDetails = nullptr; bool operationSuccess = ocppMessage->getErrorCode() == nullptr && confPayload != nullptr; if (operationSuccess) { /* * Create OCPP-J Remote Procedure Call header */ size_t json_buffsize = JSON_ARRAY_SIZE(3) + (getMessageID()->length() + 1) + confPayload->capacity(); confJson = std::unique_ptr<DynamicJsonDocument>(new DynamicJsonDocument(json_buffsize)); confJson->add(MESSAGE_TYPE_CALLRESULT); //MessageType confJson->add(*getMessageID()); //Unique message ID confJson->add(*confPayload); //Payload } else { //operation failure. Send error message instead const char *errorCode = ocppMessage->getErrorCode(); const char *errorDescription = ocppMessage->getErrorDescription(); errorDetails = std::unique_ptr<DynamicJsonDocument>(ocppMessage->getErrorDetails()); if (!errorCode) { //catch corner case when payload is null but errorCode is not set too! errorCode = "GenericError"; errorDescription = "Could not create payload (createConf() returns Null)"; errorDetails = std::unique_ptr<DynamicJsonDocument>(createEmptyDocument()); } /* * Create OCPP-J Remote Procedure Call header */ size_t json_buffsize = JSON_ARRAY_SIZE(5) + (getMessageID()->length() + 1) + strlen(errorCode) + 1 + strlen(errorDescription) + 1 + errorDetails->capacity(); confJson = std::unique_ptr<DynamicJsonDocument>(new DynamicJsonDocument(json_buffsize)); confJson->add(MESSAGE_TYPE_CALLERROR); //MessageType confJson->add(*getMessageID()); //Unique message ID confJson->add(errorCode); confJson->add(errorDescription); confJson->add(*errorDetails); //Error description } /* * Serialize and send. Destroy serialization and JSON object. */ std::string out {}; serializeJson(*confJson, out); boolean wsSuccess = ocppSocket.sendTXT(out); if (wsSuccess) { if (operationSuccess) { AO_DBG_TRAFFIC_OUT(out.c_str()); onSendConfListener(confPayload->as<JsonObject>()); } else { AO_DBG_WARN("Operation failed. JSON CallError message: %s", out.c_str()); onAbortListener(); } } return wsSuccess; } void OcppOperation::setInitiated() { if (ocppMessage) { ocppMessage->initiate(); } else { AO_DBG_ERR("Missing ocppMessage instance"); } } void OcppOperation::setOnReceiveConfListener(OnReceiveConfListener onReceiveConf){ if (onReceiveConf) onReceiveConfListener = onReceiveConf; } /** * Sets a Listener that is called after this machine processed a request by the communication counterpart */ void OcppOperation::setOnReceiveReqListener(OnReceiveReqListener onReceiveReq){ if (onReceiveReq) onReceiveReqListener = onReceiveReq; } void OcppOperation::setOnSendConfListener(OnSendConfListener onSendConf){ if (onSendConf) onSendConfListener = onSendConf; } void OcppOperation::setOnTimeoutListener(OnTimeoutListener onTimeout) { if (onTimeout) onTimeoutListener = onTimeout; } void OcppOperation::setOnReceiveErrorListener(OnReceiveErrorListener onReceiveError) { if (onReceiveError) onReceiveErrorListener = onReceiveError; } void OcppOperation::setOnAbortListener(OnAbortListener onAbort) { if (onAbort) onAbortListener = onAbort; } boolean OcppOperation::isFullyConfigured(){ return ocppMessage != nullptr; } void OcppOperation::print_debug() { if (ocppMessage) { AO_CONSOLE_PRINTF("OcppOperation of type %s\n", ocppMessage->getOcppOperationType()); } else { AO_CONSOLE_PRINTF("OcppOperation (no type)\n"); } }
30.286111
145
0.654315
[ "object" ]
52ae4c75832d857b5b6b77f67afd5eee93c046b7
3,359
cpp
C++
src/code-examples/chapter-12/bookmark-service-with-reply/main.cpp
nhatvu148/helpers
1a6875017cf39790dfe40ecec9dcee4410b1d89e
[ "MIT" ]
null
null
null
src/code-examples/chapter-12/bookmark-service-with-reply/main.cpp
nhatvu148/helpers
1a6875017cf39790dfe40ecec9dcee4410b1d89e
[ "MIT" ]
null
null
null
src/code-examples/chapter-12/bookmark-service-with-reply/main.cpp
nhatvu148/helpers
1a6875017cf39790dfe40ecec9dcee4410b1d89e
[ "MIT" ]
null
null
null
// Standard library #include <iostream> #include <string> // JSON library #include <nlohmann/json.hpp> using json = nlohmann::json; // Utilities #include "expected.h" #include "mtry.h" #include "trim.h" // Our reactive stream implementation #include "filter.h" #include "join.h" #include "sink.h" #include "transform.h" #include "values.h" // Service implementation #include "service.h" /** * For funcitons that return json objects, but which can fail * and return an exception */ using expected_json = expected<json, std::exception_ptr>; /** * Basic bookmark information. Holds an URL and a title */ struct bookmark_t { std::string url; std::string text; }; /** * Creates a string from the bookmark info in the following format: * [text](url) */ std::string to_string(const bookmark_t& page) { return "[" + page.text + "](" + page.url + ")"; } /** * Writes the bookmark info in the following format: * [text](url) */ std::ostream& operator<<(std::ostream& out, const bookmark_t& page) { return out << "[" << page.text << "](" << page.url << ")"; } /** * Type that contains a bookmark or an error (an exception) */ using expected_bookmark = expected<bookmark_t, std::exception_ptr>; /** * Tries to read the bookmark info from JSON. In the case * of failure, it will return an exception. */ expected_bookmark bookmark_from_json(const json& data) { return mtry([&] { return bookmark_t { data.at("FirstURL"), data.at("Text") }; }); } int main(int argc, char *argv[]) { using namespace reactive::operators; // We are lifting the transform and filter functions // to work on the with_client<T> type that adds the // socket information to the given value so that we // can reply to the client auto transform = [](auto f) { return reactive::operators::transform(lift_with_client(f)); }; auto filter = [](auto f) { return reactive::operators::filter(apply_with_client(f)); }; boost::asio::io_service event_loop; auto pipeline = service(event_loop) | transform(trim) // Ignoring comments and empty messages | filter([] (const std::string &message) { return message.length() > 0 && message[0] != '#'; }) // Trying to parse the input | transform([] (const std::string &message) { return mtry([&] { return json::parse(message); }); }) // Converting the result into the bookmark | transform([] (const auto& exp) { return mbind(exp, bookmark_from_json); }) | sink([] (const auto &message) { const auto exp_bookmark = message.value; if (!exp_bookmark) { message.reply("ERROR: Request not understood\n"); return; } if (exp_bookmark->text.find("C++") != std::string::npos) { message.reply("OK: " + to_string(exp_bookmark.get()) + "\n"); } else { message.reply("ERROR: Not a C++-related link\n"); } }); // Starting the Boost.ASIO service std::cerr << "Service is running...\n"; event_loop.run(); }
25.641221
81
0.574873
[ "transform" ]
1ed1860441ed1eccc130772814cff3e755e029e0
26,038
cpp
C++
OpenSim/Common/Mtx.cpp
MaartenAfschrift/OpenSim_SourceAD
e063021c44e15744cfc5438b5fe5250d02018098
[ "Apache-2.0" ]
2
2020-10-30T09:08:44.000Z
2020-12-08T07:15:54.000Z
OpenSim/Common/Mtx.cpp
MaartenAfschrift/OpenSim_SourceAD
e063021c44e15744cfc5438b5fe5250d02018098
[ "Apache-2.0" ]
null
null
null
OpenSim/Common/Mtx.cpp
MaartenAfschrift/OpenSim_SourceAD
e063021c44e15744cfc5438b5fe5250d02018098
[ "Apache-2.0" ]
null
null
null
///* -------------------------------------------------------------------------- * // * OpenSim: Mtx.cpp * // * -------------------------------------------------------------------------- * // * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * // * See http://opensim.stanford.edu and the NOTICE file for more information. * // * OpenSim is developed at Stanford University and supported by the US * // * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * // * through the Warrior Web program. * // * * // * Copyright (c) 2005-2017 Stanford University and the Authors * // * Author(s): Frank C. Anderson * // * * // * 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. * // * -------------------------------------------------------------------------- */ // ///* Note: This code was originally developed by Realistic Dynamics Inc. // * Author: Frank C. Anderson // */ // //#include "Mtx.h" //#include <string.h> // for memcpy in Linux // // ////============================================================================= //// STATIC VARIABLES ////============================================================================= // // //using namespace OpenSim; //using SimTK::Vec3; // //int Mtx::_PSpaceSize = 0; //int Mtx::_WSpaceSize = 0; //osim_double_adouble** Mtx::_P1Space = NULL; //osim_double_adouble** Mtx::_P2Space = NULL; //osim_double_adouble* Mtx::_WSpace = NULL; //static const osim_double_adouble eps = std::numeric_limits<osim_double_adouble>::epsilon(); // // ////============================================================================= //// CONSTRUCTOR(S) AND DESTRUCTOR ////============================================================================= // ////----------------------------------------------------------------------------- //// INTERPOLATION ////----------------------------------------------------------------------------- ////_____________________________________________________________________________ ///** // * Linearly interpolate or extrapolate an array of data. // */ //void Mtx:: //Interpolate(int aN,osim_double_adouble aT1,osim_double_adouble *aY1,osim_double_adouble aT2,osim_double_adouble *aY2, // osim_double_adouble aT,osim_double_adouble *aY) //{ // // DETERMINE PERCENT OF INTERVAL // int i; // osim_double_adouble pct; // osim_double_adouble num = aT-aT1; // osim_double_adouble den = aT2-aT1; // if(den==0.0) { // pct = 0.0; // } else { // pct = num/den; // } // // // LOOP OVER ARRAY // for(i=0;i<aN;i++) { // if(pct==0.0) { // aY[i] = aY1[i]; // } else { // aY[i] = aY1[i] + pct*(aY2[i]-aY1[i]); // } // } //} ////_____________________________________________________________________________ ///** // * Linearly interpolate or extrapolate two data points. // */ //osim_double_adouble Mtx:: //Interpolate(osim_double_adouble aT1,osim_double_adouble aY1,osim_double_adouble aT2,osim_double_adouble aY2,osim_double_adouble aT) //{ // // DETERMINE PERCENT OF INTERVAL // osim_double_adouble pct; // osim_double_adouble num = aT-aT1; // osim_double_adouble den = aT2-aT1; // if(den==0.0) { // pct = 0.0; // } else { // pct = num/den; // } // // // INTERP // osim_double_adouble y; // if(pct==0.0) { // y = aY1; // } else { // y = aY1 + pct*(aY2-aY1); // } // return(y); //} // // ////============================================================================= //// TRANSLATION AND ROTATION ////============================================================================= ////----------------------------------------------------------------------------- //// TRANSLATION ////----------------------------------------------------------------------------- ////_____________________________________________________________________________ ///** // * Translate a point by a specified amount. // * // * @param aX Amount to translate in the X direction. // * @param aY Amount to translate in the Y direction. // * @param aZ Amount to translate in the Z direction. // * @param aP Point to translate. // * @param rP Translated point. aP and rP may coincide in memory. // */ //void Mtx:: //Translate(osim_double_adouble aX,osim_double_adouble aY,osim_double_adouble aZ,const osim_double_adouble aP[3],osim_double_adouble rP[3]) //{ // rP[0] = aP[0] + aX; // rP[1] = aP[1] + aY; // rP[2] = aP[2] + aZ; //} // ////----------------------------------------------------------------------------- //// ROTATE BY RADIANS ////----------------------------------------------------------------------------- ////_____________________________________________________________________________ ///** // * Rotate a point about the X, Y, or Z axis by a specified amount. // * // * @param aXYZ Specify whether to rotate about the X (aXYZ=0), Y (aXYZ=1), // * or Z (aXYZ=2) axes. If aXYZ is not 0, 1, or 2, no rotation is performed. // * @param aRadians Amount of rotation in radians. // * @param aP Point to rotate. // * @param rP Rotated point. aP and rP may coincide in memory. // */ //void Mtx:: //Rotate(int aXYZ,osim_double_adouble aRadians,const osim_double_adouble aP[3],osim_double_adouble rP[3]) //{ // if(aP==NULL) return; // if(rP==NULL) return; // // // COPY // osim_double_adouble p0 = aP[0]; // osim_double_adouble p1 = aP[1]; // osim_double_adouble p2 = aP[2]; // // // COMPUTE SIN AND COS // osim_double_adouble c = cos(aRadians); // osim_double_adouble s = sin(aRadians); // // // X // if(aXYZ==0) { // rP[0] = p0; // rP[1] = c*p1 - s*p2; // rP[2] = s*p1 + c*p2; // // // Y // } else if(aXYZ==1) { // rP[0] = c*p0 + s*p2; // rP[1] = p1; // rP[2] = -s*p0 + c*p2; // // // Z // } else if(aXYZ==2) { // rP[0] = c*p0 - s*p1; // rP[1] = s*p0 + c*p1; // rP[2] = p2; // } //} ////_____________________________________________________________________________ ///** // * Rotate a point about a specified axis by a specified amount. // * // * @param aAxis Axis about which to rotate. The axis is not assumed to be // * a unit vector; however, if the axis is the zero vector, no rotation // * is performed. // * @param aRadians Amount of rotation in radians. // * @param aP Point to rotate. // * @param rP Rotated point. aP and rP may coincide in memory. // */ //void Mtx:: //Rotate(const osim_double_adouble aAxis[3],osim_double_adouble aRadians,const osim_double_adouble aP[3],osim_double_adouble rP[3]) //{ // if(aAxis==0) return; // if(aP==NULL) return; // if(rP==NULL) return; // //} // ////----------------------------------------------------------------------------- //// ROTATE BY DEGREES ////----------------------------------------------------------------------------- ////_____________________________________________________________________________ ///** // * Rotate a point about the X axis by a specified amount. // * // * @param aXYZ Specify whether to rotate about the X (aXYZ=0), Y (aXYZ=1), // * or Z (aXYZ=2) axis. If aXYZ is not 0, 1, or 2, no rotation is performed. // * @param aDegrees Amount of rotation in degrees. // * @param aP Point to rotate. // * @param rP Rotated point. aP and rP may coincide in memory. // */ //void Mtx:: //RotateDeg(int aXYZ,osim_double_adouble aDegrees,const osim_double_adouble aP[3],osim_double_adouble rP[3]) //{ // Rotate(aXYZ,SimTK_DEGREE_TO_RADIAN*aDegrees,aP,rP); //} ////_____________________________________________________________________________ ///** // * Rotate a point about a specified axis by a specified amount. // * // * @param aAxis Axis about which to rotate. // * @param aDegrees Amount of rotation in degrees. // * @param aP Point to rotate. // * @param rP Rotated point. aP and rP may coincide in memory. // */ //void Mtx:: //RotateDeg(const osim_double_adouble aAxis[3],osim_double_adouble aDegrees,const osim_double_adouble aP[3],osim_double_adouble rP[3]) //{ // Rotate(aAxis,SimTK_DEGREE_TO_RADIAN*aDegrees,aP,rP); //} // // ////============================================================================= //// MATRIX ARITHMETIC ////============================================================================= ////_____________________________________________________________________________ ///** // * Assign a square matrix to the identity matrix: rI = I. // * The matrix must be square. // * // * @param aN Dimension of the matrix (aN=nRows, aN=nCols). // * @param rI Output identity matrix (rI = I). // * @return 0 on success, -1 on error. // * // */ //int Mtx:: //Identity(int aN,osim_double_adouble *rI) //{ // if(rI==NULL) return(-1); // if(aN<=0) return(-1); // // // ASSIGN // int i,j; // for(i=0;i<aN;i++) { // for(j=0;j<aN;j++,rI++) { // if(i==j) { // *rI = 1.0; // } else { // *rI = 0.0; // } // } // } // // return(0); //} ////_____________________________________________________________________________ ///** // * Add two matrices. // * // * If the arguments are not valid, then a -1 is returned. // * Otherwise, 0 is returned. // * // * It is permissible for aM to coincide with either aM1 or aM2. // */ //int Mtx:: //Add(int aNR,int aNC,const osim_double_adouble *aM1,const osim_double_adouble *aM2,osim_double_adouble *aM) //{ // if(aM1==NULL) return(-1); // if(aM2==NULL) return(-1); // if(aM ==NULL) return(-1); // if(aNR<=0) return(-1); // if(aNC<=0) return(-1); // // // MULTIPLY // int i,n=aNR*aNC; // for(i=0;i<n;i++,aM1++,aM2++,aM++) *aM = *aM1 + *aM2; // // return(0); //} ////_____________________________________________________________________________ ///** // * Subtract two matrices. // * // * If the arguments are not valid, then a -1 is returned. // * Otherwise, 0 is returned. // * // * It is permissible for aM to coincide with either aM1 or aM2. aM1 - aM2 // */ //int Mtx:: //Subtract(int aNR,int aNC,const osim_double_adouble *aM1,const osim_double_adouble *aM2,osim_double_adouble *aM) //{ // if(aM1==NULL) return(-1); // if(aM2==NULL) return(-1); // if(aM ==NULL) return(-1); // if(aNR<=0) return(-1); // if(aNC<=0) return(-1); // // // MULTIPLY // int i,n=aNR*aNC; // for(i=0;i<n;i++,aM1++,aM2++,aM++) *aM = *aM1 - *aM2; // // return(0); //} ////_____________________________________________________________________________ ///** // * Multiply a matrix by a scalar. // * // * It is permissible for aM and rM to coincide in memory. // * // * @param aNR Number of rows in aM. // * @param aNC Number of columns in aM. // * @param aM Matrix laid out in memory as aM[aNR][aNC]. // * @param aScalar Scalar value by which to multiply aM. // * @param rM Result of aScalar * aM. // * @return -1 if an error is encountered, 0 otherwise. // */ //int Mtx:: //Multiply(int aNR,int aNC,const osim_double_adouble *aM,osim_double_adouble aScalar,osim_double_adouble *rM) //{ // if(aM==NULL) return(-1); // if(rM ==NULL) return(-1); // if(aNR<=0) return(-1); // if(aNC<=0) return(-1); // // // MULTIPLY // int i,n=aNR*aNC; // for(i=0;i<n;i++,aM++,rM++) *rM = *aM * aScalar; // // return(0); //} ////_____________________________________________________________________________ ///** // * Multiply two matrices. // * // * If the arguments are not valid (aM1,aM2,aM==NULL), then a -1 is returned. // * Otherwise, 0 is returned. // * // * It is permissible for aM to overlap with either aM1 or aM2. // */ //int Mtx:: //Multiply(int aNR1,int aNCR,int aNC2,const osim_double_adouble *aM1,const osim_double_adouble *aM2, // osim_double_adouble *rM) //{ // if(aM1==NULL) return(-1); // if(aM2==NULL) return(-1); // if(rM ==NULL) return(-1); // if(aNR1<=0) return(-1); // if(aNCR<=0) return(-1); // if(aNC2<=0) return(-1); // // // ENSURE WORKSPACE CAPACITY // EnsureWorkSpaceCapacity(aNR1*aNC2); // // // SET POINTER INTO WORKSPACE // osim_double_adouble *m = _WSpace; // // // MULTIPLY // const osim_double_adouble *ij1=NULL,*ij2=NULL; // osim_double_adouble result,*ij=NULL; // int r1,cr,c2; // for(r1=0,ij=m;r1<aNR1;r1++) { // // for(c2=0;c2<aNC2;c2++,ij++) { // // // SET POINTERS TO BEGINNING OF ROW OF aM1 AND COLUMN OF aM2 // ij1 = aM1 + r1*aNCR; // ij2 = aM2 + c2; // // // MULTIPLY ROW OF aM1 AND COLUMN OF aM2 // for(result=0.0,cr=0;cr<aNCR;cr++,ij1++,ij2+=aNC2) { // result += (*ij1) * (*ij2); // } // *ij = result; // } // } // // // COPY RESULTS INTO rM // memcpy(rM,m,aNR1*aNC2*sizeof(osim_double_adouble)); // // return(0); //} ////_____________________________________________________________________________ ///** // * Compute the inverse of a matrix. // * // * If the arguments are not valid (aM==NULL), then -1 is returned. // * If the matrix is not invertible, then -2 is returned. // * Otherwise, 0 is returned. // * // * It is permissible for aM to overlap in memory with aMInv. // */ //int Mtx:: //Invert(int aN,const osim_double_adouble *aM,osim_double_adouble *rMInv) //{ // if(aN<=0) return(-1); // if(aM==NULL) return(-1); // if(rMInv==NULL) return(-1); // // // VARIABLE DECLARATIONS // osim_double_adouble *M,**Mp,**Mr,**Ip,**Ir,*Mrj,*Irj,*Mij,*Iij,d; // int r,i,j,n; // // // ENSURE WORKSPACE CAPACITY // EnsureWorkSpaceCapacity(aN*aN); // EnsurePointerSpaceCapacity(aN); // // // INITIALIZE M (A COPY OF aM) // n = aN*aN*sizeof(osim_double_adouble); // M = _WSpace; // memcpy(M,aM,n); // // // INITIALIZE rMInv TO THE IDENTITY MATRIX // memset(rMInv,0,n); // for(r=0,Irj=rMInv,n=aN+1;r<aN;r++,Irj+=n) *Irj=1.0; // // // INITIALIZE ROW POINTERS // Mp = _P1Space; // POINTER TO BEGINNING OF POINTER1 SPACE // Mr = _P1Space; // ROW POINTERS INTO M // Ip = _P2Space; // POINTER TO BEGINNING OF POINTER2 SPACE // Ir = _P2Space; // ROW POINTERS INTO aMInv // for(r=0;r<aN;r++,Mr++,Ir++) { // i = r*aN; // *Mr = M + i; // *Ir = rMInv + i; // } // // // REDUCE MATRIX TO UPPER TRIANGULAR USING ROW OPERATIONS // for(r=0,n=aN-1;r<n;r++) { // // // SWAP // if(std::fabs(*(Mrj=Mp[r]+r)) < eps ) { // for(i=r+1;i<aN;i++) if(std::fabs(*(Mp[i]+r)) > eps ) break; // // // NON-INVERTIBLE? // if(i==aN) return(-2); // // // SWAP // Mrj=Mp[r]; Mp[r]=Mp[i]; Mp[i]=Mrj; Mrj=Mp[r]+r; // for(j=0,Irj=Ip[r],Iij=Ip[i];j<aN;j++) { // d= *Irj; *(Irj++) = *Iij; *(Iij++) = d; } // } // // // REDUCE // for(i=r+1;i<aN;i++) { // if(std::fabs(*(Mij=Mp[i]+r)) < eps ) continue; // Mrj=Mp[r]+r; // d = (*Mij)/(*Mrj); *(Mij++)=0.0; Mrj++; // for(j=r+1;j<aN;j++) *(Mij++) -= *(Mrj++)*d; // Irj=Ip[r]; Iij=Ip[i]; // for(j=0;j<aN;j++) *(Iij++) -= *(Irj++)*d; // } // } // // // NORMALIZE LAST ROW OF M AND rMInv // if(std::fabs(*(Mrj=Mp[r]+r)) < eps) return(-2); // d = 1.0 / *Mrj; *Mrj=1.0; // for(j=0,Irj=Ip[r];j<aN;j++) *(Irj++) *= d; // // // DIAGONALIZE USING ROW OPERATIONS // for(r=aN-1;r>0;) { // for(i=r-1;i>=0;i--) { // if(std::fabs(*(Mij=Mp[i]+r)) < eps) continue; // d = *Mij; *Mij=0.0; // for(j=0,Iij=Ip[i],Irj=Ip[r];j<aN;j++) *(Iij++) -= *(Irj++)*d; // } // r--; // d = 1.0 / *(Mrj=Mp[r]+r); *Mrj=1.0; // for(j=0,Irj=Ip[r];j<aN;j++) *(Irj++) *= d; // } // // return(0); //} ////_____________________________________________________________________________ ///** // * Transpose a matrix. // * // * If the arguments are invalid (e.g.,aM==NULL), then a -1 is returned. // * Otherwise, 0 is returned. // * // * It is permissible for aM to overlap in memory with aMT. // */ //int Mtx:: //Transpose(int aNR,const int aNC,const osim_double_adouble *aM,osim_double_adouble *rMT) //{ // if(aNR<=0) return(-1); // if(aNC<=0) return(-1); // if(aM==NULL) return(-1); // if(rMT==NULL) return(-1); // // // ENSURE WORKSPACE CAPACITY // int n = aNR*aNC; // EnsureWorkSpaceCapacity(n); // // // SET UP COUNTERS AND POINTERS // int r,c; // const osim_double_adouble *Mrc; // osim_double_adouble *Mcr; // osim_double_adouble *MT = _WSpace; // // // TRANSPOSE // for(r=0,Mrc=aM;r<aNR;r++) { // Mcr = MT + r; // for(c=0;c<aNC;c++,Mcr+=aNR,Mrc++) { // *Mcr = *(Mrc); // } // } // // // COPY RESULTS // memcpy(rMT,MT,n*sizeof(osim_double_adouble)); // // return(0); //} ////_____________________________________________________________________________ ///** // * Print a matrix. // */ //void Mtx:: //Print(int aNR,int aNC,const osim_double_adouble *aM,int aPrecision) //{ // int r,c,I; // // // HEADER // char format0[256]; sprintf(format0," %%%dd:",6+aPrecision); // printf(" "); // for(c=0;c<aNC;c++) printf(format0,c); // printf("\n"); // // // ROWS // char format1[256]; sprintf(format1," %%4.%dle",aPrecision); // char format2[256]; sprintf(format2," %%4.%dle",aPrecision); // for(r=0;r<aNR;r++) { // printf("%6d:",r); // for(c=0;c<aNC;c++) { // I = ComputeIndex(r,aNC,c); // if(aM[I]<0.0) { // printf(format1,aM[I]); // } else { // printf(format2,aM[I]); // } // } // printf("\n"); // } //} // // ////============================================================================= //// INDEX OPERATIONS ////============================================================================= ////_____________________________________________________________________________ ///** // * Starting at aIndex, move through the array aT and find the index of // * the element whose value is closest to but less than aTime. It is assumed // * that the array aT is monotonically increasing and has at least 2 elements. // * // * If aTime lies outside the interval of aT, the index of either the first // * point or second to last point is returned depending on whether aTime // * is below or above the interval of aT. // * // * -1 is if an error is encountered. // */ //int Mtx:: //FindIndex(int aIndex,osim_double_adouble aTime,int aNT,osim_double_adouble *aT) //{ // // ERROR CHECK // if(aNT<=1) return(-1); // if(aT==NULL) return(-1); // // // MAKE SURE aIndex IS VALID // if((aIndex>=aNT)||(aIndex<0)) aIndex=0; // // // CHECK FOR BELOW RANGE // if(aTime<=aT[0]) return(0); // // // CHECK FOR ABOVE RANGE // if(aTime>=aT[aNT-1]) return(aNT-2); // // // SEARCH BACKWARDS // int i; // if(aT[aIndex]>aTime) { // for(i=aIndex-1;i>=0;i--) { // if(aT[i]<=aTime) return(i); // } // // // SEARCH FORWARDS // } else { // for(i=aIndex+1;i<aNT;i++) { // if(aT[i]>aTime) return(i-1); // } // } // // return(-1); //} ////_____________________________________________________________________________ ///** // * Scan from the beginning of the array, aX, and find the index of the // * element such that the element's value is less than or equal to aValue and // * the next element's value is greater than aValue. // * // * If no value in the array is greater than aValue, the index of the last // * element in the array is returned. // * // * If no value in the array is less than or equal to aValue, -1 is returned. // */ //int Mtx:: //FindIndexLess(int aNX,osim_double_adouble *aX,osim_double_adouble aValue) //{ // if(aX==NULL) return(-1); // // int i,index=-1; // for(i=0;i<aNX;i++) { // if(aX[i]<=aValue) { // index = i; // } // if(aX[i]>aValue) break; // } // // return(index); //} ////_____________________________________________________________________________ ///** // * Scan from the end of the array, aX, and find the index of the // * element such that the element's value is greater than or equal to aValue // * and such that the next element's value is less than aValue. // * // * If no value in the array is less than aValue, the index of the first // * element in the array is returned. // * // * If no value in the array is greater than or equal to aValue, -1 is returned. // */ //int Mtx:: //FindIndexGreater(int aNX,osim_double_adouble *aX,osim_double_adouble aValue) //{ // if(aX==NULL) return(-1); // // int i,index=-1; // for(i=aNX-1;i>=0;i--) { // if(aX[i]>=aValue) { // index = i; // } // if(aX[i]<aValue) break; // } // // return(index); //} ////_____________________________________________________________________________ ///** // * Compute the index for an element of a three dimensional matrix as though // * the matrix were laid out in one dimension. // */ //int Mtx:: //ComputeIndex(int i2,int n1,int i1) //{ // int i = i1 + i2*n1; // return(i); //} ////_____________________________________________________________________________ ///** // * Compute the index for an element of a three dimensional matrix as though // * the matrix were laid out in one dimension. // */ //int Mtx:: //ComputeIndex(int i3,int n2,int i2,int n1,int i1) //{ // int i = i1 + i2*n1 + i3*n2*n1; // return(i); //} // ////_____________________________________________________________________________ ///** // * Get elements *,i2,i1 of a three dimensional matrix as an array, where * // * varies along the 3rd dimension, i2 the 2nd, and i1 the 1st. The first // * dimension is the dimension which varies most rapidly when the data // * is laid out in a one dimensional array, and the second dimension is the // * one which varies second most rapidly, and so on. // * // * For now, it is assumed that parameter a has enough memory allocated to // * hold the array. // */ //void Mtx:: //GetDim3(int n3,int n2,int n1,int i2,int i1,osim_double_adouble *m,osim_double_adouble *a) //{ // int i3,I; // for(i3=0;i3<n3;i3++) { // I = ComputeIndex(i3,n2,i2,n1,i1); // a[i3] = m[I]; // } //} ////_____________________________________________________________________________ ///** // * Set elements *,i2,i1 of a three dimensional matrix to the values in array a, // * where * varies along the 3rd dimension, i2 the 2nd, and i1 the 1st. The // * first dimension is the dimension which varies most rapidly when the data // * is laid out in a one dimensional array, and the second dimension is the // * one which varies second most rapidly, and so on. // */ //void Mtx:: //SetDim3(int n3,int n2,int n1,int i2,int i1,osim_double_adouble *m,osim_double_adouble *a) //{ // int i3,I; // for(i3=0;i3<n3;i3++) { // I = ComputeIndex(i3,n2,i2,n1,i1); // m[I] = a[i3]; // } //} // // ////============================================================================= //// WORKSPACE MANAGEMENT ////============================================================================= ////_____________________________________________________________________________ ///** // * Ensure that the work space is at least of size aN. // * // * If the capacity could not be increased to aN, -1 is returned. Otherwise, // * 0 is returned. // */ //int Mtx:: //EnsureWorkSpaceCapacity(int aN) //{ // if(aN>_WSpaceSize) { // // _WSpaceSize = aN; // // // DELETE EXISTING ALLOCATION // if(_WSpace!=NULL) delete[] _WSpace; // // // W // _WSpace = new osim_double_adouble[_WSpaceSize]; // if(_WSpace==NULL) { _WSpaceSize=0; return(-1); } // } // // return(0); //} ////_____________________________________________________________________________ ///** // * Ensure that the pointer spaces is at least of size aN. // * // * If the capacity could not be increased to aN, -1 is returned. Otherwise, // * 0 is returned. // */ //int Mtx:: //EnsurePointerSpaceCapacity(int aN) //{ // if(aN>_PSpaceSize) { // // _PSpaceSize = aN; // // // DELETE EXISTING ALLOCATIONS // if(_P1Space!=NULL) delete[] _P1Space; // if(_P2Space!=NULL) delete[] _P2Space; // // // P1 // _P1Space = new osim_double_adouble*[_PSpaceSize]; // if(_P1Space==NULL) { _PSpaceSize=0; return(-1); } // // // P2 // _P2Space = new osim_double_adouble*[aN]; // if(_P2Space==NULL) { delete[] _P1Space; _PSpaceSize=0; return(-1); } // } // // return(0); //} ////_____________________________________________________________________________ ///** // * Free the work and pointer spaces. // */ //void Mtx:: //FreeWorkAndPointerSpaces() //{ // if(_WSpace!=NULL) { delete[] _WSpace; _WSpace=NULL; } // if(_P1Space!=NULL) { delete[] _P1Space; _P1Space=NULL; } // if(_P2Space!=NULL) { delete[] _P2Space; _P2Space=NULL; } // _WSpaceSize = 0; // _PSpaceSize = 0; //}
33.001267
139
0.546509
[ "vector" ]
1ed649883c89ec7149ff27032ba902cfabd9b3fa
2,466
inl
C++
include/visionaray/detail/point_light.inl
ukoeln-vis/ctpperf
2d896c4e8f4a46a6aee198ed6492e7571361e00b
[ "MIT" ]
5
2017-08-11T00:11:45.000Z
2022-01-24T14:47:47.000Z
include/visionaray/detail/point_light.inl
ukoeln-vis/ctpperf
2d896c4e8f4a46a6aee198ed6492e7571361e00b
[ "MIT" ]
null
null
null
include/visionaray/detail/point_light.inl
ukoeln-vis/ctpperf
2d896c4e8f4a46a6aee198ed6492e7571361e00b
[ "MIT" ]
null
null
null
// This file is distributed under the MIT license. // See the LICENSE file for details. namespace visionaray { //------------------------------------------------------------------------------------------------- // point_light members // template <typename T> template <typename U> VSNRAY_FUNC inline vector<3, U> point_light<T>::intensity(vector<3, U> const& pos) const { U att(1.0); #if 1 // use attenuation auto dist = length(vector<3, U>(position_) - pos); att = U( 1.0 / (constant_attenuation_ + linear_attenuation_ * dist + quadratic_attenuation_ * dist * dist) ); #endif return vector<3, U>(cl_ * kl_) * att; } template <typename T> template <typename Sampler> VSNRAY_FUNC inline vector<3, typename Sampler::value_type> point_light<T>::sample(Sampler& samp) const { VSNRAY_UNUSED(samp); return vector<3, typename Sampler::value_type>(position()); } template <typename T> template <size_t N, typename Sampler> VSNRAY_FUNC inline void point_light<T>::sample( array<vector<3, typename Sampler::value_type>, N>& result, Sampler& samp ) const { for (size_t i = 0; i < N; ++i) { result[i] = sample(samp); } } template <typename T> VSNRAY_FUNC inline vector<3, T> point_light<T>::position() const { return position_; } template <typename T> VSNRAY_FUNC inline T point_light<T>::constant_attenuation() const { return constant_attenuation_; } template <typename T> VSNRAY_FUNC inline T point_light<T>::linear_attenuation() const { return linear_attenuation_; } template <typename T> VSNRAY_FUNC inline T point_light<T>::quadratic_attenuation() const { return quadratic_attenuation_; } template <typename T> VSNRAY_FUNC inline void point_light<T>::set_cl(vector<3, T> const& cl) { cl_ = cl; } template <typename T> VSNRAY_FUNC inline void point_light<T>::set_kl(T kl) { kl_ = kl; } template <typename T> VSNRAY_FUNC inline void point_light<T>::set_position(vector<3, T> const& pos) { position_ = pos; } template <typename t> VSNRAY_FUNC inline void point_light<t>::set_constant_attenuation(t att) { constant_attenuation_ = att; } template <typename t> VSNRAY_FUNC inline void point_light<t>::set_linear_attenuation(t att) { linear_attenuation_ = att; } template <typename t> VSNRAY_FUNC inline void point_light<t>::set_quadratic_attenuation(t att) { quadratic_attenuation_ = att; } } // visionaray
19.728
99
0.670316
[ "vector" ]
1ee141cb7dc48f4e4446c2074fae26ac160155dc
1,493
cc
C++
Codeforces/209 Division 2/Problem C/C.cc
VastoLorde95/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
170
2017-07-25T14:47:29.000Z
2022-01-26T19:16:31.000Z
Codeforces/209 Division 2/Problem C/C.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
null
null
null
Codeforces/209 Division 2/Problem C/C.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
55
2017-07-28T06:17:33.000Z
2021-10-31T03:06:22.000Z
#include<cstdio> #include<iostream> #include<cmath> #include<algorithm> #include<cstring> #include<map> #include<set> #include<vector> #include<utility> #include<queue> #include<stack> #define sd(x) scanf("%d",&x) #define sd2(x,y) scanf("%d%d",&x,&y) #define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z) #define fi first #define se second #define pb(x) push_back(x) #define mp(x,y) make_pair(x,y) #define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); #define tr(x) cout<<x<<endl; #define tr2(x,y) cout<<x<<" "<<y<<endl; #define tr3(x,y,z) cout<<x<<" "<<y<<" "<<z<<endl; using namespace std; long long n, x, a[100000]; long long sum, mn = 1ll<<60, MOD = 1000000007, res; long long exp(long long a, long long b){ long long ret = 1; while(b){ if(b%2) ret = (ret*a)%MOD; a = (a*a)%MOD; b >>= 1; } return ret; } int main(){ _ cin >> n >> x; for(int i = 0; i < n; i++){ cin >> a[i]; sum += a[i]; } sort(a, a+n); mn = sum - a[n-1]; res = exp(x, mn); // tr(res); int cnt = 0; for(int i = n-1; i >= 0; i--){ if(sum-a[i] == mn) cnt++; else{ if(cnt%x == 0){ while(cnt%x == 0){ if(sum-a[i] > mn){ cnt /= x; res = (res*x)%MOD; // tr(res); mn++; } else break; } if(i >= 0 and sum-a[i] == mn) cnt++; } else break; } } while(cnt%x == 0){ cnt /= x; res = (res*x)%MOD; mn++; } // tr(mn); if(mn <= sum) cout << res << endl; else cout << exp(x,sum) << endl; return 0; }
16.053763
72
0.525787
[ "vector" ]
1ee25d1d8abcfda53df266eead26d16ffad25297
1,004
hpp
C++
MemLeak/src/RenderTexture/RenderTexture.hpp
pk8868/MemLeak
72f937110c2b67547f67bdea60d2e80b0f5581a1
[ "MIT" ]
null
null
null
MemLeak/src/RenderTexture/RenderTexture.hpp
pk8868/MemLeak
72f937110c2b67547f67bdea60d2e80b0f5581a1
[ "MIT" ]
null
null
null
MemLeak/src/RenderTexture/RenderTexture.hpp
pk8868/MemLeak
72f937110c2b67547f67bdea60d2e80b0f5581a1
[ "MIT" ]
null
null
null
#pragma once #include "RenderTarget/RenderTarget.hpp" namespace ml { class Image; class Sprite; class Rectangle; class Line; class Text; class Window; struct Color; class RenderTexture : public RenderTarget { public: RenderTexture(Vec2i size, Window& window); ~RenderTexture(); // delete copy constructors RenderTexture(const RenderTexture& r) = delete; void operator=(const RenderTexture& r) = delete; void clear(Color color); void render(Sprite& sprite); void render(Rectangle& rectangle); void render(Line& line); void render(Text& text); void display(); void setDeleteTexture(bool deleteTexture) { m_deleteTexture = deleteTexture; } bool getDeleteTexture() { return m_deleteTexture; } Vec2i getSize() { return m_size; } SDL_Texture* const getNativeHandle() { return m_texture; } private: bool m_deleteTexture = true; private: SDL_Texture* m_texture; Vec2i m_size; Window& r_windowRef; private: void setColor(const Color& color); }; }
19.686275
80
0.724104
[ "render" ]
1ee4049ac8bf0ee2217bb765c7a61807aeea276c
418
hpp
C++
Entity.hpp
leonidlist/sfmlRPG
b652ee803bcd41e7be546191a6ddb7164f8cf046
[ "MIT" ]
2
2019-03-12T13:25:01.000Z
2019-05-20T16:08:15.000Z
Entity.hpp
leonidlist/sfmlRPG
b652ee803bcd41e7be546191a6ddb7164f8cf046
[ "MIT" ]
null
null
null
Entity.hpp
leonidlist/sfmlRPG
b652ee803bcd41e7be546191a6ddb7164f8cf046
[ "MIT" ]
null
null
null
#ifndef RPGSFML_ENTITY_H #define RPGSFML_ENTITY_H #include <stdio.h> #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include <iostream> #include <random> #include <cmath> #include <cstdlib> #include <functional> #include <tgmath.h> #include <deque> #include <list> #include <vector> #include <unistd.h> class Entity { public: sf::RectangleShape rect; sf::Sprite sprite; sf::Text text; }; #endif
16.076923
28
0.715311
[ "vector" ]
1ef4c6a67f2958c3d22e2ba9f0fe98a70c857158
2,105
cpp
C++
aws-cpp-sdk-config/source/model/DescribeRetentionConfigurationsRequest.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
2
2019-03-11T15:50:55.000Z
2020-02-27T11:40:27.000Z
aws-cpp-sdk-config/source/model/DescribeRetentionConfigurationsRequest.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-config/source/model/DescribeRetentionConfigurationsRequest.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
1
2019-01-18T13:03:55.000Z
2019-01-18T13:03:55.000Z
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/config/model/DescribeRetentionConfigurationsRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::ConfigService::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; DescribeRetentionConfigurationsRequest::DescribeRetentionConfigurationsRequest() : m_retentionConfigurationNamesHasBeenSet(false), m_nextTokenHasBeenSet(false) { } Aws::String DescribeRetentionConfigurationsRequest::SerializePayload() const { JsonValue payload; if(m_retentionConfigurationNamesHasBeenSet) { Array<JsonValue> retentionConfigurationNamesJsonList(m_retentionConfigurationNames.size()); for(unsigned retentionConfigurationNamesIndex = 0; retentionConfigurationNamesIndex < retentionConfigurationNamesJsonList.GetLength(); ++retentionConfigurationNamesIndex) { retentionConfigurationNamesJsonList[retentionConfigurationNamesIndex].AsString(m_retentionConfigurationNames[retentionConfigurationNamesIndex]); } payload.WithArray("RetentionConfigurationNames", std::move(retentionConfigurationNamesJsonList)); } if(m_nextTokenHasBeenSet) { payload.WithString("NextToken", m_nextToken); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection DescribeRetentionConfigurationsRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "StarlingDoveService.DescribeRetentionConfigurations")); return headers; }
31.893939
173
0.797625
[ "model" ]
1ef9d720296ae6a7019906f9f7cb2906c74325e4
1,829
cc
C++
tests/call_command_test.cc
elp2/edge
a3914d7ce73a4ffdb19d38d140351881190b3fee
[ "Apache-2.0" ]
3
2020-05-30T22:04:03.000Z
2021-12-04T06:05:46.000Z
tests/call_command_test.cc
elp2/edge
a3914d7ce73a4ffdb19d38d140351881190b3fee
[ "Apache-2.0" ]
null
null
null
tests/call_command_test.cc
elp2/edge
a3914d7ce73a4ffdb19d38d140351881190b3fee
[ "Apache-2.0" ]
null
null
null
#include "cpu.h" #include "gtest/gtest.h" #include "mmu.h" #include "ppu.h" #include "rom.h" #include "utils.h" class CallCommandTest : public ::testing::Test { protected: CallCommandTest(){}; ~CallCommandTest(){}; }; TEST(CallCommandTest, CALLnn) { const uint8_t CALLnn = 0xCD; CPU *cpu = getTestingCPUWithInstructions(vector<uint8_t>{CALLnn, 0x34, 0x12}); uint32_t cycles = cpu->cycles(); uint16_t expected_pushed_pc = cpu->Get16Bit(Register_PC) + 3; cpu->Step(); ASSERT_EQ(cpu->Get16Bit(Register_PC), 0x1234); ASSERT_EQ(cpu->cycles(), cycles + 24); ASSERT_EQ(cpu->Pop16Bit(), expected_pushed_pc); } TEST(CallCommandTest, CALLNZnnJump) { const uint8_t CALLnn = 0xC4; CPU *cpu = getTestingCPUWithInstructions(vector<uint8_t>{CALLnn, 0x34, 0x12}); // After returning, come back to the positon afterwards the command. uint16_t expected_pushed_pc = cpu->Get16Bit(Register_PC) + 3; cpu->flags.z = false; uint32_t cycles = cpu->cycles(); cpu->Step(); ASSERT_EQ(cpu->Get16Bit(Register_PC), 0x1234); ASSERT_EQ(cpu->cycles(), cycles + 24); ASSERT_EQ(cpu->Pop16Bit(), expected_pushed_pc); } TEST(CallCommandTest, CALLNCnnNoJump) { const uint8_t CALLNCnn = 0xD4; CPU *cpu = getTestingCPUWithInstructions(vector<uint8_t>{CALLNCnn, 0x12, 0x34}); uint16_t pc = cpu->Get16Bit(Register_PC); cpu->flags.c = true; uint32_t cycles = cpu->cycles(); cpu->Step(); // Advances after the call withtout jumping. ASSERT_EQ(cpu->Get16Bit(Register_PC), pc + 3); ASSERT_EQ(cpu->cycles(), cycles + 12); } TEST(CallCommandTest, RST18H) { const uint8_t RST18H = 0xDF; CPU *cpu = getTestingCPUWithInstructions(vector<uint8_t>{RST18H, 0x18}); uint32_t cycles = cpu->cycles(); cpu->Step(); ASSERT_EQ(cpu->Get16Bit(Register_PC), 0x18); ASSERT_EQ(cpu->cycles(), cycles + 16); }
29.031746
80
0.705303
[ "vector" ]
1efaf3aa72d25e7f21d6416b23ffa7e114996295
1,489
cpp
C++
Practicas/P3/ParaAlumnos/MancalaEngine/JosePadialBot.cpp
josepadial/IA
1399eb587fab8626e50429521391c9064a2d229b
[ "MIT" ]
null
null
null
Practicas/P3/ParaAlumnos/MancalaEngine/JosePadialBot.cpp
josepadial/IA
1399eb587fab8626e50429521391c9064a2d229b
[ "MIT" ]
null
null
null
Practicas/P3/ParaAlumnos/MancalaEngine/JosePadialBot.cpp
josepadial/IA
1399eb587fab8626e50429521391c9064a2d229b
[ "MIT" ]
null
null
null
/* * JosePadialBot.cpp * * Created on: 15 mayo 2018 * Author: Jose Antonio Padial Molina */ #include "JosePadialBot.h" #include <string> #include <cstdlib> #include <iostream> using namespace std; JosePadialBot::JosePadialBot() { // Inicializar las variables necesarias para ejecutar la partida } JosePadialBot::~JosePadialBot() { // Liberar los recursos reservados (memoria, ficheros, etc.) } void JosePadialBot::initialize() { // Inicializar el bot antes de jugar una partida } string JosePadialBot::getName() { return "JosePadialBot"; // Sustituir por el nombre del bot } Move JosePadialBot::nextMove(const vector<Move> &adversary, const GameState &state) { Player miTurno = this->getPlayer(); long timeout = this->getTimeOut(); Move movimiento= M_NONE; for (int i = 1; i < 7; i++) { if (state.getSeedsAt(miTurno, (Position)i) == i) { movimiento = (Move)i; break; } } // Implementar aquí la selección de la acción a realizar // OJO: Recordatorio. NO USAR cin NI cout. // Para salidas por consola (debug) utilizar cerr. Ejemplo: // cerr<< "Lo que quiero mostrar"<<endl; // OJO: Recordatorio. El nombre del bot y de la clase deben coincidir. // En caso contrario, el bot no podrá participar en la competición. // Se deberá sustituir el nombre JosePadialBot como nombre de la clase por otro // seleccionado por el alumno. Se deberá actualizar también el nombre // devuelto por el método getName() acordemente. return movimiento; }
23.634921
85
0.711887
[ "vector" ]
48064921e9b61c1ca3a3d8150a75adc5efff4c2f
9,184
cpp
C++
RNAstructure_Source/PARTS/src/parts/ppf_w_bpi.cpp
mayc2/PseudoKnot_research
33e94b84435d87aff3d89dbad970c438ac173331
[ "MIT" ]
null
null
null
RNAstructure_Source/PARTS/src/parts/ppf_w_bpi.cpp
mayc2/PseudoKnot_research
33e94b84435d87aff3d89dbad970c438ac173331
[ "MIT" ]
null
null
null
RNAstructure_Source/PARTS/src/parts/ppf_w_bpi.cpp
mayc2/PseudoKnot_research
33e94b84435d87aff3d89dbad970c438ac173331
[ "MIT" ]
null
null
null
#include <string.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include "parts_compilation_directives.h" #include "ppf_w_bpi.h" #include "ppf_v.h" #include "ppf_w.h" #include "ppf_w_mb.h" #include "ppf_v_bpi.h" #include "ss_str.h" #include "process_sequences.h" #include "ppf_math.h" #include "alignment_priors.h" #include "phmm_parameters.h" #include "template_pf_array.h" #include "single_pf_array.h" #include "structural_parameters.h" #include "ppf_w_bp_aln_up.h" #include "ppf_v_bp_aln_up.h" #include "ppf_v_mhe.h" #include "ppf_w_mhi.h" #include "ppf_loops.h" #include <iostream> #include "loop_limits.h" using namespace std; #define min(a,b) (((a)<(b))?(a):(b)) #define max(a,b) (((a)>(b))?(a):(b)) // t_ppf_W_bpi: Handles base pair insertions on V array, note that t_ppf_W_bpi inserts base pairs one by one to each sequence // so it can handle INS1 followed by an INS2 or vice versa, so this is basically different in how insertions are handled // by consecutive insertion handling with t_ppf_V::calculate_W_helix_ins(...). In the calculations this will go to // initialization of W array. t_ppf_W_bpi covers structural alignments where i-j and k-l are paired however either one of those // are inserted. And base pair insertions start on top of aligned base pairs, that is, on top of V array. extern bool problem; bool _DUMP_PPF_OS_BPI_MESSAGES_ = false; t_ppf_W_bpi::t_ppf_W_bpi(t_ppf_loops* _ppf_loops) { this->ppf_loops = _ppf_loops; // Copy sequence lengths. this->N1 = this->ppf_loops->seq_man->get_l_seq1(); this->N2 = this->ppf_loops->seq_man->get_l_seq2(); // Alloc and init two template pf arrays. // Those are needed for keeping track of insertion places. /* this->os_ij_bpi_pf_array = new t_template_pf_array(seq_man); this->os_kl_bpi_pf_array = new t_template_pf_array(seq_man); */ this->seq1_spf = this->ppf_loops->seq1_spf; this->seq2_spf = this->ppf_loops->seq2_spf; this->aln_priors = this->ppf_loops->aln_priors; } t_ppf_W_bpi::~t_ppf_W_bpi() { printf("Destruct'ing a t_ppf_W_bpi object.\n"); } bool t_ppf_W_bpi::check_boundary(int i1, int i2) { if(t_template_pf_array::low_limits[i1] <= i2 && t_template_pf_array::high_limits[i1] >= i2) { return(true); } else { return(false); } } // Access to partition function array by reference. double& t_ppf_W_bpi::x_ij_bpi(int i, int j, int k, int l) { if(this->os_ij_bpi_pf_array->check_4D_ll(i,j,k,l)) { return(this->os_ij_bpi_pf_array->x(i,j,k,l)); } else { return(this->os_ij_bpi_pf_array->zero); } } // Access to partition function array by reference. double& t_ppf_W_bpi::x_kl_bpi(int i, int j, int k, int l) { return(this->os_kl_bpi_pf_array->x(i,j,k,l)); } // Return SUM of possible base pair insertions. double t_ppf_W_bpi::x_bpi(int i, int j, int k, int l) { //if(_DUMP_PPF_OS_BPI_MESSAGES_) //printf("Returning SUM!!!\n"); return(SUM(this->os_kl_bpi_pf_array->x(i,j,k,l), this->os_ij_bpi_pf_array->x(i,j,k,l))); } // Return max of possible base pair insertions. double t_ppf_W_bpi::x_map_bpi(int i, int j, int k, int l) { return(max(this->os_kl_bpi_pf_array->x(i,j,k,l), this->os_ij_bpi_pf_array->x(i,j,k,l))); } double t_ppf_W_bpi::calculate_os_ij_bpi(int i, int j, int k, int l) // Arrays to use. { // Have to fork for j > N, do bound checking... if( !this->ppf_loops->W_mhi->w_ij_mhi_pf_array->check_4D_ll(i, j, k, l) ) { printf("Returning from w_bpi calculation @ %s(%d) before calculating W_bi(%d, %d, %d, %d)\n", __FILE__, __LINE__, i,j,k,l); return(ZERO); } if(_DUMP_PPF_OS_BPI_MESSAGES_) printf("\nw_bpi(%d, %d, %d, %d):\n", i,j,k,l); // Following checks are for making sure that insertions are valid. bool i_inc_k_inc = this->check_boundary(i + 1, k + 1); bool i_inc_k = this->check_boundary(i + 1, k); bool i_k_inc = this->check_boundary(i, k + 1); bool i_dec_k_dec = this->check_boundary(i - 1, k - 1); bool i_dec_k = this->check_boundary(i - 1, k); bool i_k_dec = this->check_boundary(i, k - 1); bool j_dec_l_dec = this->check_boundary(j - 1 , l - 1); bool j_l_dec = this->check_boundary(j, l - 1); bool j_dec_l = this->check_boundary(j - 1 , l); // Insert i-j base pair on top of (W+WMB+os_ij_bpi+ss_str)(i+1, j-1, k, l) // Note that we are taking k-l as an open structure, which is for ss_str, an open ss. double i_j_bp_ins_score = CONVERT_FROM_LIN(0.0); double i_INS_prior = CONVERT_FROM_LIN(0.0); double j_INS_prior = CONVERT_FROM_LIN(0.0); double i_j_pairing_score = CONVERT_FROM_LIN(0.0); if((j <= N1 && (j-i) > MIN_LOOP)) // This check makes sure that MIN_LOOP constraint is applied correctly. i_j_pairing_score = seq1_spf->px(i, j); // An i insertion implies a transition from alignment position i-1, k-1 to alignment position i, k-1. //if(i_dec_k_dec && i_k_dec) if(this->ppf_loops->W->w_pf_array->check_4D_ll(i+1, j-1, k, l)) { i_INS_prior = aln_priors->x(i, k - 1, STATE_INS1); j_INS_prior = aln_priors->x(j, l, STATE_INS1); } i_j_bp_ins_score = MUL(i_j_pairing_score, MUL(i_INS_prior, j_INS_prior)); double int_ppf_W_WMB_os_score = CONVERT_FROM_LIN(0.0); if(((j-i) > MIN_LOOP && j <= N1)) { //double closed_W_score = SUM(V->x(i+1, j-1, k, l), SUM(V_bpi->x_bpi(i+1, j-1, k, l), v_bp_aln_up->x(i+1, j-1, k, l))); //double closed_W_score = SUM(V->x(i+1, j-1, k, l), V_bpi->x_bpi(i+1, j-1, k, l)); double closed_W_score = this->ppf_loops->MAX_SUM(this->ppf_loops->V->x(i+1, j-1, k, l), this->ppf_loops->V_mhe->x_mhe(i+1, j-1, k, l)); double open_W_score = SUB(this->ppf_loops->W->x(i+1, j-1, k, l), closed_W_score); int_ppf_W_WMB_os_score = this->ppf_loops->MAX_SUM(open_W_score, this->ppf_loops->WMB->x(i+1, j-1, k, l)); //int_ppf_W_WMB_os_score = SUM(int_ppf_W_WMB_os_score, this->x_ij_bpi(i+1, j-1, k, l)); //int_ppf_W_WMB_os_score = SUM(int_ppf_W_WMB_os_score, w_bp_aln_up->x_ij_aln_up(i+1, j-1, k,l)); int_ppf_W_WMB_os_score = SUM(int_ppf_W_WMB_os_score, this->ppf_loops->W_mhi->x_ij_mhi(i+1, j-1, k, l)); } // Must take ij exclusive of scores since ij is emitted by base pair insertion. double int_ss_score = this->ppf_loops->SS->x(i+1, j-1, k, l); //this->x_ij_bpi(i, j, k, l) = MUL(i_j_bp_ins_score, SUM(int_ppf_W_WMB_os_score, int_ss_score)); return( MUL(i_j_bp_ins_score, SUM(int_ppf_W_WMB_os_score, int_ss_score)) ); } double t_ppf_W_bpi::calculate_os_kl_bpi(int i, int j, int k, int l) // Arrays to use. { // Have to fork for j > N, do bound checking... if( !this->ppf_loops->W_mhi->w_kl_mhi_pf_array->check_4D_ll(i, j, k, l) ) { //printf("Returning from w_bpi calculation @ %s(%d) before calculating W_bi(%d, %d, %d, %d)\n", __FILE__, __LINE__, i,j,k,l); return(ZERO); } if(_DUMP_PPF_OS_BPI_MESSAGES_) printf("\nw_bpi(%d, %d, %d, %d):\n", i,j,k,l); // Following checks are for making sure that insertions are valid. bool i_inc_k_inc = this->check_boundary(i + 1, k + 1); bool i_inc_k = this->check_boundary(i + 1, k); bool i_k_inc = this->check_boundary(i, k + 1); bool i_dec_k_dec = this->check_boundary(i - 1, k - 1); bool i_dec_k = this->check_boundary(i - 1, k); bool i_k_dec = this->check_boundary(i, k - 1); bool j_dec_l_dec = this->check_boundary(j - 1 , l - 1); bool j_l_dec = this->check_boundary(j, l - 1); bool j_dec_l = this->check_boundary(j - 1 , l); // Insert k-l base pair on top of V(i, j, k+1, l-1) and w_bpi(i, j, k+1, l-1). double k_l_bp_ins_score = CONVERT_FROM_LIN(0.0); double k_INS_prior = CONVERT_FROM_LIN(0.0); double l_INS_prior = CONVERT_FROM_LIN(0.0); double k_l_pairing_score = CONVERT_FROM_LIN(0.0); if((l-k) > MIN_LOOP && l <= N2) // This check makes sure that MIN_LOOP constraint is applied correctly. k_l_pairing_score = seq2_spf->px(k, l); // k insertion implies a transition from (i-1, k-1) into (i-1, k). if(this->ppf_loops->W->w_pf_array->check_4D_ll(i, j, k+1, l-1)) { k_INS_prior = aln_priors->x(i-1, k, STATE_INS2); l_INS_prior = aln_priors->x(j, l, STATE_INS2); } k_l_bp_ins_score = MUL(k_l_pairing_score, MUL(k_INS_prior, l_INS_prior)); double int_ppf_W_WMB_os_score = CONVERT_FROM_LIN(0.0); // Recurse on i+1, j-1, k, l of w_bpi, W and WMB for inserting i-j pair. if(((k > (l-N2) && l > N2) || ((l-k) > MIN_LOOP && l <= N2)) && k != N2 && l != N2+1) { double closed_W_score = this->ppf_loops->MAX_SUM(this->ppf_loops->V->x(i, j, k+1, l-1), this->ppf_loops->V_mhe->x_mhe(i, j, k+1, l-1)); double open_W_score = SUB(this->ppf_loops->W->x(i, j, k+1, l-1), closed_W_score); int_ppf_W_WMB_os_score = SUM(open_W_score, this->ppf_loops->WMB->x(i, j, k+1, l-1)); int_ppf_W_WMB_os_score = SUM(int_ppf_W_WMB_os_score, this->ppf_loops->W_mhi->x_kl_mhi(i, j, k+1, l-1)); if(_DUMP_PPF_OS_BPI_MESSAGES_) { printf("open_W_score = %f - %f = %f\n", this->ppf_loops->W->x(i, j, k+1, l-1), closed_W_score, open_W_score); printf("int_ppf_W_WMB_os_score = %f + %f + %f = %f\n", open_W_score, this->ppf_loops->WMB->x(i, j, k+1, l-1), this->ppf_loops->W_mhi->x_kl_mhi(i, j, k+1, l-1), int_ppf_W_WMB_os_score); } } // Determine ss containing structure scores. double int_ss_score = this->ppf_loops->SS->x(i, j, k+1, l-1); // Must take inclusive ss scores. return( MUL(k_l_bp_ins_score, SUM(int_ppf_W_WMB_os_score, int_ss_score)) ); }
37.485714
186
0.694904
[ "object" ]
48142b3fd894e8841a293de1dc2ae09a7536ae2f
416
cpp
C++
test/test_mutex.cpp
huzqujm/multi_thread_producer_and_consumer
5565ee7e200559191b004f3b4b068cf73fd4d581
[ "MIT" ]
null
null
null
test/test_mutex.cpp
huzqujm/multi_thread_producer_and_consumer
5565ee7e200559191b004f3b4b068cf73fd4d581
[ "MIT" ]
null
null
null
test/test_mutex.cpp
huzqujm/multi_thread_producer_and_consumer
5565ee7e200559191b004f3b4b068cf73fd4d581
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <thread> std::mutex mtx; void print(const int& num) { mtx.lock(); std::cout << num << std::endl; mtx.unlock(); } int main(int argc, char* argv[]) { std::vector<std::thread> t_pool; for (int i = 0; i < 10; ++i) { t_pool.push_back(std::thread(print, i)); } for (int i = 0; i < 10; ++i) { if (t_pool[i].joinable()) { t_pool[i].join(); } } return 0; }
16.64
42
0.576923
[ "vector" ]
4814bfe13761d21186a659554466746eb964cd87
22,038
cpp
C++
src/Cello/simulation_Simulation.cpp
ThomasBolden/cello-mod
68431de28a3575c95bb40c47fce7a352c6b92145
[ "MIT", "BSD-3-Clause" ]
null
null
null
src/Cello/simulation_Simulation.cpp
ThomasBolden/cello-mod
68431de28a3575c95bb40c47fce7a352c6b92145
[ "MIT", "BSD-3-Clause" ]
null
null
null
src/Cello/simulation_Simulation.cpp
ThomasBolden/cello-mod
68431de28a3575c95bb40c47fce7a352c6b92145
[ "MIT", "BSD-3-Clause" ]
null
null
null
// See LICENSE_CELLO file for license and copyright information /// @file simulation_Simulation.cpp /// @author James Bordner (jobordner@ucsd.edu) /// @date 2010-11-10 /// @brief Implementation of the Simulation class #include "cello.hpp" #include "main.hpp" #include "simulation.hpp" #include "charm_simulation.hpp" // #define DEBUG_SIMULATION Simulation::Simulation ( const char * parameter_file, int n ) /// Initialize the Simulation object : #if defined(CELLO_DEBUG) || defined(CELLO_VERBOSE) fp_debug_(NULL), #endif factory_(NULL), parameters_(&g_parameters), parameter_file_(parameter_file), rank_(0), cycle_(0), cycle_watch_(-1), time_(0.0), dt_(0), stop_(false), phase_(phase_unknown), config_(&g_config), problem_(NULL), timer_(), performance_(NULL), #ifdef CONFIG_USE_PROJECTIONS projections_tracing_(false), projections_schedule_on_(NULL), projections_schedule_off_(NULL), #endif schedule_balance_(NULL), monitor_(NULL), hierarchy_(NULL), field_descr_(NULL), particle_descr_(NULL), sync_output_begin_(), sync_output_write_() { #ifdef DEBUG_SIMULATION CkPrintf ("%d DEBUG_SIMULATION Simulation(parameter_file,n)\n",CkMyPe()); fflush(stdout); char name[40]; sprintf (name,"parameters-%02d.text",CkMyPe()); parameters_->write(name); #endif debug_open(); monitor_ = Monitor::instance(); #ifdef CELLO_DEBUG monitor_->set_mode(monitor_mode_all); #else monitor_->set_mode(monitor_mode_root); #endif } //---------------------------------------------------------------------- Simulation::Simulation() : #if defined(CELLO_DEBUG) || defined(CELLO_VERBOSE) fp_debug_(NULL), #endif factory_(NULL), parameters_(&g_parameters), parameter_file_(""), rank_(0), cycle_(0), cycle_watch_(-1), time_(0.0), dt_(0), stop_(false), phase_(phase_unknown), config_(&g_config), problem_(NULL), timer_(), performance_(NULL), #ifdef CONFIG_USE_PROJECTIONS projections_tracing_(false), projections_schedule_on_(NULL), projections_schedule_off_(NULL), #endif schedule_balance_(NULL), monitor_(NULL), hierarchy_(NULL), field_descr_(NULL), particle_descr_(NULL), sync_output_begin_(), sync_output_write_() { #ifdef DEBUG_SIMULATION CkPrintf ("%d DEBUG_SIMULATION Simulation()\n",CkMyPe()); fflush(stdout); #endif TRACE("Simulation()"); } //---------------------------------------------------------------------- void Simulation::pup (PUP::er &p) { #ifdef DEBUG_SIMULATION CkPrintf ("%d DEBUG_SIMULATION Simulation::pup()\n",CkMyPe()); fflush(stdout); #endif // NOTE: change this function whenever attributes change TRACEPUP; CBase_Simulation::pup(p); bool up = p.isUnpacking(); if (up) debug_open(); p | factory_; // PUP::able p | config_; p | parameter_file_; p | rank_; p | cycle_; p | cycle_watch_; p | time_; p | dt_; p | stop_; p | phase_; if (up) problem_ = new Problem; p | * problem_; if (up) performance_ = new Performance; p | *performance_; // p | projections_tracing_; // if (up) projections_schedule_on_ = new Schedule; // p | *projections_schedule_on_; // if (up) projections_schedule_off_ = new Schedule; // p | *projections_schedule_off_; if (up) monitor_ = Monitor::instance(); p | *monitor_; if (up) hierarchy_ = new Hierarchy; p | *hierarchy_; if (up) field_descr_ = new FieldDescr; p | *field_descr_; if (up) particle_descr_ = new ParticleDescr; p | *particle_descr_; if (up && (phase_ == phase_restart)) { monitor_->print ("Simulation","restarting"); } p | sync_output_begin_; p | sync_output_write_; if (up) sync_output_begin_.set_stop(0); if (up) sync_output_write_.set_stop(0); p | schedule_balance_; } //---------------------------------------------------------------------- Simulation::Simulation (CkMigrateMessage *m) : CBase_Simulation(m), #if defined(CELLO_DEBUG) || defined(CELLO_VERBOSE) fp_debug_(NULL), #endif factory_(NULL), parameters_(&g_parameters), parameter_file_(""), rank_(0), cycle_(0), cycle_watch_(-1), time_(0.0), dt_(0), stop_(false), phase_(phase_unknown), config_(&g_config), problem_(NULL), timer_(), performance_(NULL), #ifdef CONFIG_USE_PROJECTIONS projections_tracing_(false), projections_schedule_on_(NULL), projections_schedule_off_(NULL), #endif schedule_balance_(NULL), monitor_(NULL), hierarchy_(NULL), field_descr_(NULL), particle_descr_(NULL), sync_output_begin_(), sync_output_write_() { #ifdef DEBUG_SIMULATION CkPrintf ("%d DEBUG_SIMULATION Simulation(msg)\n",CkMyPe()); fflush(stdout); #endif TRACE("Simulation(CkMigrateMessage)"); } //---------------------------------------------------------------------- Simulation::~Simulation() { deallocate_(); } //---------------------------------------------------------------------- void Simulation::finalize() throw() { TRACE0; performance_->stop_region(perf_simulation); performance_->end(); } //====================================================================== void Simulation::initialize_simulation_() throw() { #ifdef DEBUG_SIMULATION CkPrintf ("%d DEBUG_SIMULATION Simulation::initialize_simulation_()\n",CkMyPe()); fflush(stdout); #endif rank_ = config_->mesh_root_rank; ASSERT ("Simulation::initialize_simulation_()", "Parameter 'Mesh:root_rank' must be specified", rank_ != 0); ASSERT ("Simulation::initialize_simulation_()", "Parameter 'Mesh:root_rank' must be 1, 2, or 3", (1 <= rank_) && (rank_ <= 3)); cycle_ = config_->initial_cycle; cycle_watch_ = cycle_ - 1; time_ = config_->initial_time; dt_ = 0; } //---------------------------------------------------------------------- void Simulation::initialize_memory_() throw() { Memory * memory = Memory::instance(); if (memory) { memory->set_active(config_->memory_active); memory->set_warning_mb (config_->memory_warning_mb); memory->set_limit_gb (config_->memory_limit_gb); } } //---------------------------------------------------------------------- void Simulation::initialize_performance_() throw() { performance_ = new Performance (config_); const bool in_charm = true; Performance * p = performance_; p->new_region(perf_unknown, "unknown"); p->new_region(perf_simulation, "simulation"); p->new_region(perf_cycle, "cycle"); p->new_region(perf_initial, "initial"); p->new_region(perf_adapt_apply,"adapt_apply"); p->new_region(perf_adapt_apply_sync, "adapt_apply_sync",in_charm); p->new_region(perf_adapt_notify, "adapt_notify"); p->new_region(perf_adapt_notify_sync, "adapt_notify_sync",in_charm); p->new_region(perf_adapt_update, "adapt_update"); p->new_region(perf_adapt_update_sync, "adapt_update_sync",in_charm); p->new_region(perf_adapt_end, "adapt_end"); p->new_region(perf_adapt_end_sync, "adapt_end_sync",in_charm); p->new_region(perf_refresh_store, "refresh_store"); p->new_region(perf_refresh_child, "refresh_child"); p->new_region(perf_refresh_exit, "refresh_exit"); p->new_region(perf_refresh_store_sync, "refresh_store_sync",in_charm); p->new_region(perf_refresh_child_sync, "refresh_child_sync",in_charm); p->new_region(perf_refresh_exit_sync, "refresh_exit_sync",in_charm); p->new_region(perf_compute, "compute"); p->new_region(perf_control, "control"); p->new_region(perf_output, "output"); p->new_region(perf_stopping, "stopping"); p->new_region(perf_block, "block"); p->new_region(perf_exit, "exit"); timer_.start(); #ifdef CONFIG_USE_PAPI for (size_t i=0; i<config_->performance_papi_counters.size(); i++) { p->new_counter(counter_type_papi, config_->performance_papi_counters[i]); } #endif p->begin(); p->start_region(perf_simulation); } //---------------------------------------------------------------------- void Simulation::initialize_config_() throw() { TRACE("BEGIN Simulation::initialize_config_"); TRACE("END Simulation::initialize_config_"); } //---------------------------------------------------------------------- void Simulation::initialize_monitor_() throw() { bool debug = config_->monitor_debug; int debug_mode = debug ? monitor_mode_all : monitor_mode_none; monitor_->set_mode("DEBUG",debug_mode); monitor_->set_verbose(config_->monitor_verbose); } //---------------------------------------------------------------------- void Simulation::initialize_data_descr_() throw() { //-------------------------------------------------- // parameter: Field : list //-------------------------------------------------- field_descr_ = new FieldDescr; // Add data fields for (size_t i=0; i<config_->field_list.size(); i++) { field_descr_->insert_permanent (config_->field_list[i]); } // Define default ghost zone depth for all fields, default value of 1 int gx = config_->field_ghost_depth[0]; int gy = config_->field_ghost_depth[1]; int gz = config_->field_ghost_depth[2]; for (int i=0; i<field_descr_->field_count(); i++) { field_descr_->set_ghost_depth (i,gx,gy,gz); } // Default precision for (int i=0; i<field_descr_->field_count(); i++) { field_descr_->set_precision(i,config_->field_precision); } //-------------------------------------------------- // parameter: Field : alignment //-------------------------------------------------- int alignment = config_->field_alignment; ASSERT1 ("Simulation::initialize_data_descr_", "Illegal Field:alignment parameter value %d", alignment, 1 <= alignment ); field_descr_->set_alignment (alignment); field_descr_->set_padding (config_->field_padding); for (int i=0; i<field_descr_->field_count(); i++) { std::string field_name = field_descr_->field_name(i); const int cx = config_->field_centering[0][i]; const int cy = config_->field_centering[1][i]; const int cz = config_->field_centering[2][i]; field_descr_->set_centering(i,cx,cy,cz); } // field groups int num_fields = config_->field_group_list.size(); for (int index_field=0; index_field<num_fields; index_field++) { std::string field = config_->field_list[index_field]; int num_groups = config_->field_group_list[index_field].size(); for (int index_group=0; index_group<num_groups; index_group++) { std::string group = config_->field_group_list[index_field][index_group]; field_descr_->groups()->add(field,group); } } //-------------------------------------------------- // parameter: Particle : list //-------------------------------------------------- particle_descr_ = new ParticleDescr; // Set particle batch size particle_descr_->set_batch_size(config_->particle_batch_size); // Add particle types // ... first map attribute scalar type name to type_enum int std::map<std::string,int> type_val; for (int i=0; i<NUM_TYPES; i++) { type_val[cello::type_name[i]] = i; } for (size_t it=0; it<config_->particle_list.size(); it++) { particle_descr_->new_type (config_->particle_list[it]); // Add particle constants int nc = config_->particle_constant_name[it].size(); for (int ic=0; ic<nc; ic++) { std::string name = config_->particle_constant_name[it][ic]; int type = type_val[config_->particle_constant_type[it][ic]]; particle_descr_->new_constant(it,name,type); union { char * c; long long * ill; float * f; double * d; long double * ld; int8_t * i8; int16_t * i16; int32_t * i32; int64_t * i64; }; c = particle_descr_->constant_value(it,ic); if (type == type_default) type = default_type; switch (type) { case type_single: *f = config_->particle_constant_value[it][ic]; break; case type_double: *d = config_->particle_constant_value[it][ic]; break; case type_quadruple: *ld = config_->particle_constant_value[it][ic]; break; case type_int8: *i8 = config_->particle_constant_value[it][ic]; break; case type_int16: *i16 = config_->particle_constant_value[it][ic]; break; case type_int32: *i32 = config_->particle_constant_value[it][ic]; break; case type_int64: *i64 = config_->particle_constant_value[it][ic]; break; default: ERROR3 ("Simulation::initialize_data_descr_()", "Unrecognized type %d for particle constant %s in type %s", type,name.c_str(),config_->particle_list[it].c_str()); break; } } // Add particle attributes int na = config_->particle_attribute_name[it].size(); for (int ia=0; ia<na; ia++) { std::string name = config_->particle_attribute_name[it][ia]; int type = type_val[config_->particle_attribute_type[it][ia]]; particle_descr_->new_attribute(it,name,type); } // position and velocity attributes particle_descr_->set_position (it, config_->particle_attribute_position[0][it], config_->particle_attribute_position[1][it], config_->particle_attribute_position[2][it]); particle_descr_->set_velocity (it, config_->particle_attribute_velocity[0][it], config_->particle_attribute_velocity[1][it], config_->particle_attribute_velocity[2][it]); } // particle groups int num_particles = config_->particle_group_list.size(); for (int index_particle=0; index_particle<num_particles; index_particle++) { std::string particle = config_->particle_list[index_particle]; int num_groups = config_->particle_group_list[index_particle].size(); for (int index_group=0; index_group<num_groups; index_group++) { std::string group = config_->particle_group_list[index_particle][index_group]; particle_descr_->groups()->add(particle,group); } } } //---------------------------------------------------------------------- void Simulation::initialize_hierarchy_() throw() { #ifdef DEBUG_SIMULATION CkPrintf ("%d DEBUG_SIMULATION Simulation::initialize_hierarchy_()\n",CkMyPe()); fflush(stdout); #endif ASSERT("Simulation::initialize_hierarchy_", "data must be initialized before hierarchy", field_descr_ != NULL); //---------------------------------------------------------------------- // Create and initialize Hierarchy //---------------------------------------------------------------------- const int refinement = 2; hierarchy_ = factory()->create_hierarchy (rank_,refinement,config_->mesh_max_level); // Domain extents hierarchy_->set_lower (config_->domain_lower[0], config_->domain_lower[1], config_->domain_lower[2]); hierarchy_->set_upper (config_->domain_upper[0], config_->domain_upper[1], config_->domain_upper[2]); //---------------------------------------------------------------------- // Create and initialize root Patch in Hierarchy //---------------------------------------------------------------------- //-------------------------------------------------- // parameter: Mesh : root_size // parameter: Mesh : root_blocks //-------------------------------------------------- hierarchy_->set_root_size(config_->mesh_root_size[0], config_->mesh_root_size[1], config_->mesh_root_size[2]); hierarchy_->set_blocking(config_->mesh_root_blocks[0], config_->mesh_root_blocks[1], config_->mesh_root_blocks[2]); } //---------------------------------------------------------------------- void Simulation::initialize_balance_() throw() { int index = config_->balance_schedule_index; schedule_balance_ = (index == -1) ? NULL : Schedule::create ( config_->schedule_var[index], config_->schedule_type[index], config_->schedule_start[index], config_->schedule_stop[index], config_->schedule_step[index], config_->schedule_list[index]); #ifdef TEMP_BALANCE_MANUAL if (schedule_balance_) { TurnManualLBOn(); } #endif } //---------------------------------------------------------------------- void Simulation::initialize_forest_() throw() { bool allocate_blocks = (CkMyPe() == 0); // Don't allocate blocks if reading data from files // bool allocate_data = ! ( config_->initial_type == "file" || // config_->initial_type == "checkpoint" ); bool allocate_data = true; if (allocate_blocks) { // Create the root-level blocks for level = 0 hierarchy_->create_forest (field_descr_, allocate_data); // Create the "sub-root" blocks if mesh_min_level < 0 if (config_->mesh_min_level < 0) { hierarchy_->create_subforest (field_descr_, allocate_data, config_->mesh_min_level); } hierarchy_->block_array()->doneInserting(); } } //---------------------------------------------------------------------- void Simulation::deallocate_() throw() { delete factory_; factory_ = 0; delete parameters_; parameters_ = 0; delete hierarchy_; hierarchy_ = 0; delete field_descr_; field_descr_ = 0; delete performance_; performance_ = 0; } //---------------------------------------------------------------------- const Factory * Simulation::factory() const throw() { TRACE("Simulation::factory()"); if (factory_ == NULL) factory_ = new Factory; return factory_; } //====================================================================== void Simulation::update_state(int cycle, double time, double dt, double stop) { cycle_ = cycle; time_ = time; dt_ = dt; stop_ = stop != 0; } //====================================================================== void Simulation::monitor_insert_block(int count) { #ifdef CELLO_DEBUG PARALLEL_PRINTF ("%d: ++sync_output_begin_ %d %d\n", CkMyPe(),sync_output_begin_.stop(),hierarchy_->num_blocks()); #endif if (hierarchy_) hierarchy_->increment_block_count(count); sync_output_begin_ += count; sync_output_write_ += count; } //---------------------------------------------------------------------- void Simulation::monitor_delete_block(int count) { if (hierarchy_) hierarchy_->increment_block_count(-count); sync_output_begin_ -= count; sync_output_write_ -= count; } //---------------------------------------------------------------------- void Simulation::monitor_insert_zones(int64_t count_total, int64_t count_real) { ASSERT2 ("Simulation::monitor_insert_zones()", "Total number of zones %ld must be no larger than " "number of real zones %ld", count_total,count_real, count_total >= count_real); if (hierarchy_) hierarchy_->increment_total_zone_count(count_total); if (hierarchy_) hierarchy_->increment_real_zone_count (count_real); } //---------------------------------------------------------------------- void Simulation::monitor_delete_zones(int64_t count_total, int64_t count_real) { ASSERT2 ("Simulation::monitor_insert_zones()", "Total number of zones %ld must be no larger than " "number of real zones %ld", count_total,count_real, count_total >= count_real); if (hierarchy_) hierarchy_->increment_total_zone_count(-count_total); if (hierarchy_) hierarchy_->increment_real_zone_count(-count_real); } //---------------------------------------------------------------------- void Simulation::monitor_insert_particles(int64_t count) { if (hierarchy_) hierarchy_->increment_particle_count(count); } //---------------------------------------------------------------------- void Simulation::monitor_delete_particles(int64_t count) { if (hierarchy_) hierarchy_->increment_particle_count(-count); } //---------------------------------------------------------------------- void Simulation::p_monitor() { monitor()-> print("", "-------------------------------------"); monitor()-> print("Simulation", "cycle %04d", cycle_); monitor()-> print("Simulation", "time-sim %15.12e",time_); monitor()-> print("Simulation", "dt %15.12e", dt_); proxy_simulation.p_monitor_performance(); } //---------------------------------------------------------------------- void Simulation::monitor_performance() { int nr = performance_->num_regions(); int nc = performance_->num_counters(); int n = nr * nc + 2; long long * counters_long_long = new long long [nc]; long * counters_long = new long [n]; int m = 0; counters_long[m++] = hierarchy_->num_particles(); counters_long[m++] = hierarchy_->num_blocks(); for (int ir = 0; ir < nr; ir++) { performance_->region_counters(ir,counters_long_long); for (int ic = 0; ic < nc; ic++,m++) { counters_long[m] = (long) counters_long_long[ic]; } } // -------------------------------------------------- CkCallback callback (CkIndex_Simulation::r_monitor_performance(NULL), thisProxy); contribute (n*sizeof(long), counters_long,CkReduction::sum_long,callback); // -------------------------------------------------- delete [] counters_long; delete [] counters_long_long; } //---------------------------------------------------------------------- void Simulation::r_monitor_performance(CkReductionMsg * msg) { int nr = performance_->num_regions(); int nc = performance_->num_counters(); long * counters_long = (long * )msg->getData(); int index_region_cycle = performance_->region_index("cycle"); int m = 0; monitor()->print("Performance","simulation num-particles total %ld", counters_long[m++]); monitor()->print("Performance","simulation num-blocks %d", counters_long[m++]); for (int ir = 0; ir < nr; ir++) { for (int ic = 0; ic < nc; ic++, m++) { bool do_print = (ir != perf_unknown) && ( (performance_->counter_type(ic) != counter_type_abs) || (ir == index_region_cycle)); if (do_print) { monitor()->print("Performance","%s %s %ld", performance_->region_name(ir).c_str(), performance_->counter_name(ic).c_str(), counters_long[m]); } } } Memory::instance()->reset_high(); delete msg; }
27.274752
84
0.602959
[ "mesh", "object" ]
4816dc9f55cd1f606024b7080d528e60ac8135dc
3,691
cpp
C++
src/app/main.cpp
mteichtahl/simhub
4c409c61e38bb5deeb58a09c6cb89730d38280e1
[ "MIT" ]
3
2018-03-19T18:09:12.000Z
2021-06-17T03:56:05.000Z
src/app/main.cpp
mteichtahl/simhub
4c409c61e38bb5deeb58a09c6cb89730d38280e1
[ "MIT" ]
19
2017-04-29T11:25:52.000Z
2021-05-07T14:48:59.000Z
src/app/main.cpp
mteichtahl/simhub
4c409c61e38bb5deeb58a09c6cb89730d38280e1
[ "MIT" ]
9
2017-04-26T22:45:06.000Z
2022-02-27T01:08:54.000Z
#include <condition_variable> #include <iostream> #include <map> #include <signal.h> #include <string> #include <thread> #include <vector> #if defined(_AWS_SDK) #include "aws/aws.h" #endif #include "common/configmanager/configmanager.h" #include "libs/commandLine.h" // https://github.com/tanakh/cmdline #include "log/clog.h" #include "plugins/common/simhubdeviceplugin.h" #include "simhub.h" /** Configure the main CLI interdace @param cmdline::parser pointer - command line parameters passed in by user */ void configureCli(cmdline::parser *cli) { cli->add<std::string>("config", 'c', "config file", false, "config/config.cfg"); cli->add<std::string>("logConfig", 'l', "log config file", false, "config/zlog.conf"); ///! If the AWS SDK is being used then allow Polly as a CLI option #if defined(_AWS_SDK) cli->add<bool>("polly", 'p', "Use Amazon Polly", false, true); cli->add<bool>("kinesis", 'k', "Use Amazon Kinesis", false, true); #endif cli->set_program_name("simhub"); cli->footer("\n"); } //! this static allows the signal handlers to control shutdown/restart logic in main() static bool ReloadRestart = false; // TODO: handle SIGHUP for settings reload void sigint_handler(int sigid) { if (sigid == SIGINT) { // tell app event loop to end on control+c logger.log(LOG_INFO, "Shutting down simhub, this may take a couple seconds..."); SimHubEventController::EventControllerInstance()->ceaseEventLoop(); ReloadRestart = false; } else if (sigid == SIGHUP || sigid == SIGQUIT) { // tell app event loop to end on control+h // -- destroy and reload event controller // -- cheat a little and capture SIGQUIT so we can use ctrl+\ // as keyboard shortcut for this logger.log(LOG_INFO, "Reload simhub, this may take a couple seconds..."); ReloadRestart = true; SimHubEventController::EventControllerInstance()->ceaseEventLoop(); } } void run_simhub(const cmdline::parser &cli) { ConfigManager config(cli.get<std::string>("config")); std::shared_ptr<SimHubEventController> simhubController = SimHubEventController::EventControllerInstance(); ///! If the AWS SDK is being used then read in the polly cli and load up polly ///! initialise the configuration if (!config.init(simhubController)) { logger.log(LOG_ERROR, "Could not initialise configuration"); exit(1); } #if defined(_AWS_SDK) simhubController->enablePolly(); simhubController->enableKinesis(); #endif if (simhubController->loadPokeyPlugin()) { if (simhubController->loadPrepare3dPlugin()) { // kick off the simhub envent loop simhubController->runEventLoop([=](std::shared_ptr<Attribute> value) { bool deliveryResult = simhubController->deliverValue(value); #if defined(_AWS_SDK) simhubController->deliverKinesisValue(value); #endif return deliveryResult; }); } else { logger.log(LOG_ERROR, "error loading prepare3d plugin"); } } else { logger.log(LOG_ERROR, "Could not load pokey plugin"); } } int main(int argc, char *argv[]) { struct sigaction act; act.sa_handler = sigint_handler; sigaction(SIGINT, &act, NULL); sigaction(SIGHUP, &act, NULL); sigaction(SIGQUIT, &act, NULL); cmdline::parser cli; configureCli(&cli); cli.parse_check(argc, argv); logger.init(cli.get<std::string>("logConfig")); do { run_simhub(cli); SimHubEventController::DestroyEventControllerInstance(); } while (ReloadRestart); return 0; }
29.528
111
0.660526
[ "vector" ]
4817e7e426b07d0b70aece3d260a016b700d5c99
4,756
cc
C++
components/copresence/copresence_state_unittest.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-28T08:09:58.000Z
2021-11-15T15:32:10.000Z
components/copresence/copresence_state_unittest.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/copresence/copresence_state_unittest.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.000Z
// Copyright 2014 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 <string> #include <vector> #include "base/time/time.h" #include "components/copresence/copresence_state_impl.h" #include "components/copresence/proto/data.pb.h" #include "components/copresence/public/copresence_observer.h" #include "components/copresence/tokens.h" #include "testing/gmock/include/gmock/gmock.h" using testing::ElementsAre; using testing::Key; using testing::SizeIs; using testing::UnorderedElementsAre; // TODO(ckehoe): Test start and end time tracking. namespace google { namespace protobuf { bool operator==(const MessageLite& A, const MessageLite& B) { std::string serializedA; CHECK(A.SerializeToString(&serializedA)); std::string serializedB; CHECK(B.SerializeToString(&serializedB)); return serializedA == serializedB; } } // namespace protobuf } // namespace google namespace copresence { namespace { const base::Time kStartTime = base::Time::FromDoubleT(10); const base::Time kStopTime = base::Time::FromDoubleT(20); Directive CreateDirective(const std::string& token, bool transmit) { Directive directive; TokenInstruction* instruction = directive.mutable_token_instruction(); instruction->set_token_id(token); instruction->set_medium(AUDIO_ULTRASOUND_PASSBAND); if (transmit) instruction->set_token_instruction_type(TRANSMIT); return directive; } template<typename TokenType> TokenType CreateToken(const std::string& id) { TokenType token; token.id = id; token.medium = AUDIO_ULTRASOUND_PASSBAND; token.start_time = kStartTime; return token; } } // namespace class CopresenceStateTest : public CopresenceObserver, public testing::Test { public: CopresenceStateTest() : directive_notifications_(0) { state_.AddObserver(this); } protected: CopresenceStateImpl state_; int directive_notifications_; std::vector<std::string> transmitted_updates_; std::vector<std::string> received_updates_; private: // CopresenceObserver implementation. void DirectivesUpdated() override { directive_notifications_++; } void TokenTransmitted(const TransmittedToken& token) override { transmitted_updates_.push_back(token.id); } void TokenReceived(const ReceivedToken& token) override { received_updates_.push_back(token.id); } }; TEST_F(CopresenceStateTest, Directives) { std::vector<Directive> directives; directives.push_back(CreateDirective("transmit 1", true)); directives.push_back(CreateDirective("transmit 2", true)); directives.push_back(CreateDirective("receive", false)); state_.UpdateDirectives(directives); EXPECT_EQ(1, directive_notifications_); EXPECT_EQ(directives, state_.active_directives()); EXPECT_THAT(transmitted_updates_, ElementsAre("transmit 1", "transmit 2")); EXPECT_THAT(state_.transmitted_tokens(), UnorderedElementsAre(Key("transmit 1"), Key("transmit 2"))); directives.clear(); directives.push_back(CreateDirective("transmit 1", true)); state_.UpdateDirectives(directives); EXPECT_EQ(2, directive_notifications_); EXPECT_EQ(directives, state_.active_directives()); EXPECT_THAT(state_.transmitted_tokens(), SizeIs(2)); } TEST_F(CopresenceStateTest, TransmittedTokens) { state_.UpdateTransmittedToken(CreateToken<TransmittedToken>("A")); state_.UpdateTransmittedToken(CreateToken<TransmittedToken>("B")); EXPECT_THAT(transmitted_updates_, ElementsAre("A", "B")); EXPECT_THAT(state_.transmitted_tokens(), UnorderedElementsAre(Key("A"), Key("B"))); TransmittedToken tokenA = CreateToken<TransmittedToken>("A"); tokenA.stop_time = kStopTime; state_.UpdateTransmittedToken(tokenA); EXPECT_THAT(transmitted_updates_, ElementsAre("A", "B", "A")); EXPECT_EQ(kStopTime, state_.transmitted_tokens().find("A")->second.stop_time); state_.UpdateReceivedToken(CreateToken<ReceivedToken>("B")); EXPECT_THAT(transmitted_updates_, ElementsAre("A", "B", "A", "B")); EXPECT_TRUE(state_.transmitted_tokens().find("B") ->second.broadcast_confirmed); } TEST_F(CopresenceStateTest, ReceivedTokens) { state_.UpdateReceivedToken(CreateToken<ReceivedToken>("A")); state_.UpdateReceivedToken(CreateToken<ReceivedToken>("B")); EXPECT_THAT(received_updates_, ElementsAre("A", "B")); EXPECT_THAT(state_.received_tokens(), UnorderedElementsAre(Key("A"), Key("B"))); state_.UpdateTokenStatus("A", copresence::VALID); EXPECT_THAT(received_updates_, ElementsAre("A", "B", "A")); EXPECT_EQ(ReceivedToken::VALID, state_.received_tokens().find("A")->second.valid); } } // namespace copresence
31.706667
80
0.746005
[ "vector" ]
481d06db768cfb7abc45e01e46d58f59e5d9eded
12,706
cpp
C++
Cpp/fost-core/jcursor.cpp
KayEss/fost-base
05ac1b6a1fb672c61ba6502efea86f9c5207e28f
[ "BSL-1.0" ]
2
2016-05-25T22:17:38.000Z
2019-04-02T08:34:17.000Z
Cpp/fost-core/jcursor.cpp
KayEss/fost-base
05ac1b6a1fb672c61ba6502efea86f9c5207e28f
[ "BSL-1.0" ]
5
2018-07-13T10:43:05.000Z
2019-09-02T14:54:42.000Z
Cpp/fost-core/jcursor.cpp
KayEss/fost-base
05ac1b6a1fb672c61ba6502efea86f9c5207e28f
[ "BSL-1.0" ]
1
2020-10-22T20:44:24.000Z
2020-10-22T20:44:24.000Z
/** Copyright 2007-2020 Red Anchor Trading Co. Ltd. Distributed under the Boost Software License, Version 1.0. See <http://www.boost.org/LICENSE_1_0.txt> */ #include "fost-core.hpp" #include <fost/json.hpp> #include <fost/insert.hpp> #include <fost/unicode.hpp> #include <fost/detail/coerce.hpp> #include <fost/detail/utility.hpp> #include <fost/parse/jcursor.hpp> #include <fost/exception/json_error.hpp> #include <fost/exception/not_implemented.hpp> #include <fost/exception/not_null.hpp> #include <fost/exception/null.hpp> #include <fost/exception/out_of_range.hpp> #include <fost/exception/parse_error.hpp> /** * ## fostlib */ bool fostlib::operator==( const fostlib::jcursor::value_type &lhs, f5::u8view rhs) { auto lhs_sp = std::get_if<fostlib::string>(&lhs); if (lhs_sp) { return *lhs_sp == rhs; } else { return false; } } /** * ## fostlib::jcursor */ fostlib::jcursor::jcursor() {} fostlib::jcursor::jcursor(int i) { m_position.push_back(fostlib::coerce<std::size_t>(i)); } fostlib::jcursor::jcursor(json::array_t::size_type i) { m_position.push_back(i); } fostlib::jcursor::jcursor(nliteral n) { m_position.push_back(fostlib::string(n)); } fostlib::jcursor::jcursor(f5::u8view s) { m_position.push_back(s); } fostlib::jcursor::jcursor(fostlib::string &&s) { m_position.push_back(std::move(s)); } fostlib::jcursor::jcursor(const json &j) { nullable<int64_t> i = j.get<int64_t>(); if (i) { m_position.push_back(coerce<json::array_t::size_type>(i.value())); } else { auto s = j.get<f5::u8view>(); if (s) { m_position.push_back(s.value()); } else { throw exceptions::json_error( "The jcursor location must be a string or integer", j); } } } fostlib::jcursor::jcursor(stack_t::const_iterator b, stack_t::const_iterator e) : m_position(b, e) {} fostlib::jcursor fostlib::jcursor::split(const string &s, const string &c) { fostlib::split_type path = fostlib::split(s, c); fostlib::jcursor position; for (fostlib::split_type::const_iterator part(path.begin()); part != path.end(); ++part) { try { int index = fostlib::coerce<int>(*part); position /= index; } catch (fostlib::exceptions::parse_error &) { position /= *part; } } return position; } fostlib::jcursor &fostlib::jcursor::operator/=(json::array_t::size_type i) { m_position.push_back(i); return *this; } fostlib::jcursor &fostlib::jcursor::operator/=(f5::u8view i) { m_position.push_back(i); return *this; } fostlib::jcursor &fostlib::jcursor::operator/=(const json &j) { return operator/=(jcursor(j)); } fostlib::jcursor &fostlib::jcursor::operator/=(const jcursor &r) { m_position.insert( m_position.end(), r.m_position.begin(), r.m_position.end()); return *this; } fostlib::jcursor &fostlib::jcursor::enter() { m_position.push_back(0u); return *this; } fostlib::jcursor &fostlib::jcursor::enter(const string &i) { m_position.push_back(i); return *this; } fostlib::jcursor &fostlib::jcursor::pop() { m_position.pop_back(); return *this; } fostlib::jcursor &fostlib::jcursor::operator++() { if (m_position.empty()) throw fostlib::exceptions::null{"cannot increment an empty jcursor"}; else if (std::get_if<json::array_t::size_type>(&*m_position.rbegin()) == NULL) throw fostlib::exceptions::null{ "The current jcursor isn't into an array position"}; else ++std::get<json::array_t::size_type>(*m_position.rbegin()); return *this; } namespace { struct take_step { fostlib::json const &orig; fostlib::json::element_t &element; bool isnull; take_step(fostlib::json const &o, fostlib::json::element_t &j, bool n) : orig(o), element(j), isnull(n) {} fostlib::json *operator()(fostlib::json::array_t::size_type k) const { if (isnull) element = std::make_shared<fostlib::json::array_t>(); else if (not std::get_if<fostlib::json::array_p>(&element)) { throw fostlib::exceptions::json_error( "Cannot walk through a JSON " "object/value which is not an array using an integer " "key", orig); } // Copy the array fostlib::json::array_t &array = *std::get<fostlib::json::array_p>(element); auto copy(std::make_shared<fostlib::json::array_t>( array.begin(), array.end())); while (copy->size() <= k) copy->push_back(fostlib::json{}); element = copy; return &(*copy)[k]; } fostlib::json *operator()(const fostlib::string &k) const { if (isnull) element = std::make_shared<fostlib::json::object_t>(); else if (!std::get_if<fostlib::json::object_p>(&element)) { throw fostlib::exceptions::json_error( "Cannot walk through a JSON " "array/value which is not an object using a string key", orig); } /// Copy the object and return the address of the value at the /// requested key fostlib::json::object_t &object = *std::get<fostlib::json::object_p>(element); auto copy(std::make_shared<fostlib::json::object_t>( object.begin(), object.end())); element = copy; return &(*copy)[k]; } }; } fostlib::json &fostlib::jcursor::copy_from_root(json &j) const { try { json *loc = &j; for (stack_t::const_iterator p(m_position.begin()); p != m_position.end(); ++p) { loc = std::visit(take_step(j, loc->m_element, loc->isnull()), *p); } return *loc; } catch (exceptions::exception &e) { fostlib::insert(e.data(), "jcursor", *this); fostlib::insert(e.data(), "traversing", j); throw; } } fostlib::json &fostlib::jcursor::push_back(json &j, json &&v) const { json &array = copy_from_root(j); if (array.isnull()) { json::array_t na; na.push_back(std::move(v)); array = na; } else if (array.isarray()) { fostlib::json::array_t copy{array.begin(), array.end()}; copy.push_back(std::move(v)); array = std::move(copy); } else { throw exceptions::json_error( "Can only push onto the back of a JSON array"); } return j; } fostlib::json &fostlib::jcursor::insert(json &j, json &&v) const { if (!j.has_key(*this)) { copy_from_root(j) = std::move(v); } else { exceptions::not_null error( "There is already some JSON at this key position"); fostlib::insert(error.data(), "json", j); fostlib::insert(error.data(), "value", v); fostlib::insert(error.data(), "key", *this); throw error; } return j; } fostlib::json &fostlib::jcursor::replace(json &j, json &&v) const { if (j.has_key(*this)) { copy_from_root(j) = std::move(v); } else { throw exceptions::null( "There is nothing to replace at this key position", json::unparse(j, true) + "\n" + json::unparse(v, true)); } return j; } fostlib::json &fostlib::jcursor::set(json &j, json &&v) const { copy_from_root(j) = std::move(v); return j; } namespace { struct del_key { fostlib::json::element_t &element; del_key(fostlib::json::element_t &j) : element(j) {} void operator()(fostlib::json::array_t::size_type k) const { fostlib::json::array_p *arr( std::get_if<fostlib::json::array_p>(&element)); if (!arr) throw fostlib::exceptions::json_error( "A numeric key can only be used to delete from a JSON " "array"); if (k >= (*arr)->size()) throw fostlib::exceptions::out_of_range<std::size_t>( "Trying to erase beyond the end of the array", 0, (*arr)->size(), k); (*arr)->erase((*arr)->begin() + k); } void operator()(const fostlib::string &k) const { fostlib::json::object_p *obj( std::get_if<fostlib::json::object_p>(&element)); if (not obj) throw fostlib::exceptions::json_error( "A string key can only be deleted from JSON objects"); fostlib::json::object_t::iterator p((*obj)->find(k)); if (p == (*obj)->end()) throw fostlib::exceptions::json_error( "Key can't be removed from object as it doesn't exist " "in the object", **obj); (*obj)->erase(p); } }; } fostlib::json &fostlib::jcursor::del_key(json &j) const { try { if (m_position.size() == 0) { throw exceptions::out_of_range<std::size_t>( "The jcursor must have at least one level of items in it", 1, std::numeric_limits<std::size_t>::max(), m_position.size()); } else if (j.has_key(*this)) { copy_from_root(j); jcursor head(begin(), --end()); auto &from = const_cast<json::element_t &>(j[head].m_element); std::visit(::del_key(from), *m_position.rbegin()); } else { throw exceptions::json_error( "The key cannot be deleted because it doesn't exist"); } return j; } catch (exceptions::exception &e) { fostlib::insert(e.data(), "json", j); fostlib::insert(e.data(), "path", *this); throw; } } bool fostlib::jcursor::operator==(const jcursor &j) const { return m_position == j.m_position; } /** * ## JSON pointer */ fostlib::jcursor fostlib::jcursor::parse_json_pointer_string(f5::u8view s) { jcursor ret; auto pos = f5::cord::make_u32u16_iterator(s.begin(), s.end()); const json_pointer_parser< f5::cord::const_u32u16_iterator<f5::u8view::const_iterator>> parser; if (boost::spirit::qi::parse(pos.first, pos.second, parser, ret) && pos.first == pos.second) { return ret; } else { throw exceptions::parse_error( "Whilst parsing JSON pointer string", string(pos.first.u32_iterator(), pos.second.u32_iterator())); } } fostlib::jcursor fostlib::jcursor::parse_json_pointer_fragment(f5::u8view s) { jcursor ret; auto *pos = s.data(), *end = s.data() + s.bytes(); const json_pointer_fragment_parser<decltype(pos)> parser; if (boost::spirit::qi::parse(pos, end, parser, ret) && pos == end) { return ret; } else { throw exceptions::parse_error( "Whilst parsing JSON pointer fragment", f5::u8view{pos, std::size_t(end - pos)}); } } fostlib::ascii_printable_string fostlib::jcursor::as_json_pointer() const { struct proc { std::string pointer; char digit(utf8 dig) { if (dig < 0x0a) return dig + '0'; if (dig < 0x10) return dig + 'A' - 0x0a; throw fostlib::exceptions::out_of_range<int>( "Number to convert to hex digit is too big", 0, 0x10, dig); } void hex(utf8 ch) { pointer += '%'; pointer += digit((ch & 0xf0) >> 4); pointer += digit(ch & 0x0f); } void operator()(const string &s) { pointer += '/'; for (const auto c : s) { if (c == '~') { pointer += "~0"; } else if (c == '/') { pointer += "~1"; } else if (c == 0x25) { pointer += "%25"; } else if (c < 0x7f) { // 7 bit safe pointer += c; } else { auto [bytes, chars] = f5::cord::u8encode(c); for (char b{}; b < bytes; ++b) { hex(chars[b]); } } } } void operator()(std::size_t s) { pointer += '/'; pointer += std::to_string(s); } } visitor; for (const auto &p : m_position) { std::visit(visitor, p); } return fostlib::string{std::move(visitor.pointer)}; }
32.579487
82
0.546671
[ "object" ]
482078a269d949e1addf8469ee02290aa58b3a42
49,614
hpp
C++
src/UTIL/utilities_acml.hpp
Seideman-Group/chiML
9ace5dccdbc6c173e8383f6a31ff421b4fefffdf
[ "MIT" ]
1
2019-04-27T05:25:27.000Z
2019-04-27T05:25:27.000Z
src/UTIL/utilities_acml.hpp
Seideman-Group/chiML
9ace5dccdbc6c173e8383f6a31ff421b4fefffdf
[ "MIT" ]
null
null
null
src/UTIL/utilities_acml.hpp
Seideman-Group/chiML
9ace5dccdbc6c173e8383f6a31ff421b4fefffdf
[ "MIT" ]
2
2019-04-03T10:08:21.000Z
2019-09-30T22:40:28.000Z
/** @file UTIL/utilities_acml.hpp * @brief wrapper functions to a acml blas functionality * * @author Thomas A. Purcell (tpurcell90) * @author Joshua E. Szekely (jeszekely) * @bug No known bugs */ // To see documentation look up functions here: https://software.intel.com/en-us/mkl-reference-manual-for-c #ifndef FDTD_UTILITIES #define FDTD_UTILITIES #include <UTIL/typedefs.hpp> //BLAS extern "C" { void dgemv(char trans, int m, int n, double alpha, double* a, int lda, double* x, int incx, double beta, double* y, int incy); void dgemm(char transa, char transb, int m, int n, int k, double alpha, double *a, int lda, double *b, int ldb, double beta, double *c, int ldc); void dsyev(char jobz, char uplo, int n, double *a, int lda, double *w, int *info); void zheev(char jobz, char uplo, int n, cplx *a, int lda, double *w, int *info); double ddot(int n, double *x, int incx, double *y, int incy); void saxpy(int n, float alpha, float *x, int incx, float *y, int incy); void scopy(int n, float *x, int incx, float *y, int incy); void sscal(int n, float alpha, float *x, int incx); void daxpy(int n, double alpha, double *x, int incx, double *y, int incy); void dcopy(int n, double *x, int incx, double *y, int incy); void dscal(int n, double alpha, double *y, int incy); // void mkl_domatcopy_(char, char, int *, int *, double *, double* , int *, double* , int *); void zaxpy(int n, cplx *alpha, cplx *x, int incx, cplx *y, int incy); void zcopy(int n, cplx *x, int incx, cplx *y, int incy); void zscal(int n, cplx* alpha, cplx *y, int incy); void zgemm(char transa, char transb, int m, int n, int k, cplx *alpha, cplx *a, int lda, cplx *b, int ldb, cplx *beta, cplx *c, int ldc); void zgemv(char transa, int m, int n, cplx *alpha, cplx *a, int lda, cplx *x, int incx, cplx *beta, cplx *y, int incy); void zhemm(char side, char uplo, int m, int n, cplx *alpha, cplx *a, int lda, cplx *b, int ldb, cplx *beta, cplx *c, int ldc); // void mkl_zomatcopy_(char, char, int *, int *, cplx *, cplx* , int *, cplx* , int *); int izamax(int n, cplx *x, int incx); // int izamin(int*, cplx*, int*); int idamax(int n, double *x, int incx); // int idamin(int*, double*, int*); int isamax(int n, float *x, int incx); double dasum_(const int*, const double*, const int*); // int isamin(int*, int*, int*); cplx zdotc(int n, cplx *x, int incx, cplx *y, int incy); } //LAPACK extern "C" { void dgesvd(char jobu, char jobvt, int m, int n, double *a, int lda, double *sing, double *u, int ldu, double *vt, int ldvt, int *info); void dsyevr(char jobz, char range, char uplo, int n, double *a, int lda, double vl, double vu, int il, int iu, double abstol, int *m, double *w, double *z, int ldz, int *isuppz, int *info); } //AlignmentTool interface namespace { /** * @brief Wrapper for dgemv_: c<-$\alpha A*x + /beta*y * * @param[in] trans 'T' or 't' for Transpose, 'C' or c' for Hermitian Conjugate, 'N' or 'n' for neither on Matrix B * @param[in] m Specifies the number of rows of the matrix op(A) and of the matrix C. The value of m must be at least zero. * @param[in] n Specifies the number of columns of the matrix op(A) and the number of rows of the matrix op(B). * @param[in] alpha Specifies the scalar alpha. * @param[in] a Array size lda by ka, where ka is k when transa = 'N' or 'n', and is m otherwise. Before entry with transa = 'N' or 'n', the leading m-by-k part of the array a must contain the matrix A, otherwise the leading k-by-m part of the array a must contain the matrix A. * @param[in] lda specifies the leading dimension of a as declared in the calling (sub)program. * @param[in] x Array, size at least (1+(n-1)*abs(incx)) when trans= 'N' or 'n' and at least (1+(m - 1)*abs(incx)) otherwise. Before entry, the incremented array x must contain the vector x. * @param[in] incx specifies the increment of x. * @param[in] beta Specifies the scalar beta. * @param[in] y Array, size at least (1 +(m - 1)*abs(incy)) when trans= 'N' or 'n' and at least (1 +(n - 1)*abs(incy)) otherwise. Before entry with non-zero beta, the incremented array y must contain the vector y. * @param[in] incy Specifies the increment of y. */ void dgemv_(char trans, int m, int n, double alpha, double* a, int lda, double* x, int incx, double beta, double* y, int incy) { ::dgemv_(trans, m, n, alpha, a, lda, x, incx, beta, y, incy); } /** * @brief Wrapper for dgemm_: c<-$\alpha a*b + /beta*c * * @param[in] transa 'T' or 't' for Transpose, 'C' or c' for Hermitian Conjugate, 'N' or 'n' for neither on Matrix A * @param[in] transb 'T' or 't' for Transpose, 'C' or c' for Hermitian Conjugate, 'N' or 'n' for neither on Matrix B * @param[in] m Specifies the number of rows of the matrix op(A) and of the matrix C. The value of m must be at least zero. * @param[in] n Specifies the number of columns of the matrix op(A) and the number of rows of the matrix op(B). * @param[in] k Specifies the number of columns of the matrix op(A) and the number of rows of the matrix op(B). * @param[in] alpha Specifies the scalar alpha. * @param[in] a Array size lda by ka, where ka is k when transa = 'N' or 'n', and is m otherwise. Before entry with transa = 'N' or 'n', the leading m-by-k part of the array a must contain the matrix A, otherwise the leading k-by-m part of the array a must contain the matrix A. * @param[in] lda specifies the leading dimension of a as declared in the calling (sub)program. * @param[in] b Array, size ldb by kb, where kb is n when transa = 'N' or 'n', and is k otherwise. Before entry with transa = 'N' or 'n', the leading k-by-n part of the array b must contain the matrix B, otherwise the leading n-by-k part of the array b must contain the matrix B. * @param[in] ldb specifies the leading dimension of a as declared in the calling (sub)program. * @param[in] beta Specifies the scalar beta. * @param[in] c Array, size ldc by n. Before entry, the leading m-by-n part of the array c must contain the matrix C, except when beta is equal to zero, in which case c need not be set on entry. * @param[in] ldc Specifies the leading dimension of c as declared in the calling (sub)program. */ void dgemm_(char transa, char transb, int m, int n, int k, double alpha, double* a, int lda, double* b, int ldb, double beta, double* c, int ldc) { ::dgemm(transa,transb,m,n,k,alpha,a,lda,b,ldb,beta,c,ldc); } /** * @brief Wrapper for dgemm_: c<-$\alpha a*b + /beta*c * * @param[in] transa 'T' or 't' for Transpose, 'C' or c' for Hermitian Conjugate, 'N' or 'n' for neither on Matrix A * @param[in] transb 'T' or 't' for Transpose, 'C' or c' for Hermitian Conjugate, 'N' or 'n' for neither on Matrix B * @param[in] m Specifies the number of rows of the matrix op(A) and of the matrix C. The value of m must be at least zero. * @param[in] n Specifies the number of columns of the matrix op(A) and the number of rows of the matrix op(B). * @param[in] k Specifies the number of columns of the matrix op(A) and the number of rows of the matrix op(B). * @param[in] alpha Specifies the scalar alpha. * @param[in] a Array size lda by ka, where ka is k when transa = 'N' or 'n', and is m otherwise. Before entry with transa = 'N' or 'n', the leading m-by-k part of the array a must contain the matrix A, otherwise the leading k-by-m part of the array a must contain the matrix A. * @param[in] lda specifies the leading dimension of a as declared in the calling (sub)program. * @param[in] b Array, size ldb by kb, where kb is n when transa = 'N' or 'n', and is k otherwise. Before entry with transa = 'N' or 'n', the leading k-by-n part of the array b must contain the matrix B, otherwise the leading n-by-k part of the array b must contain the matrix B. * @param[in] ldb specifies the leading dimension of a as declared in the calling (sub)program. * @param[in] beta Specifies the scalar beta. * @param[in] c Array, size ldc by n. Before entry, the leading m-by-n part of the array c must contain the matrix C, except when beta is equal to zero, in which case c need not be set on entry. * @param[in] ldc Specifies the leading dimension of c as declared in the calling (sub)program. */ void dgemm_(char transa, char transb, int m, int n, int k, double alpha, std::unique_ptr<double []>& a, int lda, std::unique_ptr<double []>& b, int ldb, double beta, std::unique_ptr<double []>& c, int ldc) { ::dgemm(transa,transb,m,n,k,alpha,a.get(),lda,b.get(),ldb,beta,c.get(),ldc); } /** * @brief The routine computes all the eigenvalues and, optionally, the eigenvectors of a square real symmetric matrix A. * * @param[in] jobz Must be 'N' or 'V'. If jobz = 'N', then only eigenvalues are computed. If jobz = 'V', then eigenvalues and eigenvectors are computed. * @param[in] uplo Must be 'U' or 'L'. If uplo = 'U', a stores the upper triangular part of A. If uplo = 'L', a stores the lower triangular part of A. * @param[in] n The order of the matrix A (n ≥ 0). * @param a a (size max(1, lda*n)) is an array containing either upper or lower triangular part of the symmetric matrix A, as specified by uplo. * @param[in] lda The leading dimension of the array a. * @param w Array, size at least max(1, n). If INFO = 0, contains the eigenvalues of the matrix A in ascending order. * @param WORK array, dimension (MAX(1,LWORK)) On exit, if i = 0, g(1) returns the optimal LWORK. * @param[in] LWORK The length of the array WORK. LWORK >= max(1,3*N-1). For optimal efficiency, WORK >= (NB+2)*N, where NB is the blocksize for DSYTRD returned by ILAENV. If WORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the LWORK array, returns this value as the first entry of the LWORK array, and no error message related to WORK is issued by XERBLA. * @param INFO If INFO=0, the execution is successful. If INFO = -i, the i-th parameter had an illegal value. If INFO = i, then the algorithm failed to converge; i indicates the number of elements of an intermediate tridiagonal form which did not converge to zero. */ void dsyev_(char* jobz, char* uplo, int n, double* a, int lda, double* w, double* WORK, int LWORK, int INFO) { ::dsyev(*jobz,*uplo,n,a,lda,w, &INFO);} /** * @brief The routine computes all the eigenvalues and, optionally, the eigenvectors of a square real symmetric matrix A. * * @param[in] jobz Must be 'N' or 'V'. If jobz = 'N', then only eigenvalues are computed. If jobz = 'V', then eigenvalues and eigenvectors are computed. * @param[in] uplo Must be 'U' or 'L'. If uplo = 'U', a stores the upper triangular part of A. If uplo = 'L', a stores the lower triangular part of A. * @param[in] n The order of the matrix A (n ≥ 0). * @param a a (size max(1, lda*n)) is an array containing either upper or lower triangular part of the symmetric matrix A, as specified by uplo. * @param[in] lda The leading dimension of the array a. * @param w Array, size at least max(1, n). If INFO = 0, contains the eigenvalues of the matrix A in ascending order. * @param WORK array, dimension (MAX(1,LWORK)) On exit, if i = 0, g(1) returns the optimal LWORK. * @param[in] LWORK The length of the array WORK. LWORK >= max(1,3*N-1). For optimal efficiency, WORK >= (NB+2)*N, where NB is the blocksize for DSYTRD returned by ILAENV. If WORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the LWORK array, returns this value as the first entry of the LWORK array, and no error message related to WORK is issued by XERBLA. * @param INFO If INFO=0, the execution is successful. If INFO = -i, the i-th parameter had an illegal value. If INFO = i, then the algorithm failed to converge; i indicates the number of elements of an intermediate tridiagonal form which did not converge to zero. */ void dsyev_(char* jobz, char* uplo, int n, std::unique_ptr<double []>& a, int lda, std::unique_ptr<double []>& w, std::unique_ptr<double []>& WORK, int LWORK, int INFO) { ::dsyev(*jobz,*uplo,n,a.get(),lda,w.get(), &INFO);} /** * @brief wrapper for dgesvd_ * * @param[in] jobu Must be 'A', 'S', 'O', or 'N'. Specifies options for computing all or part of the matrix U. If jobu = 'A', all m columns of U are returned in the array u; if jobu = 'S', the first min(m, n) columns of U (the left singular vectors) are returned in the array u; if jobu = 'O', the first min(m, n) columns of U (the left singular vectors) are overwritten on the array a; if jobu = 'N', no columns of U (no left singular vectors) are computed. * @param[in] jobvt Must be 'A', 'S', 'O', or 'N'. Specifies options for computing all or part of the matrix VT/VH. If jobvt = 'A', all n rows of VT/VH are returned in the array vt; if jobvt = 'S', the first min(m,n) rows of VT/VH (the right singular vectors) are returned in the array vt; if jobvt = 'O', the first min(m,n) rows of VT/VH) (the right singular vectors) are overwritten on the array a; if jobvt = 'N', no rows of VT/VH (no right singular vectors) are computed. jobvt and jobu cannot both be 'O'. * @param[in] m The number of rows of the matrix A (m ≥ 0). * @param[in] n The number of columns in A (n ≥ 0). * @param a Arrays: a(size at least max(1, lda*n) for column major layout and max(1, lda*m) for row major layout) is an array containing the m-by-n matrix A. * @param[in] lda The leading dimension of the array a. Must be at least max(1, m) for column major layout and at least max(1, n) for row major layout . * @param s array, dimension (min(M,N)) The singular values of A, sorted so that S(i) >= S(i+1). * @param u U is DOUBLE PRECISION array, dimension (LDU,UCOL) (LDU,M) if JOBU = 'A' or (LDU,min(M,N)) if JOBU = 'S'. If JOBU = 'A', U contains the M-by-M orthogonal matrix U; if JOBU = 'S', U contains the first min(m,n) columns of U (the left singular vectors, stored columnwise); if JOBU = 'N' or 'O', U is not referenced. * @param[in] ldu LDU is INTEGER The leading dimension of the array U. LDU >= 1; if JOBU = 'S' or 'A', LDU >= M. * @param vt VT is DOUBLE PRECISION array, dimension (LDVT,N) If JOBVT = 'A', VT contains the N-by-N orthogonal matrix V**T; if JOBVT = 'S', VT contains the first min(m,n) rows of V**T (the right singular vectors, stored rowwise); if JOBVT = 'N' or 'O', VT is not referenced. * @param[in] ldvt LDVT is INTEGER The leading dimension of the array VT. LDVT >= 1; if JOBVT = 'A', LDVT >= N; if JOBVT = 'S', LDVT >= min(M,N). * @param superb If ?bdsqr does not converge (indicated by the return value info > 0), on exit superb(0:min(m,n)-2) contains the unconverged superdiagonal elements of an upper bidiagonal matrix B whose diagonal is in s (not necessarily sorted). B satisfies A = u*B*VT (real flavors) or A = u*B*VH (complex flavors), so it has the same singular values as A, and singular vectors related by u and vt. * @param[in] lwork LWORK is INTEGER The dimension of the array WORK. LWORK >= MAX(1,5*MIN(M,N)) for the paths (see comments inside code): - PATH 1 (M much larger than N, JOBU='N') - PATH 1t (N much larger than M, JOBVT='N') LWORK >= MAX(1,3*MIN(M,N)+MAX(M,N),5*MIN(M,N)) for the other paths For good performance, LWORK should generally be larger. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. * @param info INFO is INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. > 0: if DBDSQR did not converge, INFO specifies how many superdiagonals of an intermediate bidiagonal form B did not converge to zero. See the description of WORK above for details. */ void dgesvd_(char* jobu, char* jobvt, int m, int n, double* a, int lda, double* s, double* u, int ldu, double* vt, int ldvt, double* superb, int lwork , int& info) {return ::dgesvd(*jobu, *jobvt, m, n, a, lda, s, u, ldu, vt, ldvt, &info); } /** * @brief mkl_domatcopy_ wrapper * * @param[in] ordering Ordering of the matrix storage. If ordering = 'R' or 'r', the ordering is row-major. If ordering = 'C' or 'c', the ordering is column-major. * @param[in] trans Parameter that specifies the operation type. If trans = 'N' or 'n', op(A)=A and the matrix A is assumed unchanged on input. If trans = 'T' or 't', it is assumed that A should be transposed. If trans = 'C' or 'c', it is assumed that A should be conjugate transposed. If trans = 'R' or 'r', it is assumed that A should be only conjugated. If the data is real, then trans = 'R' is the same as trans = 'N', and trans = 'C' is the same as trans = 'T'. * @param[in] r he number of rows in the source matrix. * @param[in] c The number of columns in the source matrix. * @param[in] alpha This parameter scales the input matrix by alpha. * @param[in] A Array * @param[in] nr Distance between the first elements in adjacent columns (in the case of the column-major order) or rows (in the case of the row-major order) in the source matrix; measured in the number of elements. This parameter must be at least max(1,rows) if ordering = 'C' or 'c', and max(1,cols) otherwise. * @param[in] B Array * @param[in] nc Distance between the first elements in adjacent columns (in the case of the column-major order) or rows (in the case of the row-major order) in the destination matrix; measured in the number of elements. To determine the minimum value of ldb on output, consider the following guideline: If ordering = 'C' or 'c', then If trans = 'T' or 't' or 'C' or 'c', this parameter must be at least max(1,cols) If trans = 'N' or 'n' or 'R' or 'r', this parameter must be at least max(1,rows) If ordering = 'R' or 'r', then If trans = 'T' or 't' or 'C' or 'c', this parameter must be at least max(1,rows) If trans = 'N' or 'n' or 'R' or 'r', this parameter must be at least max(1,cols) */ // void mkl_domatcopy_(char* ordering, char* trans, int r, int c, double alpha, double* A, int nr, double* B, int nc) {::mkl_domatcopy_(ordering,trans,&r,&c,&alpha,A,&nr,B,&nc);} /** * @brief wrapper for ddot * * @param[in] n INTEGER. Specifies the number of elements in vectors x and y. * @param[in] x Array, size at least (1+(n-1)*abs(incx)). * @param[in] incx INTEGER. Specifies the increment for the elements of x. * @param[in] y Array, size at least (1+(n-1)*abs(incy)). * @param[in] incy INTEGER. Specifies the increment for the elements of y. * * @return Contains the result of the dot product of x and y, if n is positive. Otherwise, 0. */ double ddot_(int n, double* x, int incx, double* y, int incy) { return ::ddot(n,x,incx,y,incy);} /** * @brief wrapper for ddot * * @param[in] n INTEGER. Specifies the number of elements in vectors x and y. * @param[in] x Array, size at least (1+(n-1)*abs(incx)). * @param[in] incx INTEGER. Specifies the increment for the elements of x. * @param[in] y Array, size at least (1+(n-1)*abs(incy)). * @param[in] incy INTEGER. Specifies the increment for the elements of y. * * @return Contains the result of the dot product of x and y, if n is positive. Otherwise, 0. */ double ddot_(int n, std::unique_ptr<double []>& x, int incx, std::unique_ptr<double []>& y, int incy) { return ::ddot(n,x.get(), incx,y.get(),incy); } /** * @brief { function_description } * * @param[in] jobz Must be 'N' or 'V'. If jobz = 'N', then only eigenvalues are computed. If jobz = 'V', then eigenvalues and eigenvectors are computed. * @param[in] range Must be 'A' or 'V' or 'I'. If range = 'A', the routine computes all eigenvalues. If range = 'V', the routine computes eigenvalues w[i] in the half-open interval: vl < w[i] ≤ vu. If range = 'I', the routine computes eigenvalues with indices il to iu. * @param[in] uplo Must be 'U' or 'L'. If uplo = 'U', a stores the upper triangular part of A. If uplo = 'L', a stores the lower triangular part of A. * @param[in] n The order of the matrix A (n ≥ 0). * @param[in] a a (size max(1, lda*n)) is an array containing either upper or lower triangular part of the symmetric matrix A, as specified by uplo. * @param[in] lda The leading dimension of the array a. * @param[in] vl If range = 'V', the lower and upper bounds of the interval to be searched for eigenvalues.aint: vl< vu.If range = 'A' or 'I', vl and vu are not referenced. * @param[in] vu The upper bound for vl * @param[in] il If range = 'I', the indices in ascending order of the smallest and largest eigenvalues to be returned. aint: 1 ≤ il ≤ iu ≤ n, if n > 0; il=1 and iu=0, if n = 0. If range = 'A' or 'V', il and iu are not referenced. * @param[in] iu upper bound for il * @param[in] abstol If jobz = 'V', the eigenvalues and eigenvectors output have residual norms bounded by abstol, and the dot products between different eigenvectors are bounded by abstol. If abstol < n *eps*||T||, then n *eps*||T|| is used instead, where eps is the machine precision, and ||T|| is the 1-norm of the matrix T. The eigenvalues are computed to an accuracy of eps*||T|| irrespective of abstol. If high relative accuracy is important, set abstol to ?lamch('S'). * @param[in] m The total number of eigenvalues found, 0 ≤ m ≤ n. If range = 'A', m = n, if range = 'I', m = iu-il+1, and if range = 'V' the exact value of m is not known in advance. * @param[in] w Arrays: w, size at least max(1, n), contains the selected eigenvalues in ascending order, stored in w[0] to w[m - 1]; * @param[in] z z(size max(1, ldz*m) for column major layout and max(1, ldz*n) for row major layout) . If jobz = 'V', then if info = 0, the first m columns of z contain the orthonormal eigenvectors of the matrix A corresponding to the selected eigenvalues, with the i-th column of z holding the eigenvector associated with w[i - 1]. If jobz = 'N', then z is not referenced. * @param[in] ldz The leading dimension of the output array z. aints: ldz ≥ 1 if jobz = 'N' and ldz ≥ max(1, n) for column major layout and ldz ≥ max(1, m) for row major layout if jobz = 'V'. * @param[in] isuppz Array, size at least 2 *max(1, m). The support of the eigenvectors in z, i.e., the indices indicating the nonzero elements in z. The i-th eigenvector is nonzero only in elements isuppz[2i - 2] through isuppz[2i - 1]. Referenced only if eigenvectors are needed (jobz = 'V') and all eigenvalues are needed, that is, range = 'A' or range = 'I' and il = 1 and iu = n. * @param[in] work outputs I can't find definitions for on the website * @param[in] lwork outputs I can't find definitions for on the website * @param[in] iwork outputs I can't find definitions for on the website * @param[in] liwork outputs I can't find definitions for on the website * @param[in] info If info=0, the execution is successful. If info = -i, the i-th parameter had an illegal value. If info = i, then the algorithm failed to converge; i indicates the number of elements of an intermediate tridiagonal form which did not converge to zero. */ // void dsyevr_(char* jobz, char* range, char* uplo, int n, double* a, int lda, double vl, double vu, int il, int iu, double abstol, int m, double* w, double* z, int ldz, int* isuppz, double* work, int lwork, int* iwork, int liwork, int& info) // { ::dsyevr(*jobz, *range, *uplo, &n, a, &lda, vl, vu, il, iu, abstol, &m, w, z, ldz, isuppz, &info);} /** * @brief wrapper for saxpy_ * * @param[in] n INTEGER. Specifies the number of elements in vectors x and y. * @param[in] a Specifies the scalar a. * @param[in] x Array, size at least (1 + (n-1)*abs(incx)). * @param[in] incx INTEGER. Specifies the increment for the elements of x * @param y Array, size at least (1 + (n-1)*abs(incy)). * @param[in] incy INTEGER. Specifies the increment for the elements of y. */ void saxpy_(int n, int a, int* x, int incx, int* y, int incy) { ::saxpy(n,a,reinterpret_cast<float*>(x),incx,reinterpret_cast<float*>(y),incy); } /** * @brief wrapper for scopy_ * * @param[in] n INTEGER. Specifies the number of elements in vectors x and y. * @param[in] x Array, size at least (1 + (n-1)*abs(incx)). * @param[in] incx INTEGER. Specifies the increment for the elements of x * @param y Array, size at least (1 + (n-1)*abs(incy)). * @param[in] incy INTEGER. Specifies the increment for the elements of y. */ void scopy_(int n, int* x, int incx, int* y, int incy) { ::scopy(n,reinterpret_cast<float*>(x),incx,reinterpret_cast<float*>(y),incy);} /** * @brief wrapper for saxpy_ * * @param[in] n INTEGER. Specifies the number of elements in vectors x and y. * @param[in] a Specifies the scalar a. * @param[in] x Array, size at least (1 + (n-1)*abs(incx)). * @param[in] incx INTEGER. Specifies the increment for the elements of x */ void sscal_(int n, int a, int* x, int incx) {::sscal(n,a,reinterpret_cast<float*>(x),incx);} /** * @brief wrapper for saxpy_ * * @param[in] n INTEGER. Specifies the number of elements in vectors x and y. * @param[in] a Specifies the scalar a. * @param[in] x Array, size at least (1 + (n-1)*abs(incx)). * @param[in] incx INTEGER. Specifies the increment for the elements of x * @param y Array, size at least (1 + (n-1)*abs(incy)). * @param[in] incy INTEGER. Specifies the increment for the elements of y. */ void daxpy_(int n, double a, double* x, int incx, double* y, int incy) { ::daxpy(n,a,x,incx,y,incy); } /** * @brief wrapper for daxpy_ * * @param[in] n INTEGER. Specifies the number of elements in vectors x and y. * @param[in] x Array, size at least (1 + (n-1)*abs(incx)). * @param[in] incx INTEGER. Specifies the increment for the elements of x * @param y Array, size at least (1 + (n-1)*abs(incy)). * @param[in] incy INTEGER. Specifies the increment for the elements of y. */ void dcopy_(int n, double* x, int incx, double* y, int incy) {::dcopy(n,x,incx,y,incy); } /** * @brief wrapper for saxpy_ * * @param[in] n INTEGER. Specifies the number of elements in vectors x and y. * @param[in] a Specifies the scalar a. * @param[in] x Array, size at least (1 + (n-1)*abs(incx)). * @param[in] incx INTEGER. Specifies the increment for the elements of x */ void dscal_(int n, double a, double* x, int incx) {::dscal(n,a,x,incx);} /** * @brief wrapper for zaxpy_ * * @param[in] n INTEGER. Specifies the number of elements in vectors x and y. * @param[in] a Specifies the scalar a. * @param[in] x Array, size at least (1 + (n-1)*abs(incx)). * @param[in] incx INTEGER. Specifies the increment for the elements of x * @param y Array, size at least (1 + (n-1)*abs(incy)). * @param[in] incy INTEGER. Specifies the increment for the elements of y. */ void zaxpy_(int n, cplx a, cplx* x, int incx, cplx* y, int incy) { ::zaxpy(n,&a,x,incx,y,incy); } /** * @brief wrapper for daxpy_ * * @param[in] n INTEGER. Specifies the number of elements in vectors x and y. * @param[in] x Array, size at least (1 + (n-1)*abs(incx)). * @param[in] incx INTEGER. Specifies the increment for the elements of x * @param y Array, size at least (1 + (n-1)*abs(incy)). * @param[in] incy INTEGER. Specifies the increment for the elements of y. */ void zcopy_(int n, cplx* x, int incx, cplx* y, int incy) { ::zcopy(n,x,incx,y,incy);} /** * @brief wrapper for saxpy_ * * @param[in] n INTEGER. Specifies the number of elements in vectors x and y. * @param[in] a Specifies the scalar a. * @param[in] x Array, size at least (1 + (n-1)*abs(incx)). * @param[in] incx INTEGER. Specifies the increment for the elements of x */ void zscal_(int n, cplx a, cplx* x, int incx) {::zscal(n,&a,x,incx);} /** * @brief Wrapper for zgemm3m_: c<-$\alpha a*b + /beta*c (Similar to zgemm_ but different algorithm to do it) * * @param[in] transa 'T' or 't' for Transpose, 'C' or c' for Hermitian Conjugate, 'N' or 'n' for neither on Matrix A * @param[in] transb 'T' or 't' for Transpose, 'C' or c' for Hermitian Conjugate, 'N' or 'n' for neither on Matrix B * @param[in] m Specifies the number of rows of the matrix op(A) and of the matrix C. The value of m must be at least zero. * @param[in] n Specifies the number of columns of the matrix op(A) and the number of rows of the matrix op(B). * @param[in] k Specifies the number of columns of the matrix op(A) and the number of rows of the matrix op(B). * @param[in] alpha Specifies the scalar alpha. * @param[in] a Array size lda by ka, where ka is k when transa = 'N' or 'n', and is m otherwise. Before entry with transa = 'N' or 'n', the leading m-by-k part of the array a must contain the matrix A, otherwise the leading k-by-m part of the array a must contain the matrix A. * @param[in] lda specifies the leading dimension of a as declared in the calling (sub)program. * @param[in] b Array, size ldb by kb, where kb is n when transa = 'N' or 'n', and is k otherwise. Before entry with transa = 'N' or 'n', the leading k-by-n part of the array b must contain the matrix B, otherwise the leading n-by-k part of the array b must contain the matrix B. * @param[in] ldb specifies the leading dimension of a as declared in the calling (sub)program. * @param[in] beta Specifies the scalar beta. * @param[in] c Array, size ldc by n. Before entry, the leading m-by-n part of the array c must contain the matrix C, except when beta is equal to zero, in which case c need not be set on entry. * @param[in] ldc Specifies the leading dimension of c as declared in the calling (sub)program. */ void zgemm_(char transa, char transb, int& m, int& n, int& k, cplx& alpha, cplx* a, int& lda, cplx* b, int& ldb, cplx& beta, cplx* c, int& ldc) { ::zgemm(transa,transb,m,n,k,&alpha,a,lda,b,ldb,&beta,c,ldc); } /** * @brief Wrapper for zgemm3m_: c<-$\alpha a*b + /beta*c (Similar to zgemm_ but different algorithm to do it) * * @param[in] transa 'T' or 't' for Transpose, 'C' or c' for Hermitian Conjugate, 'N' or 'n' for neither on Matrix A * @param[in] transb 'T' or 't' for Transpose, 'C' or c' for Hermitian Conjugate, 'N' or 'n' for neither on Matrix B * @param[in] m Specifies the number of rows of the matrix op(A) and of the matrix C. The value of m must be at least zero. * @param[in] n Specifies the number of columns of the matrix op(A) and the number of rows of the matrix op(B). * @param[in] k Specifies the number of columns of the matrix op(A) and the number of rows of the matrix op(B). * @param[in] alpha Specifies the scalar alpha. * @param[in] a Array size lda by ka, where ka is k when transa = 'N' or 'n', and is m otherwise. Before entry with transa = 'N' or 'n', the leading m-by-k part of the array a must contain the matrix A, otherwise the leading k-by-m part of the array a must contain the matrix A. * @param[in] lda specifies the leading dimension of a as declared in the calling (sub)program. * @param[in] b Array, size ldb by kb, where kb is n when transa = 'N' or 'n', and is k otherwise. Before entry with transa = 'N' or 'n', the leading k-by-n part of the array b must contain the matrix B, otherwise the leading n-by-k part of the array b must contain the matrix B. * @param[in] ldb specifies the leading dimension of a as declared in the calling (sub)program. * @param[in] beta Specifies the scalar beta. * @param[in] c Array, size ldc by n. Before entry, the leading m-by-n part of the array c must contain the matrix C, except when beta is equal to zero, in which case c need not be set on entry. * @param[in] ldc Specifies the leading dimension of c as declared in the calling (sub)program. */ void zgemm_(char transa, char transb, int& m, int& n, int& k, cplx alpha, std::unique_ptr<cplx[]>& a, int& lda, std::unique_ptr<cplx[]>& b, int& ldb, cplx& beta, std::unique_ptr<cplx[]>& c, int& ldc) { ::zgemm(transa,transb,m,n,k,&alpha,a.get(),lda,b.get(),ldb,&beta,c.get(),ldc); } void zhemm_(char side, char uplo, int m, int n, cplx alpha, cplx *a, int lda, cplx *b, int ldb, cplx beta, cplx *c, int ldc) { ::zhemm(side,uplo,m,n,&alpha,a,lda,b,ldb,&beta,c,ldc); } void zhemm_(char side, char uplo, int m, int n, cplx alpha, std::unique_ptr<cplx[]>& a, int lda, std::unique_ptr<cplx[]>& b, int ldb, cplx beta, std::unique_ptr<cplx[]>& c, int ldc) { ::zhemm(side,uplo,m,n,&alpha,a.get(),lda,b.get(),ldb,&beta,c.get(),ldc); } /** * @brief zgemv_ wrapper * * @param[in] trans CHARACTER*1. Specifies the operation: if trans= 'N' or 'n', then y := alpha*A*x + beta*y; if trans= 'T' or 't', then y := alpha*A'*x + beta*y; if trans= 'C' or 'c', then y := alpha *conjg(A')*x + beta*y. * @param[in] m INTEGER. Specifies the number of rows of the matrix A. The value of m must be at least zero. * @param[in] n INTEGER. Specifies the number of columns of the matrix A. The value of n must be at least zero. * @param[in] alpha Specifies the scalar alpha. * @param[in] a Array, size (lda, n). Before entry, the leading m-by-n part of the array a must contain the matrix of coefficients. * @param[in] lda Specifies the leading dimension of a as declared in the calling (sub)program. * @param[in] x Array, size at least (1+(n-1)*abs(incx)) when trans= 'N' or 'n' and at least (1+(m - 1)*abs(incx)) otherwise. Before entry, the incremented array x must contain the vector x. * @param[in] incx Specifies the increment for the elements of x. The value of incx must not be zero. * @param[in] beta Specifies the scalar beta. When beta is set to zero, then y need not be set on input. * @param y Array, size at least (1 +(m - 1)*abs(incy)) when trans= 'N' or 'n' and at least (1 +(n - 1)*abs(incy)) otherwise. Before entry with non-zero beta, the incremented array y must contain the vector y. * @param[in] incy Specifies the increment for the elements of y. The value of incy must not be zero. */ void zgemv_(char* trans, int m, int n, cplx alpha, cplx* a, int lda, cplx* x, int incx, cplx beta, cplx* y, int incy) { ::zgemv(*trans, m, n, &alpha, a, lda, x, incx, &beta, y, incy); } /** * @brief zgemv_ wrapper * * @param[in] trans CHARACTER*1. Specifies the operation: if trans= 'N' or 'n', then y := alpha*A*x + beta*y; if trans= 'T' or 't', then y := alpha*A'*x + beta*y; if trans= 'C' or 'c', then y := alpha *conjg(A')*x + beta*y. * @param[in] m INTEGER. Specifies the number of rows of the matrix A. The value of m must be at least zero. * @param[in] n INTEGER. Specifies the number of columns of the matrix A. The value of n must be at least zero. * @param[in] alpha Specifies the scalar alpha. * @param[in] a Array, size (lda, n). Before entry, the leading m-by-n part of the array a must contain the matrix of coefficients. * @param[in] lda Specifies the leading dimension of a as declared in the calling (sub)program. * @param[in] x Array, size at least (1+(n-1)*abs(incx)) when trans= 'N' or 'n' and at least (1+(m - 1)*abs(incx)) otherwise. Before entry, the incremented array x must contain the vector x. * @param[in] incx Specifies the increment for the elements of x. The value of incx must not be zero. * @param[in] beta Specifies the scalar beta. When beta is set to zero, then y need not be set on input. * @param y Array, size at least (1 +(m - 1)*abs(incy)) when trans= 'N' or 'n' and at least (1 +(n - 1)*abs(incy)) otherwise. Before entry with non-zero beta, the incremented array y must contain the vector y. * @param[in] incy Specifies the increment for the elements of y. The value of incy must not be zero. */ void zgemv_(char* trans, int m, int n, cplx alpha, std::unique_ptr<cplx []>& a, int lda, std::unique_ptr<cplx []>& x, int incx, cplx beta, std::unique_ptr<cplx []>& y, int incy) { ::zgemv(*trans, m, n, &alpha, a.get(), lda, x.get(), incx, &beta, y.get(), incy); } /** * @brief mkl_zomatcopy_ wrapper * * @param[in] ordering Ordering of the matrix storage. If ordering = 'R' or 'r', the ordering is row-major. If ordering = 'C' or 'c', the ordering is column-major. * @param[in] trans Parameter that specifies the operation type. If trans = 'N' or 'n', op(A)=A and the matrix A is assumed unchanged on input. If trans = 'T' or 't', it is assumed that A should be transposed. If trans = 'C' or 'c', it is assumed that A should be conjugate transposed. If trans = 'R' or 'r', it is assumed that A should be only conjugated. If the data is real, then trans = 'R' is the same as trans = 'N', and trans = 'C' is the same as trans = 'T'. * @param[in] r he number of rows in the source matrix. * @param[in] c The number of columns in the source matrix. * @param[in] alpha This parameter scales the input matrix by alpha. * @param[in] A Array * @param[in] nr Distance between the first elements in adjacent columns (in the case of the column-major order) or rows (in the case of the row-major order) in the source matrix; measured in the number of elements. This parameter must be at least max(1,rows) if ordering = 'C' or 'c', and max(1,cols) otherwise. * @param[in] B Array * @param[in] nc Distance between the first elements in adjacent columns (in the case of the column-major order) or rows (in the case of the row-major order) in the destination matrix; measured in the number of elements. To determine the minimum value of ldb on output, consider the following guideline: If ordering = 'C' or 'c', then If trans = 'T' or 't' or 'C' or 'c', this parameter must be at least max(1,cols) If trans = 'N' or 'n' or 'R' or 'r', this parameter must be at least max(1,rows) If ordering = 'R' or 'r', then If trans = 'T' or 't' or 'C' or 'c', this parameter must be at least max(1,rows) If trans = 'N' or 'n' or 'R' or 'r', this parameter must be at least max(1,cols) */ // void mkl_zomatcopy_(char* ordering, char* trans, int r, int c, cplx alpha, cplx* A, int nr, cplx* B, int nc) // {::mkl_zomatcopy_(ordering,trans,&r,&c,&alpha,A,&nr,B,&nc);} /** * @brief izamax_ wrapper * * @param[in] n INTEGER. Specifies the number of elements in vectors x and y. * @param[in] x Array, size at least (1 + (n-1)*abs(incx)). * @param[in] inc INTEGER. Specifies the increment for the elements of x * * @return INTEGER Contains the position of vector element that has the largest absolute value such that x(index) has the largest absolute value. */ int izamax_(int n, cplx *x, int inc) { return ::izamax(n,x,inc);} /** * @brief izamin_ wrapper * * @param[in] n INTEGER. Specifies the number of elements in vectors x and y. * @param[in] x Array, size at least (1 + (n-1)*abs(incx)). * @param[in] inc INTEGER. Specifies the increment for the elements of x * * @return INTEGER. Indicates the position of vector element with the smallest absolute value such that x(index) has the smallest absolute value. */ // int izamin_(int n, cplx *x, int inc) // { return ::izamin(&n,x,&inc);} /** * @brief idamax_ wrapper * * @param[in] n INTEGER. Specifies the number of elements in vectors x and y. * @param[in] x Array, size at least (1 + (n-1)*abs(incx)). * @param[in] inc INTEGER. Specifies the increment for the elements of x * * @return INTEGER Contains the position of vector element that has the largest absolute value such that x(index) has the largest absolute value. */ int idamax_(int n, double *x, int inc) { return ::idamax(n,x,inc);} /** * @brief idamin_ wrapper * * @param[in] n INTEGER. Specifies the number of elements in vectors x and y. * @param[in] x Array, size at least (1 + (n-1)*abs(incx)). * @param[in] inc INTEGER. Specifies the increment for the elements of x * * @return INTEGER. Indicates the position of vector element with the smallest absolute value such that x(index) has the smallest absolute value. */// // int idamin_(int n, double *x, int inc) // { return ::idamin(&n,x,&inc);} /** * @brief isamax_ wrapper * * @param[in] n INTEGER. Specifies the number of elements in vectors x and y. * @param[in] x Array, size at least (1 + (n-1)*abs(incx)). * @param[in] inc INTEGER. Specifies the increment for the elements of x * * @return INTEGER Contains the position of vector element that has the largest absolute value such that x(index) has the largest absolute value. */ int isamax_(int n, int *x, int inc) { return ::isamax(n,reinterpret_cast<float*>(x),inc);} /** * @brief isamin_ wrapper * * @param[in] n INTEGER. Specifies the number of elements in vectors x and y. * @param[in] x Array, size at least (1 + (n-1)*abs(incx)). * @param[in] inc INTEGER. Specifies the increment for the elements of x * * @return INTEGER. Indicates the position of vector element with the smallest absolute value such that x(index) has the smallest absolute value. */ // int isamin_(int n, int *x, int inc) // { return ::isamin(&n,x,&inc);} /** * @brief dasum_ wrapper * * @param[in] n INTEGER. Specifies the number of elements in vectors x and y. * @param[in] x Array, size at least (1 + (n-1)*abs(incx)). * @param[in] inc INTEGER. Specifies the increment for the elements of x * * @return DOUBLE. Contains the sum of magnitudes of real and imaginary parts of all elements of the vector.. */ double dasum_(const int n, const double* x, const int inc) { return ::dasum_(&n,x,&inc);} /** * @brief wrapper for zheev_ * * @param[in] jobz Must be 'N' or 'V'. If jobz = 'N', then only eigenvalues are computed. If jobz = 'V', then eigenvalues and eigenvectors are computed. * @param[in] uplo Must be 'U' or 'L'. If uplo = 'U', a stores the upper triangular part of A. If uplo = 'L', a stores the lower triangular part of A. * @param[in] n The order of the matrix A (n ≥ 0). * @param a a (size max(1, lda*n)) is an array containing either upper or lower triangular part of the Hermitian matrix A, as specified by uplo. * @param[in] lda The leading dimension of the array a. Must be at least max(1, n). * @param w Array, size at least max(1, n). * @param WORK (workspace/output) COMPLEX*16 array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. * @param[in] LWORK (input) INTEGER The length of the array WORK. LWORK >= max(1,2*N-1). For optimal efficiency, LWORK >= (NB+1)*N, where NB is the blocksize for ZHETRD returned by ILAENV. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. * @param RWORK (workspace) DOUBLE PRECISION array, dimension (max(1, 3*N-2)) * @param info INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: if INFO = i, the algorithm failed to converge; i off-diagonal elements of an intermediate tridiagonal form did not converge to zero. */ void zheev_(char* jobz, char* uplo, int n, cplx* a, int lda,double* w, cplx* WORK, int LWORK,double* RWORK, int& info ) { ::zheev( *jobz, *uplo, n, a, lda, w, &info); } /** * @brief wrapper for zheev_ * * @param[in] jobz Must be 'N' or 'V'. If jobz = 'N', then only eigenvalues are computed. If jobz = 'V', then eigenvalues and eigenvectors are computed. * @param[in] uplo Must be 'U' or 'L'. If uplo = 'U', a stores the upper triangular part of A. If uplo = 'L', a stores the lower triangular part of A. * @param[in] n The order of the matrix A (n ≥ 0). * @param a a (size max(1, lda*n)) is an array containing either upper or lower triangular part of the Hermitian matrix A, as specified by uplo. * @param[in] lda The leading dimension of the array a. Must be at least max(1, n). * @param w Array, size at least max(1, n). * @param WORK (workspace/output) COMPLEX*16 array, dimension (LWORK) On exit, if INFO = 0, WORK(1) returns the optimal LWORK. * @param[in] LWORK (input) INTEGER The length of the array WORK. LWORK >= max(1,2*N-1). For optimal efficiency, LWORK >= (NB+1)*N, where NB is the blocksize for ZHETRD returned by ILAENV. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. * @param RWORK (workspace) DOUBLE PRECISION array, dimension (max(1, 3*N-2)) * @param info INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value > 0: if INFO = i, the algorithm failed to converge; i off-diagonal elements of an intermediate tridiagonal form did not converge to zero. */ void zheev_(char* jobz, char* uplo, int n, std::unique_ptr<cplx []>& a, int lda, std::unique_ptr<double[]>& w, std::unique_ptr<cplx []>& WORK, int LWORK, std::unique_ptr<double[]>& RWORK, int& info ) { ::zheev( *jobz, *uplo, n, a.get(), lda, w.get(), &info ); } /** * @brief wrapper for zdotc_ * * @param[in] n INTEGER. Specifies the number of elements in vectors x and y. * @param[in] x Array, size at least (1+(n-1)*abs(incx)). * @param[in] incx INTEGER. Specifies the increment for the elements of x. * @param[in] y Array, size at least (1+(n-1)*abs(incy)). * @param[in] incy INTEGER. Specifies the increment for the elements of y. * * @return Contains the result of the dot product of x and y, if n is positive. Otherwise, 0. */ cplx zdotc_(int n, cplx* x, int incx, cplx* y, int incy) { return ::zdotc(n,x,incx,y,incy); } /** * @brief wrapper for zdotc_ * * @param[in] n INTEGER. Specifies the number of elements in vectors x and y. * @param[in] x Array, size at least (1+(n-1)*abs(incx)). * @param[in] incx INTEGER. Specifies the increment for the elements of x. * @param[in] y Array, size at least (1+(n-1)*abs(incy)). * @param[in] incy INTEGER. Specifies the increment for the elements of y. * * @return Contains the result of the dot product of x and y, if n is positive. Otherwise, 0. */ cplx zdotc_(int n, std::unique_ptr<cplx []>& x, int incx, std::unique_ptr<cplx []>& y, int incy) { return ::zdotc(n,x.get(),incx,y.get(),incy); } // Sparse routines // void mkl_dcsrsymv_(char* uplo, int m, double* a, int* ia, int* ja, double* x, double* y) // {mkl_dcsrsymv_(uplo, m, a, ia, ja, x, y); }; // void mkl_dscrgemv_(char* transa, int m, double* a, int* ia, int* ja, double* x, double* y) // {mkl_dscrgemv_(transa, m, a, ia, ja, x, y); }; } #endif
79.509615
701
0.635365
[ "vector" ]
482350b524d102f46adf928ecd99965eba9aed1d
1,650
cc
C++
packages/transport/Transport_Discretization.cc
brbass/ibex
5a4cc5b4d6d46430d9667970f8a34f37177953d4
[ "MIT" ]
2
2020-04-13T20:06:41.000Z
2021-02-12T17:55:54.000Z
packages/transport/Transport_Discretization.cc
brbass/ibex
5a4cc5b4d6d46430d9667970f8a34f37177953d4
[ "MIT" ]
1
2018-10-22T21:03:35.000Z
2018-10-22T21:03:35.000Z
packages/transport/Transport_Discretization.cc
brbass/ibex
5a4cc5b4d6d46430d9667970f8a34f37177953d4
[ "MIT" ]
3
2019-04-03T02:15:37.000Z
2022-01-04T05:50:23.000Z
#include "Transport_Discretization.hh" #include "Angular_Discretization.hh" #include "Energy_Discretization.hh" #include "Spatial_Discretization.hh" #include "XML_Node.hh" using std::shared_ptr; using std::vector; Transport_Discretization:: Transport_Discretization(shared_ptr<Spatial_Discretization> spatial, shared_ptr<Angular_Discretization> angular, shared_ptr<Energy_Discretization> energy): spatial_(spatial), angular_(angular), energy_(energy) { int number_of_points = spatial->number_of_points(); int number_of_nodes = spatial->number_of_nodes(); int number_of_boundary_points = spatial->number_of_boundary_points(); int number_of_groups = energy->number_of_groups(); int number_of_ordinates = angular->number_of_ordinates(); int number_of_moments = angular->number_of_moments(); has_reflection_ = spatial->has_reflection(); phi_size_ = number_of_points * number_of_groups * number_of_moments * number_of_nodes; psi_size_ = number_of_points * number_of_groups * number_of_ordinates * number_of_nodes; if (has_reflection_) { number_of_augments_ = number_of_boundary_points * number_of_groups * number_of_ordinates * number_of_nodes; } else { number_of_augments_ = 0; } } void Transport_Discretization:: output(XML_Node output_node) const { output_node.set_attribute(has_reflection_, "has_reflection"); output_node.set_child_value(phi_size_, "phi_size"); output_node.set_child_value(psi_size_, "psi_size"); output_node.set_child_value(number_of_augments_, "number_of_augments"); }
35.106383
115
0.747879
[ "vector" ]
4823c311cfa743df9fded1e7d6b69b6054038a64
11,628
cpp
C++
engine/std/shader.cpp
jjzhang166/OpenGLEngine
e5d86f41536834499f4dd534c590fbeed045ff7c
[ "MIT" ]
1
2021-08-12T07:35:49.000Z
2021-08-12T07:35:49.000Z
engine/std/shader.cpp
jjzhang166/OpenGLEngine
e5d86f41536834499f4dd534c590fbeed045ff7c
[ "MIT" ]
null
null
null
engine/std/shader.cpp
jjzhang166/OpenGLEngine
e5d86f41536834499f4dd534c590fbeed045ff7c
[ "MIT" ]
null
null
null
// // shader.cpp // OpenGLEngine // // Created by 彭怀亮 on 5/28/19. // Copyright © 2019 彭怀亮. All rights reserved. // #include "shader.hpp" #include "util.hpp" #ifdef _GLES_ #include "FilePath.h" #endif namespace engine { Shader::Shader(const char* vertexPath, const char* fragmentPath, const char* geometryPath, std::string macro) { // 1. retrieve the vertex/fragment source code from filePath #ifdef DEBUG this->vertexPath = vertexPath; this->fragmentPath = fragmentPath; this->geometryPath = geometryPath; #endif vertexCode = openFile(vertexPath); fragmentCode = openFile(fragmentPath); if(geometryPath != nullptr) geometryCode = openFile(geometryPath); else geometryCode = ""; this->ID = 0; this->macro = macro; this->compiled = false; } Shader::~Shader() { if(ID > 0) { glDeleteProgram(ID); ID = 0; } } void Shader::attach(const char* k1) { attach(k1,""); } void Shader::attach(const char* k1, const char* v1) { std::stringstream stream; stream<< macro; MACRO(k1, v1); macro = stream.str(); stream.clear(); } void Shader::attach(VertType type) { std::stringstream stream; stream.width(4); stream.fill('0'); stream<<std::hex<<type; std::string macro = "0x"+stream.str(); attach("VERT_TYPE", macro.c_str()); } void Shader::compile() { vertexCode = pre_process(vertexCode, macro); fragmentCode = pre_process(fragmentCode, macro); const char* vShaderCode = vertexCode.c_str(); const char* fShaderCode = fragmentCode.c_str(); // 2. compile shaders GLuint vertex, fragment; // vertex shader vertex = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex, 1, &vShaderCode, NULL); glCompileShader(vertex); checkCompileErrors(vertex, "VERTEX"); // fragment Shader fragment = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment, 1, &fShaderCode, NULL); glCompileShader(fragment); checkCompileErrors(fragment, "FRAGMENT"); GLuint geometry = 0; if(!geometryCode.empty()) { #ifndef _GLES_ const char * gShaderCode = geometryCode.c_str(); geometry = glCreateShader(GL_GEOMETRY_SHADER); glShaderSource(geometry, 1, &gShaderCode, NULL); glCompileShader(geometry); checkCompileErrors(geometry, "GEOMETRY"); #endif } ID = glCreateProgram(); glAttachShader(ID, vertex); glAttachShader(ID, fragment); if(!geometryCode.empty()) glAttachShader(ID, geometry); glLinkProgram(ID); checkCompileErrors(ID, "PROGRAM"); #ifdef DEBUG save(vertexCode, vertexPath); save(fragmentCode, fragmentPath); if(!geometryCode.empty()) save(geometryCode, geometryPath); #endif // delete the shaders as they're linked into our program now and no longer necessery glDeleteShader(vertex); vertexCode = ""; glDeleteShader(fragment); fragmentCode = ""; if(!geometryCode.empty()){ glDeleteShader(geometry); geometryCode=""; } compiled = true; } bool Shader::use() { bool resut = compiled; if(!compiled) { compile(); } glUseProgram(ID); return resut; } void Shader::Shader::setBool(const std::string &name, bool value) const { glUniform1i(glGetUniformLocation(ID, name.c_str()), (int)value); } void Shader::setInt(const std::string &name, int value) const { glUniform1i(glGetUniformLocation(ID, name.c_str()), value); } void Shader::setFloat(const std::string &name, float value) const { glUniform1f(glGetUniformLocation(ID, name.c_str()), value); } void Shader::setVec2(const std::string &name, const glm::vec2 &value) const { glUniform2fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]); } void Shader::setVec2(const std::string &name, float x, float y) const { glUniform2f(glGetUniformLocation(ID, name.c_str()), x, y); } void Shader::setVec3(const std::string &name, const glm::vec3 &value) const { glUniform3fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]); } void Shader::setVec3(const std::string &name, float x, float y, float z) const { glUniform3f(glGetUniformLocation(ID, name.c_str()), x, y, z); } void Shader::setVec3(const std::string &name, GLsizei count, const glm::vec3 &value) const { glUniform3fv(glGetUniformLocation(ID, name.c_str()), count, glm::value_ptr(value)); } void Shader::setVec4(const std::string &name, const glm::vec4 &value) const { glUniform4fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]); } void Shader::setVec4(const std::string &name, float x, float y, float z, float w) { glUniform4f(glGetUniformLocation(ID, name.c_str()), x, y, z, w); } void Shader::setMat2(const std::string &name, const glm::mat2 &mat) const { glUniformMatrix2fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]); } void Shader::setMat3(const std::string &name, const glm::mat3 &mat) const { glUniformMatrix3fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]); } void Shader::setMat4(const std::string &name, const glm::mat4 &mat) const { glUniformMatrix4fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]); } void Shader::setMat4(const std::string &name, GLsizei count, const glm::mat4 &mat) const { glUniformMatrix4fv(glGetUniformLocation(ID, name.c_str()), count, GL_FALSE, &mat[0][0]); } std::string Shader::pre_process(const std::string& source,const std::string macro) { auto str = preprocess(source,macro,0); headers.clear(); return str; } std::string Shader::preprocess(const std::string& source,const std::string macro, int level) { if(level > 32) throw "header inclusion depth limit reached, might be caused by cyclic header inclusion"; std::regex re("^[ ]*#[ ]*include[ ]+[\"<](.*)[\">].*"); std::stringstream input; std::stringstream output; input << source; size_t line_number = 1; std::smatch matches; bool find = false; std::string line; while(std::getline(input,line)) { bool title = false; if(!find && level == 0) { std::size_t found = line.find("#version"); title = found != std::string::npos; #ifdef _GLES_ line = "#version 300 es"; #endif find = true; } if (std::regex_search(line, matches, re)) { std::string include_file = matches[1]; if(std::find(headers.begin(), headers.end(), include_file)==headers.end()) { headers.push_back(include_file); #ifdef _GLES_ size_t idx = include_file.rfind("/"); include_file = include_file.replace(0, idx+1, ""); #endif std::string include_string = openFile(include_file.c_str()); output << preprocess(include_string, "", level + 1) << std::endl; } } else { output << line << std::endl; } if(title) { #ifdef _GLES_ output<<"precision mediump float;"<<std::endl; #endif output<<macro<<std::endl; } ++line_number; } return output.str(); } //complete shader for debug void Shader::save(std::string text, const char* name) { std::string path(name); #ifdef _GLES_ #ifndef TARGET_IPHONE_SIMULATOR return; #endif path = "/tmp/"+path; #else path = "temp/"+path; #endif // _GLES_ size_t idx = path.rfind("/"); CheckDir(path.substr(0,idx).c_str()); std::ofstream file; file.exceptions (std::ofstream::failbit | std::ofstream::badbit); try { file.open(path,std::ostream::trunc); file << text; file.close(); } catch (std::ofstream::failure e) { std::cout << "ERROR::SHADER::SAVE, " <<name<< std::endl; } } std::string Shader::openFile(const char* name) { std::string text; std::ifstream file; file.exceptions (std::ifstream::failbit | std::ifstream::badbit); try { #ifdef _GLES_ std::string path = getPath(name); #else std::string path(name); path = "shader/" + path; path = WORKDIR + path; #endif file.open(path); std::stringstream stream; stream << file.rdbuf(); file.close(); text = stream.str(); } catch (std::ifstream::failure e) { std::cout << "ERROR::SHADER::READ, "<<name << std::endl; } return text; } void Shader::checkCompileErrors(GLuint shader, std::string type) { GLint success; GLchar infoLog[1024]; if(type != "PROGRAM") { glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if(!success) { glGetShaderInfoLog(shader, 1024, NULL, infoLog); const char* name = ""; #ifdef DEBUG if(type == "VERTEX") name = this->vertexPath; if(type == "FRAGMENT") name = this->fragmentPath; #endif std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << type<<" "<<name << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } } else { glGetProgramiv(shader, GL_LINK_STATUS, &success); if(!success) { glGetProgramInfoLog(shader, 1024, NULL, infoLog); std::cout << "ERROR::PROGRAM_LINKING_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } } } LightShader::LightShader(const char* vertexPath, const char* fragmentPath, const char* geometryPath, std::string macro, glm::vec3 ambinent, glm::vec3 diffuse, glm::vec3 specular, float shiness) :Shader(vertexPath, fragmentPath, geometryPath, macro) { this->ambinent = ambinent; this->diffuse = diffuse; this->specular = specular; this->shininess = shiness; } bool LightShader::use() { if(!Shader::use()) { ApplyLight(); } return compiled; } void LightShader::ApplyLight() { setVec3("material.ambient", ambinent); setVec3("material.diffuse", diffuse); setVec3("material.specular", specular); setFloat("material.shininess", shininess); } }
30.28125
191
0.542828
[ "geometry" ]
482898acb003b6eba1c724229148dfbce650d2f4
2,531
cpp
C++
Game/OGRE/OgreMain/src/OgreRenderWindow.cpp
hackerlank/SourceCode
b702c9e0a9ca5d86933f3c827abb02a18ffc9a59
[ "MIT" ]
4
2021-07-31T13:56:01.000Z
2021-11-13T02:55:10.000Z
Game/OGRE/OgreMain/src/OgreRenderWindow.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
null
null
null
Game/OGRE/OgreMain/src/OgreRenderWindow.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
7
2021-08-31T14:34:23.000Z
2022-01-19T08:25:58.000Z
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2005 The OGRE Team Also see acknowledgements in Readme.html This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/copyleft/lesser.txt. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "OgreRenderWindow.h" #include "OgreRoot.h" #include "OgreRenderSystem.h" #include "OgreViewport.h" #include "OgreSceneManager.h" namespace Ogre { RenderWindow::RenderWindow() : RenderTarget(), mIsPrimary(false) { } //----------------------------------------------------------------------- void RenderWindow::getMetrics(unsigned int& width, unsigned int& height, unsigned int& colourDepth, int& left, int& top) { width = mWidth; height = mHeight; colourDepth = mColourDepth; left = mLeft; top = mTop; } //----------------------------------------------------------------------- bool RenderWindow::isFullScreen(void) const { return mIsFullScreen; } //----------------------------------------------------------------------- bool RenderWindow::isPrimary(void) const { return mIsPrimary; } //----------------------------------------------------------------------- void RenderWindow::update(void) { update(true); } //----------------------------------------------------------------------- void RenderWindow::update(bool swap) { // call superclass RenderTarget::update(); if (swap) { // Swap buffers swapBuffers(Root::getSingleton().getRenderSystem()->getWaitForVerticalBlank()); } } }
31.6375
103
0.55077
[ "object" ]
4831d99f348c402b3f3de68e34714ae9b7c3607e
7,742
cpp
C++
Example/Source/GameStates/SpriteDemo.cpp
amitukind/WebGL-Game-Engine
c78973803938c1cfba703d9bb437ec46a4c48045
[ "Unlicense" ]
null
null
null
Example/Source/GameStates/SpriteDemo.cpp
amitukind/WebGL-Game-Engine
c78973803938c1cfba703d9bb437ec46a4c48045
[ "Unlicense" ]
null
null
null
Example/Source/GameStates/SpriteDemo.cpp
amitukind/WebGL-Game-Engine
c78973803938c1cfba703d9bb437ec46a4c48045
[ "Unlicense" ]
null
null
null
/* Copyright (c) 2018-2021 Piotr Doan. All rights reserved. Software distributed under the permissive MIT License. */ #include "../Precompiled.hpp" #include "SpriteDemo.hpp" #include <Engine.hpp> #include <System/Timer.hpp> #include <System/InputManager.hpp> #include <System/ResourceManager.hpp> #include <Graphics/TextureAtlas.hpp> #include <Graphics/Sprite/SpriteAnimationList.hpp> #include <Game/TickTimer.hpp> #include <Game/GameInstance.hpp> #include <Game/GameFramework.hpp> #include <Game/EntitySystem.hpp> #include <Game/ComponentSystem.hpp> #include <Game/Systems/IdentitySystem.hpp> #include <Game/Components/TransformComponent.hpp> #include <Game/Components/CameraComponent.hpp> #include <Game/Components/SpriteComponent.hpp> #include <Game/Components/SpriteAnimationComponent.hpp> #include <Editor/EditorSystem.hpp> SpriteDemo::SpriteDemo() = default; SpriteDemo::~SpriteDemo() = default; SpriteDemo::CreateResult SpriteDemo::Create(Engine::Root* engine) { LOG_PROFILE_SCOPE("Create game scene"); // Validate engine reference. CHECK_ARGUMENT_OR_RETURN(engine != nullptr, Common::Failure(CreateErrors::InvalidArgument)); // Acquire engine systems. auto* inputManager = engine->GetSystems().Locate<System::InputManager>(); auto* resourceManager = engine->GetSystems().Locate<System::ResourceManager>(); auto* gameFramework = engine->GetSystems().Locate<Game::GameFramework>(); // Create instance. auto instance = std::unique_ptr<SpriteDemo>(new SpriteDemo()); // Create tick timer. instance->m_tickTimer = Game::TickTimer::Create().UnwrapOr(nullptr); if(instance->m_tickTimer == nullptr) { LOG_ERROR("Could not create tick timer!"); return Common::Failure(CreateErrors::FailedTickTimerCreate); } // Create game instance. instance->m_gameInstance = Game::GameInstance::Create().UnwrapOr(nullptr); if(instance->m_gameInstance == nullptr) { LOG_ERROR("Could not create game instance!"); return Common::Failure(CreateErrors::FailedGameInstanceCreate); } // Load sprite animation list. Graphics::SpriteAnimationList::LoadFromFile spriteAnimationListParams; spriteAnimationListParams.engineSystems = &engine->GetSystems(); auto spriteAnimationList = resourceManager->Acquire<Graphics::SpriteAnimationList>( "Data/Textures/Checker.animation", spriteAnimationListParams).UnwrapOr(nullptr); if(spriteAnimationList == nullptr) { LOG_ERROR("Could not load sprite animation list!"); return Common::Failure(CreateErrors::FailedResourceLoad); } // Load texture atlas. Graphics::TextureAtlas::LoadFromFile textureAtlasParams; textureAtlasParams.engineSystems = &engine->GetSystems(); auto textureAtlas = resourceManager->Acquire<Graphics::TextureAtlas>( "Data/Textures/Checker.atlas", textureAtlasParams).UnwrapOr(nullptr); if(textureAtlas == nullptr) { LOG_ERROR("Could not load texture atlas!"); return Common::Failure(CreateErrors::FailedResourceLoad); } // Retrieve game systems. auto* entitySystem = instance->m_gameInstance->GetSystems().Locate<Game::EntitySystem>(); auto* componentSystem = instance->m_gameInstance->GetSystems().Locate<Game::ComponentSystem>(); auto* identitySystem = instance->m_gameInstance->GetSystems().Locate<Game::IdentitySystem>(); ASSERT(entitySystem && componentSystem && identitySystem); // Create camera entity. { // Create named entity. Game::EntityHandle cameraEntity = entitySystem->CreateEntity().Unwrap(); identitySystem->SetEntityName(cameraEntity, "Camera"); // Create transform component. auto* transform = componentSystem->Create<Game::TransformComponent>(cameraEntity).Unwrap(); ASSERT(transform != nullptr, "Could not create transform component!"); transform->SetPosition(glm::vec3(0.0f, 0.0f, 2.0f)); // Create camera component. auto* camera = componentSystem->Create<Game::CameraComponent>(cameraEntity).Unwrap(); ASSERT(camera != nullptr, "Could not create camera component!"); camera->SetupOrthogonal(glm::vec2(16.0f, 9.0f), 0.1f, 1000.0f); } // Create player entity. { // Create named entity. Game::EntityHandle playerEntity = entitySystem->CreateEntity().Unwrap(); identitySystem->SetEntityName(playerEntity, "Player"); // Create transform component. auto* transform = componentSystem->Create<Game::TransformComponent>(playerEntity).Unwrap(); transform->SetPosition(glm::vec3(0.0f, 0.0f, 0.0f)); transform->SetScale(glm::vec3(1.0f) * (2.0f + (float)glm::cos(0.0f))); transform->SetRotation(glm::rotate(glm::identity<glm::quat>(), 2.0f * glm::pi<float>() * ((float)std::fmod(0.0f, 10.0) / 10.0f), glm::vec3(0.0f, 0.0f, 1.0f))); // Create sprite component. auto* sprite = componentSystem->Create<Game::SpriteComponent>(playerEntity).Unwrap(); sprite->SetRectangle(glm::vec4(-0.5f, -0.5f, 0.5f, 0.5f)); sprite->SetColor(glm::vec4(1.0f, 1.0f, 1.0f, 1.0f)); sprite->SetTextureView(textureAtlas->GetRegion("animation_frame_3")); sprite->SetTransparent(false); sprite->SetFiltered(true); // Create sprite animation component. auto* spriteAnimation = componentSystem->Create<Game::SpriteAnimationComponent>(playerEntity).Unwrap(); spriteAnimation->SetSpriteAnimationList(spriteAnimationList); spriteAnimation->Play("rotation", true); } // Save engine reference. instance->m_engine = engine; return Common::Success(std::move(instance)); } void SpriteDemo::Tick(const float tickTime) { // Retrieve game systems. auto* componentSystem = m_gameInstance->GetSystems().Locate<Game::ComponentSystem>(); auto* identitySystem = m_gameInstance->GetSystems().Locate<Game::IdentitySystem>(); // Retrieve player transform. Game::EntityHandle playerEntity = identitySystem->GetEntityByName("Player").Unwrap(); auto transform = componentSystem->Lookup<Game::TransformComponent>(playerEntity).Unwrap(); // Animate the entity. double timeAccumulated = m_tickTimer->GetTotalTickSeconds(); transform->SetScale(glm::vec3(1.0f) * (2.0f + (float)glm::cos(timeAccumulated))); transform->SetRotation(glm::rotate(glm::identity<glm::quat>(), 2.0f * glm::pi<float>() * ((float)std::fmod(timeAccumulated, 10.0) / 10.0f), glm::vec3(0.0f, 0.0f, 1.0f))); // Control the entity with keyboard. auto* inputManager = m_engine->GetSystems().Locate<System::InputManager>(); System::InputState& inputState = inputManager->GetInputState(); glm::vec3 direction(0.0f, 0.0f, 0.0f); if(inputState.IsKeyboardKeyPressed(System::KeyboardKeys::KeyLeft)) { direction.x -= 1.0f; } if(inputState.IsKeyboardKeyPressed(System::KeyboardKeys::KeyRight)) { direction.x += 1.0f; } if(inputState.IsKeyboardKeyPressed(System::KeyboardKeys::KeyUp)) { direction.y += 1.0f; } if(inputState.IsKeyboardKeyPressed(System::KeyboardKeys::KeyDown)) { direction.y -= 1.0f; } if(direction != glm::vec3(0.0f)) { transform->SetPosition(transform->GetPosition() + 4.0f * glm::normalize(direction) * tickTime); } } void SpriteDemo::Update(const float timeDelta) { } void SpriteDemo::Draw(const float timeAlpha) { } Game::TickTimer* SpriteDemo::GetTickTimer() const { return m_tickTimer.get(); } Game::GameInstance* SpriteDemo::GetGameInstance() const { return m_gameInstance.get(); }
36.518868
99
0.689873
[ "transform" ]
4837bd8a4fd9b16bb21a7979448ad61a98563a77
1,733
cpp
C++
compiler/parser/visitors/typecheck/typecheck.cpp
markhend/seq
c5c924a679a5dd21ad85bb3c847df0afca39776b
[ "Apache-2.0" ]
625
2019-10-24T12:02:58.000Z
2022-03-30T06:07:22.000Z
compiler/parser/visitors/typecheck/typecheck.cpp
markhend/seq
c5c924a679a5dd21ad85bb3c847df0afca39776b
[ "Apache-2.0" ]
101
2019-11-01T00:37:38.000Z
2022-02-17T02:50:04.000Z
compiler/parser/visitors/typecheck/typecheck.cpp
markhend/seq
c5c924a679a5dd21ad85bb3c847df0afca39776b
[ "Apache-2.0" ]
48
2019-11-13T14:39:31.000Z
2022-02-17T02:08:41.000Z
/* * typecheck.cpp --- Type inference and type-dependent AST transformations. * * (c) Seq project. All rights reserved. * This file is subject to the terms and conditions defined in * file 'LICENSE', which is part of this source code package. */ #include "util/fmt/format.h" #include <memory> #include <utility> #include <vector> #include "parser/ast.h" #include "parser/common.h" #include "parser/visitors/simplify/simplify_ctx.h" #include "parser/visitors/typecheck/typecheck.h" #include "parser/visitors/typecheck/typecheck_ctx.h" using fmt::format; using std::deque; using std::dynamic_pointer_cast; using std::get; using std::move; using std::ostream; using std::stack; using std::static_pointer_cast; namespace seq { namespace ast { using namespace types; TypecheckVisitor::TypecheckVisitor(shared_ptr<TypeContext> ctx, const shared_ptr<vector<StmtPtr>> &stmts) : ctx(move(ctx)), allowVoidExpr(false) { prependStmts = stmts ? stmts : make_shared<vector<StmtPtr>>(); } StmtPtr TypecheckVisitor::apply(shared_ptr<Cache> cache, StmtPtr stmts) { auto ctx = make_shared<TypeContext>(cache); cache->typeCtx = ctx; TypecheckVisitor v(ctx); auto infer = v.inferTypes(stmts->clone(), true, "<top>"); return move(infer.second); } TypePtr TypecheckVisitor::unify(TypePtr &a, const TypePtr &b) { if (!a) return a = b; seqassert(b, "rhs is nullptr"); types::Type::Unification undo; if (a->unify(b.get(), &undo) >= 0) return a; undo.undo(); // LOG("{} / {}", a->debugString(true), b->debugString(true)); a->unify(b.get(), &undo); error("cannot unify {} and {}", a->toString(), b->toString()); return nullptr; } } // namespace ast } // namespace seq
27.078125
76
0.687825
[ "vector" ]
483afbd06b3063069421b426d93fdbb324eea54b
1,165
hpp
C++
include/mandoline/barycentric_triangle_face.hpp
mtao/mandoline
79438c5b210a2ca4b9f72cbfd2879a9ae6a665da
[ "MIT" ]
54
2019-11-12T11:07:03.000Z
2022-03-23T11:09:19.000Z
include/mandoline/barycentric_triangle_face.hpp
mtao/mandoline
79438c5b210a2ca4b9f72cbfd2879a9ae6a665da
[ "MIT" ]
2
2019-12-17T01:49:44.000Z
2020-03-29T19:46:36.000Z
include/mandoline/barycentric_triangle_face.hpp
mtao/mandoline
79438c5b210a2ca4b9f72cbfd2879a9ae6a665da
[ "MIT" ]
8
2019-11-29T02:30:49.000Z
2022-02-19T06:15:22.000Z
#pragma once #include <mtao/types.hpp> #include <Eigen/Sparse> #include "mandoline/cutface.hpp" namespace mandoline { // BarycentricTriangleFan stores the vertices of a simple polygon struct BarycentricTriangleFace { mtao::ColVecs3d barys; int parent_fid = -1; // reads off the vertex info in the format {cut-vertex index, triangle-vertex} = barycentric // this format is creates std::map<std::array<int, 2>, double> sparse_matrix_entries(const std::vector<int> &indices, const mtao::ColVecs3i &F) const; // we can just pass a cut-face in. Cut-faces of trianglees only have a single face so we can just extract that one std::map<std::array<int, 2>, double> sparse_matrix_entries(const CutFace<3> &face, const mtao::ColVecs3i &F) const { assert(face.is_mesh_face()); assert(face.indices.size() == 1); return sparse_matrix_entries(*face.indices.begin(), F); } std::map<std::array<int, 2>, double> sparse_matrix_entries(const CutMeshFace<3> &face, const mtao::ColVecs3i &F) const { return sparse_matrix_entries(face.indices, F); } double volume() const; }; }// namespace mandoline
37.580645
128
0.699571
[ "vector" ]
483d05d85f298c72e95a4c120957cbdb0ae95f6d
8,105
hpp
C++
src/cpp/features.hpp
laudv/veritas
ba1761cc333b08b4381afa720b24ace065a9f106
[ "Apache-2.0" ]
6
2020-10-29T10:20:48.000Z
2022-03-31T13:39:47.000Z
src/cpp/features.hpp
laudv/veritas
ba1761cc333b08b4381afa720b24ace065a9f106
[ "Apache-2.0" ]
1
2021-11-25T13:15:11.000Z
2021-12-08T09:23:24.000Z
src/cpp/features.hpp
laudv/veritas
ba1761cc333b08b4381afa720b24ace065a9f106
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2020 DTAI Research Group - KU Leuven. * License: Apache License 2.0 * Author: Laurens Devos */ #ifndef VERITAS_FEAT_MAP_HPP #define VERITAS_FEAT_MAP_HPP #include "basics.hpp" #include "tree.hpp" #include <vector> #include <string> #include <map> #include <memory> #include <iostream> #include <functional> namespace veritas { /** * A dataset has a list of features, usually with names. * Internally, an index is used to refer to a particular feature, going * from 0 for the first feature name, and len(features) for the last * feature name. * * * */ class FeatMap { std::vector<std::string> names_; std::map<std::reference_wrapper<const std::string>, FeatId, std::less<const std::string>> index_map_; // disjoint set data structure mapping index -> feat id // vector is twice the length of names_, first set for first instance, second set for second instance mutable std::vector<FeatId> feat_ids_; using IterValueType = std::tuple<const std::string&, FeatId>; public: template <typename ...Args> explicit FeatMap(Args... feature_names) : names_(feature_names...) { init(); } FeatMap(FeatId num_features) { for (FeatId index = 0; index < num_features; ++index) { std::stringstream buffer; buffer << "feature" << index; names_.push_back(buffer.str()); } init(); } size_t num_features() const { return names_.size(); } FeatId get_index(const std::string& feature_name, int instance) const { auto it = index_map_.find(feature_name); if (it != index_map_.end()) return get_index(it->second, instance); throw std::runtime_error("invalid feature name"); } FeatId get_index(FeatId index, int instance) const { // second instance's indexes are offset by number of features int offset = clean_instance(instance) * num_features(); return index + offset; } int get_instance(FeatId index) const { return static_cast<size_t>(index) >= num_features(); } const std::string& get_name(FeatId index) const { return names_.at(index % num_features()); } void get_indices_map(std::multimap<FeatId, FeatId>& out, int instance=-1) const { FeatId begin = (instance==1) * static_cast<FeatId>(num_features()); FeatId end = (static_cast<FeatId>(instance!=0) + 1) * static_cast<FeatId>(num_features()); for (FeatId index = begin; index < end; ++index) { FeatId feat_id = get_feat_id(index); out.insert({feat_id, index}); } } std::multimap<FeatId, FeatId> get_indices_map(int instance=-1) const { std::multimap<FeatId, FeatId> mmap; get_indices_map(mmap, instance); return mmap; } void share_all_features_between_instances() { for (FeatId index = 0; static_cast<size_t>(index) < names_.size(); ++index) uf_union(index, index+num_features()); } FeatId get_feat_id(FeatId index) const { return uf_find(index); } FeatId get_feat_id(const std::string& feat_name, int instance=0) const { return get_feat_id(get_index(feat_name, instance)); } void use_same_id_for(FeatId index1, FeatId index2) { uf_union(index1, index2); } /** Replace the feature ids used in the given at by the replacements in this FeatMap. */ AddTree transform(const AddTree& at, int instance=0) const { instance = clean_instance(instance); AddTree new_at; for (const Tree& t : at) { Tree& new_t = new_at.add_tree(); transform(t.root(), new_t.root(), instance); } return new_at; } class iterator { // simple range iter over indexes friend FeatMap; FeatId index; public: iterator(FeatId index) : index(index) {} iterator& operator++() { ++index; return *this; } iterator operator++(int) { iterator retval = *this; ++(*this); return retval; } bool operator==(iterator other) const { return index == other.index; } bool operator!=(iterator other) const { return !(*this == other); } FeatId operator*() { return index; } // iterator traits using value_type = FeatId; using difference_type = size_t; using pointer = const FeatId*; using reference = const FeatId&; using iterator_category = std::forward_iterator_tag; }; iterator begin(int instance = 0) const { return {static_cast<FeatId>(clean_instance(instance) * num_features())}; } iterator end(int instance = 1) const { return {static_cast<FeatId>((1+clean_instance(instance)) * num_features())}; } struct instance_iter_helper { FeatId begin_, end_; iterator begin() const { return {begin_}; } iterator end() const { return {end_}; } }; instance_iter_helper iter_instance(int instance) const { return { begin(instance).index, end(instance).index }; } private: // https://en.wikipedia.org/wiki/Disjoint-set_data_structure FeatId uf_find(FeatId index) const { while (feat_ids_[index] != index) { feat_ids_[index] = feat_ids_[feat_ids_[index]]; index = feat_ids_[index]; } return index; } void uf_union(FeatId index1, FeatId index2) { index1 = uf_find(index1); index2 = uf_find(index2); if (index1 == index2) return; if (index1 > index2) std::swap(index1, index2); feat_ids_[index2] = index1; } int clean_instance(int instance) const { return std::min(1, std::max(0, instance)); } void init() { for (const std::string& name : names_) { index_map_.insert({name, feat_ids_.size()}); feat_ids_.push_back(feat_ids_.size()); } // add len(names) to feat_ids_ for second instance for (size_t i = 0; i < names_.size(); ++i) feat_ids_.push_back(feat_ids_.size()); } /** * Replace the feat_ids in the given AddTree. * * Assumed is that the AddTree uses indexes as feature_ids not yet * offset for instance0 or instance1. */ void transform(Tree::ConstRef n, Tree::MutRef m, int instance) const { if (n.is_internal()) { LtSplit s = n.get_split(); FeatId index = get_index(s.feat_id, instance); if (static_cast<size_t>(index) >= feat_ids_.size()) throw std::runtime_error("feature index out of bounds"); FeatId feat_id = get_feat_id(index); m.split({feat_id, s.split_value}); transform(n.right(), m.right(), instance); transform(n.left(), m.left(), instance); } else { m.set_leaf_value(n.leaf_value()); } } }; std::ostream& operator<<(std::ostream& s, const FeatMap& fm) { s << "FeatMap {" << std::endl; for (auto index : fm) s << " [" << index << "] `" << fm.get_name(index) << "` -> " << fm.get_feat_id(index) << " (instance " << fm.get_instance(index) << ')' << std::endl; s << '}'; return s; } } #endif // VERITAS_FEAT_MAP_HPP
32.035573
109
0.545959
[ "vector", "transform" ]
c61723ebf1b61784ae5d81ef8faa29d09ed86540
6,488
cc
C++
JXIO/src/c/src/Events.cc
chesvectain/i2am
82aee4f617d0cefe5f358d0a0f83b0b2b6a1ef9b
[ "Apache-2.0" ]
8
2018-05-30T11:08:04.000Z
2021-01-05T08:45:38.000Z
JXIO/src/c/src/Events.cc
chesvectain/i2am
82aee4f617d0cefe5f358d0a0f83b0b2b6a1ef9b
[ "Apache-2.0" ]
9
2020-05-15T20:34:55.000Z
2021-12-14T21:14:52.000Z
JXIO/src/c/src/Events.cc
chesvectain/i2am
82aee4f617d0cefe5f358d0a0f83b0b2b6a1ef9b
[ "Apache-2.0" ]
13
2016-11-07T06:20:07.000Z
2021-02-25T06:57:04.000Z
/* ** Copyright (C) 2013 Mellanox Technologies ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at: ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, ** either express or implied. See the License for the specific language ** governing permissions and limitations under the License. ** */ #include <string.h> #include <map> #include "bullseye.h" #include "Events.h" typedef enum { EVENT_SESSION_ERROR = 0, EVENT_MSG_ERROR_SERVER = 1, EVENT_MSG_ERROR_CLIENT = 2, EVENT_SESSION_ESTABLISHED = 3, EVENT_REQUEST_RECEIVED = 4, EVENT_REPLY_RECEIVED = 5, EVENT_SESSION_NEW = 6, EVENT_MSG_SEND_COMPLETE = 7, EVENT_FD_READY = 8, EVENT_LAST } event_type_t; Events::Events() { this->size = 0; } int Events::writeOnSessionErrorEvent(char *buf, void *ptrForJava, struct xio_session_event_data *event_data) { struct queued_event_t* event = (struct queued_event_t*)buf; event->type = htonl(EVENT_SESSION_ERROR); event->ptr = htobe64(intptr_t(ptrForJava)); event->event_specific.session_error.error_type = htonl(event_data->event); event->event_specific.session_error.error_reason = htonl(event_data->reason); this->size = sizeof(struct event_session_error) + sizeof((queued_event_t *)0)->type + sizeof((queued_event_t *)0)->ptr; return this->size; } int Events::writeOnSessionEstablishedEvent (char *buf, void *ptrForJava, struct xio_session *session, struct xio_new_session_rsp *rsp) { struct queued_event_t* event = (struct queued_event_t*)buf; event->type = htonl(EVENT_SESSION_ESTABLISHED); event->ptr = htobe64(intptr_t(ptrForJava)); this->size = sizeof((queued_event_t *)0)->type + sizeof((queued_event_t *)0)->ptr; return this->size; } int Events::writeOnNewSessionEvent(char *buf, void *ptrForJava, void *serverSession, struct xio_new_session_req *req) { struct queued_event_t* event = (struct queued_event_t*)buf; event->type = htonl(EVENT_SESSION_NEW); event->ptr = htobe64(intptr_t(ptrForJava)); event->event_specific.new_session.ptr_session = htobe64(intptr_t(serverSession)); event->event_specific.new_session.uri_len = htonl(req->uri_len); //copy data so far this->size = sizeof((queued_event_t *)0)->type + sizeof((queued_event_t *)0)->ptr + sizeof((struct event_new_session *)0)->ptr_session + sizeof((struct event_new_session *)0)->uri_len; //copy first string strcpy(buf + this->size, req->uri); size += req->uri_len; //calculate ip address int len; char * ip; struct sockaddr *ipStruct = (struct sockaddr *)&req->src_addr; BULLSEYE_EXCLUDE_BLOCK_START if (ipStruct->sa_family == AF_INET) { static char addr[INET_ADDRSTRLEN]; struct sockaddr_in *v4 = (struct sockaddr_in *) ipStruct; ip = (char *) inet_ntop(AF_INET, &(v4->sin_addr), addr, INET_ADDRSTRLEN); len = strlen(ip); } else if (ipStruct->sa_family == AF_INET6) { static char addr[INET6_ADDRSTRLEN]; struct sockaddr_in6 *v6 = (struct sockaddr_in6 *) ipStruct; ip = (char *) inet_ntop(AF_INET6, &(v6->sin6_addr), addr, INET6_ADDRSTRLEN); len = INET6_ADDRSTRLEN; } else { LOG_ERR("can not get src ip"); return 0; } BULLSEYE_EXCLUDE_BLOCK_END int32_t ip_len = htonl(len); memcpy(buf + this->size, &ip_len, sizeof(int32_t)); this->size += sizeof((struct event_new_session *) 0)->ip_len; strcpy(buf + this->size, ip); this->size += len; return this->size; } int Events::writeOnMsgErrorEventServer(char *buf, void *ptrForJavaMsg, void* ptrForJavaSession, enum xio_status error) { struct queued_event_t* event = (struct queued_event_t*) buf; event->type = htonl(EVENT_MSG_ERROR_SERVER); event->ptr = htobe64(intptr_t(ptrForJavaMsg)); event->event_specific.msg_error_server.error_reason = htonl(error); event->event_specific.msg_error_server.ptr_session = htobe64(intptr_t(ptrForJavaSession)); this->size = sizeof(struct event_msg_error_server) + sizeof((queued_event_t *) 0)->type + sizeof((queued_event_t *) 0)->ptr; return this->size; } int Events::writeOnMsgErrorEventClient(char *buf, void *ptrForJavaMsg, enum xio_status error) { struct queued_event_t* event = (struct queued_event_t*)buf; event->type = htonl(EVENT_MSG_ERROR_CLIENT); event->ptr = htobe64(intptr_t(ptrForJavaMsg)); event->event_specific.msg_error_client.error_reason = htonl(error); this->size = sizeof(struct event_msg_error_client) + sizeof((queued_event_t *)0)->type + sizeof((queued_event_t *)0)->ptr; return this->size; } int Events::writeOnRequestReceivedEvent(char *buf, void *ptrForJavaMsg, const int32_t msg_in_size, const int32_t msg_out_size, void *ptrForJavaSession) { struct queued_event_t* event = (struct queued_event_t*)buf; event->type = htonl(EVENT_REQUEST_RECEIVED); event->ptr = htobe64(intptr_t(ptrForJavaMsg)); event->event_specific.req_received.msg_in_size = htonl(msg_in_size); event->event_specific.req_received.msg_out_size = htonl(msg_out_size); event->event_specific.req_received.ptr_session = htobe64(intptr_t(ptrForJavaSession)); this->size = sizeof(struct event_req_received) + sizeof((queued_event_t *)0)->type + sizeof((queued_event_t *)0)->ptr; return this->size; } int Events::writeOnResponseReceivedEvent(char *buf, void *ptrForJavaMsg, const int32_t msg_in_size) { struct queued_event_t* event = (struct queued_event_t*)buf; event->type = htonl(EVENT_REPLY_RECEIVED); event->ptr = htobe64(intptr_t(ptrForJavaMsg)); event->event_specific.res_received.msg_size = htonl(msg_in_size); this->size = sizeof(struct event_res_received) + sizeof((queued_event_t *)0)->type + sizeof((queued_event_t *)0)->ptr; return this->size; } #if _BullseyeCoverage #pragma BullseyeCoverage off #endif int Events::writeOnFdReadyEvent(char *buf, int fd, int epoll_event) { struct queued_event_t* event = (struct queued_event_t*)buf; event->type = htonl(EVENT_FD_READY); event->ptr = 0; // The java object receiving this event will be the EQH which handles this event_queue event->event_specific.fd_ready.fd = htonl(fd); event->event_specific.fd_ready.epoll_event = htonl(epoll_event); this->size = sizeof(struct event_fd_ready) + sizeof((queued_event_t *)0)->type + sizeof((queued_event_t *)0)->ptr; return this->size; } #if _BullseyeCoverage #pragma BullseyeCoverage on #endif
36.044444
151
0.752004
[ "object" ]
c61982a7689dbdc66923f3e3459540f8880ace4d
8,012
cpp
C++
Waifu2xAvisynth/waifu2xAvisynth.cpp
sunnyone/Waifu2xAvisynth
c6de02e6a1a9f038111e1303cb2491b32ebd66aa
[ "BSD-3-Clause" ]
45
2015-05-30T00:42:34.000Z
2021-04-28T06:14:37.000Z
Waifu2xAvisynth/waifu2xAvisynth.cpp
sahwar/Waifu2xAvisynth
c6de02e6a1a9f038111e1303cb2491b32ebd66aa
[ "BSD-3-Clause" ]
3
2015-06-06T11:55:46.000Z
2020-03-26T09:16:25.000Z
Waifu2xAvisynth/waifu2xAvisynth.cpp
sahwar/Waifu2xAvisynth
c6de02e6a1a9f038111e1303cb2491b32ebd66aa
[ "BSD-3-Clause" ]
9
2015-05-30T15:21:49.000Z
2020-06-13T13:53:32.000Z
#include <future> #include <Windows.h> #include <avisynth.h> #include <sstream> #include <string> #include "picojson.h" #include "tclap/CmdLine.h" #include "modelHandler.hpp" EXTERN_C IMAGE_DOS_HEADER __ImageBase; void outputDebug(std::function<void(std::ostringstream&)> func) { std::ostringstream str; func(str); OutputDebugStringA(str.str().c_str()); } class Waifu2xVideoFilter : public GenericVideoFilter { public: Waifu2xVideoFilter(PClip child, int nr, int scale, int jobs, std::string& modelsDir, IScriptEnvironment* env); void Initialize(IScriptEnvironment* env); PVideoFrame __stdcall GetFrame(int n, IScriptEnvironment* env); private: std::string modelsDir; int jobs; int nrLevel; bool enableScaling; int iterTimesTwiceScaling; int scaleRatioAdjusted; std::vector<std::unique_ptr<w2xc::Model>> modelsNR; std::vector<std::unique_ptr<w2xc::Model>> modelsScale; }; Waifu2xVideoFilter::Waifu2xVideoFilter(PClip child, int nr, int scale, int jobs, std::string& modelsDir, IScriptEnvironment* env) : GenericVideoFilter(child) { this->modelsDir = modelsDir; this->jobs = jobs; if (nr == 1 || nr == 2) { this->nrLevel = nr; } else { this->nrLevel = 0; } if (scale > 1) { this->enableScaling = true; this->iterTimesTwiceScaling = static_cast<int>(std::ceil(std::log2(scale))); this->scaleRatioAdjusted = pow(2, this->iterTimesTwiceScaling); this->vi.height *= this->scaleRatioAdjusted; this->vi.width *= this->scaleRatioAdjusted; } else { this->enableScaling = false; this->scaleRatioAdjusted = 1; } } void Waifu2xVideoFilter::Initialize(IScriptEnvironment* env) { if (vi.pixel_type != VideoInfo::CS_Y8 && vi.pixel_type != VideoInfo::CS_YV12 && vi.pixel_type != VideoInfo::CS_YV16 && vi.pixel_type != VideoInfo::CS_YV24) { env->ThrowError("Currently only Y8, YV12, YV16 or YV24 are supported."); return; } if (nrLevel > 0) { OutputDebugStringA("Waifu2x Loading NR Models."); std::string modelFileName(modelsDir); modelFileName = modelFileName + "\\noise" + std::to_string(this->nrLevel) + "_model.json"; if (!w2xc::modelUtility::generateModelFromJSON(modelFileName, this->modelsNR)) { env->ThrowError("A noise model file is not found: %s", modelFileName.c_str()); return; } for (auto&& model : this->modelsNR) { model->setNumberOfJobs(jobs); } } if (enableScaling) { OutputDebugStringA("Waifu2x Loading Scale Models."); std::string modelFileName(modelsDir); modelFileName = modelFileName + "/scale2.0x_model.json"; if (!w2xc::modelUtility::generateModelFromJSON(modelFileName, this->modelsScale)) { env->ThrowError("A scale model file is not found: %s", modelFileName.c_str()); return; } for (auto&& model : this->modelsScale) { model->setNumberOfJobs(jobs); } } OutputDebugStringA("Waifu2x Finished Initializing."); } bool filterWithModels(std::vector<std::unique_ptr<w2xc::Model>>& models, cv::Mat& srcImgY, cv::Mat& dstImgY) { std::unique_ptr<std::vector<cv::Mat>> inputPlanes = std::unique_ptr<std::vector<cv::Mat>>( new std::vector<cv::Mat>()); std::unique_ptr<std::vector<cv::Mat>> outputPlanes = std::unique_ptr<std::vector<cv::Mat>>( new std::vector<cv::Mat>()); inputPlanes->clear(); inputPlanes->push_back(srcImgY); for (int index = 0; index < models.size(); index++) { outputDebug([&](std::ostringstream& s) { s << "Waifu2x Iteration #" << (index + 1) << "..." << std::endl; }); if (!models[index]->filter(*inputPlanes, *outputPlanes)) { return false; } if (index != models.size() - 1) { inputPlanes = std::move(outputPlanes); outputPlanes = std::unique_ptr<std::vector<cv::Mat>>( new std::vector<cv::Mat>()); } } outputPlanes->at(0).copyTo(dstImgY); return true; } PVideoFrame Waifu2xVideoFilter::GetFrame(int n, IScriptEnvironment* env) { int percent = (int)((n / (double)vi.num_frames) * 100); outputDebug([&](std::ostringstream& s) { s << "Waifu2x GetFrame Starting: " << n << "/" << vi.num_frames << "(" << percent << "%)"; }); PVideoFrame src = child->GetFrame(n, env); // Assume Y8, YV12, YV16 or YV24 (with chroma, planar) // Process Y at first. cv::Mat yImg(src->GetHeight(PLANAR_Y), src->GetRowSize(PLANAR_Y), CV_8U, (void *)src->GetReadPtr(PLANAR_Y), src->GetPitch(PLANAR_Y)); yImg.convertTo(yImg, CV_32F, 1.0 / 255.0); if (this->nrLevel > 0) { OutputDebugStringA("Waifu2x NR Start."); if (!filterWithModels(this->modelsNR, yImg, yImg)) { env->ThrowError("Waifu2x NR Failed."); return src; } OutputDebugStringA("Waifu2x NR Finished."); } if (this->enableScaling) { OutputDebugStringA("Waifu2x Scaling Start."); int curRowSize = src->GetRowSize(PLANAR_Y); int curHeight = src->GetHeight(PLANAR_Y); for (int i = 0; i < iterTimesTwiceScaling; i++) { curRowSize *= 2; curHeight *= 2; cv::resize(yImg, yImg, cv::Size(curRowSize, curHeight), 0, 0, cv::INTER_NEAREST); if (!filterWithModels(this->modelsScale, yImg, yImg)) { env->ThrowError("Waifu2x filtering failed."); return src; } } OutputDebugStringA("Waifu2x Scaling Finished."); } yImg.convertTo(yImg, CV_8U, 255.0); // If Y8, skip processing U, V if (vi.pixel_type == VideoInfo::CS_Y8) { auto dst = env->NewVideoFrame(vi); env->BitBlt(dst->GetWritePtr(PLANAR_Y), dst->GetPitch(PLANAR_Y), yImg.data, yImg.step, yImg.cols, yImg.rows); OutputDebugStringA("Waifu2x GetFrame Finished (Y only)."); return dst; } // Finally process U, V cv::Mat uImg(src->GetHeight(PLANAR_U), src->GetRowSize(PLANAR_U), CV_8U, (void *)src->GetReadPtr(PLANAR_U), src->GetPitch(PLANAR_U)); cv::Mat vImg(src->GetHeight(PLANAR_V), src->GetRowSize(PLANAR_V), CV_8U, (void *)src->GetReadPtr(PLANAR_V), src->GetPitch(PLANAR_V)); if (this->enableScaling) { // process U and V at first (just INTER_CUBIC resize). cv::resize(uImg, uImg, cv::Size(uImg.cols * this->scaleRatioAdjusted, uImg.rows * this->scaleRatioAdjusted), 0, 0, cv::INTER_CUBIC); cv::resize(vImg, vImg, cv::Size(vImg.cols * this->scaleRatioAdjusted, vImg.rows * this->scaleRatioAdjusted), 0, 0, cv::INTER_CUBIC); } auto dst = env->NewVideoFrame(vi); env->BitBlt(dst->GetWritePtr(PLANAR_Y), dst->GetPitch(PLANAR_Y), yImg.data, yImg.step, yImg.cols, yImg.rows); env->BitBlt(dst->GetWritePtr(PLANAR_U), dst->GetPitch(PLANAR_U), uImg.data, uImg.step, uImg.cols, uImg.rows); env->BitBlt(dst->GetWritePtr(PLANAR_V), dst->GetPitch(PLANAR_V), vImg.data, vImg.step, vImg.cols, vImg.rows); OutputDebugStringA("Waifu2x GetFrame Finished."); return dst; } AVSValue __cdecl Waifu2x(AVSValue args, void *, IScriptEnvironment* env) { enum { ARG_CLIP, ARG_NR, ARG_SCALE, ARG_JOBS, ARG_MODELS, }; PClip clip = args[ARG_CLIP].AsClip(); int nr = args[ARG_NR].Defined() ? args[ARG_NR].AsInt() : 1; int scale = args[ARG_SCALE].Defined() ? args[ARG_SCALE].AsInt() : 2; int jobs = args[ARG_JOBS].Defined() ? args[ARG_JOBS].AsInt() : 0; if (jobs <= 0) { SYSTEM_INFO systemInfo; GetSystemInfo(&systemInfo); jobs = systemInfo.dwNumberOfProcessors; } std::string modelsDir; if (args[ARG_MODELS].Defined()) { modelsDir.assign(args[ARG_MODELS].AsString()); } else { char dllPathChars[MAX_PATH] = { 0 }; GetModuleFileNameA((HINSTANCE)&__ImageBase, dllPathChars, _countof(dllPathChars)); // TODO: multibyte dll name may not work. std::string dllPath(dllPathChars); modelsDir.assign(dllPath.substr(0, dllPath.find_last_of('\\')) + "\\models"); if (modelsDir.size() > MAX_PATH) { // TODO: need testing env->ThrowError("The models directory path is too long."); } } auto filter = new Waifu2xVideoFilter(clip, nr, scale, jobs, modelsDir, env); filter->Initialize(env); return filter; } const AVS_Linkage *AVS_linkage = nullptr; extern "C" __declspec(dllexport) const char* __stdcall AvisynthPluginInit3(IScriptEnvironment* env, const AVS_Linkage* const vectors) { AVS_linkage = vectors; env->AddFunction("waifu2x", "c[nr]i[scale]i[jobs]i[models]s", Waifu2x, 0); return ""; }
30.007491
135
0.693585
[ "vector", "model" ]
c61ae3295f3e88dea9bff721955785e0aaebb07c
12,168
cpp
C++
code/engine/xrRenderPC_R4/r4_loader.cpp
InNoHurryToCode/xray-162
fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e
[ "Apache-2.0" ]
58
2016-11-20T19:14:35.000Z
2021-12-27T21:03:35.000Z
code/engine/xrRenderPC_R4/r4_loader.cpp
InNoHurryToCode/xray-162
fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e
[ "Apache-2.0" ]
59
2016-09-10T10:44:20.000Z
2018-09-03T19:07:30.000Z
code/engine/xrRenderPC_R4/r4_loader.cpp
InNoHurryToCode/xray-162
fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e
[ "Apache-2.0" ]
39
2017-02-05T13:35:37.000Z
2022-03-14T11:00:12.000Z
#include "stdafx.h" #include "r4.h" #include "xrRenderCommon/ResourceManager.h" #include "xrRenderCommon/fbasicvisual.h" #include "xrEngine/fmesh.h" #include "xrEngine/xrLevel.h" #include "xrEngine/x_ray.h" #include "xrEngine/IGame_Persistent.h" #include "xrCore/stream_reader.h" #include "xrRenderCommon/dxRenderDeviceRender.h" #include "../xrRenderDX10/dx10BufferUtils.h" #include "../xrRenderDX10/3DFluid/dx103DFluidVolume.h" #include "xrRenderCommon/FHierrarhyVisual.h" #pragma warning(push) #pragma warning(disable : 4995) #include <malloc.h> #pragma warning(pop) void CRender::level_Load(IReader* fs) { R_ASSERT(0 != g_pGameLevel); R_ASSERT(!b_loaded); // Begin pApp->LoadBegin(); dxRenderDeviceRender::Instance().Resources->DeferredLoad(TRUE); IReader* chunk; // Shaders // g_pGamePersistent->LoadTitle ("st_loading_shaders"); g_pGamePersistent->LoadTitle(); { chunk = fs->open_chunk(fsL_SHADERS); R_ASSERT2(chunk, "Level doesn't builded correctly."); u32 count = chunk->r_u32(); Shaders.resize(count); for (u32 i = 0; i < count; i++) // skip first shader as "reserved" one { string512 n_sh, n_tlist; LPCSTR n = LPCSTR(chunk->pointer()); chunk->skip_stringZ(); if (0 == n[0]) continue; xr_strcpy(n_sh, n); LPSTR delim = strchr(n_sh, '/'); *delim = 0; xr_strcpy(n_tlist, delim + 1); Shaders[i] = dxRenderDeviceRender::Instance().Resources->Create(n_sh, n_tlist); } chunk->close(); } // Components Wallmarks = xr_new<CWallmarksEngine>(); Details = xr_new<CDetailManager>(); // VB,IB,SWI // g_pGamePersistent->LoadTitle("st_loading_geometry"); g_pGamePersistent->LoadTitle(); { CStreamReader* geom = FS.rs_open("$level$", "level.geom"); R_ASSERT2(geom, "level.geom"); LoadBuffers(geom, FALSE); LoadSWIs(geom); FS.r_close(geom); } //...and alternate/fast geometry { CStreamReader* geom = FS.rs_open("$level$", "level.geomx"); R_ASSERT2(geom, "level.geomX"); LoadBuffers(geom, TRUE); FS.r_close(geom); } // Visuals // g_pGamePersistent->LoadTitle("st_loading_spatial_db"); g_pGamePersistent->LoadTitle(); chunk = fs->open_chunk(fsL_VISUALS); LoadVisuals(chunk); chunk->close(); // Details // g_pGamePersistent->LoadTitle("st_loading_details"); g_pGamePersistent->LoadTitle(); Details->Load(); // Sectors // g_pGamePersistent->LoadTitle("st_loading_sectors_portals"); g_pGamePersistent->LoadTitle(); LoadSectors(fs); // 3D Fluid Load3DFluid(); // HOM HOM.Load(); // Lights // pApp->LoadTitle ("Loading lights..."); LoadLights(fs); // End pApp->LoadEnd(); // sanity-clear lstLODs.clear(); lstLODgroups.clear(); mapLOD.clear(); // signal loaded b_loaded = TRUE; } void CRender::level_Unload() { if (0 == g_pGameLevel) return; if (!b_loaded) return; u32 I; // HOM HOM.Unload(); //*** Details Details->Unload(); //*** Sectors // 1. xr_delete(rmPortals); pLastSector = 0; vLastCameraPos.set(0, 0, 0); // 2. for (I = 0; I < Sectors.size(); I++) xr_delete(Sectors[I]); Sectors.clear(); // 3. for (I = 0; I < Portals.size(); I++) xr_delete(Portals[I]); Portals.clear(); //*** Lights // Glows.Unload (); Lights.Unload(); //*** Visuals for (I = 0; I < Visuals.size(); I++) { Visuals[I]->Release(); xr_delete(Visuals[I]); } Visuals.clear(); //*** SWI for (I = 0; I < SWIs.size(); I++) xr_free(SWIs[I].sw); SWIs.clear(); //*** VB/IB for (I = 0; I < nVB.size(); I++) _RELEASE(nVB[I]); for (I = 0; I < xVB.size(); I++) _RELEASE(xVB[I]); nVB.clear(); xVB.clear(); for (I = 0; I < nIB.size(); I++) _RELEASE(nIB[I]); for (I = 0; I < xIB.size(); I++) _RELEASE(xIB[I]); nIB.clear(); xIB.clear(); nDC.clear(); xDC.clear(); //*** Components xr_delete(Details); xr_delete(Wallmarks); //*** Shaders Shaders.clear(); b_loaded = FALSE; } void CRender::LoadBuffers(CStreamReader* base_fs, BOOL _alternative) { R_ASSERT2(base_fs, "Could not load geometry. File not found."); dxRenderDeviceRender::Instance().Resources->Evict(); // u32 dwUsage = D3DUSAGE_WRITEONLY; xr_vector<VertexDeclarator>& _DC = _alternative ? xDC : nDC; xr_vector<ID3DVertexBuffer*>& _VB = _alternative ? xVB : nVB; xr_vector<ID3DIndexBuffer*>& _IB = _alternative ? xIB : nIB; // Vertex buffers { // Use DX9-style declarators CStreamReader* fs = base_fs->open_chunk(fsL_VB); R_ASSERT2(fs, "Could not load geometry. File 'level.geom?' corrupted."); u32 count = fs->r_u32(); _DC.resize(count); _VB.resize(count); for (u32 i = 0; i < count; i++) { // decl // D3DVERTEXELEMENT9* dcl = (D3DVERTEXELEMENT9*) //fs().pointer(); u32 buffer_size = (MAXD3DDECLLENGTH + 1) * sizeof(D3DVERTEXELEMENT9); D3DVERTEXELEMENT9* dcl = (D3DVERTEXELEMENT9*)_alloca(buffer_size); fs->r(dcl, buffer_size); fs->advance(-(int)buffer_size); u32 dcl_len = D3DXGetDeclLength(dcl) + 1; _DC[i].resize(dcl_len); fs->r(_DC[i].begin(), dcl_len * sizeof(D3DVERTEXELEMENT9)); // count, size u32 vCount = fs->r_u32(); u32 vSize = D3DXGetDeclVertexSize(dcl, 0); Msg("* [Loading VB] %d verts, %d Kb", vCount, (vCount * vSize) / 1024); // Create and fill // BYTE* pData = 0; // R_CHK // (HW.pDevice->CreateVertexBuffer(vCount*vSize,dwUsage,0,D3DPOOL_MANAGED,&_VB[i],0)); // R_CHK (_VB[i]->Lock(0,0,(void**)&pData,0)); // CopyMemory (pData,fs().pointer(),vCount*vSize); // fs->r (pData,vCount*vSize); //_VB[i]->Unlock (); // TODO: DX10: Check fragmentation. // Check if buffer is less then 2048 kb BYTE* pData = xr_alloc<BYTE>(vCount * vSize); fs->r(pData, vCount * vSize); dx10BufferUtils::CreateVertexBuffer(&_VB[i], pData, vCount * vSize); xr_free(pData); // fs->advance (vCount*vSize); } fs->close(); } // Index buffers { CStreamReader* fs = base_fs->open_chunk(fsL_IB); u32 count = fs->r_u32(); _IB.resize(count); for (u32 i = 0; i < count; i++) { u32 iCount = fs->r_u32(); Msg("* [Loading IB] %d indices, %d Kb", iCount, (iCount * 2) / 1024); // Create and fill // BYTE* pData = 0; // R_CHK // (HW.pDevice->CreateIndexBuffer(iCount*2,dwUsage,D3DFMT_INDEX16,D3DPOOL_MANAGED,&_IB[i],0)); // R_CHK (_IB[i]->Lock(0,0,(void**)&pData,0)); // CopyMemory (pData,fs().pointer(),iCount*2); // fs->r (pData,iCount*2); //_IB[i]->Unlock (); // TODO: DX10: Check fragmentation. // Check if buffer is less then 2048 kb BYTE* pData = xr_alloc<BYTE>(iCount * 2); fs->r(pData, iCount * 2); dx10BufferUtils::CreateIndexBuffer(&_IB[i], pData, iCount * 2); xr_free(pData); // fs().advance (iCount*2); } fs->close(); } } void CRender::LoadVisuals(IReader* fs) { IReader* chunk = 0; u32 index = 0; dxRender_Visual* V = 0; ogf_header H; while ((chunk = fs->open_chunk(index)) != 0) { chunk->r_chunk_safe(OGF_HEADER, &H, sizeof(H)); V = Models->Instance_Create(H.type); V->Load(0, chunk, 0); Visuals.push_back(V); chunk->close(); index++; } } void CRender::LoadLights(IReader* fs) { // lights Lights.Load(fs); Lights.LoadHemi(); } struct b_portal { u16 sector_front; u16 sector_back; svector<Fvector, 6> vertices; }; void CRender::LoadSectors(IReader* fs) { // allocate memory for portals u32 size = fs->find_chunk(fsL_PORTALS); R_ASSERT(0 == size % sizeof(b_portal)); u32 count = size / sizeof(b_portal); Portals.resize(count); for (u32 c = 0; c < count; c++) Portals[c] = xr_new<CPortal>(); // load sectors IReader* S = fs->open_chunk(fsL_SECTORS); for (u32 i = 0;; i++) { IReader* P = S->open_chunk(i); if (0 == P) break; CSector* __S = xr_new<CSector>(); __S->load(*P); Sectors.push_back(__S); P->close(); } S->close(); // load portals if (count) { CDB::Collector CL; fs->find_chunk(fsL_PORTALS); for (u32 i = 0; i < count; i++) { b_portal P; fs->r(&P, sizeof(P)); CPortal* __P = (CPortal*)Portals[i]; __P->Setup(P.vertices.begin(), P.vertices.size(), (CSector*)getSector(P.sector_front), (CSector*)getSector(P.sector_back)); for (u32 j = 2; j < P.vertices.size(); j++) CL.add_face_packed_D(P.vertices[0], P.vertices[j - 1], P.vertices[j], u32(i)); } if (CL.getTS() < 2) { Fvector v1, v2, v3; v1.set(-20000.f, -20000.f, -20000.f); v2.set(-20001.f, -20001.f, -20001.f); v3.set(-20002.f, -20002.f, -20002.f); CL.add_face_packed_D(v1, v2, v3, 0); } // build portal model rmPortals = xr_new<CDB::MODEL>(); rmPortals->build(CL.getV(), int(CL.getVS()), CL.getT(), int(CL.getTS())); } else { rmPortals = 0; } // debug // for (int d=0; d<Sectors.size(); d++) // Sectors[d]->DebugDump (); pLastSector = 0; } void CRender::LoadSWIs(CStreamReader* base_fs) { // allocate memory for portals if (base_fs->find_chunk(fsL_SWIS)) { CStreamReader* fs = base_fs->open_chunk(fsL_SWIS); u32 item_count = fs->r_u32(); xr_vector<FSlideWindowItem>::iterator it = SWIs.begin(); xr_vector<FSlideWindowItem>::iterator it_e = SWIs.end(); for (; it != it_e; ++it) xr_free((*it).sw); SWIs.clear(); SWIs.resize(item_count); for (u32 c = 0; c < item_count; c++) { FSlideWindowItem& swi = SWIs[c]; swi.reserved[0] = fs->r_u32(); swi.reserved[1] = fs->r_u32(); swi.reserved[2] = fs->r_u32(); swi.reserved[3] = fs->r_u32(); swi.count = fs->r_u32(); VERIFY(NULL == swi.sw); swi.sw = xr_alloc<FSlideWindow>(swi.count); fs->r(swi.sw, sizeof(FSlideWindow) * swi.count); } fs->close(); } } void CRender::Load3DFluid() { // if (strstr(Core.Params,"-no_volumetric_fog")) if (!RImplementation.o.volumetricfog) return; string_path fn_game; if (FS.exist(fn_game, "$level$", "level.fog_vol")) { IReader* F = FS.r_open(fn_game); u16 version = F->r_u16(); if (version == 3) { u32 cnt = F->r_u32(); for (u32 i = 0; i < cnt; ++i) { dx103DFluidVolume* pVolume = xr_new<dx103DFluidVolume>(); pVolume->Load("", F, 0); // Attach to sector's static geometry CSector* pSector = (CSector*)detectSector(pVolume->getVisData().sphere.P); // 3DFluid volume must be in render sector VERIFY(pSector); dxRender_Visual* pRoot = pSector->root(); // Sector must have root VERIFY(pRoot); VERIFY(pRoot->getType() == MT_HIERRARHY); ((FHierrarhyVisual*)pRoot)->children.push_back(pVolume); } } FS.r_close(F); } }
28.765957
106
0.541667
[ "geometry", "render", "model", "3d" ]
c61e5aecb914387b9f6540e937bba6175a4efbc3
17,380
cpp
C++
include/Gui.cpp
sjokic/WallDestruction
2e1c000096df4aa027a91ff1732ce50a205b221a
[ "MIT" ]
1
2021-11-03T11:30:05.000Z
2021-11-03T11:30:05.000Z
include/Gui.cpp
sjokic/WallDestruction
2e1c000096df4aa027a91ff1732ce50a205b221a
[ "MIT" ]
null
null
null
include/Gui.cpp
sjokic/WallDestruction
2e1c000096df4aa027a91ff1732ce50a205b221a
[ "MIT" ]
null
null
null
#include "Gui.h" #include <igl/Hit.h> #include <igl/project.h> #include <igl/writeOFF.h> #include <iomanip> #include <sstream> void Gui::setSimulation(Simulation *sim) { p_simulator = new Simulator(sim); p_simulator->reset(); p_simulator->setSimulationSpeed(m_simSpeed); } void Gui::addParticlesToViewer() { int n = m_pParticleData->getNumParticles(); Eigen::MatrixXd particlePositionsMat(n, 3); uint initializedRows = 0; for (auto particlePosition : m_pParticleData->getPositions()) { for (uint i = 0; i < 3; i++) { particlePositionsMat(initializedRows, i) = particlePosition(i); } initializedRows++; } Eigen::MatrixXd particleColorsMat = Eigen::MatrixXd::Ones(n, 3); bool hasColor = OwnCustomAttribute<vector<Eigen::Vector3d>>::get(m_pParticleData)->hasAttribute("color"); if (hasColor) { auto c = OwnCustomAttribute<vector<Eigen::Vector3d>>::get(m_pParticleData)->getAttribute("color"); uint initializedRows = 0; for (auto particleColor : c) { for (uint i = 0; i < 3; i++) { particleColorsMat(initializedRows, i) = particleColor(i); } initializedRows++; } } m_viewer.data_list[0].add_points(particlePositionsMat, particleColorsMat); } void Gui::start() { // message: http://patorjk.com/software/taag/#p=display&v=0&f=Roman&t=PBS%2019 std::string usage( R"( ooooooooo. oooooooooo. .oooooo..o `888 `Y88. `888' `Y8b d8P' `Y8 888 .d88' 888 888 Y88bo. 888ooo88P' 888oooo888' `"Y8888o. 888 888 `88b `"Y88b 888 888 .88P oo .d8P o888o o888bood8P' 8""88888P' 252-0546-00L Physically-Based Simulation in Computer Graphics @ ETH Zurich Course Exercise Framework Shortcuts: [drag] Rotate scene | [space] Start/pause simulation I,i Toggle invert normals | A,a Single step L,l Toggle wireframe | R,r Reset simulation T,t Toggle filled faces | C,c Clear screen ; Toggle vertex labels | : Toggle face labels - Toggle fast forward | Z Snap to canonical view . Turn up lighting | , Turn down lighting O,o Toggle orthographic/perspective projection)"); std::cout << usage << std::endl; // setting up viewer m_viewer.data().show_lines = false; m_viewer.data().point_size = 2.0f; m_viewer.core.is_animating = true; m_viewer.core.camera_zoom = 0.1; m_viewer.core.object_scale = 1.0; // setting up menu igl::opengl::glfw::imgui::ImGuiMenu menu; m_viewer.plugins.push_back(&menu); menu.callback_draw_viewer_window = [&]() { drawMenuWindow(menu); }; showAxes(m_showAxes); p_simulator->setNumRecords(m_numRecords); p_simulator->setMaxSteps(m_maxSteps); // callbacks m_viewer.callback_key_pressed = [&](igl::opengl::glfw::Viewer &viewer, unsigned int key, int modifiers) { return keyCallback(viewer, key, modifiers); }; m_viewer.callback_pre_draw = [&](igl::opengl::glfw::Viewer &viewer) { return drawCallback(viewer); }; m_viewer.callback_mouse_scroll = [&](igl::opengl::glfw::Viewer &viewer, float delta_y) { return scrollCallback(viewer, delta_y); }; m_viewer.callback_mouse_down = [&](igl::opengl::glfw::Viewer &viewer, int button, int modifier) { return mouseCallback(viewer, menu, button, modifier); }; // start viewer m_viewer.launch(); } void Gui::resetSimulation() { p_simulator->reset(); m_timerAverage = 0.0; } #pragma region ArrowInterface int Gui::addArrow(const Eigen::Vector3d &start, const Eigen::Vector3d &end, const Eigen::Vector3d &color) { m_arrows.push_back(Arrow(start, end, color)); m_arrows.back().id = m_numArrows++; return m_arrows.back().id; } void Gui::removeArrow(size_t index) { bool found = false; for (size_t i = 0; i < m_arrows.size(); i++) { if (m_arrows[i].id == index) { found = true; m_arrows.erase(m_arrows.begin() + i); } } assert(found && "unable to find index"); } void Gui::drawArrow(const Arrow &arrow) { m_viewer.data_list[0].add_edges(arrow.start, arrow.end, arrow.color); m_viewer.data_list[0].add_edges(arrow.end, arrow.head[0], arrow.color); m_viewer.data_list[0].add_edges(arrow.end, arrow.head[1], arrow.color); m_viewer.data_list[0].add_edges(arrow.end, arrow.head[2], arrow.color); m_viewer.data_list[0].add_edges(arrow.end, arrow.head[3], arrow.color); m_viewer.data_list[0].add_edges(arrow.head[0], arrow.head[2], arrow.color); m_viewer.data_list[0].add_edges(arrow.head[1], arrow.head[2], arrow.color); m_viewer.data_list[0].add_edges(arrow.head[1], arrow.head[3], arrow.color); m_viewer.data_list[0].add_edges(arrow.head[3], arrow.head[0], arrow.color); m_viewer.data_list[0].add_edges(arrow.head[3], arrow.head[2], arrow.color); m_viewer.data_list[0].add_edges(arrow.head[1], arrow.head[0], arrow.color); } #pragma endregion ArrowInterface void Gui::drawReferencePlane() { m_viewer.data_list[0].add_edges(m_referencePlane.start, m_referencePlane.end, m_referencePlane.color); } void Gui::showVertexArrow() { if (m_clickedArrow >= 0) { removeArrow(m_clickedArrow); m_clickedArrow = -1; } if (m_clickedVertex >= 0) { Eigen::Vector3d pos; Eigen::Vector3d norm; if (callback_clicked_vertex) { callback_clicked_vertex(m_clickedVertex, m_clickedObject, pos, norm); } else { pos = m_viewer.data_list[m_clickedObject].V.row(m_clickedVertex); norm = m_viewer.data_list[m_clickedObject].V_normals.row( m_clickedVertex); } m_clickedArrow = addArrow(pos, pos + norm, Eigen::RowVector3d(1.0, 0, 0)); } } bool Gui::drawCallback(igl::opengl::glfw::Viewer &viewer) { if (m_request_clear) { for (auto &d : viewer.data_list) { d.clear(); } m_request_clear = false; m_clickedVertex = -1; if (m_clickedArrow >= 0) { removeArrow(m_clickedArrow); m_clickedArrow = -1; } } viewer.data_list[0].clear(); if (m_arrows.size() > 0 || m_showReferencePlane) { for (size_t i = 0; i < m_arrows.size(); i++) { drawArrow(m_arrows[i]); } if (m_showReferencePlane) drawReferencePlane(); } p_simulator->render(viewer); //if(m_pParticleData) // addParticlesToViewer(); return false; } bool Gui::scrollCallback(igl::opengl::glfw::Viewer &viewer, float delta_y) { double factor = 1.5; if (delta_y > 0) viewer.core.camera_zoom *= factor; else viewer.core.camera_zoom /= factor; return true; } void Gui::toggleSimulation() { if (p_simulator->isPaused()) { if (!p_simulator->hasStarted()) { updateSimulationParameters(); } p_simulator->run(); } else { p_simulator->pause(); } } void Gui::singleStep() { if (!p_simulator->hasStarted()) { updateSimulationParameters(); } p_simulator->run(true); } void Gui::clearScreen() { m_request_clear = true; clearSimulation(); } bool Gui::keyCallback(igl::opengl::glfw::Viewer &viewer, unsigned int key, int modifiers) { switch (key) { case 'I': case 'i': for (auto &d : viewer.data_list) { d.dirty |= igl::opengl::MeshGL::DIRTY_NORMAL; d.invert_normals = !d.invert_normals; } return true; case 'L': case 'l': for (auto &d : viewer.data_list) { d.show_lines = !d.show_lines; } return true; case 'T': case 't': for (auto &d : viewer.data_list) { d.show_faces = !d.show_faces; } return true; case ';': for (auto &d : viewer.data_list) { d.show_vertid = !d.show_vertid; } return true; case ':': for (auto &d : viewer.data_list) { d.show_faceid = !d.show_faceid; } return true; case ' ': toggleSimulation(); return true; case 'r': case 'R': resetSimulation(); return true; case 'a': case 'A': singleStep(); case 'c': case 'C': clearScreen(); return true; case '-': setFastForward(!m_fastForward); return true; case '.': viewer.core.lighting_factor += 0.1; break; case ',': viewer.core.lighting_factor -= 0.1; break; default: return childKeyCallback(viewer, key, modifiers); } viewer.core.lighting_factor = std::min(std::max(viewer.core.lighting_factor, 0.f), 1.f); return false; } bool Gui::mouseCallback(igl::opengl::glfw::Viewer &viewer, igl::opengl::glfw::imgui::ImGuiMenu &menu, int button, int modifier) { // get vertices, project them onto screen and find closest vertex to mouse float minDist = std::numeric_limits<float>::infinity(); int vertex = -1; int object = -1; for (size_t i = 0; i < viewer.data_list.size(); i++) { Eigen::MatrixXf Vf = viewer.data_list[i].V.cast<float>(); Eigen::MatrixXf projections; igl::project(Vf, viewer.core.view, viewer.core.proj, viewer.core.viewport, projections); Eigen::VectorXf x = projections.col(0).array() - viewer.current_mouse_x; Eigen::VectorXf y = -projections.col(1).array() + viewer.core.viewport(3) - viewer.current_mouse_y; Eigen::VectorXf distances = (x.array().square() + y.array().square()).matrix().cwiseSqrt(); int vi = -1; float dist = distances.minCoeff(&vi); if (dist < minDist) { minDist = dist; vertex = vi; object = i; } } if (minDist < 20) { // only select vertex if user clicked "close" m_clickedVertex = vertex; m_clickedObject = object; showVertexArrow(); } return false; } void Gui::drawMenuWindow(igl::opengl::glfw::imgui::ImGuiMenu &menu) { glfwSetWindowTitle(m_viewer.window, "PBS Exercises"); float menu_width = 220.f * menu.menu_scaling(); // Controls ImGui::SetNextWindowPos(ImVec2(0.0f, 0.0f), ImGuiSetCond_FirstUseEver); ImGui::SetNextWindowSize(ImVec2(0.0f, 0.0f), ImGuiSetCond_FirstUseEver); ImGui::SetNextWindowSizeConstraints(ImVec2(menu_width, -1.0f), ImVec2(menu_width, -1.0f)); bool _viewer_menu_visible = true; ImGui::Begin( "Viewer", &_viewer_menu_visible, ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize); ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f); drawMenu(m_viewer, menu); ImGui::PopItemWidth(); ImGui::End(); // Clicking if (m_clickedVertex >= 0) { ImGui::SetNextWindowPos(ImVec2(0, 0), ImGuiSetCond_FirstUseEver); ImGui::SetNextWindowSize(ImGui::GetIO().DisplaySize, ImGuiSetCond_FirstUseEver); bool visible = true; ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0, 0, 0, 0)); ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0); ImGui::Begin( "ViewerLabels", &visible, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoInputs); Eigen::Vector3d pos = m_viewer.data_list[m_clickedObject].V.row(m_clickedVertex); Eigen::Vector3d norm = m_viewer.data_list[m_clickedObject].V_normals.row(m_clickedVertex); std::string text = "(" + std::to_string(pos(0)) + ", " + std::to_string(pos(1)) + ", " + std::to_string(pos(2)) + ")"; ImDrawList *drawList = ImGui::GetWindowDrawList(); Eigen::Vector3f c0 = igl::project( Eigen::Vector3f((pos + 0.1 * norm).cast<float>()), m_viewer.core.view, m_viewer.core.proj, m_viewer.core.viewport); drawList->AddText(ImGui::GetFont(), ImGui::GetFontSize() * 1.2, ImVec2(c0(0), m_viewer.core.viewport[3] - c0(1)), ImGui::GetColorU32(ImVec4(0, 0, 10, 255)), &text[0], &text[0] + text.size()); ImGui::End(); ImGui::PopStyleColor(); ImGui::PopStyleVar(); showVertexArrow(); } // Stats if (m_showStats) { int width, height; glfwGetWindowSize(m_viewer.window, &width, &height); ImGui::SetNextWindowPos(ImVec2(width - menu_width, 0.0f), ImGuiSetCond_FirstUseEver); ImGui::SetNextWindowSize(ImVec2(0.0f, 0.0f), ImGuiSetCond_FirstUseEver); ImGui::SetNextWindowSizeConstraints(ImVec2(menu_width, -1.0f), ImVec2(menu_width, -1.0f)); ImGui::Begin("Stats", &_viewer_menu_visible, ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize); ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f); if (!p_simulator->isPaused()) { if (m_timerAverage > 0.0) { double alpha = 0.95; m_timerAverage = m_timerAverage * alpha + (1.0 - alpha) * p_simulator->getDuration(); } else { m_timerAverage = p_simulator->getDuration(); } } ImGui::Text("Iteration: %ld", p_simulator->getSimulationStep()); ImGui::Text("Average time per iteration: %.2fms", m_timerAverage); ImGui::Text("Current time: %.5f", p_simulator->getSimulationTime()); drawSimulationStats(); ImGui::PopItemWidth(); ImGui::End(); } } inline std::string getFilename(int total_numObj, int obj, int total_steps, int step) { std::stringstream ss; ss << "_object" << std::setw(std::log10(total_numObj)) << std::setfill('0') << obj << "_" << std::setw(std::log10(total_steps)) << step << ".obj"; return ss.str(); } void Gui::exportRecording() { std::string path = igl::file_dialog_save(); size_t finddot = path.find_last_of("."); path = path.substr(0, finddot); std::cout << "Exporting Recording to " << path << "_objectxxx_xxx.obj" << std::endl; auto rec = p_simulator->getRecords(); int steps = rec[0].size(); for (size_t i = 0; i < rec.size(); i++) { int j = 0; while (rec[i].size() > 0) { std::string filename = path + getFilename(rec.size(), i, steps, j++); auto p = rec[i].front(); rec[i].pop(); if (j % 2 == 0) { continue; } bool succ = igl::writeOBJ(filename, p.first, p.second); if (!succ) { std::cerr << "Failed to write recording" << std::endl; } } } } bool Gui::drawMenu(igl::opengl::glfw::Viewer &viewer, igl::opengl::glfw::imgui::ImGuiMenu &menu) { if (ImGui::CollapsingHeader("Simulation Control", ImGuiTreeNodeFlags_DefaultOpen)) { if (ImGui::Button( p_simulator->isPaused() ? "Run Simulation" : "Pause Simulation", ImVec2(-1, 0))) { toggleSimulation(); } if (ImGui::Button("Single Step", ImVec2(-1, 0))) { singleStep(); } if (ImGui::Button("Reset Simulation", ImVec2(-1, 0))) { resetSimulation(); } if (ImGui::Button("Clear Screen", ImVec2(-1, 0))) { clearScreen(); } if (ImGui::SliderInt("Steps/Second", &m_simSpeed, 1, m_maxSimSpeed)) { p_simulator->setSimulationSpeed(m_simSpeed); } if (ImGui::InputInt("Max Steps", &m_maxSteps, -1, -1)) { p_simulator->setMaxSteps(m_maxSteps); } } if (ImGui::CollapsingHeader("Overlays", ImGuiTreeNodeFlags_DefaultOpen)) { if (ImGui::Checkbox("Wireframe", &(viewer.data().show_lines))) { for (size_t i = 0; i < viewer.data_list.size(); i++) { viewer.data_list[i].show_lines = viewer.data().show_lines; } } if (ImGui::Checkbox("Fill", &(viewer.data().show_faces))) { for (size_t i = 0; i < viewer.data_list.size(); i++) { viewer.data_list[i].show_faces = viewer.data().show_faces; } } if (ImGui::Checkbox("Show vertex labels", &(viewer.data().show_vertid))) { for (size_t i = 0; i < viewer.data_list.size(); i++) { viewer.data_list[i].show_vertid = viewer.data().show_vertid; } } if (ImGui::Checkbox("Show faces labels", &(viewer.data().show_faceid))) { for (size_t i = 0; i < viewer.data_list.size(); i++) { viewer.data_list[i].show_faceid = viewer.data().show_faceid; } } ImGui::Checkbox("Show stats", &m_showStats); if (ImGui::Checkbox("Show axes", &m_showAxes)) { showAxes(m_showAxes); } if (ImGui::Checkbox("Show reference plane", &m_showReferencePlane)); } if (ImGui::CollapsingHeader("Simulation Parameters", ImGuiTreeNodeFlags_DefaultOpen)) { drawSimulationParameterMenu(); } if (ImGui::CollapsingHeader("Recording")) { bool hasRecords = p_simulator->getRecords().size() > 0 && p_simulator->getRecords()[0].size() > 0; if (!hasRecords) { ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0, 0, 0, 0)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0, 0, 0, 0)); } if (ImGui::Button("Export Recording", ImVec2(-1, 0))) { if (hasRecords) { exportRecording(); } } if (!hasRecords) { ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); } if (ImGui::InputInt("Steps in Recording to keep", &m_numRecords, 0, 0)) { p_simulator->setNumRecords(m_numRecords); } bool isRecording = p_simulator->isRecording(); ImGui::PushStyleColor(ImGuiCol_Button, isRecording ? ImVec4(0.98f, 0.26f, 0.26f, 0.40f) : ImVec4(0.26f, 0.98f, 0.40f, 0.40f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, isRecording ? ImVec4(0.98f, 0.26f, 0.26f, 1.0f) : ImVec4(0.26f, 0.98f, 0.40f, 1.0f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, isRecording ? ImVec4(0.98f, 0.26f, 0.00f, 0.9f) : ImVec4(0.00f, 0.98f, 0.40f, 0.9f)); if (ImGui::Button(isRecording ? "Stop Recording" : "Start Recording", ImVec2(-1, 0))) { p_simulator->setRecording(!isRecording); } ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); } return false; } void Gui::showAxes(bool show_axes) { if (show_axes && m_axesID < 0) { Eigen::RowVector3d origin = Eigen::Vector3d::Zero(); m_axesID = addArrow(origin, Eigen::Vector3d(1, 0, 0), Eigen::Vector3d(1, 0, 0)); addArrow(origin, Eigen::Vector3d(0, 1, 0), Eigen::Vector3d(0, 1, 0)); addArrow(origin, Eigen::Vector3d(0, 0, 1), Eigen::Vector3d(0, 0, 1)); } if (!show_axes && m_axesID >= 0) { removeArrow(m_axesID); removeArrow(m_axesID + 1); removeArrow(m_axesID + 2); m_axesID = -1; } }
30.173611
107
0.672209
[ "render", "object", "vector" ]
c61f1130d5fd2234ad1cf5f07206bdef7281dfdf
4,932
cpp
C++
extra_visitors/yaml_cpp/src/reader.cpp
sevenbill/ariles
700236c9bfdba5a87dac2bc2e4735e1457c1c29f
[ "Apache-2.0" ]
null
null
null
extra_visitors/yaml_cpp/src/reader.cpp
sevenbill/ariles
700236c9bfdba5a87dac2bc2e4735e1457c1c29f
[ "Apache-2.0" ]
null
null
null
extra_visitors/yaml_cpp/src/reader.cpp
sevenbill/ariles
700236c9bfdba5a87dac2bc2e4735e1457c1c29f
[ "Apache-2.0" ]
null
null
null
/** @file @author Alexander Sherikov @copyright 2018-2020 Alexander Sherikov, Licensed under the Apache License, Version 2.0. (see @ref LICENSE or http://www.apache.org/licenses/LICENSE-2.0) @brief */ #include <ariles/visitors/yaml_cpp.h> #include <yaml-cpp/yaml.h> namespace ariles { namespace ns_yaml_cpp { typedef ariles::Node<YAML::Node> NodeWrapper; } } // namespace ariles namespace ariles { namespace ns_yaml_cpp { namespace impl { class ARILES_VISIBILITY_ATTRIBUTE Reader { public: /// Stack of nodes. std::vector<NodeWrapper> node_stack_; public: const YAML::Node getRawNode(const std::size_t depth) { if (node_stack_[depth].isArray()) { return (getRawNode(depth - 1)[node_stack_[depth].index_]); } else { return (node_stack_[depth].node_); } } const YAML::Node getRawNode() { return (getRawNode(node_stack_.size() - 1)); } }; } // namespace impl } // namespace ns_yaml_cpp } // namespace ariles namespace ariles { namespace ns_yaml_cpp { Reader::Reader(const std::string &file_name) { impl_ = ImplPtr(new Impl()); impl_->node_stack_.push_back(NodeWrapper(YAML::LoadFile(file_name))); } Reader::Reader(std::istream &input_stream) { impl_ = ImplPtr(new Impl()); impl_->node_stack_.push_back(NodeWrapper(YAML::Load(input_stream))); } std::size_t Reader::getMapSize(const bool /*expect_empty*/) { ARILES_TRACE_FUNCTION; return (impl_->getRawNode().size()); } bool Reader::descend(const std::string &child_name) { ARILES_TRACE_FUNCTION; YAML::Node child = impl_->getRawNode()[child_name]; if (false == child.IsDefined() or true == child.IsNull()) { return (false); } else { impl_->node_stack_.push_back(NodeWrapper(child)); return (true); } } void Reader::ascend() { ARILES_TRACE_FUNCTION; impl_->node_stack_.pop_back(); } bool Reader::getMapEntryNames(std::vector<std::string> &child_names) { ARILES_TRACE_FUNCTION; YAML::Node selected_node = impl_->getRawNode(); if (false == selected_node.IsMap()) { return (false); } else { child_names.resize(selected_node.size()); std::size_t i = 0; for (YAML::const_iterator it = selected_node.begin(); it != selected_node.end(); ++it, ++i) { child_names[i] = it->first.as<std::string>(); } return (true); } } std::size_t Reader::startArray() { ARILES_TRACE_FUNCTION; ARILES_ASSERT(true == impl_->getRawNode().IsSequence(), "Entry is not an array."); std::size_t size = impl_->getRawNode().size(); impl_->node_stack_.push_back(NodeWrapper(0, size)); return (size); } void Reader::shiftArray() { ARILES_TRACE_FUNCTION; ARILES_ASSERT(true == impl_->node_stack_.back().isArray(), "Internal error: expected array."); ARILES_ASSERT( impl_->node_stack_.back().index_ < impl_->node_stack_.back().size_, "Internal error: array has more elements than expected."); ++impl_->node_stack_.back().index_; } void Reader::endArray() { ARILES_TRACE_FUNCTION; impl_->node_stack_.pop_back(); } #define ARILES_BASIC_TYPE(type) \ void Reader::readElement(type &element) \ { \ ARILES_TRACE_FUNCTION; \ element = impl_->getRawNode().as<type>(); \ } ARILES_MACRO_SUBSTITUTE(ARILES_BASIC_TYPES_LIST) #undef ARILES_BASIC_TYPE } // namespace ns_yaml_cpp } // namespace ariles
27.864407
120
0.46472
[ "vector" ]
c61f7d37201b3c1f1b9be1548c8b21a5891387a7
5,403
cpp
C++
MPLECS/Systems/Time.cpp
Agaanii/Dictator
6221e997fbd86ed47c6a52860879d47746bf6530
[ "MIT" ]
3
2017-07-10T20:31:16.000Z
2018-07-23T21:00:23.000Z
MPLECS/Systems/Time.cpp
Agaanii/Dictator
6221e997fbd86ed47c6a52860879d47746bf6530
[ "MIT" ]
null
null
null
MPLECS/Systems/Time.cpp
Agaanii/Dictator
6221e997fbd86ed47c6a52860879d47746bf6530
[ "MIT" ]
null
null
null
//----------------------------------------------------------------------------- // All code is property of Dictator Developers Inc // Contact at Loesby.dev@gmail.com for permission to use // Or to discuss ideas // (c) 2018 // Systems/Time.cpp // The boilerplate system code, to ease new system creation #include "../Core/typedef.h" #include "Time.h" #include "../Components/UIComponents.h" void Time::ProgramInit() {} extern sf::Font s_font; void Time::SetupGameplay() { auto index = m_managerRef.createHandle(); m_managerRef.addComponent<ECS_Core::Components::C_TimeTracker>(index); auto& uiFrameComponent = m_managerRef.addComponent<ECS_Core::Components::C_UIFrame>(index); uiFrameComponent.m_frame = DefineUIFrame( "Calendar", DataBinding(ECS_Core::Components::C_TimeTracker, m_year), DataBinding(ECS_Core::Components::C_TimeTracker, m_month), DataBinding(ECS_Core::Components::C_TimeTracker, m_day)); uiFrameComponent.m_dataStrings[{0}] = { { 0,0 }, std::make_shared<sf::Text>() }; uiFrameComponent.m_dataStrings[{1}] = { { 0,35 }, std::make_shared<sf::Text>() }; uiFrameComponent.m_dataStrings[{2}] = { { 50,35 }, std::make_shared<sf::Text>() }; uiFrameComponent.m_topLeftCorner = { 1400, 100 }; uiFrameComponent.m_size = { 100, 70 }; uiFrameComponent.m_global = true; auto& drawable = m_managerRef.addComponent<ECS_Core::Components::C_SFMLDrawable>(index); auto timeBackground = std::make_shared<sf::RectangleShape>(sf::Vector2f(100, 70)); timeBackground->setFillColor({}); drawable.m_drawables[ECS_Core::Components::DrawLayer::MENU][0].push_back({ timeBackground,{} }); for (auto&& [key, dataStr] : uiFrameComponent.m_dataStrings) { dataStr.m_text->setFillColor({ 255,255,255 }); dataStr.m_text->setOutlineColor({ 128,128,128 }); dataStr.m_text->setFont(s_font); drawable.m_drawables[ECS_Core::Components::DrawLayer::MENU][255].push_back({ dataStr.m_text, dataStr.m_relativePosition }); } } void Time::Operate(GameLoopPhase phase, const timeuS& frameDuration) { switch (phase) { case GameLoopPhase::PREPARATION: m_managerRef.forEntitiesMatching<ECS_Core::Signatures::S_TimeTracker>([frameDuration]( ecs::EntityIndex mI, ECS_Core::Components::C_TimeTracker& time) { if (time.m_paused) { time.m_frameDuration = 0; } else { time.m_frameDuration = min(1., 0.000001 * frameDuration * time.m_gameSpeed); time.m_dayProgress += time.m_frameDuration; } if (time.m_dayProgress >= 1) { time.m_dayProgress -= 1; if (++time.m_day > 30) { time.m_day -= 30; if (++time.m_month > 12) { time.m_month -= 12; ++time.m_year; } } } return ecs::IterationBehavior::CONTINUE; }); break; case GameLoopPhase::ACTION: // Adjust timescale, pause/unpause { m_managerRef.forEntitiesMatching<ECS_Core::Signatures::S_Planner>([&manager = m_managerRef]( const ecs::EntityIndex&, ECS_Core::Components::C_ActionPlan& plan) { for (auto&& action : plan.m_plan) { if (std::holds_alternative<Action::LocalPlayer::TimeManipulation>(action.m_command)) { auto& timeManip = std::get<Action::LocalPlayer::TimeManipulation>(action.m_command); if (timeManip.m_gameSpeedAction) { switch (*timeManip.m_gameSpeedAction) { case Action::LocalPlayer::GameSpeedAction::SPEED_UP: manager.forEntitiesMatching<ECS_Core::Signatures::S_TimeTracker>([]( ecs::EntityIndex mI, ECS_Core::Components::C_TimeTracker& time) { time.m_gameSpeed = min<int>(1000, ++time.m_gameSpeed); return ecs::IterationBehavior::CONTINUE; }); break; case Action::LocalPlayer::GameSpeedAction::SLOW_DOWN: manager.forEntitiesMatching<ECS_Core::Signatures::S_TimeTracker>([]( ecs::EntityIndex mI, ECS_Core::Components::C_TimeTracker& time) { time.m_gameSpeed = max<int>(1, --time.m_gameSpeed); return ecs::IterationBehavior::CONTINUE; }); break; } } if (timeManip.m_pauseAction) { switch (*timeManip.m_pauseAction) { case Action::LocalPlayer::PauseAction::PAUSE: manager.forEntitiesMatching<ECS_Core::Signatures::S_TimeTracker>([]( ecs::EntityIndex mI, ECS_Core::Components::C_TimeTracker& time) { time.m_paused = true; return ecs::IterationBehavior::CONTINUE; }); break; case Action::LocalPlayer::PauseAction::UNPAUSE: manager.forEntitiesMatching<ECS_Core::Signatures::S_TimeTracker>([]( ecs::EntityIndex mI, ECS_Core::Components::C_TimeTracker& time) { time.m_paused = false; return ecs::IterationBehavior::CONTINUE; }); break; case Action::LocalPlayer::PauseAction::TOGGLE_PAUSE: manager.forEntitiesMatching<ECS_Core::Signatures::S_TimeTracker>([]( ecs::EntityIndex mI, ECS_Core::Components::C_TimeTracker& time) { time.m_paused = !time.m_paused; return ecs::IterationBehavior::CONTINUE; }); break; } } } } return ecs::IterationBehavior::CONTINUE; }); } break; case GameLoopPhase::INPUT: case GameLoopPhase::ACTION_RESPONSE: case GameLoopPhase::RENDER: case GameLoopPhase::CLEANUP: return; } } bool Time::ShouldExit() { return false; } DEFINE_SYSTEM_INSTANTIATION(Time);
31.231214
125
0.666667
[ "render" ]
c62056b005cd788c383be226c9eb02e6b63998ab
12,797
cpp
C++
3D Engine/AK/IntegrationDemo/DemoPages/DemoFootstepsManyVariables.cpp
botttos/PalmGine
5335b00e8100a14c86280a9d6fdbef9728480bf0
[ "Apache-2.0" ]
null
null
null
3D Engine/AK/IntegrationDemo/DemoPages/DemoFootstepsManyVariables.cpp
botttos/PalmGine
5335b00e8100a14c86280a9d6fdbef9728480bf0
[ "Apache-2.0" ]
null
null
null
3D Engine/AK/IntegrationDemo/DemoPages/DemoFootstepsManyVariables.cpp
botttos/PalmGine
5335b00e8100a14c86280a9d6fdbef9728480bf0
[ "Apache-2.0" ]
3
2019-10-26T12:51:27.000Z
2021-01-10T22:01:38.000Z
/******************************************************************************* The content of this file includes portions of the AUDIOKINETIC Wwise Technology released in source code form as part of the SDK installer package. Commercial License Usage Licensees holding valid commercial licenses to the AUDIOKINETIC Wwise Technology may use this file in accordance with the end user license agreement provided with the software or, alternatively, in accordance with the terms contained in a written agreement between you and Audiokinetic Inc. Version: v2017.2.6 Build: 6636 Copyright (c) 2006-2018 Audiokinetic Inc. *******************************************************************************/ // DemoFootstepsManyVariables.cpp /// \file /// Defines all methods declared in DemoFootstepsManyVariables.h #include "stdafx.h" #include <math.h> #include "Menu.h" #include "MovableChip.h" #include "Helpers.h" #include "DemoFootstepsManyVariables.h" #include "IntegrationDemo.h" #include <AK/SoundEngine/Common/AkSoundEngine.h> // Sound engine #include <string> //If you get a compiling error here, it means the file wasn't generated with the banks. Did you generate the soundbanks before compiling? #include "../WwiseProject/GeneratedSoundBanks/Wwise_IDs.h" //Our game object ID. Completely arbitrary. #define GAME_OBJECT_HUMAN 10 struct SurfaceInfo { SurfaceInfo( const char* in_szName ) : strBankFile( BuildBankFileName( in_szName ) ) , idSwitch( AK::SoundEngine::GetIDFromString( in_szName ) ) { } const std::string strBankFile; const AkUniqueID idSwitch; private: SurfaceInfo & operator=( const SurfaceInfo & in_other ); static std::string BuildBankFileName( const char* in_szName ) { std::string strBankFile( in_szName ); strBankFile.append( ".bnk" ); return strBankFile; } }; static const SurfaceInfo k_surfaces[] = { SurfaceInfo( "Dirt" ), SurfaceInfo( "Wood" ), SurfaceInfo( "Metal" ), SurfaceInfo( "Gravel" ), }; #define DEMOFOOTSTEPS_SURFACE_COUNT IntegrationDemoHelpers::AK_ARRAYSIZE( k_surfaces ) ///////////////////////////////////////////////////////////////////// // DemoFootstepsManyVariables Public Methods ///////////////////////////////////////////////////////////////////// DemoFootstepsManyVariables::DemoFootstepsManyVariables( Menu& in_ParentMenu ): Page( in_ParentMenu, "Footsteps with multiple variables") { m_weight = 25; m_LastX = 0; m_LastY = 0; m_maskCurrentBanks = 0; m_iSurface = -1; m_iLastFootstepTick = m_pParentMenu->GetTickCount(); m_szHelp = "This demo shows various ways to deal with footsteps in " "Wwise. It also shows environmental effects usage.\n\n" "The screen is divided in 4 surfaces, which correspond " "to the Surface switch. In the middle of the screen, " "where all 4 surfaces meet, there is a hangar. When " "entering this zone, the Hangar environmental effect " "becomes active.\n\n" "To test the footsteps, move the 'o' around with " "the <<DIRECTIONAL_TYPE>> or with the right stick. " "The displacement of the stick drives the Footstep_Speed RTPC. " "You can change the weight with <<UG_BUTTON3>> and <<UG_BUTTON4>> " "which drives the Footstep_Weight RTPC." #if defined( _DEMOFOOTSTEPS_DYNAMIC_BANK_LOADING ) "\n\nIf you connect the Wwise Profiler, you will also see " "that banks are loaded dynamically in this demo." #endif // defined( _DEMOFOOTSTEPS_DYNAMIC_BANK_LOADING ) ; } bool DemoFootstepsManyVariables::Init() { // Register the "Human" game object AK::SoundEngine::RegisterGameObj( GAME_OBJECT_HUMAN, "Human" ); // Load the sound bank ManageSurfaces(m_pParentMenu->GetWidth() / 2, m_pParentMenu->GetHeight() / 2, GAME_OBJECT_HUMAN); return Page::Init(); } void DemoFootstepsManyVariables::Release() { AK::SoundEngine::UnregisterGameObj( GAME_OBJECT_HUMAN ); for ( size_t i = 0; i < DEMOFOOTSTEPS_SURFACE_COUNT; ++i ) { int iBit = 1 << i; if ( m_maskCurrentBanks & iBit ) { AK::SoundEngine::UnloadBank( k_surfaces[i].strBankFile.c_str(), NULL ); } } Page::Release(); } #define HANGAR_TRANSITION_ZONE 25.f #define HANGAR_SIZE 70 #define BUFFER_ZONE 20 #define RUN_SPEED 5.0f #define DIST_TO_SPEED (10/RUN_SPEED) //The RTPC for speed is between 0 and 10. #define WALK_PERIOD 30 void DemoFootstepsManyVariables::UpdateGameObjPos() { float x, y; m_pChip->GetPos(x, y); //Check on which surface we are. In this demo, the screen is divided in 4 surfaces. ManageSurfaces((int)x, (int)y, GAME_OBJECT_HUMAN); //Set the environment ratios for this game object. ManageEnvironement((int)x, (int)y, GAME_OBJECT_HUMAN); //Compute the speed RTPC float dx = x - m_LastX; float dy = y - m_LastY; float dist = sqrt((float)dx*dx + dy*dy); float speed = dist * DIST_TO_SPEED; AK::SoundEngine::SetRTPCValue(AK::GAME_PARAMETERS::FOOTSTEP_SPEED, speed, GAME_OBJECT_HUMAN); float period = WALK_PERIOD - speed; //Just to simulate that when running, the steps are faster. No funky maths here, just a fudge factor. //Post the Footstep event if appropriate (if we are moving!) if (dist < 0.1f && m_iLastFootstepTick != -1) { //It stopped. Play one last footstep. Make it lighter (half) as if the other foot just came to rest. AK::SoundEngine::SetRTPCValue(AK::GAME_PARAMETERS::FOOTSTEP_WEIGHT, m_weight / 2.0f, GAME_OBJECT_HUMAN); AK::SoundEngine::PostEvent(AK::EVENTS::PLAY_FOOTSTEPS, GAME_OBJECT_HUMAN); m_iLastFootstepTick = -1; } else if (dist > 0.1f && m_pParentMenu->GetTickCount() - m_iLastFootstepTick > period) { //Reset the RTPC to its original value so it has the proper value when starting again. AK::SoundEngine::SetRTPCValue(AK::GAME_PARAMETERS::FOOTSTEP_WEIGHT, m_weight, GAME_OBJECT_HUMAN); AK::SoundEngine::PostEvent(AK::EVENTS::PLAY_FOOTSTEPS, GAME_OBJECT_HUMAN); m_iLastFootstepTick = m_pParentMenu->GetTickCount(); } m_LastX = x; m_LastY = y; } bool DemoFootstepsManyVariables::Update() { bool bRedraw = false; UniversalInput::Iterator it; for ( it = m_pParentMenu->Input()->Begin(); it != m_pParentMenu->Input()->End(); it++ ) { // Skip this input device if it's not connected if ( ! it->IsConnected() ) continue; m_pChip->Update(*it); if( it->IsButtonDown( UG_BUTTON3 ) ) { m_weight += 1.0f; if (m_weight > 100.f) { m_weight = 100; } } if( it->IsButtonDown( UG_BUTTON4 ) ) { m_weight -= 1.0f; if (m_weight < 0.f) { m_weight = 0; } } bRedraw = true; } if (bRedraw) { UpdateGameObjPos(); } return Page::Update(); } #if defined( _DEMOFOOTSTEPS_DYNAMIC_BANK_LOADING ) int DemoFootstepsManyVariables::ComputeUsedBankMask(int x, int y) { /* The screen is divided in 4 sections for the surfaces. There is a buffer section between each where the banks of the adjacent sections are loaded so the footsteps aren't delayed by bank loading. So there is a total 9 possible areas to manage. LD RD Dirt | D+W | Wood ----------------- TD D+M | All | W+G ----------------- BD Metal| M+G | Gravel LD = Left Division RD = Right Division TD = Top Division BD = Bottom Division */ int iHalfWidth = m_pParentMenu->GetWidth() / 2; int iHalfHeight = m_pParentMenu->GetHeight() / 2; int iBufferZone = (int)BUFFER_ZONE * 2; int bLeftDiv = x > iHalfWidth - iBufferZone; int bRightDiv = x < iHalfWidth + iBufferZone; int bTopDiv = y > iHalfHeight - iBufferZone; int bBottomDiv = y < iHalfHeight + iBufferZone; int maskBanks = ((bRightDiv & bBottomDiv) << 0) | //Is the Dirt bank needed ((bLeftDiv & bBottomDiv) << 1) | //Is the Wood bank needed ((bRightDiv & bTopDiv) << 2) | //Is the Metal bank needed ((bLeftDiv & bTopDiv) << 3); //Is the Gravel bank needed return maskBanks; } #endif // defined( _DEMOFOOTSTEPS_DYNAMIC_BANK_LOADING ) void DemoFootstepsManyVariables::ManageSurfaces(int x, int y, int in_GameObject) { #if defined( _DEMOFOOTSTEPS_DYNAMIC_BANK_LOADING ) int maskBanks = ComputeUsedBankMask(x, y); for(size_t i = 0; i < DEMOFOOTSTEPS_SURFACE_COUNT; i++) { AkBankID bankID; // Not used int iBit = 1 << i; if ((maskBanks & iBit) && !(m_maskCurrentBanks & iBit)) { //Load banks asynchronously to avoid blocking the game thread. if (AK::SoundEngine::LoadBank(k_surfaces[i].strBankFile.c_str(), NULL, NULL, AK_INVALID_POOL_ID, bankID) != AK_Success) maskBanks &= ~iBit; //This bank could not be loaded. } //Unload banks asynchronously to avoid blocking the game thread. if (!(maskBanks & iBit) && (m_maskCurrentBanks & iBit)) { if (AK::SoundEngine::UnloadBank(k_surfaces[i].strBankFile.c_str(), NULL, NULL, NULL ) != AK_Success) maskBanks |= iBit; //This bank is still loaded } } //Remember which banks we loaded. m_maskCurrentBanks = maskBanks; #else // defined( _DEMOFOOTSTEPS_DYNAMIC_BANK_LOADING ) if ( m_maskCurrentBanks == 0 ) { for(int i = 0; i < DEMOFOOTSTEPS_SURFACE_COUNT; i++) { // Load banks synchronously to make sure they're all available right from the start AkBankID bankID; // Not used if ( AK::SoundEngine::LoadBank( k_surfaces[i].strBankFile.c_str(), AK_INVALID_POOL_ID, bankID ) == AK_Success ) m_maskCurrentBanks |= 1 << i; // Remember which banks we loaded. } } #endif // defined( _DEMOFOOTSTEPS_DYNAMIC_BANK_LOADING ) //Find which surface we are actually walking on. int iHalfWidth = m_pParentMenu->GetWidth() / 2; int iHalfHeight = m_pParentMenu->GetHeight() / 2; int indexSurface = (x > iHalfWidth) | ((y > iHalfHeight) << 1); if (indexSurface != m_iSurface) { AK::SoundEngine::SetSwitch(AK::SWITCHES::SURFACE::GROUP, k_surfaces[indexSurface].idSwitch, in_GameObject); m_iSurface = indexSurface; } } void DemoFootstepsManyVariables::ManageEnvironement(int x, int y, int ) { AkAuxSendValue aHangarEnv; aHangarEnv.auxBusID = AK::SoundEngine::GetIDFromString( "Hangar_Env" ); aHangarEnv.fControlValue = 0.f; //There is a hangar in the middle of the screen with a transition zone around it where //the walker is still outside but starts to hear the effects of the hangar. int iHalfWidth = m_pParentMenu->GetWidth() / 2; int iHalfHeight = m_pParentMenu->GetHeight() / 2; int iDiffX = abs(x - iHalfWidth); int iDiffY = abs(y - iHalfHeight); //Ramp the environment value in the transition zone. If the object is outside this zone, //the value will be capped anyway. The result of this ramp is <0 when outside //the hangar and >1 when totally inside. float fPercentOutsideX = AkMax((iDiffX - HANGAR_SIZE)/HANGAR_TRANSITION_ZONE, 0.0f); float fPercentOutsideY = AkMax((iDiffY - HANGAR_SIZE)/HANGAR_TRANSITION_ZONE, 0.0f); aHangarEnv.fControlValue = 1.0f - AkMax(fPercentOutsideX, fPercentOutsideY); aHangarEnv.fControlValue = AkMax(0.0f, aHangarEnv.fControlValue); aHangarEnv.listenerID = LISTENER_ID; AK::SoundEngine::SetGameObjectOutputBusVolume(GAME_OBJECT_HUMAN, LISTENER_ID, 1.0f - aHangarEnv.fControlValue / 2.0f); AK::SoundEngine::SetGameObjectAuxSendValues( GAME_OBJECT_HUMAN, &aHangarEnv, 1 ); } void DemoFootstepsManyVariables::Weight_ValueChanged( void* in_pSender, ControlEvent* ) { NumericControl* sender = (NumericControl*)in_pSender; AK::SoundEngine::SetRTPCValue(AK::GAME_PARAMETERS::FOOTSTEP_WEIGHT, (AkRtpcValue)sender->GetValue(), GAME_OBJECT_HUMAN); } void DemoFootstepsManyVariables::Draw() { //Identify the 4 zones const int iTextWidth = 40; //Approx. int iTextHeight = GetLineHeight(DrawStyle_Control); int iHalfWidth = m_pParentMenu->GetWidth() / 2; int iHalfHeight = m_pParentMenu->GetHeight() / 2; DrawTextOnScreen("Dirt", iHalfWidth - BUFFER_ZONE - iTextWidth, iHalfHeight - BUFFER_ZONE - iTextHeight, DrawStyle_Control); DrawTextOnScreen("Metal", iHalfWidth - BUFFER_ZONE - iTextWidth, iHalfHeight + BUFFER_ZONE, DrawStyle_Control); DrawTextOnScreen("Wood", iHalfWidth + BUFFER_ZONE, iHalfHeight - BUFFER_ZONE - iTextHeight, DrawStyle_Control); DrawTextOnScreen("Gravel", iHalfWidth + BUFFER_ZONE, iHalfHeight + BUFFER_ZONE, DrawStyle_Control); char strBuf[50]; int iPosX = m_pParentMenu->GetWidth() / 10; int iPosY = m_pParentMenu->GetHeight() / 5; snprintf( strBuf, 50, "Weight is: %.2f", m_weight ); // Draw the play position and subtitles DrawTextOnScreen( strBuf, iPosX, iPosY, DrawStyle_Text ); m_pChip->Draw(); Page::Draw(); } bool DemoFootstepsManyVariables::OnPointerEvent( PointerEventType in_eType, int in_x, int in_y ) { if ( in_eType == PointerEventType_Moved ) { m_pChip->SetPos( (float) in_x, (float) in_y ); UpdateGameObjPos(); } return Page::OnPointerEvent( in_eType, in_x, in_y ); } void DemoFootstepsManyVariables::InitControls() { m_pChip = new MovableChip(*this); m_pChip->SetLabel( "o" ); m_pChip->UseJoystick(UG_STICKRIGHT); m_pChip->SetMaxSpeed(RUN_SPEED); m_pChip->SetNonLinear(); }
32.981959
139
0.709619
[ "object" ]
c623bad85473b247b2a83c37f4e69744a72ec850
7,206
cc
C++
device/serial/data_source_sender.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-28T08:09:58.000Z
2021-11-15T15:32:10.000Z
device/serial/data_source_sender.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
device/serial/data_source_sender.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.000Z
// Copyright 2014 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 "device/serial/data_source_sender.h" #include <algorithm> #include <limits> #include <memory> #include <utility> #include "base/bind.h" #include "base/location.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" namespace device { // Represents a send that is not yet fulfilled. class DataSourceSender::PendingSend { public: PendingSend(DataSourceSender* sender, const ReadyCallback& callback); // Asynchronously fills |data_| with up to |num_bytes| of data. Following // this, one of Done() and DoneWithError() will be called with the result. void GetData(uint32_t num_bytes); private: class Buffer; // Reports a successful write of |bytes_written|. void Done(uint32_t bytes_written); // Reports a partially successful or unsuccessful write of |bytes_written| // with an error of |error|. void DoneWithError(uint32_t bytes_written, int32_t error); // The DataSourceSender that owns this. DataSourceSender* sender_; // The callback to call to get data. ReadyCallback callback_; // Whether the buffer specified by GetData() has been passed to |callback_|, // but has not yet called Done() or DoneWithError(). bool buffer_in_use_; // The data obtained using |callback_| to be dispatched to the client. std::vector<char> data_; }; // A Writable implementation that provides a view of a buffer owned by a // DataSourceSender. class DataSourceSender::PendingSend::Buffer : public WritableBuffer { public: Buffer(scoped_refptr<DataSourceSender> sender, PendingSend* send, char* buffer, uint32_t buffer_size); ~Buffer() override; // WritableBuffer overrides. char* GetData() override; uint32_t GetSize() override; void Done(uint32_t bytes_written) override; void DoneWithError(uint32_t bytes_written, int32_t error) override; private: // The DataSourceSender of whose buffer we are providing a view. scoped_refptr<DataSourceSender> sender_; // The PendingSend to which this buffer has been created in response. PendingSend* pending_send_; char* buffer_; uint32_t buffer_size_; }; DataSourceSender::DataSourceSender( mojo::InterfaceRequest<serial::DataSource> source, mojo::InterfacePtr<serial::DataSourceClient> client, const ReadyCallback& ready_callback, const ErrorCallback& error_callback) : binding_(this, std::move(source)), client_(std::move(client)), ready_callback_(ready_callback), error_callback_(error_callback), available_buffer_capacity_(0), paused_(false), shut_down_(false), weak_factory_(this) { DCHECK(!ready_callback.is_null() && !error_callback.is_null()); binding_.set_connection_error_handler( base::Bind(&DataSourceSender::OnConnectionError, base::Unretained(this))); client_.set_connection_error_handler( base::Bind(&DataSourceSender::OnConnectionError, base::Unretained(this))); } void DataSourceSender::ShutDown() { shut_down_ = true; ready_callback_.Reset(); error_callback_.Reset(); } DataSourceSender::~DataSourceSender() { } void DataSourceSender::Init(uint32_t buffer_size) { available_buffer_capacity_ = buffer_size; GetMoreData(); } void DataSourceSender::Resume() { if (pending_send_) { DispatchFatalError(); return; } paused_ = false; GetMoreData(); } void DataSourceSender::ReportBytesReceived(uint32_t bytes_sent) { available_buffer_capacity_ += bytes_sent; if (!pending_send_ && !paused_) GetMoreData(); } void DataSourceSender::OnConnectionError() { DispatchFatalError(); } void DataSourceSender::GetMoreData() { if (shut_down_ || paused_ || pending_send_ || !available_buffer_capacity_) return; pending_send_.reset(new PendingSend(this, ready_callback_)); pending_send_->GetData(available_buffer_capacity_); } void DataSourceSender::Done(const std::vector<char>& data) { DoneInternal(data); if (!shut_down_ && available_buffer_capacity_) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&DataSourceSender::GetMoreData, weak_factory_.GetWeakPtr())); } } void DataSourceSender::DoneWithError(const std::vector<char>& data, int32_t error) { DoneInternal(data); if (!shut_down_) client_->OnError(error); paused_ = true; // We don't call GetMoreData here so we don't send any additional data until // Resume() is called. } void DataSourceSender::DoneInternal(const std::vector<char>& data) { DCHECK(pending_send_); if (shut_down_) return; available_buffer_capacity_ -= static_cast<uint32_t>(data.size()); if (!data.empty()) { mojo::Array<uint8_t> data_to_send(data.size()); std::copy(data.begin(), data.end(), &data_to_send[0]); client_->OnData(std::move(data_to_send)); } pending_send_.reset(); } void DataSourceSender::DispatchFatalError() { if (shut_down_) return; error_callback_.Run(); ShutDown(); } DataSourceSender::PendingSend::PendingSend(DataSourceSender* sender, const ReadyCallback& callback) : sender_(sender), callback_(callback), buffer_in_use_(false) { } void DataSourceSender::PendingSend::GetData(uint32_t num_bytes) { DCHECK(num_bytes); DCHECK(!buffer_in_use_); buffer_in_use_ = true; data_.resize(num_bytes); callback_.Run(std::unique_ptr<WritableBuffer>( new Buffer(sender_, this, &data_[0], num_bytes))); } void DataSourceSender::PendingSend::Done(uint32_t bytes_written) { DCHECK(buffer_in_use_); DCHECK_LE(bytes_written, data_.size()); buffer_in_use_ = false; data_.resize(bytes_written); sender_->Done(data_); } void DataSourceSender::PendingSend::DoneWithError(uint32_t bytes_written, int32_t error) { DCHECK(buffer_in_use_); DCHECK_LE(bytes_written, data_.size()); buffer_in_use_ = false; data_.resize(bytes_written); sender_->DoneWithError(data_, error); } DataSourceSender::PendingSend::Buffer::Buffer( scoped_refptr<DataSourceSender> sender, PendingSend* send, char* buffer, uint32_t buffer_size) : sender_(sender), pending_send_(send), buffer_(buffer), buffer_size_(buffer_size) { } DataSourceSender::PendingSend::Buffer::~Buffer() { if (pending_send_) pending_send_->Done(0); } char* DataSourceSender::PendingSend::Buffer::GetData() { return buffer_; } uint32_t DataSourceSender::PendingSend::Buffer::GetSize() { return buffer_size_; } void DataSourceSender::PendingSend::Buffer::Done(uint32_t bytes_written) { DCHECK(sender_.get()); PendingSend* send = pending_send_; pending_send_ = nullptr; send->Done(bytes_written); sender_ = nullptr; } void DataSourceSender::PendingSend::Buffer::DoneWithError( uint32_t bytes_written, int32_t error) { DCHECK(sender_.get()); PendingSend* send = pending_send_; pending_send_ = nullptr; send->DoneWithError(bytes_written, error); sender_ = nullptr; } } // namespace device
28.258824
80
0.721621
[ "vector" ]
c63a4e357a742c68597ac4a2336dcdbe092afb9f
1,177
cpp
C++
src/cpp/2016-12-4-BestTimetoBuyandSellStock/Code13-122BestTimetoBuyandSellStock2.cpp
spurscoder/forTest
2ab069d6740f9d7636c6988a5a0bd3825518335d
[ "MIT" ]
null
null
null
src/cpp/2016-12-4-BestTimetoBuyandSellStock/Code13-122BestTimetoBuyandSellStock2.cpp
spurscoder/forTest
2ab069d6740f9d7636c6988a5a0bd3825518335d
[ "MIT" ]
1
2018-10-24T05:48:27.000Z
2018-10-24T05:52:14.000Z
src/cpp/2016-12-4-BestTimetoBuyandSellStock/Code13-122BestTimetoBuyandSellStock2.cpp
spurscoder/forTest
2ab069d6740f9d7636c6988a5a0bd3825518335d
[ "MIT" ]
null
null
null
/* Description: Say you have an array for which the ith element is the price of a given stock on day i, Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie. buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie. you must sell the stock before you buy again). Tags : Array, Greedy. Explanation: Second, suppose the first sequence is "a <= b <= c <= d", the profit is "d - a = (b - a) + (c - b) + (d - c)" without a doubt. And suppose another one is "a <= b >= b' <= c <= d", the profit is not difficult to be figured out as "(b - a) + (d - b')". So you just target at monotone sequences. */ class Solution { public: int maxProfit (vector<int>& prices) { int maxpro = 0; for (int i = 0; i < prices.size() - 1; ++i) { maxpro += max(prices[i+1] - prices[i], 0); } return maxpro; } }; // Python class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ return sum(max(prices[i + 1] - prices[i], 0) for i in range(len(prices) - 1))
30.179487
85
0.621071
[ "object", "vector" ]
c63c87604ca1e8498aa136186892b20d9929105c
2,584
cpp
C++
modules/skshaper/src/SkShaper_primitive.cpp
CarbonROM/android_external_skqp
72c9856641fddcfe46a1c2287550604061f1eefd
[ "BSD-3-Clause" ]
1
2019-04-04T19:37:54.000Z
2019-04-04T19:37:54.000Z
modules/skshaper/src/SkShaper_primitive.cpp
CarbonROM/android_external_skqp
72c9856641fddcfe46a1c2287550604061f1eefd
[ "BSD-3-Clause" ]
null
null
null
modules/skshaper/src/SkShaper_primitive.cpp
CarbonROM/android_external_skqp
72c9856641fddcfe46a1c2287550604061f1eefd
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkShaper.h" #include "SkFontMetrics.h" #include "SkStream.h" #include "SkTo.h" #include "SkTypeface.h" struct SkShaper::Impl { sk_sp<SkTypeface> fTypeface; }; SkShaper::SkShaper(sk_sp<SkTypeface> tf) : fImpl(new Impl) { fImpl->fTypeface = tf ? std::move(tf) : SkTypeface::MakeDefault(); } SkShaper::~SkShaper() {} bool SkShaper::good() const { return true; } // This example only uses public API, so we don't use SkUTF8_NextUnichar. unsigned utf8_lead_byte_to_count(const char* ptr) { uint8_t c = *(const uint8_t*)ptr; SkASSERT(c <= 0xF7); SkASSERT((c & 0xC0) != 0x80); return (((0xE5 << 24) >> ((unsigned)c >> 4 << 1)) & 3) + 1; } SkPoint SkShaper::shape(RunHandler* handler, const SkFont& srcFont, const char* utf8text, size_t textBytes, bool leftToRight, SkPoint point, SkScalar width) const { sk_ignore_unused_variable(leftToRight); sk_ignore_unused_variable(width); SkFont font(srcFont); font.setTypeface(fImpl->fTypeface); int glyphCount = font.countText(utf8text, textBytes, SkTextEncoding::kUTF8); if (glyphCount <= 0) { return point; } SkFontMetrics metrics; font.getMetrics(&metrics); point.fY -= metrics.fAscent; const RunHandler::RunInfo info = { 0, { font.measureText(utf8text, textBytes, SkTextEncoding::kUTF8), 0 }, metrics.fAscent, metrics.fDescent, metrics.fLeading, }; const auto buffer = handler->newRunBuffer(info, font, glyphCount, textBytes); SkAssertResult(font.textToGlyphs(utf8text, textBytes, SkTextEncoding::kUTF8, buffer.glyphs, glyphCount) == glyphCount); font.getPos(buffer.glyphs, glyphCount, buffer.positions, point); if (buffer.utf8text) { memcpy(buffer.utf8text, utf8text, textBytes); } if (buffer.clusters) { const char* txtPtr = utf8text; for (int i = 0; i < glyphCount; ++i) { // Each charater maps to exactly one glyph via SkGlyphCache::unicharToGlyph(). buffer.clusters[i] = SkToU32(txtPtr - utf8text); txtPtr += utf8_lead_byte_to_count(txtPtr); SkASSERT(txtPtr <= utf8text + textBytes); } } return point + SkVector::Make(0, metrics.fDescent + metrics.fLeading); }
31.13253
95
0.617647
[ "shape" ]
c63e0bd9aa51b0c99ab37af64fe2777081e9e2d7
8,739
hpp
C++
include/recompression.hpp
christopherosthues/recompression
1932cc5aa77a533d9994dbe0c80dbb889a4d25ec
[ "ECL-2.0", "Apache-2.0" ]
5
2019-07-18T12:48:14.000Z
2022-01-04T13:54:13.000Z
include/recompression.hpp
christopherosthues/recompression
1932cc5aa77a533d9994dbe0c80dbb889a4d25ec
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
include/recompression.hpp
christopherosthues/recompression
1932cc5aa77a533d9994dbe0c80dbb889a4d25ec
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
#pragma once #include <memory> #include "recompression/defs.hpp" #include "recompression/recompression.hpp" #include "recompression/fast_recompression.hpp" #include "recompression/parallel_ls_recompression.hpp" #include "recompression/parallel_gr_recompression.hpp" #include "recompression/experimental/parallel_lock_recompression.hpp" #include "recompression/experimental/parallel_gr2_recompression.hpp" #include "recompression/hash_recompression.hpp" #include "recompression/parallel_lp_recompression.hpp" #include "recompression/parallel_recompression.hpp" #include "recompression/parallel_rnd_recompression.hpp" #include "recompression/parallel_rnddir_recompression.hpp" #include "recompression/lce_query.hpp" #include "recompression/radix_sort.hpp" #include "recompression/rlslp.hpp" #include "recompression/util.hpp" #include "recompression/experimental/parallel_gr_alternate_recompression.hpp" #include "recompression/experimental/parallel_order_great_recompression.hpp" #include "recompression/experimental/parallel_order_less_recompression.hpp" #include "recompression/experimental/parallel_ls3_recompression.hpp" #include "recompression/experimental/parallel_ls5_recompression.hpp" #include "recompression/experimental/parallel_ls_gain_recompression.hpp" #include "recompression/experimental/parallel_parhip_recompression.hpp" #include "recompression/io/bitistream.hpp" #include "recompression/io/bitostream.hpp" #include "recompression/coders/coder.hpp" #include "recompression/coders/plain_rlslp_coder.hpp" #include "recompression/coders/plain_fixed_rlslp_coder.hpp" #include "recompression/coders/sorted_rlslp_coder.hpp" #include "recompression/coders/sorted_rlslp_dr_coder.hpp" #include "recompression/coders/rlslp_rule_sorter.hpp" namespace recomp { void sequential_variants(std::vector<std::string>& variants) { variants.emplace_back("fast_seq"); variants.emplace_back("hash"); } void parallel_variants(std::vector<std::string>& variants) { variants.emplace_back("parallel"); variants.emplace_back("parallel_lp"); variants.emplace_back("parallel_rnd"); variants.emplace_back("parallel_ls"); variants.emplace_back("parallel_gr"); variants.emplace_back("parallel_rnddir"); variants.emplace_back("parallel_lock"); } void experimental_variants(std::vector<std::string>& variants) { variants.emplace_back("parallel_ls3"); variants.emplace_back("parallel_ls5"); variants.emplace_back("parallel_ls_gain"); variants.emplace_back("parallel_gr2"); variants.emplace_back("parallel_gr_alternate"); variants.emplace_back("parallel_order_gr"); variants.emplace_back("parallel_order_ls"); variants.emplace_back("parallel_parhip"); } /** * @brief Creates a unique pointer for the given class name. * * @tparam variable_t The type of non-terminals * @param name The name of the recompression algorithm * @param dataset The dataset to test * @param parhip The path to the executable of parhip * @param dir The directory where parhip puts the partition file * @return A unique pointer of the recompression class */ template<typename variable_t = var_t> std::unique_ptr<recompression<variable_t>> create_recompression(const std::string& name, std::string& dataset, std::string parhip, std::string dir) { size_t k = 1; if (name.find("parallel_rnd") == 0) { bool dir = false; if (name != "parallel_rnd") { auto number = name.substr(12); if (number.find("dir") == 0) { number = name.substr(15); dir = true; } if (!number.empty()) { k = util::str_to_int(number); } else { k = 1; } std::cout << "Using " << k << " iterations for " << name << std::endl; } if (dir) { return std::make_unique<parallel::parallel_rnddir_recompression<variable_t>>(dataset, k); } else { return std::make_unique<parallel::parallel_rnd_recompression<variable_t>>(dataset, k); } } if (name == "parallel") { return std::make_unique<parallel::parallel_recompression<variable_t>>(dataset); } else if (name == "parallel_parhip") { if (parhip.empty() || dir.empty()) { std::cerr << "Error. parhip and/or dir not specified" << std::endl; exit(-1); } return std::make_unique<parallel::parallel_parhip_recompression<variable_t>>(dataset, parhip, dir); } else if (name == "parallel_ls") { return std::make_unique<parallel::parallel_ls_recompression<variable_t>>(dataset); } else if (name == "parallel_ls3") { return std::make_unique<parallel::parallel_ls3_recompression<variable_t>>(dataset); } else if (name == "parallel_ls5") { return std::make_unique<parallel::parallel_ls5_recompression<variable_t>>(dataset); } else if (name == "parallel_ls_gain") { return std::make_unique<parallel::parallel_ls_gain_recompression<variable_t>>(dataset); } else if (name == "parallel_gr") { return std::make_unique<parallel::parallel_gr_recompression<variable_t>>(dataset); } else if (name == "parallel_gr2") { return std::make_unique<parallel::parallel_gr2_recompression<variable_t>>(dataset); } else if (name == "parallel_gr_alternate") { return std::make_unique<parallel::parallel_gr_alternate_recompression<variable_t>>(dataset); } else if (name == "parallel_lp") { return std::make_unique<parallel::parallel_lp_recompression<variable_t>>(dataset); } else if (name == "parallel_lock") { return std::make_unique<parallel::parallel_lock_recompression<variable_t>>(dataset); } else if (name == "parallel_order_ls") { return std::make_unique<parallel::recompression_order_ls<variable_t>>(dataset); } else if (name == "parallel_order_gr") { return std::make_unique<parallel::recompression_order_gr<variable_t>>(dataset); } else if (name == "fast_seq") { return std::make_unique<recompression_fast<variable_t>>(dataset); } else if (name == "hash") { return std::make_unique<hash_recompression<variable_t>>(dataset); } else { return std::unique_ptr<recompression<variable_t>>(nullptr); } } namespace coder { /** * @brief Encodes the given rlslp with the specified encoder and writes it to the file. * * @tparam variable_t The type of non-terminals * @param coder The name of the coder * @param file_name The name of the file to write to * @param rlslp The rlslp to encode */ template<typename variable_t = var_t> void encode(const std::string& coder, const std::string& file_name, rlslp<variable_t>& rlslp) { if (coder == "plain") { PlainRLSLPCoder::Encoder enc{file_name}; enc.encode(rlslp); } else if (coder == "fixed") { PlainFixedRLSLPCoder::Encoder enc{file_name}; enc.encode(rlslp); } else if (coder == "sorted") { SortedRLSLPCoder::Encoder enc{file_name}; enc.encode(rlslp); } else if (coder == "sorted_dr") { SortedRLSLPDRCoder::Encoder enc{file_name}; enc.encode(rlslp); } } /** * @brief Reads and decodes the rlslp from the given file with the specified decoder. * * @tparam variable_t The type of non-terminals * @param coder The name of the coder * @param file_name The name of the file to read from * @return The decoded rlslp */ template<typename variable_t = var_t> rlslp<variable_t> decode(const std::string& coder, const std::string& file_name) { if (coder == "plain") { PlainRLSLPCoder::Decoder dec{file_name}; return dec.decode(); } else if (coder == "fixed") { PlainFixedRLSLPCoder::Decoder dec{file_name}; return dec.decode(); } else if (coder == "sorted") { SortedRLSLPCoder::Decoder dec{file_name}; return dec.decode(); } else if (coder == "sorted_dr") { SortedRLSLPDRCoder::Decoder dec{file_name}; return dec.decode(); } else { return rlslp<variable_t>{}; } } /** * @brief Returns the file extension used for the specified coder. * * @param name The name of the coder * @return The file extension for the coder */ std::string get_coder_extension(const std::string& name) { if (name == "plain") { return coder::PlainRLSLPCoder::k_extension; } else if (name == "fixed") { return coder::PlainFixedRLSLPCoder::k_extension; } else if (name == "sorted") { return coder::SortedRLSLPCoder::k_extension; } else if (name == "sorted_dr") { return coder::SortedRLSLPDRCoder::k_extension; } else { return "unkown"; } } } // namespace coder } // namespace recomp
40.458333
149
0.697792
[ "vector" ]
c6449494efc5f4f13b7d6ed2176c601933b5dd7f
2,018
cpp
C++
source/core/source/core/gl/opengles2/GLES2_ShaderLoader.cpp
NiklasReiche/yage
f4a2dfb2bf584884e45d2751da21a13c15631e98
[ "MIT" ]
null
null
null
source/core/source/core/gl/opengles2/GLES2_ShaderLoader.cpp
NiklasReiche/yage
f4a2dfb2bf584884e45d2751da21a13c15631e98
[ "MIT" ]
2
2020-11-12T18:17:42.000Z
2020-11-12T18:18:05.000Z
source/core/source/core/gl/opengles2/GLES2_ShaderLoader.cpp
NiklasReiche/yage
f4a2dfb2bf584884e45d2751da21a13c15631e98
[ "MIT" ]
null
null
null
#include "GLES2_ShaderLoader.h" namespace gles2 { GLES2_ShaderLoader::GLES2_ShaderLoader(sys::PlatformHandle* systemHandle, GLES2_Context* glContext) : systemHandle(systemHandle), glContext(glContext) {} GLES2_Shader GLES2_ShaderLoader::loadFromFile(std::string vertex_path, std::string fragment_path) { std::vector<std::string> attributes; std::string vertexCode(""), fragmentCode(""); std::string vertexCodeLine, fragmentCodeLine; // File Handle try { std::stringstream vertexFile, fragmentFile; sys::File vertexFileHandle = systemHandle->open(vertex_path); sys::File fragmentFileHandle = systemHandle->open(fragment_path); vertexFileHandle.read(vertexFile); fragmentFileHandle.read(fragmentFile); while (getline(vertexFile, vertexCodeLine)) { vertexCode += vertexCodeLine + "\n"; std::stringstream line(vertexCodeLine); std::string qualifier; line >> qualifier; if (qualifier == "attribute") { std::string type, name; line >> type; line >> name; attributes.push_back(name); } } while (getline(fragmentFile, fragmentCodeLine)) { fragmentCode += fragmentCodeLine + "\n"; } } catch (std::exception err) { systemHandle->log("ERROR::SHADER_LOADER: File Handling Error"); } return glContext->compileShader(vertexCode, fragmentCode, attributes); } GLES2_Shader GLES2_ShaderLoader::loadFromString(std::string vertexCode, std::string fragmentCode) { std::vector<std::string> attributes; std::stringstream vertexFile(vertexCode); std::stringstream fragmentFile(fragmentCode); std::string vertexCodeLine; while (getline(vertexFile, vertexCodeLine)) { std::stringstream line(vertexCodeLine); std::string qualifier; line >> qualifier; if (qualifier == "attribute") { std::string type, name; line >> type; line >> name; attributes.push_back(name); } } return glContext->compileShader(vertexCode, fragmentCode, attributes); } }
28.828571
100
0.700694
[ "vector" ]
c6575f1e7dfa48d27cc072cb8e2ca91c7bcdb7f4
8,115
cpp
C++
gif/src/main/cpp/GifDecoder.cpp
dandycheung/APNG4Android
b5ca5cc3e1f6c09c30be44eaaf1a74155ab060e5
[ "Apache-2.0" ]
null
null
null
gif/src/main/cpp/GifDecoder.cpp
dandycheung/APNG4Android
b5ca5cc3e1f6c09c30be44eaaf1a74155ab060e5
[ "Apache-2.0" ]
null
null
null
gif/src/main/cpp/GifDecoder.cpp
dandycheung/APNG4Android
b5ca5cc3e1f6c09c30be44eaaf1a74155ab060e5
[ "Apache-2.0" ]
null
null
null
#include <jni.h> #include <string> #include <vector> #include "common.h" #include "Reader.h" struct Slice { int *ptr_data; size_t len_data; }; void uncompressLZW( JNIEnv *env, jobject /* this */, jobject jReader, jintArray colorTable, jint transparentColorIndex, jintArray pixels, jint width, jint height, jint lzwMinCodeSize, jboolean interlace, jbyteArray buffer) { Reader reader(env, jReader, buffer); char buf[0xff]; jboolean b = JNI_FALSE; int *pixelsBuffer = env->GetIntArrayElements(pixels, &b); size_t idx_pixel = 0; size_t offset_data = 0; size_t idx_data = 0; size_t bits = 0; size_t code_size = lzwMinCodeSize + 1; size_t pixelsSize = width * height; int datum = 0; int code_clear = 1 << lzwMinCodeSize; int code_end = code_clear + 1; int code; std::vector<Slice> table_string; Slice prefix; prefix.len_data = 0; prefix.ptr_data = nullptr; int table_max_size = (1 << 12) - code_end - 1; while (idx_pixel < pixelsSize) { if (offset_data == 0) { offset_data = reader.peek() & 0xff; if (offset_data <= 0) { // DECODE ERROR break; } reader.read(buf, offset_data); idx_data = 0; } datum += (buf[idx_data] & 0xff) << bits; bits += 8; idx_data++; offset_data--; while (bits >= code_size) { code = datum & ((1 << code_size) - 1); datum >>= code_size; bits -= code_size; if (code == code_clear) { table_string.clear(); code_size = lzwMinCodeSize + 1; prefix.len_data = 0; prefix.ptr_data = nullptr; continue; } else if (code == code_end) { break; } else { if (prefix.len_data > 0 && prefix.ptr_data) { //Add to String Table Slice slice; int sufix; // Find suffix if (code > code_end) { if (code - code_end > table_string.size()) { sufix = *prefix.ptr_data; //output current slice to buffer memcpy(pixelsBuffer + idx_pixel, prefix.ptr_data, prefix.len_data * sizeof(int)); //update slice ptr,so that this continious memory includes sufix slice.ptr_data = pixelsBuffer + idx_pixel; idx_pixel += prefix.len_data; pixelsBuffer[idx_pixel++] = sufix; slice.len_data = prefix.len_data + 1; prefix.ptr_data = slice.ptr_data; prefix.len_data = slice.len_data; } else { // Get Prefix's first char as sufix Slice current = table_string.at( code - code_end - 1); // sufix = *current.ptr_data; // update ptr so that new table item contain sufix slice.ptr_data = pixelsBuffer + idx_pixel - prefix.len_data; slice.len_data = prefix.len_data + 1; memcpy(pixelsBuffer + idx_pixel, current.ptr_data, current.len_data * sizeof(int)); idx_pixel += current.len_data; prefix.ptr_data = current.ptr_data; prefix.len_data = current.len_data; } } else { sufix = code; pixelsBuffer[idx_pixel] = sufix; // It's been copied to pixelsBuffer,so just move forward so that sufix can be contained slice.len_data = prefix.len_data + 1; slice.ptr_data = pixelsBuffer + idx_pixel - prefix.len_data; // Set prefix to just one code prefix.len_data = 1; prefix.ptr_data = pixelsBuffer + idx_pixel; idx_pixel++; } if (table_string.size() < table_max_size) { //Add to string table table_string.push_back(slice); if (table_string.size() >= (1 << code_size) - code_end - 1 && table_string.size() < table_max_size) { code_size++; } } } else { pixelsBuffer[idx_pixel] = code & 0xff; prefix.ptr_data = pixelsBuffer + idx_pixel; prefix.len_data = 1; idx_pixel++; } } } } int *colors = env->GetIntArrayElements(colorTable, &b); int idx; for (int loop = 0; loop < idx_pixel; loop++) { idx = pixelsBuffer[loop] & 0xff; if (idx == transparentColorIndex) { pixelsBuffer[loop] = 0; } else { pixelsBuffer[loop] = colors[idx]; } } while (idx_pixel < pixelsSize) { pixelsBuffer[idx_pixel++] = 0; } if (interlace) { // interlace flag size_t i = 0; int *pixels_copy = static_cast<int *>(malloc(sizeof(int) * pixelsSize)); size_t src_row = 0; size_t pack = 1; size_t step = 8; size_t start = 8; for (; pack <= 4 & src_row < height;) { switch (pack) { case 1: step = 8; start = 0; break; case 2: step = 8; start = 4; break; case 3: step = 4; start = 2; break; case 4: step = 2; start = 1; break; } i = start; do { // copy memcpy(pixels_copy + i * width, pixelsBuffer + src_row * width, width * (sizeof(int))); src_row++; i += step; } while (i < height); pack++; } memcpy(pixelsBuffer, pixels_copy, pixelsSize * sizeof(int)); free(pixels_copy); } env->ReleaseIntArrayElements(pixels, pixelsBuffer, 0); env->ReleaseIntArrayElements(colorTable, colors, JNI_ABORT); } static JNINativeMethod methods[] = { {"uncompressLZW", "(Lcom/github/penfeizhou/animation/gif/io/GifReader;[II[IIIIZ[B)V", (void *) &uncompressLZW}, }; int jniRegisterNativeMethods(JNIEnv *env, const char *className, const JNINativeMethod *gMethods, int numMethods) { jclass clazz; int tmp; clazz = env->FindClass(className); if (clazz == nullptr) { return -1; } if ((tmp = env->RegisterNatives(clazz, gMethods, numMethods)) < 0) { return -1; } return 0; } int registerNativeMethods(JNIEnv *env) { return jniRegisterNativeMethods(env, "com/github/penfeizhou/animation/gif/decode/GifFrame", methods, sizeof(methods) / sizeof(methods[0])); } jint JNI_OnLoad(JavaVM *vm, void *reserved) { JNIEnv *env; if (vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) != JNI_OK) { return -1; } if (JavaReader_OnLoad(env)) { LOGE("Failed to load JavaReader"); return -1; } if (registerNativeMethods(env) != JNI_OK) { return -1; } return JNI_VERSION_1_6; }
34.828326
119
0.463093
[ "vector" ]
c659ea20070c5efa1293efa931798c71c2f33f9e
14,170
hpp
C++
include/imu-core/imu_3DM_GX3_25_msg.hpp
machines-in-motion/imu_core
a2708b18fd8b8d7350688c3f1e8a21e768e9e0f9
[ "BSD-3-Clause" ]
null
null
null
include/imu-core/imu_3DM_GX3_25_msg.hpp
machines-in-motion/imu_core
a2708b18fd8b8d7350688c3f1e8a21e768e9e0f9
[ "BSD-3-Clause" ]
2
2021-06-23T16:10:07.000Z
2021-07-27T14:39:08.000Z
include/imu-core/imu_3DM_GX3_25_msg.hpp
machines-in-motion/imu_core
a2708b18fd8b8d7350688c3f1e8a21e768e9e0f9
[ "BSD-3-Clause" ]
null
null
null
#ifndef IMU_3DM_GX3_25_MSG_HPP #define IMU_3DM_GX3_25_MSG_HPP #include "imu-core/imu_interface.hpp" namespace imu_core { namespace imu_3DM_GX3_25 { /** * @brief This structure defines the data type streamed by the IMU upon * setting the continuous mode. */ struct DataType{ /** * @brief The IMU broadcasts the acceleration and the angular rate. * This is the strongly recommanded interface. */ static const uint8_t AccGyro = 0xc2; /** * @brief The IMU broadcasts the stabilized acceleration, the angular rate * and the magnetometer measurement. */ static const uint8_t StabAccGyroMagn = 0xd2; /** * @brief The IMU broadcasts the acceleration, the angular rate and the * rotation matrix. The orientation is computed using an Extended Kalman * Filter integrated in the hardware. (Not recommanded). */ static const uint8_t AccGyroRotMat = 0xc8; /** * @brief The IMU broadcasts the quaternion representation the IMU attitude * through the computation an Extended Kalman Filter integrated in the * hardware. (Not recommanded). */ static const uint8_t Quaternion = 0xdf; /** * @brief Check if the data requested is supported * * @param data_type the type of the data (acceleration, angular velocity,...) * @return true if sucess * @return false if failure */ static bool check_data_type(uint8_t data_type) { return (data_type == AccGyro || data_type == StabAccGyroMagn || data_type == AccGyroRotMat || data_type == Quaternion); } }; /** * @brief This class allows us to send a simple message to the IMU in order to * modify its communication settings. */ class CommunicationSettingsMsg: public ImuMsg { public: /** * @brief this allow us to define if the value should return, changed, or * changed and stored. */ enum ChangeParam{ GetCurrentValue=0, ChangeValueTemporarily=1, ChangeValuePermanently=2, }; /** * @brief Construct a new CommunicationSettingsMsg object * * @param baude_rate_cst is the baude rate the imu can use based on the * available ones: * (int)115200 * (int)230400 * (int)460800 * (int)921600 * change_param allow the user to ask for permanent change of paramters * or not */ CommunicationSettingsMsg(int baude_rate_cst): ImuMsg() { command_.resize(11); command_[0] = 0xd9 ; // header command_[1] = 0xc3 ; // user confirmation 1 command_[2] = 0x55 ; // user confirmation 2 command_[3] = (uint8_t)1; // UART1, Primary UART for host communication command_[4] = (uint8_t)ChangeParam::ChangeValueTemporarily; *(uint32_t *)(&command_[5]) = ImuInterface::bswap_32(baude_rate_cst); command_[9] = (uint8_t)2; // 2: Selected UART Enabled ; 0: Selected UART Disabled command_[10] = (uint8_t)0; // Reserved: Set to 0 /** * Reply */ reply_.resize(10, 0); } /** * @brief Get the baude rate setup return by the imu with this request * * @return int the baude rate */ int get_baude_rate() { uint8_t baude_rate_unit8[4]; baude_rate_unit8[0] = reply_[2]; baude_rate_unit8[1] = reply_[3]; baude_rate_unit8[2] = reply_[4]; baude_rate_unit8[3] = reply_[5]; uint32_t baude_rate = ImuInterface::bswap_32(*(uint32_t*)baude_rate_unit8); return baude_rate; } }; /** * @brief This class allows us to send a simple message to the IMU in order to * modify its data sampling settings. * * with the previous implementation we were sending: * [db a8 b9 01 00 02 05 13 0f 11 00 0a 00 0a 00 00 00 00 00 00 ] * * with the new one: * [DB A8 B9 01 00 01 0D 10 0F 11 00 0A 00 0A 00 00 00 00 00 00 ] * [DB A8 B9 01 00 01 15 13 0F 11 00 0A 00 0A 00 00 00 00 00 00 ] */ class SamplingSettingsMsg: public ImuMsg { public: /** * @brief Construct a new SamplingSettingsMsg object * * data_rate_decimation this divides the maximum rate of data (1000Hz). * So if data_rate_decimation = 1, the rate of data is 1000Hz. * And if data_rate_decimation = 1000, the rate of data is 1Hz. * command_[3] allow the user to ask for permanent change of paramters * or not * gyro_acc_window_filter_divider is defining the Gyrometer and * Accelerometer filter window size. The size is * (1000/gyro_acc_window_filter_divider). The default value is (1000/15). * 1 <= gyro_acc_window_filter_divider <= 32 * magn_window_filter_divider is defining the Magnetometer filter * window size. The size is (1000/magn_window_filter_divider). The default * value is (1000/17). 1 <= magn_window_filter_divider <= 32 */ SamplingSettingsMsg(): ImuMsg() { command_.resize(20); command_[0] = 0xdb ; // header command_[1] = 0xa8 ; // user confirmation 1 command_[2] = 0xb9 ; // user confirmation 2 command_[3] = 2 ; // change value temporarily; /** * Data Rate decimation value. This valueisdivided intoa fixed 1000Hz * reference ratetoestablish the data output rate. Settingthis value to 10 * gives an output data rate of 1000/10= 100 samples/sec. When using the * UART for communications, atdata rates higher than 250, the UART baud * rate must be increased (see command 0xD9).Minimum Value is 1, Maximum * value is 1000. */ uint16_t data_rate_decimation = 1; assert(data_rate_decimation <= 1000 && data_rate_decimation >= 1 && "The data rate decimation must be in [1 ; 1000]"); *(uint32_t *)(&command_[4]) = ImuInterface::bswap_16(data_rate_decimation); /** * Data conditioning function selector: * Bit 0: if set -Calculate orientation. Default is “1” * Bit 1: if set -Enable Coning&Sculling. Default is “1” * Bit 2 –3: reserved. Default is “0” * Bit 4: if set –Floating Pointdata is sent in Little Endian format * (only floating point data from IMU to HOST is affected). * Default is “0” * Bit 5: if set –NaN data is suppressed. Default is “0” * Bit 6: if set, enable finite size correctionDefault is “0” * Bit 7: reserved. Default is “0” * Bit 8: if set, disables magnetometerDefault is “0” * Bit 9: reserved. Default is “0” * Bit 10: if set, disables magnetic north compensationDefault is “0” * Bit 11: if set, disables gravity compensation Default is “0” * Bit 12: if set, enables Quaternion calculation Default is “0” * Bit 13–15: reserved. Default is “0” * We select uniquely the accelerometer and gyroscope data. */ uint16_t fselect = 0b0000110100010000; // get the acc and gyro // fselect = 0b0001010100010011; // calculate quaternion, needs 500Hz // fselect = 0b0000010100010011; // calculate rotation matrix, needs 500Hz *(uint16_t *)(&command_[6]) = ImuInterface::bswap_16(fselect); /** * Gyro and Accel digital filter window size. First null is 1000 divided by * this value. Minimum value is 1, maximum value is 32. Default is 15 */ uint8_t gyro_acc_window_filter_divider = 15; // assert(1 <= gyro_acc_window_filter_divider && // gyro_acc_window_filter_divider <= 32 && // "gyro acc filter divider must be in [1, 32]"); command_[8] = gyro_acc_window_filter_divider; /** * Mag digital filter window size. First null is 1000 divided by this * value. Minimum value is 1, maximum value is 32 Default is 17. */ uint8_t magn_window_filter_divider = 17; // assert(1 <= magn_window_filter_divider && // magn_window_filter_divider <= 32 && // "magn filter divider must be in [1, 32]"); command_[9] = magn_window_filter_divider; /** * Up Compensation in seconds. Determines how quickly the gravitational * vector corrects the gyro stabilized pitch and roll. Minimum value is 1, * maximum value is 1000.Default is 10 */ command_[10] = 0; command_[11] = 10; /** * NorthCompensation in seconds. Determines how quickly the magnetometer * vector corrects the gyro stabilized yaw. Minimum value is 1, maximum * value is 1000.Default is 10 */ command_[12] = 0; command_[13] = 10; /** * Mag Power/Bandwidth setting. * 0: Highest bandwidth, highest power. * 1: Lowerpower, bandwidthcoupled to data rate */ command_[14] = 0; /** * reserved bytes to be all zeros */ command_[15] = 0; command_[16] = 0; command_[17] = 0; command_[18] = 0; command_[19] = 0; /** * Reply */ reply_.resize(19, 0); } }; /** * @brief This class allows us to (re)set or receive the onboard time stamp. */ class TimerMsg: public ImuMsg { public: /** * @brief Function selector: (8bit unsigned integer) * 0: Do not change the time stamp, just return current value * 1: Restart the time stamp at the new value * 2: Restart the PPS Seconds counter at the new value */ enum ChangeParam { ReturnCurrent = 0, RestartTimerAtNewValue = 1, RestartPPSsecCounterAtNewValue = 2 }; /** * @brief Construct a new TimerMsg object */ TimerMsg(): ImuMsg() { // Reset onboard timestamp: command_.resize(8); command_[0] = 0xd7 ; // header command_[1] = 0xc1 ; // user confirmation 1 command_[2] = 0x29 ; // user confirmation 2 command_[3] = (uint8_t)ChangeParam::RestartTimerAtNewValue ; // start at 0 command_[4] = 0; command_[5] = 0; command_[6] = 0; command_[7] = 0; // *(uint32_t *)(&command_[4]) = ImuInterface::bswap_32(0); /** * Reply */ reply_.resize(7, 0); } }; /** * @brief This class allows us to compute the gyro bias after a certain time. * I assume this period of time is used by the onboard (extended kalman) filter * in order to compute the Bias. */ class CaptureGyroBiasMsg: public ImuMsg { public: /** * @brief Construct a new CaptureGyroBiasMsg object * * @param calibration_duration is the duration given to the IMU to compute the * gyroscope bias. */ CaptureGyroBiasMsg(uint16_t calibration_duration = 3): ImuMsg() { // Record gyroscope biases: command_.resize(5); command_[0] = 0xcd ; // header command_[1] = 0xc1 ; // user confirmation 1 command_[2] = 0x29 ; // user confirmation 2 // by default we wait 3seconds *(uint32_t *)(&command_[3]) = ImuInterface::bswap_32(calibration_duration); /** * Reply is of size 19 */ reply_.resize(19); } }; /** * @brief This class allows us to ask for the data steam to start. */ class StartDataStreamMsg: public ImuMsg { public: /** * @brief Construct a new StartDataStreamMsg object * * @param data_type define which data we receive from the IMU: * + AccGyro * + StabAccGyroMagn * + AccGyroRotMat * + Quaternion * See the DataType struct for more details. */ StartDataStreamMsg(uint8_t data_type = DataType::AccGyro): ImuMsg() { assert(DataType::check_data_type(data_type) && "This data type is not supported."); // Set continuous mode: command_.resize(4); command_[0] = 0xc4 ; // header command_[1] = 0xc1 ; // user confirmation 1 command_[2] = 0x29 ; // user confirmation 2 command_[3] = DataType::AccGyro; /** * Reply */ reply_.resize(8); } }; /** * @brief This class allows us to ask for the data steam to stop. */ class StopDataStreamMsg: public ImuMsg { public: /** * @brief Construct a new StopDataStreamMsg object */ StopDataStreamMsg(): ImuMsg() { if(1) // reuse the set continuous mode message (get a reply) { // Set continuous mode: command_.resize(4); command_[0] = 0xc4 ; // header command_[1] = 0xc1 ; // user confirmation 1 command_[2] = 0x29 ; // user confirmation 2 command_[3] = 0; // here we deactivate the continuous mode with this 0 /** * Reply */ reply_.resize(8); }else // use the stop continuous mode message (No reply) { // Stop continuous mode: command_.resize(3); command_[0] = 0xfa ; // header command_[1] = 0x75 ; // user confirmation 1 command_[2] = 0xb4 ; // user confirmation 2 /** * No reply */ reply_.clear(); } } }; /** * @brief Message requesting the soft reset of the imu. */ class ResetMsg: public ImuMsg { public: ResetMsg(): ImuMsg() { // Acceleration and angular rate: command_.resize(3); command_[0] = 0xfa; command_[0] = 0x75; command_[0] = 0xb4; /** * No reply */ reply_.clear(); } }; /** * @brief Message requesting the Accelerometer and Gyroscope measurements. */ class AccGyroMsg: public ImuMsg { public: AccGyroMsg(): ImuMsg() { // Acceleration and angular rate: command_.resize(1); command_[0] = 0xc2; /** * Reply */ reply_.resize(31); } }; /** * @brief Message requesting the Stabilized Accelerometer, Gyroscope and * Magnetometer measurements. */ class StabAccGyroMagnMsg: public ImuMsg { public: StabAccGyroMagnMsg(): ImuMsg() { // Stabilized acceleration, angular rate and magnetometer: command_.resize(1); command_[0] = 0xd2; /** * Reply */ reply_.resize(43); } }; /** * @brief Message requesting the Accelerometer, Gyroscope and rotation matrix * measurements. */ class AccGyroRotMatMsg: public ImuMsg { public: AccGyroRotMatMsg(): ImuMsg() { // Acceleration, angular rate and orientation matrix: command_.resize(1); command_[0] = 0xc8; /** * Reply */ reply_.resize(67); } }; /** * @brief Message requesting the quaternion measurement. */ class QuaternionMsg: public ImuMsg { public: QuaternionMsg(): ImuMsg() { // Quaternion: command_.resize(1); command_[0] = 0xdf; /** * Reply */ reply_.resize(23); } }; } // namespace imu_3DM_GX3_25 } // namespace imu_core #endif // IMU_3DM_GX3_25_MSG_HPP
28.684211
85
0.641143
[ "object", "vector" ]
c660e9bf5b1dd6c8f8eac78174061678020c9b13
1,609
cpp
C++
main/binary-tree-preorder-traversal/binary-tree-preorder-traversal-fromgeneral.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
main/binary-tree-preorder-traversal/binary-tree-preorder-traversal-fromgeneral.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
main/binary-tree-preorder-traversal/binary-tree-preorder-traversal-fromgeneral.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> preorderTraversal(const TreeNode* root); }; namespace { template<typename FPre, typename FIn, typename FPost> void traverse(const TreeNode* root, FPre f_pre, FIn f_in, FPost f_post) { stack<const TreeNode*> nodes; const TreeNode* post {}; while (root || !nodes.empty()) { // Go left as far as possbile, doing the preorder action. for (; root; root = root->left) { f_pre(root->val); nodes.push(root); } const auto cur = nodes.top(); if (!cur->right || cur->right != post) { // We just came from the left subtree. Do the inorder action. f_in(cur->val); } if (cur->right && cur->right != post) { // We can visit the right subtree but haven't. Do that. root = cur->right; } else { // Retreat and do the postorder action. post = cur; nodes.pop(); f_post(post->val); } } } constexpr auto noop = [](auto) noexcept { }; } vector<int> Solution::preorderTraversal(const TreeNode* root) { vector<int> ret; traverse(root, [&ret](const auto val) { ret.push_back(val); }, noop, noop); return ret; }
28.22807
79
0.502175
[ "vector" ]
c66108ab8809c754f430de9f3fc4d0c7f246ba9e
4,072
cpp
C++
Source/Sentry/Private/IOS/Infrastructure/SentryConvertorsIOS.cpp
getsentry/sentry-unreal
052690dd2773cc45fe56d67c677c451e596c86d8
[ "MIT" ]
6
2022-03-03T17:09:23.000Z
2022-03-25T11:53:18.000Z
Source/Sentry/Private/IOS/Infrastructure/SentryConvertorsIOS.cpp
getsentry/sentry-unreal
052690dd2773cc45fe56d67c677c451e596c86d8
[ "MIT" ]
2
2022-03-18T14:35:42.000Z
2022-03-22T18:25:41.000Z
Source/Sentry/Private/IOS/Infrastructure/SentryConvertorsIOS.cpp
getsentry/sentry-unreal
052690dd2773cc45fe56d67c677c451e596c86d8
[ "MIT" ]
null
null
null
// Copyright (c) 2022 Sentry. All Rights Reserved. #include "SentryConvertorsIOS.h" #include "SentryScope.h" #include "SentryId.h" #include "SentryDefines.h" #include "IOS/SentryScopeIOS.h" #include "IOS/SentryIdIOS.h" SentryLevel SentryConvertorsIOS::SentryLevelToNative(ESentryLevel level) { SentryLevel nativeLevel = kSentryLevelDebug; switch (level) { case ESentryLevel::Debug: nativeLevel = kSentryLevelDebug; break; case ESentryLevel::Info: nativeLevel = kSentryLevelInfo; break; case ESentryLevel::Warning: nativeLevel = kSentryLevelWarning; break; case ESentryLevel::Error: nativeLevel = kSentryLevelError; break; case ESentryLevel::Fatal: nativeLevel = kSentryLevelFatal; break; default: UE_LOG(LogSentrySdk, Warning, TEXT("Unknown sentry level value used. Debug will be returned.")); } return nativeLevel; } NSDictionary* SentryConvertorsIOS::StringMapToNative(const TMap<FString, FString>& map) { NSMutableDictionary* dict = [NSMutableDictionary dictionaryWithCapacity:map.Num()]; for (auto it = map.CreateConstIterator(); it; ++it) { [dict setValue:it.Value().GetNSString() forKey:it.Key().GetNSString()]; } return dict; } NSArray* SentryConvertorsIOS::StringArrayToNative(const TArray<FString>& array) { NSMutableArray *arr = [NSMutableArray arrayWithCapacity:array.Num()]; for (auto it = array.CreateConstIterator(); it; ++it) { [arr addObject:it->GetNSString()]; } return arr; } NSData* SentryConvertorsIOS::ByteDataToNative(const TArray<uint8>& array) { return [NSData dataWithBytes:array.GetData() length:array.Num()]; } ESentryLevel SentryConvertorsIOS::SentryLevelToUnreal(SentryLevel level) { ESentryLevel unrealLevel = ESentryLevel::Debug; switch (level) { case kSentryLevelDebug: unrealLevel = ESentryLevel::Debug; break; case kSentryLevelInfo: unrealLevel = ESentryLevel::Info; break; case kSentryLevelWarning: unrealLevel = ESentryLevel::Warning; break; case kSentryLevelError: unrealLevel = ESentryLevel::Error; break; case kSentryLevelFatal: unrealLevel = ESentryLevel::Fatal; break; default: UE_LOG(LogSentrySdk, Warning, TEXT("Unknown sentry level value used. Debug will be returned.")); } return unrealLevel; } TMap<FString, FString> SentryConvertorsIOS::StringMapToUnreal(NSDictionary* dict) { TMap<FString, FString> map; for(id key in dict) { map.Add(FString(key), FString(dict[key])); } return map; } TArray<FString> SentryConvertorsIOS::StringArrayToUnreal(NSArray* array) { TArray<FString> arr; for (id object in array) { arr.Add(FString(object)); } return arr; } TArray<uint8> SentryConvertorsIOS::ByteDataToUnreal(NSData* data) { TArray<uint8> ByteData; uint8* ByteArray = (uint8*)data.bytes; for (int i = 0; i < data.length; i++) { ByteData.Add(ByteArray[i]); } return ByteData; } USentryScope* SentryConvertorsIOS::SentryScopeToUnreal(SentryScope* scope) { TSharedPtr<SentryScopeIOS> scopeNativeImpl = MakeShareable(new SentryScopeIOS(scope)); USentryScope* unrealScope = NewObject<USentryScope>(); unrealScope->InitWithNativeImpl(scopeNativeImpl); return unrealScope; } USentryId* SentryConvertorsIOS::SentryIdToUnreal(SentryId* id) { TSharedPtr<SentryIdIOS> idNativeImpl = MakeShareable(new SentryIdIOS(id)); USentryId* unrealId = NewObject<USentryId>(); unrealId->InitWithNativeImpl(idNativeImpl); return unrealId; } SentryLevel SentryConvertorsIOS::StringToSentryLevel(NSString* string) { SentryLevel nativeLevel = kSentryLevelDebug; if ([string isEqualToString:@"debug"]) { nativeLevel = kSentryLevelDebug; } else if ([string isEqualToString:@"info"]) { nativeLevel = kSentryLevelInfo; } else if ([string isEqualToString:@"warning"]) { nativeLevel = kSentryLevelWarning; } else if ([string isEqualToString:@"error"]) { nativeLevel = kSentryLevelError; } else if ([string isEqualToString:@"fatal"]) { nativeLevel = kSentryLevelFatal; } else { UE_LOG(LogSentrySdk, Warning, TEXT("Unknown sentry level value used. Debug will be returned.")); } return nativeLevel; }
23.402299
98
0.751965
[ "object" ]
c6648a763654bf439706f68508cfc5ae81b09e2b
10,910
cc
C++
libtransport/src/auth/verifier.cc
manang/hicn
006c9aec768d5ff80fed0bf36cc51990f7fa1d8e
[ "Apache-2.0" ]
null
null
null
libtransport/src/auth/verifier.cc
manang/hicn
006c9aec768d5ff80fed0bf36cc51990f7fa1d8e
[ "Apache-2.0" ]
null
null
null
libtransport/src/auth/verifier.cc
manang/hicn
006c9aec768d5ff80fed0bf36cc51990f7fa1d8e
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <hicn/transport/auth/verifier.h> #include <protocols/errors.h> extern "C" { #ifndef _WIN32 TRANSPORT_CLANG_DISABLE_WARNING("-Wextern-c-compat") #endif #include <hicn/hicn.h> } #include <sys/stat.h> using namespace std; namespace transport { namespace auth { const std::vector<VerificationPolicy> Verifier::DEFAULT_FAILED_POLICIES = { VerificationPolicy::DROP, VerificationPolicy::ABORT, }; Verifier::Verifier() : hasher_(nullptr), verifier_(nullptr), verification_failed_cb_(interface::VOID_HANDLER), failed_policies_(DEFAULT_FAILED_POLICIES) { parcSecurity_Init(); PARCInMemoryVerifier *in_memory_verifier = parcInMemoryVerifier_Create(); verifier_ = parcVerifier_Create(in_memory_verifier, PARCInMemoryVerifierAsVerifier); parcInMemoryVerifier_Release(&in_memory_verifier); } Verifier::~Verifier() { if (hasher_) parcCryptoHasher_Release(&hasher_); if (verifier_) parcVerifier_Release(&verifier_); parcSecurity_Fini(); } bool Verifier::verifyPacket(PacketPtr packet) { bool valid_packet = false; core::Packet::Format format = packet->getFormat(); if (!packet->authenticationHeader()) { throw errors::MalformedAHPacketException(); } // Get crypto suite and hash type auto suite = static_cast<PARCCryptoSuite>(packet->getValidationAlgorithm()); PARCCryptoHashType hash_type = parcCryptoSuite_GetCryptoHash(suite); // Copy IP+TCP / ICMP header before zeroing them hicn_header_t header_copy; hicn_packet_copy_header(format, packet->packet_start_, &header_copy, false); // Fetch packet signature uint8_t *packet_signature = packet->getSignature(); size_t signature_len = Verifier::getSignatureSize(packet); vector<uint8_t> signature_raw(packet_signature, packet_signature + signature_len); // Create a signature buffer from the raw packet signature PARCBuffer *bits = parcBuffer_Wrap(signature_raw.data(), signature_len, 0, signature_len); parcBuffer_Rewind(bits); // If the signature algo is ECDSA, the signature might be shorter than the // signature field PARCSigningAlgorithm algo = parcCryptoSuite_GetSigningAlgorithm(suite); if (algo == PARCSigningAlgorithm_ECDSA) { while (parcBuffer_HasRemaining(bits) && parcBuffer_GetUint8(bits) == 0) ; parcBuffer_SetPosition(bits, parcBuffer_Position(bits) - 1); } if (!parcBuffer_HasRemaining(bits)) { parcBuffer_Release(&bits); return false; } // Create a signature object from the signature buffer PARCSignature *signature = parcSignature_Create( parcCryptoSuite_GetSigningAlgorithm(suite), hash_type, bits); // Fetch the key to verify the signature KeyId key_buffer = packet->getKeyId(); PARCBuffer *buffer = parcBuffer_Wrap(key_buffer.first, key_buffer.second, 0, key_buffer.second); PARCKeyId *key_id = parcKeyId_Create(buffer); // Reset fields that are not used to compute signature packet->resetForHash(); // Compute the packet hash if (!hasher_) setHasher(parcVerifier_GetCryptoHasher(verifier_, key_id, hash_type)); CryptoHash local_hash = computeHash(packet); // Compare the packet signature to the locally computed one valid_packet = parcVerifier_VerifyDigestSignature( verifier_, key_id, local_hash.hash_, suite, signature); // Restore the fields that were reset hicn_packet_copy_header(format, &header_copy, packet->packet_start_, false); // Release allocated objects parcBuffer_Release(&buffer); parcKeyId_Release(&key_id); parcSignature_Release(&signature); parcBuffer_Release(&bits); return valid_packet; } vector<VerificationPolicy> Verifier::verifyPackets( const vector<PacketPtr> &packets) { vector<VerificationPolicy> policies(packets.size(), VerificationPolicy::DROP); for (unsigned int i = 0; i < packets.size(); ++i) { if (verifyPacket(packets[i])) { policies[i] = VerificationPolicy::ACCEPT; } callVerificationFailedCallback(packets[i], policies[i]); } return policies; } vector<VerificationPolicy> Verifier::verifyPackets( const vector<PacketPtr> &packets, const unordered_map<Suffix, HashEntry> &suffix_map) { vector<VerificationPolicy> policies(packets.size(), VerificationPolicy::UNKNOWN); for (unsigned int i = 0; i < packets.size(); ++i) { uint32_t suffix = packets[i]->getName().getSuffix(); auto manifest_hash = suffix_map.find(suffix); if (manifest_hash != suffix_map.end()) { CryptoHashType hash_type = manifest_hash->second.first; CryptoHash packet_hash = packets[i]->computeDigest(hash_type); if (!CryptoHash::compareBinaryDigest( packet_hash.getDigest<uint8_t>().data(), manifest_hash->second.second.data(), hash_type)) { policies[i] = VerificationPolicy::ABORT; } else { policies[i] = VerificationPolicy::ACCEPT; } } callVerificationFailedCallback(packets[i], policies[i]); } return policies; } void Verifier::addKey(PARCKey *key) { parcVerifier_AddKey(verifier_, key); } void Verifier::setHasher(PARCCryptoHasher *hasher) { parcAssertNotNull(hasher, "Expected non-null hasher"); if (hasher_) parcCryptoHasher_Release(&hasher_); hasher_ = parcCryptoHasher_Acquire(hasher); } void Verifier::setVerificationFailedCallback( VerificationFailedCallback verfication_failed_cb, const vector<VerificationPolicy> &failed_policies) { verification_failed_cb_ = verfication_failed_cb; failed_policies_ = failed_policies; } void Verifier::getVerificationFailedCallback( VerificationFailedCallback **verfication_failed_cb) { *verfication_failed_cb = &verification_failed_cb_; } size_t Verifier::getSignatureSize(const PacketPtr packet) { return packet->getSignatureSize(); } CryptoHash Verifier::computeHash(PacketPtr packet) { parcAssertNotNull(hasher_, "Expected non-null hasher"); CryptoHasher crypto_hasher(hasher_); const utils::MemBuf &header_chain = *packet; const utils::MemBuf *current = &header_chain; crypto_hasher.init(); do { crypto_hasher.updateBytes(current->data(), current->length()); current = current->next(); } while (current != &header_chain); return crypto_hasher.finalize(); } void Verifier::callVerificationFailedCallback(PacketPtr packet, VerificationPolicy &policy) { if (verification_failed_cb_ == interface::VOID_HANDLER) { return; } if (find(failed_policies_.begin(), failed_policies_.end(), policy) != failed_policies_.end()) { policy = verification_failed_cb_( static_cast<const core::ContentObject &>(*packet), make_error_code( protocol::protocol_error::signature_verification_failed)); } } bool VoidVerifier::verifyPacket(PacketPtr packet) { return true; } vector<VerificationPolicy> VoidVerifier::verifyPackets( const vector<PacketPtr> &packets) { return vector<VerificationPolicy>(packets.size(), VerificationPolicy::ACCEPT); } vector<VerificationPolicy> VoidVerifier::verifyPackets( const vector<PacketPtr> &packets, const unordered_map<Suffix, HashEntry> &suffix_map) { return vector<VerificationPolicy>(packets.size(), VerificationPolicy::ACCEPT); } AsymmetricVerifier::AsymmetricVerifier(PARCKey *pub_key) { addKey(pub_key); } AsymmetricVerifier::AsymmetricVerifier(const string &cert_path) { setCertificate(cert_path); } void AsymmetricVerifier::setCertificate(const string &cert_path) { PARCCertificateFactory *factory = parcCertificateFactory_Create( PARCCertificateType_X509, PARCContainerEncoding_PEM); struct stat buffer; if (stat(cert_path.c_str(), &buffer) != 0) { throw errors::RuntimeException("Certificate does not exist"); } PARCCertificate *certificate = parcCertificateFactory_CreateCertificateFromFile(factory, cert_path.c_str(), NULL); PARCKey *key = parcCertificate_GetPublicKey(certificate); addKey(key); parcKey_Release(&key); parcCertificateFactory_Release(&factory); } SymmetricVerifier::SymmetricVerifier(const string &passphrase) : passphrase_(nullptr), signer_(nullptr) { setPassphrase(passphrase); } SymmetricVerifier::~SymmetricVerifier() { if (passphrase_) parcBuffer_Release(&passphrase_); if (signer_) parcSigner_Release(&signer_); } void SymmetricVerifier::setPassphrase(const string &passphrase) { if (passphrase_) parcBuffer_Release(&passphrase_); PARCBufferComposer *composer = parcBufferComposer_Create(); parcBufferComposer_PutString(composer, passphrase.c_str()); passphrase_ = parcBufferComposer_ProduceBuffer(composer); parcBufferComposer_Release(&composer); } void SymmetricVerifier::setSigner(const PARCCryptoSuite &suite) { parcAssertNotNull(passphrase_, "Expected non-null passphrase"); if (signer_) parcSigner_Release(&signer_); PARCSymmetricKeyStore *key_store = parcSymmetricKeyStore_Create(passphrase_); PARCSymmetricKeySigner *key_signer = parcSymmetricKeySigner_Create( key_store, parcCryptoSuite_GetCryptoHash(suite)); signer_ = parcSigner_Create(key_signer, PARCSymmetricKeySignerAsSigner); PARCKeyId *key_id = parcSigner_CreateKeyId(signer_); PARCKey *key = parcKey_CreateFromSymmetricKey( key_id, parcSigner_GetSigningAlgorithm(signer_), passphrase_); addKey(key); setHasher(parcSigner_GetCryptoHasher(signer_)); parcSymmetricKeyStore_Release(&key_store); parcSymmetricKeySigner_Release(&key_signer); parcKeyId_Release(&key_id); parcKey_Release(&key); } vector<VerificationPolicy> SymmetricVerifier::verifyPackets( const vector<PacketPtr> &packets) { vector<VerificationPolicy> policies(packets.size(), VerificationPolicy::DROP); for (unsigned int i = 0; i < packets.size(); ++i) { auto suite = static_cast<PARCCryptoSuite>(packets[i]->getValidationAlgorithm()); if (!signer_ || suite != parcSigner_GetCryptoSuite(signer_)) { setSigner(suite); } if (verifyPacket(packets[i])) { policies[i] = VerificationPolicy::ACCEPT; } callVerificationFailedCallback(packets[i], policies[i]); } return policies; } } // namespace auth } // namespace transport
32.470238
80
0.736664
[ "object", "vector" ]
c669f77d50fc85917d2eec24faba14e80b9721a6
2,586
cpp
C++
src/atcoder/apg4b/apg4b_ai/main_0.cpp
kzmsh/compete
5cbe8062689a10bd81c97612b800fd434d93aa3f
[ "MIT" ]
null
null
null
src/atcoder/apg4b/apg4b_ai/main_0.cpp
kzmsh/compete
5cbe8062689a10bd81c97612b800fd434d93aa3f
[ "MIT" ]
null
null
null
src/atcoder/apg4b/apg4b_ai/main_0.cpp
kzmsh/compete
5cbe8062689a10bd81c97612b800fd434d93aa3f
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <vector> using namespace std; int main() { { vector<int> a = {3, 1, 5, 6, 7, 2, 4}; auto iter_1 = a.begin(); iter_1 = iter_1 + 2; auto iter_2 = iter_1 + 4; cout << *iter_1 << endl; cout << *iter_2 << endl; } { vector<string> a = {"kz", "to", "yk"}; for (auto iter = a.begin(); iter != a.end(); ++iter) { cout << *iter << endl; } } { vector<int> vec = {1, 2, 3, 4, 5}; auto iter_1 = vec.begin(); cout << *iter_1 << endl; advance(iter_1, 3); cout << *iter_1 << endl; } { vector<int> vec = {1, 2, 3, 4, 5}; auto iter_1 = vec.begin(); auto iter_2 = iter_1 + 2; cout << distance(iter_1, iter_2) << endl; cout << distance(iter_2, iter_1) << endl; } { vector<int> vec = {1, 2, 3, 4, 5}; auto iter_1 = vec.begin(); cout << *iter_1 << " = 1" << endl; auto iter_2 = next(iter_1); cout << *iter_2 << " = 2" << endl; auto iter_3 = next(iter_2, 2); cout << *iter_3 << " = 4" << endl; auto iter_4 = prev(iter_3); cout << *iter_4 << " = 3" << endl; auto iter_5 = prev(iter_4, 2); cout << *iter_5 << " = 1" << endl; // runtime error // auto iter_6 = prev(iter_5, 4); // cout << *iter_6 << " = 5" << endl; } { vector<int> vec = {3, 1, 5, 6, 77, 91, 13, 45, 362}; sort(vec.begin(), vec.end()); for (auto i = vec.begin(); i != vec.end(); ++i) { cout << *i; if (i < vec.end() - 1) { cout << " "; } } cout << endl; } { vector<int> a = {1, 3, 4, 5, 9, 10}; auto iter = find_if(a.begin(), a.end(), [](int x) { return (x % 2 == 0); }); if (iter == a.end()) { cout << "not found" << endl; } else { cout << *iter << endl; } } { vector<int> vec = {53, 13, 62, 91, 45, 33, 12, 1, 97, 76, 48}; sort(vec.begin(), vec.end()); auto iter = lower_bound(vec.begin(), vec.end(), 5); if (iter == vec.end()) { cout << "not found" << endl; } else { cout << *iter << endl; } iter = lower_bound(vec.begin(), vec.end(), 34); if (iter == vec.end()) { cout << "not found" << endl; } else { cout << *iter << endl; } } }
23.509091
84
0.402552
[ "vector" ]
c66c04ff852b3a6e3f716aba4eb5a6efcd991119
172
cc
C++
SME_RF24Communicator/SME_HomeControl/SME_Remote/RF24_Addon.cc
Stephan1973/SME_RF24Communicator
9ab34def08d4b04e7294519c48b982040126338c
[ "MIT" ]
null
null
null
SME_RF24Communicator/SME_HomeControl/SME_Remote/RF24_Addon.cc
Stephan1973/SME_RF24Communicator
9ab34def08d4b04e7294519c48b982040126338c
[ "MIT" ]
null
null
null
SME_RF24Communicator/SME_HomeControl/SME_Remote/RF24_Addon.cc
Stephan1973/SME_RF24Communicator
9ab34def08d4b04e7294519c48b982040126338c
[ "MIT" ]
null
null
null
#include <node.h> #include "RF24_Wrapper.h" using namespace v8; void InitAll(Handle<Object> exports) { RF24_Wrapper::Init(exports); } NODE_MODULE(RF24_Addon, InitAll)
15.636364
38
0.75
[ "object" ]
c66d564861282ac952cff0a71dcf471b35ad5ccc
22,735
cpp
C++
tests/old/redist.cpp
tpeterka/decaf
ad6ad823070793bfd7fc8d9384d5475f7cf20848
[ "BSD-3-Clause" ]
1
2019-05-10T02:50:50.000Z
2019-05-10T02:50:50.000Z
tests/old/redist.cpp
tpeterka/decaf
ad6ad823070793bfd7fc8d9384d5475f7cf20848
[ "BSD-3-Clause" ]
2
2020-10-28T03:44:51.000Z
2021-01-18T19:49:33.000Z
tests/old/redist.cpp
tpeterka/decaf
ad6ad823070793bfd7fc8d9384d5475f7cf20848
[ "BSD-3-Clause" ]
2
2018-08-31T14:02:47.000Z
2020-04-17T16:01:54.000Z
//--------------------------------------------------------------------------- // // example of redistribution with FFS (not supported anymore) // // Matthieu Dreher // Argonne National Laboratory // 9700 S. Cass Ave. // Argonne, IL 60439 // mdreher@anl.gov // //-------------------------------------------------------------------------- #include <decaf/decaf.hpp> #include <bredala/transport/mpi/redist_count_mpi.h> #include <bredala/transport/mpi/types.h> #include "ffs.h" #include "fm.h" #include <assert.h> #include <math.h> #include <stddef.h> #include <stdint.h> #include <mpi.h> using namespace decaf; typedef struct particules { int nbParticules; int sizeArray; float *x; float *v; particules(int nb = 0) //To test if we can switch array for vector with FFS { nbParticules = nb; sizeArray = nb * 3; if(nbParticules > 0){ x = (float*)malloc(sizeArray * sizeof(float)); v = (float*)malloc(sizeArray * sizeof(float)); } } particules(int nb, float* x_, float* v_) { nbParticules = nb; sizeArray = nb * 3; x = x_; v = v_; } ~particules() { free(x); free(v); } } *particule_ptr; FMField particule_list[] = { {"nbParticules", "integer", sizeof(int), FMOffset(particule_ptr, nbParticules)}, {"sizeArray", "integer", sizeof(int), FMOffset(particule_ptr, sizeArray)}, {"positions", "float[sizeArray]", sizeof(float), FMOffset(particule_ptr, x)}, {"speed", "float[sizeArray]", sizeof(float), FMOffset(particule_ptr, v)}, { NULL, NULL, 0, 0}, }; FMStructDescRec particule_format_list[]= { {"particule", particule_list, sizeof(particules), NULL}, { NULL, NULL, 0, NULL}, }; typedef struct _block { int count; particules *p; } block, *block_ptr; FMField block_list[] = { {"count", "integer", sizeof(int), FMOffset(block_ptr, count)}, {"particules", "particule[count]", sizeof(particules), FMOffset(block_ptr, p)}, { NULL, NULL, 0, 0}, }; FMStructDescRec block_format_list[]= { {"block", block_list, sizeof(block), NULL}, {"particule", particule_list, sizeof(particules), NULL}, { NULL, NULL, 0, NULL}, }; class ParticuleType : public BaseData { public: ParticuleType(std::shared_ptr<void> data = std::shared_ptr<void>()) : buffer_(NULL), // Buffer use for the serialization size_buffer_(0), BaseData(data), p(NULL) { if(data) { p = (particules*)(data.get()); nbItems_ = p->nbParticules; nbItems_ > 1 ? splitable_ = true: splitable_ = false; //nbElements_ = 1; } } virtual ~ParticuleType(){} virtual void purgeData() { nbItems_ = 0; splitable_ = false; data_ = std::shared_ptr<void>(); } // Return true is some field in the data can be used to // compute a Z curve (should be a float* field) virtual bool hasZCurveKey() { if(p == NULL) return false; return true; } // Extract the field containing the positions to compute // the ZCurve. virtual const float* getZCurveKey(int *nbItems) { if(p == NULL) return NULL; *nbItems = nbItems_; return p->x; } virtual bool hasZCurveIndex(){ return false; } virtual bool isSystem(){ return false; } virtual const unsigned int* getZCurveIndex(int *nbItems) { *nbItems = nbItems_; return NULL; } // Return true if the data contains more than 1 item virtual bool isSplitable() { //We need at least 3 elements in the arrays for one particule if(p == NULL || p->nbParticules < 1) return false; return true; } virtual std::vector<std::shared_ptr<BaseData> > split( const std::vector<int>& range) { std::vector<std::shared_ptr<BaseData> > result; if(p == NULL) return result; //Sanity check unsigned int sum = 0; for(unsigned int i = 0; i < range.size(); i++) sum += range.at(i); if(sum != nbItems_) { std::cerr<<"ERROR in class ParticuleType, the sum of ranges " <<sum<<" does not match the number of items ("<<nbItems_<<" available."<<std::endl; return result; } int currentLocalItem = 0; for(unsigned int i = 0; i < range.size(); i++) { //Generate the structure and allocate the arrays std::shared_ptr<particules> newParticules = std::make_shared<particules>(range.at(i)); //Filling the structure //WARNING : DANGEROUS CODE memcpy(newParticules->x, p->x + (currentLocalItem * 3), range.at(i) * 3 * sizeof(float)); memcpy(newParticules->v, p->v + (currentLocalItem * 3), range.at(i) * 3 * sizeof(float)); currentLocalItem += range.at(i); std::shared_ptr<BaseData> particuleOnject = make_shared<ParticuleType>(newParticules); result.push_back(particuleOnject); } return result; } // Split the data in range.size() groups. The group i contains the items // with the indexes from range[i] // WARNING : All the indexes of the data should be included virtual std::vector< std::shared_ptr<BaseData> > split( const std::vector<std::vector<int> >& range) { std::vector< std::shared_ptr<BaseData> > result; return result; } virtual bool merge(shared_ptr<BaseData> other) { return true; } // Insert the data from other in its serialize form virtual bool merge(char* buffer, int size) { std::cout<<"Merging the data..."<<std::endl; FFSTypeHandle first_rec_handle; FFSContext fmc_r = create_FFSContext(); first_rec_handle = FFSset_fixed_target(fmc_r, &particule_format_list[0]); //buffer_ = serialdata; //size_buffer_ = size; std::cout<<"Serial buffer size : "<<size<<std::endl; shared_ptr<void> decode_buffer; //We don't already have a data. Filling the structure if(!data_) { std::cout<<"No data available in the current object, create one"<<std::endl; data_ = shared_ptr<void>(new char[sizeof(particules)], std::default_delete<char[]>()); decode_buffer = data_; std::cout<<"Decoding..."<<std::endl; FFSdecode(fmc_r, buffer, (char*)decode_buffer.get()); std::cout<<"Decoding successful"<<std::endl; p = (particules*)(data_.get()); //nbElements_ = 1; nbItems_ = p->nbParticules; nbItems_ > 1 ? splitable_ = true: splitable_ = false; } else //We have to decode elsewhere since the data will be appended //to the current data buffer { std::cout<<"Data available in the current object, create one extra buffer"<<std::endl; decode_buffer = shared_ptr<void>(new char[sizeof(particules)], std::default_delete<char[]>()); std::cout<<"Decoding..."<<std::endl; FFSdecode(fmc_r, buffer, (char*)decode_buffer.get()); std::cout<<"Decoding successful"<<std::endl; particules* otherParticule = (particules*)(decode_buffer.get()); //Can't realloc the array, we have to deep copy the data //Creating the new object std::shared_ptr<particules> new_particule = make_shared<particules>(p->nbParticules + otherParticule->nbParticules); std::cout<<"The new data has "<<new_particule->nbParticules<<" particules"<<std::endl; //Copying the data from the original structure memcpy(new_particule->x, p->x, p->sizeArray * sizeof(float)); memcpy(new_particule->v, p->v, p->sizeArray * sizeof(float)); //Copying the other structure memcpy(new_particule->x + p->nbParticules * 3, otherParticule->x, otherParticule->sizeArray * sizeof(float)); memcpy(new_particule->v+ p->nbParticules * 3, otherParticule->v, otherParticule->sizeArray * sizeof(float)); //No need to free the former data, the shared pointer take care of this data_ = static_pointer_cast<void>(new_particule); p = (particules*)(data_.get()); //Updating the info of the object //nbElements_ = 1; nbItems_ = p->nbParticules; nbItems_ > 1 ? splitable_ = true: splitable_ = false; } std::cout<<"Data successfully merged"<<std::endl; return true; } virtual bool merge() { std::cout<<"Merging the data already in place"<<std::endl; FFSTypeHandle first_rec_handle; FFSContext fmc_r = create_FFSContext(); first_rec_handle = FFSset_fixed_target(fmc_r, &particule_format_list[0]); std::cout<<"Serial buffer size : "<<size_buffer_<<std::endl; shared_ptr<void> decode_buffer; //We don't already have a data. Filling the structure if(!data_) { std::cout<<"No data available in the current object, create one"<<std::endl; data_ = shared_ptr<void>(new char[sizeof(particules)], std::default_delete<char[]>()); decode_buffer = data_; std::cout<<"Decoding..."<<std::endl; FFSdecode(fmc_r, buffer_.get(), (char*)decode_buffer.get()); std::cout<<"Decoding successful"<<std::endl; p = (particules*)(data_.get()); std::cout<<"Number of particules : "<<p->nbParticules<<std::endl; //nbElements_ = 1; nbItems_ = p->nbParticules; nbItems_ > 1 ? splitable_ = true: splitable_ = false; } else //We have to decode elsewhere since the data will be appended //to the current data buffer { std::cout<<"Data available in the current object, create one extra buffer"<<std::endl; decode_buffer = shared_ptr<void>(new char[sizeof(particules)], std::default_delete<char[]>()); std::cout<<"Decoding..."<<std::endl; FFSdecode(fmc_r, buffer_.get(), (char*)decode_buffer.get()); std::cout<<"Decoding successful"<<std::endl; particules* otherParticule = (particules*)(decode_buffer.get()); //Can't realloc the array, we have to deep copy the data //Creating the new object std::shared_ptr<particules> new_particule = make_shared<particules>(p->nbParticules + otherParticule->nbParticules); std::cout<<"The new data has "<<new_particule->nbParticules<<" particules"<<std::endl; //Copying the data from the original structure memcpy(new_particule->x, p->x, p->sizeArray * sizeof(float)); memcpy(new_particule->v, p->v, p->sizeArray * sizeof(float)); //Copying the other structure memcpy(new_particule->x + p->nbParticules * 3, otherParticule->x, otherParticule->sizeArray * sizeof(float)); memcpy(new_particule->v+ p->nbParticules * 3, otherParticule->v, otherParticule->sizeArray * sizeof(float)); //No need to free the former data, the shared pointer take care of this data_ = static_pointer_cast<void>(new_particule); p = (particules*)(data_.get()); //Updating the info of the object //nbElements_ = 1; nbItems_ = p->nbParticules; nbItems_ > 1 ? splitable_ = true: splitable_ = false; } std::cout<<"Data successfully merged"<<std::endl; return true; } // Update the datamap required to generate the datatype virtual bool setData(std::shared_ptr<void> data) { // We don't have to clean the previous value because it is just // a cast to the pointer to the shared memory which is protected data_ = data; if(data_) //If we have a data { p = (particules*)(data_.get()); //nbElements_ = 1; nbItems_ = p->nbParticules; nbItems_ > 1 ? splitable_ = true: splitable_ = false; } else { p = NULL; //nbElements_ = 1; nbItems_ = 0; splitable_ = false; } return true; } virtual bool serialize() { FMContext fmc = create_FMcontext(); FFSBuffer buf = create_FFSBuffer(); FMFormat rec_format; rec_format = FMregister_data_format(fmc, particule_format_list); std::cout<<"Register of the data format completed"<<std::endl; fflush(stdout); buffer_ = shared_ptr<char>(FFSencode(buf, rec_format, p, &size_buffer_), std::default_delete<char[]>()); std::cout<<"Serialization successful (size : "<<size_buffer_<<")"<<std::endl; return true; } virtual bool unserialize() { return false; } /*virtual char* getSerialBuffer(int* size){ *size = size_buffer_; return buffer_.get();} virtual char* getSerialBuffer(){ return buffer_.get(); } virtual int getSerialBufferSize(){ return size_buffer_; }*/ virtual char* getOutSerialBuffer(int* size) { *size = size_buffer_; //+1 for the \n caractere return buffer_.get(); //Dangerous if the string gets reallocated } virtual char* getOutSerialBuffer(){ return buffer_.get(); } virtual int getOutSerialBufferSize(){ return size_buffer_;} virtual char* getInSerialBuffer(int* size) { *size = size_buffer_; //+1 for the \n caractere return buffer_.get(); //Dangerous if the string gets reallocated } virtual char* getInSerialBuffer(){ return buffer_.get(); } virtual int getInSerialBufferSize(){ return size_buffer_; } virtual void allocate_serial_buffer(int size) { buffer_ = std::shared_ptr<char>(new char[size], std::default_delete<char[]>()); size_buffer_ = size; } // Merge all the parts we have deserialized so far virtual bool mergeStoredData() { std::cerr<<"ERROR : trying to use mergeStoredData on ParticuleType. Not implemented!"<<std::endl; return false; } // Deserialize the buffer and store the result locally for a later global merge virtual void unserializeAndStore(char* buffer, int bufferSize) { std::cerr<<"ERROR : trying to use unserializeAndStore on ParticuleType. Not implemented!"<<std::endl; return ; } protected: particules *p; std::shared_ptr<char> buffer_; // Buffer use for the serialization int size_buffer_; }; // user-defined pipeliner code void pipeliner(Decaf* decaf) { } // user-defined resilience code void checker(Decaf* decaf) { } // gets command line args void GetArgs(int argc, char **argv, DecafSizes& decaf_sizes, int& prod_nsteps) { assert(argc >= 9); decaf_sizes.prod_size = atoi(argv[1]); decaf_sizes.dflow_size = atoi(argv[2]); decaf_sizes.con_size = atoi(argv[3]); decaf_sizes.prod_start = atoi(argv[4]); decaf_sizes.dflow_start = atoi(argv[5]); decaf_sizes.con_start = atoi(argv[6]); prod_nsteps = atoi(argv[7]); // user's, not decaf's variable decaf_sizes.con_nsteps = atoi(argv[8]); } void runTestSimple() { int size_world, rank; MPI_Comm_size(MPI_COMM_WORLD, &size_world); MPI_Comm_rank(MPI_COMM_WORLD, &rank); if(rank == 0){ std::cout<<"Running simple test between one producer and one consummer"<<std::endl; std::shared_ptr<particules> p = make_shared<particules>(10); for(unsigned int i = 0; i < p->sizeArray; i++) { p->v[i] = 1.0 * (float)(i+1); p->x[i] = 3.0 * (float)(i+1); } ParticuleType *part = new ParticuleType(static_pointer_cast<void>(p)); //Serializing the data and send it if(part->serialize()) { int buffer_size; const char* buffer = part->getOutSerialBuffer(&buffer_size); std::cout<<"Size of buffer to send : "<<buffer_size<<std::endl; MPI_Send(buffer, buffer_size, MPI_BYTE, 1, 0, MPI_COMM_WORLD); } else { std::cerr<<"ERROR : Enable to serialize the data."<<std::endl; MPI_Abort(MPI_COMM_WORLD, 1); } delete part; } else if(rank == 1) { std::cout<<"Reception of the encoded message"<<std::endl; MPI_Status status; MPI_Probe(0, MPI_ANY_TAG, MPI_COMM_WORLD, &status); int nitems; MPI_Get_count(&status, MPI_BYTE, &nitems); //NOTE : To modify and use allocate of the data object instead std::vector<char> buffer(nitems); MPI_Recv(&buffer[0], nitems, MPI_BYTE, status.MPI_SOURCE, status.MPI_TAG, MPI_COMM_WORLD, &status); std::cout<<"Reception of a message of size "<<nitems<<std::endl; // Creating an empty object in which we will uncode the message ParticuleType *part = new ParticuleType(); part->merge(&buffer[0], nitems); particules *p = (particules *)(part->getData().get()); std::cout<<"First set of particule------------------"<<std::endl; std::cout<<"Number of particule : "<<p->nbParticules <<std::endl; for(unsigned int i = 0; i < p->sizeArray; i+=+3){ std::cout<<"Position : ["<<p->x[i]<<","<<p->x[i+1]<<","<<p->x[i+2]<<"]"<<std::endl; std::cout<<"Speed : ["<<p->v[i]<<","<<p->v[i+1]<<","<<p->v[i+2]<<"]"<<std::endl; } std::cout<<"Simple test between one producer and one consummer completed"<<std::endl; } } void runTestSimpleRedist() { int size_world, rank; MPI_Comm_size(MPI_COMM_WORLD, &size_world); MPI_Comm_rank(MPI_COMM_WORLD, &rank); //First 2 ranks are producer, third is consumer RedistCountMPI component(0, 2, 2, 1, MPI_COMM_WORLD); std::cout<<"Redistribution component initialized."<<std::endl; if(rank == 0 or rank == 1){ std::cout<<"Running simple Redistribution test between two producers and one consummer"<<std::endl; std::shared_ptr<particules> p = make_shared<particules>(10); for(unsigned int i = 0; i < p->sizeArray; i++) { p->v[i] = (float)(i+1) + (float)rank * (float)(i+1); p->x[i] = (float)(i+1) + (float)rank * (float)(i+1); } std::shared_ptr<BaseData> data = std::shared_ptr<ParticuleType>( new ParticuleType(static_pointer_cast<void>(p))); component.process(data, decaf::DECAF_REDIST_SOURCE); } else if(rank == 2) { std::shared_ptr<ParticuleType> result = std::shared_ptr<ParticuleType>( new ParticuleType()); component.process(result, decaf::DECAF_REDIST_DEST); particules *p = (particules *)(result->getData().get()); std::cout<<"First set of particule------------------"<<std::endl; std::cout<<"Number of particule : "<<p->nbParticules<<std::endl; for(unsigned int i = 0; i < p->sizeArray; i+=+3){ std::cout<<"Position : ["<<p->x[i]<<","<<p->x[i+1]<<","<<p->x[i+2]<<"]"<<std::endl; std::cout<<"Speed : ["<<p->v[i]<<","<<p->v[i+1]<<","<<p->v[i+2]<<"]"<<std::endl; } std::cout<<"Simple test between two producers and one consummer completed"<<std::endl; } } void runTestParallelRedist(int nbSource, int nbReceptors) { int size_world, rank; MPI_Comm_size(MPI_COMM_WORLD, &size_world); MPI_Comm_rank(MPI_COMM_WORLD, &rank); if(size_world < nbSource + nbReceptors) { std::cout<<"ERROR : not enough rank for "<<nbSource<<" sources and "<<nbReceptors<<" receivers"<<std::endl; std::cout<<"World size : "<<size_world<<std::endl; return; } if(rank >= nbSource + nbReceptors) return; //First 2 ranks are producer, third is consumer RedistCountMPI component(0, nbSource, nbSource, nbReceptors, MPI_COMM_WORLD); std::cout<<"Redistribution component initialized."<<std::endl; if(rank < nbSource){ std::cout<<"Running Redistributed test between "<<nbSource<<" producers" "and "<<nbReceptors<<" consummers"<<std::endl; std::shared_ptr<particules> p = make_shared<particules>(7); for(unsigned int i = 0; i < p->sizeArray; i++) { p->v[i] = (float)(i+1) + (float)rank * (float)(i+1); p->x[i] = (float)(i+1) + (float)rank * (float)(i+1); } std::shared_ptr<BaseData> data = std::shared_ptr<ParticuleType>( new ParticuleType(static_pointer_cast<void>(p))); component.process(data, decaf::DECAF_REDIST_SOURCE); } else if(rank < nbSource + nbReceptors) { std::shared_ptr<ParticuleType> result = std::shared_ptr<ParticuleType>( new ParticuleType()); component.process(result, decaf::DECAF_REDIST_DEST); particules *p = (particules *)(result->getData().get()); std::cout<<"First set of particule------------------"<<std::endl; std::cout<<"Number of particule : "<<p->nbParticules<<std::endl; for(unsigned int i = 0; i < p->sizeArray; i+=3){ std::cout<<"Position : ["<<p->x[i]<<","<<p->x[i+1]<<","<<p->x[i+2]<<"]"<<std::endl; std::cout<<"Speed : ["<<p->v[i]<<","<<p->v[i+1]<<","<<p->v[i+2]<<"]"<<std::endl; } std::cout<<"Simple test between two producers and one consummer completed"<<std::endl; } } void run(DecafSizes& decaf_sizes, int prod_nsteps) { MPI_Init(NULL, NULL); int size_world, rank; MPI_Comm_size(MPI_COMM_WORLD, &size_world); MPI_Comm_rank(MPI_COMM_WORLD, &rank); runTestParallelRedist(2,1); MPI_Barrier(MPI_COMM_WORLD); MPI_Finalize(); } int main(int argc, char** argv) { // parse command line args DecafSizes decaf_sizes; int prod_nsteps; //GetArgs(argc, argv, decaf_sizes, prod_nsteps); // run decaf run(decaf_sizes, prod_nsteps); return 0; }
32.294034
145
0.576248
[ "object", "vector" ]
c671e150da78d72f546d9153ea0cbdda1ebcdcfc
10,484
cpp
C++
source/lightgrp.cpp
acekiller/povray
ae6837fb8625bb9ca00830f8871c90c87dd21b75
[ "Zlib" ]
1
2015-06-21T05:27:57.000Z
2015-06-21T05:27:57.000Z
source/lightgrp.cpp
binji/povray
ae6837fb8625bb9ca00830f8871c90c87dd21b75
[ "Zlib" ]
null
null
null
source/lightgrp.cpp
binji/povray
ae6837fb8625bb9ca00830f8871c90c87dd21b75
[ "Zlib" ]
null
null
null
/******************************************************************************* * lightgrp.cpp * * Implements light group utility functions. * * from Persistence of Vision Ray Tracer ('POV-Ray') version 3.7. * Copyright 1991-2003 Persistence of Vision Team * Copyright 2003-2009 Persistence of Vision Raytracer Pty. Ltd. * --------------------------------------------------------------------------- * NOTICE: This source code file is provided so that users may experiment * with enhancements to POV-Ray and to port the software to platforms other * than those supported by the POV-Ray developers. There are strict rules * regarding how you are permitted to use this file. These rules are contained * in the distribution and derivative versions licenses which should have been * provided with this file. * * These licences may be found online, linked from the end-user license * agreement that is located at http://www.povray.org/povlegal.html * --------------------------------------------------------------------------- * POV-Ray is based on the popular DKB raytracer version 2.12. * DKBTrace was originally written by David K. Buck. * DKBTrace Ver 2.0-2.12 were written by David K. Buck & Aaron A. Collins. * --------------------------------------------------------------------------- * $File: //depot/povray/smp/source/lightgrp.cpp $ * $Revision: #20 $ * $Change: 5095 $ * $DateTime: 2010/08/07 07:51:37 $ * $Author: clipka $ *******************************************************************************/ /********************************************************************************* * NOTICE * * This file is part of a BETA-TEST version of POV-Ray version 3.7. It is not * final code. Use of this source file is governed by both the standard POV-Ray * licences referred to in the copyright header block above this notice, and the * following additional restrictions numbered 1 through 4 below: * * 1. This source file may not be re-distributed without the written permission * of Persistence of Vision Raytracer Pty. Ltd. * * 2. This notice may not be altered or removed. * * 3. Binaries generated from this source file by individuals for their own * personal use may not be re-distributed without the written permission * of Persistence of Vision Raytracer Pty. Ltd. Such personal-use binaries * are not required to have a timeout, and thus permission is granted in * these circumstances only to disable the timeout code contained within * the beta software. * * 4. Binaries generated from this source file for use within an organizational * unit (such as, but not limited to, a company or university) may not be * distributed beyond the local organizational unit in which they were made, * unless written permission is obtained from Persistence of Vision Raytracer * Pty. Ltd. Additionally, the timeout code implemented within the beta may * not be disabled or otherwise bypassed in any manner. * * The following text is not part of the above conditions and is provided for * informational purposes only. * * The purpose of the no-redistribution clause is to attempt to keep the * circulating copies of the beta source fresh. The only authorized distribution * point for the source code is the POV-Ray website and Perforce server, where * the code will be kept up to date with recent fixes. Additionally the beta * timeout code mentioned above has been a standard part of POV-Ray betas since * version 1.0, and is intended to reduce bug reports from old betas as well as * keep any circulating beta binaries relatively fresh. * * All said, however, the POV-Ray developers are open to any reasonable request * for variations to the above conditions and will consider them on a case-by-case * basis. * * Additionally, the developers request your co-operation in fixing bugs and * generally improving the program. If submitting a bug-fix, please ensure that * you quote the revision number of the file shown above in the copyright header * (see the '$Revision:' field). This ensures that it is possible to determine * what specific copy of the file you are working with. The developers also would * like to make it known that until POV-Ray 3.7 is out of beta, they would prefer * to emphasize the provision of bug fixes over the addition of new features. * * Persons wishing to enhance this source are requested to take the above into * account. It is also strongly suggested that such enhancements are started with * a recent copy of the source. * * The source code page (see http://www.povray.org/beta/source/) sets out the * conditions under which the developers are willing to accept contributions back * into the primary source tree. Please refer to those conditions prior to making * any changes to this source, if you wish to submit those changes for inclusion * with POV-Ray. * *********************************************************************************/ // frame.h must always be the first POV file included (pulls in platform config) #include "backend/frame.h" #include "backend/scene/objects.h" #include "backend/shape/csg.h" #include "backend/lighting/point.h" #include "lightgrp.h" // TODO // this must be the last file included #include "base/povdebug.h" namespace pov { void Promote_Local_Lights_Recursive(CompoundObject *Object, vector<LightSource *>& Lights); /***************************************************************************** * * FUNCTION * * Promote_Local_Lights * * INPUT * * Object - CSG union object * * OUTPUT * * Modified CSG union object with local lights added to each object * * RETURNS * * AUTHOR * * Thorsten Froehlich [trf] * * DESCRIPTION * * Collects all light sources in CSG union object (only those who are direct * children of the object, not childrens children light sources - this was * taken care of before) and adds them to local light list of every object * in the CSG union. * NOTE: Only pointers are changed, the original light source is still the * one in the CSG union, and once this light source has been deallocated, * the pointers will be invalid. Note that because of this we do not need * to (and we may not!) free the LLight lights of each object! * * CHANGES * * Jun 2000 : Creation. * ******************************************************************************/ void Promote_Local_Lights(CSG *Object) { vector<LightSource *> lights; if(Object == NULL) return; // find all light sources in the light group and connect them to form a list int light_counter = 0; int object_counter = 0; for(vector<ObjectPtr>::iterator curObject = Object->children.begin(); curObject != Object->children.end(); curObject++) { if(((*curObject)->Type & LIGHT_GROUP_LIGHT_OBJECT) == LIGHT_GROUP_LIGHT_OBJECT) { lights.push_back((LightSource *)(*curObject)); light_counter++; } else object_counter++; } // if no lights have been found in the light group we don't need to continue, but the // user should know there are no lights (also it will continue to work as a union) if(light_counter <= 0) { ;// TODO MESSAGE Warning(0, "No light source(s) found in light group."); return; } // if no objects have been found nothing will happen at all (the light group is only wasting memory) if(object_counter <= 0) { ;// TODO MESSAGE Warning(0, "No object(s) found in light group."); return; } // allow easy promotion of lights (if this is part of another light group) Object->LLights = lights; // promote light recursively to all other objects in the CSG union Promote_Local_Lights_Recursive((CompoundObject *)Object, lights); } /***************************************************************************** * * FUNCTION * * Promote_Local_Lights_Recursive * * INPUT * * Object - compound object * Lights - local lights to add to children objects * * OUTPUT * * Modified compound object with local lights added to each object * * RETURNS * * AUTHOR * * Thorsten Froehlich [trf] * * DESCRIPTION * * Adds input list of light sources to local light list of every object in * the compound object, recursively if there are other compound objects. * NOTE: Only pointers are changed and because of this we do not need to * (and we may not!) free the LLight lights of each object! * * CHANGES * * Jun 2000 : Creation. * ******************************************************************************/ void Promote_Local_Lights_Recursive(CompoundObject *Object, vector<LightSource *>& Lights) { ObjectPtr curObject = NULL; for(vector<ObjectPtr>::iterator curObject = Object->children.begin(); curObject != Object->children.end(); curObject++) { if(!(*curObject)->LLights.empty()) { for(vector<LightSource *>::iterator i = Lights.begin(); i != Lights.end(); i++) (*curObject)->LLights.push_back(*i); } else if(((*curObject)->Type & IS_COMPOUND_OBJECT) == IS_COMPOUND_OBJECT) { // allow easy promotion of lights (if this is part of another light group) (*curObject)->LLights = Lights; Promote_Local_Lights_Recursive((CompoundObject *)(*curObject), Lights); } else { (*curObject)->LLights = Lights; } } } /***************************************************************************** * * FUNCTION * * Check_Photon_Light_Group * * INPUT * * Object - any object * * OUTPUT * * RETURNS * * True if this object is lit by the photon light (according to the light_group rules) * * * AUTHOR * * Nathan Kopp [NK] * * DESCRIPTION * * If the photon light is a global light (not in a light group) as determined by * the photonOptions object, then we just check to see if the object interacts * with global lights. * * Otherwise... * * Checks to see if Light is one of Object's local lights (part of the light * group). * * CHANGES * * Apr 2002 : Creation. * ******************************************************************************/ bool Check_Photon_Light_Group(ObjectPtr Object) { /* TODO FIXME if(photonOptions.Light_Is_Global) { if((Object->Flags & NO_GLOBAL_LIGHTS_FLAG) == NO_GLOBAL_LIGHTS_FLAG) return false; else return true; } else { for(vector<LightSource *>::iterator Test_Light = Object->LLights.begin(); Test_Light != Object->LLights.end(); Test_Light++) { if(*Test_Light == photonOptions.Light) return true; } */ return true; // } } }
33.388535
126
0.64937
[ "object", "shape", "vector" ]
c673b4a09d0d1d70f53583f92d70b9bc9f83da5e
1,760
cpp
C++
lib/analysis/ReachingDefinitions/ReachingDefinitions.cpp
davidhofman/dg
cf304a691f7063f638bd4edb66f2d8e65ccad2ec
[ "MIT" ]
1
2019-09-16T07:36:46.000Z
2019-09-16T07:36:46.000Z
lib/analysis/ReachingDefinitions/ReachingDefinitions.cpp
davidhofman/dg
cf304a691f7063f638bd4edb66f2d8e65ccad2ec
[ "MIT" ]
null
null
null
lib/analysis/ReachingDefinitions/ReachingDefinitions.cpp
davidhofman/dg
cf304a691f7063f638bd4edb66f2d8e65ccad2ec
[ "MIT" ]
null
null
null
#include <set> #include "dg/analysis/ReachingDefinitions/RDMap.h" #include "dg/analysis/ReachingDefinitions/ReachingDefinitions.h" namespace dg { namespace analysis { namespace rd { RDNode UNKNOWN_MEMLOC; RDNode *UNKNOWN_MEMORY = &UNKNOWN_MEMLOC; bool ReachingDefinitionsAnalysis::processNode(RDNode *node) { bool changed = false; // merge maps from predecessors for (RDNode *n : node->predecessors) changed |= node->def_map.merge(&n->def_map, &node->overwrites /* strong update */, options.strongUpdateUnknown, *options.maxSetSize, /* max size of set of reaching definition of one definition site */ false /* merge unknown */); return changed; } void ReachingDefinitionsAnalysis::run() { assert(getRoot() && "Do not have root"); std::vector<RDNode *> to_process = getNodes(getRoot()); std::vector<RDNode *> changed; // do fixpoint do { unsigned last_processed_num = to_process.size(); changed.clear(); for (RDNode *cur : to_process) { if (processNode(cur)) changed.push_back(cur); } if (!changed.empty()) { to_process.clear(); to_process = getNodes(changed /* starting set */, last_processed_num /* expected num */); // since changed was not empty, // the to_process must not be empty too assert(!to_process.empty()); } } while (!changed.empty()); } } // namespace rd } // namespace analysis } // namespace dg
28.852459
101
0.55
[ "vector" ]
c6852270578043d5ef4c2f7f28e2b4f61d861344
3,901
hpp
C++
library/network/broker/client.hpp
msiampou/distributed-fault-tolerant-kv-store
26dd701ef133c8f463b364e085773b551dfb98ce
[ "MIT" ]
7
2021-04-17T18:47:36.000Z
2022-03-24T13:09:21.000Z
library/network/broker/client.hpp
msiampou/efficient-kv-store
26dd701ef133c8f463b364e085773b551dfb98ce
[ "MIT" ]
null
null
null
library/network/broker/client.hpp
msiampou/efficient-kv-store
26dd701ef133c8f463b364e085773b551dfb98ce
[ "MIT" ]
null
null
null
#ifndef _LIBRARY_NETWORK_BROKER_CLIENT_HPP_ #define _LIBRARY_NETWORK_BROKER_CLIENT_HPP_ #include <iostream> #include <string> #include <random> #include "../socket/socket.hpp" /// Client class represents the broker. Broker connects to the available /// servers and communicates with them through sockets. Broker is responsible /// for sending specific requests to the connected servers. class client { public: /// 'client' constructor. Receives as arguments a port number and an ip /// address for each server, and the total number of servers. template <typename Ports, typename IPs> explicit client(Ports& no_ports, IPs& addresses, std::uint32_t max_servers) : num_servers(max_servers), sockets(max_servers), new_connections(max_servers) { // creates a socket for each server and connects. 'new_connections array // holds the socket's fd for each server connection for(std::uint32_t i=0; i<num_servers; ++i) { sockets[i].create(no_ports[i], addresses[i]); new_connections[i] = sockets[i].connect(); } } /// 'client' default destructor. ~client() = default; /// Sends data to servers to index them. Takes as arguments a container and /// 'data' and a replication factor 'k'. template <typename Container> bool send_data(Container& data, std::int32_t k) { bool ok = true; std::int32_t total_active = 0; for(auto& key:data) { // send each data to k random servers for(std::int32_t srv=0; srv<k; ++srv) { std::uint32_t srv_idx = rand()%num_servers; // send put request to 'srv_idx' server bool active = sockets[srv_idx].send_request("PUT " + key); total_active += (active) ? 1:(-1); // receive results from 'srv_idx' server auto result = sockets[srv_idx].recv_result(); // check if all data were inserted successfullly if (active) { std::cout << "SERVER " << srv_idx << ": " << result << std::endl; } else { std::cout << "SERVER " << srv_idx << ": NOT RESPONDED" << std::endl; } ok = ok && (result != "ERROR") ? true:false; } if (total_active < k) { std::cout << "WARNING MORE THAN K SERVERS SEEM TO BE DOWN.." << std::endl; ok = ok && false; } } return ok; } /// Broker runs until it receives 'E' from the user. bool run(std::int32_t k) { bool ok = true; while(1) { std::string buffer; // get command from user std::getline(std::cin, buffer); // send command to all connected servers std::int32_t total_active = num_servers; for(std::uint32_t i=0; i<num_servers; ++i) { sockets[i].send_request(buffer); auto result = sockets[i].recv_result(); if (result.empty()) { std::cout << "Received from server " << i << ": NO RESPONCE" << std::endl << std::endl; --total_active; } else { std::cout << "Received from " << "server" << i << ":" << std::endl; std::cout << result << std::endl << std::endl; } } if (total_active < k) { std::cout << "WARNING MORE THAN K SERVERS SEEM TO BE DOWN.." << std::endl; std::cout << "Cannot guarantee the correctness of the results \n" << std::endl; } // user wants to terminate the proccess. if (buffer == "E") { break; } } return ok; } private: /// Total number of servers to connect to. std::uint32_t num_servers; /// Socket's vector stores a socket class for each connection. std::vector<io::socket> sockets; /// Holds the fd of each connection. std::vector<std::int32_t> new_connections; }; #endif // _LIBRARY_NETWORK_BROKER_CLIENT_HPP_
37.509615
99
0.58908
[ "vector" ]
c689e7f622363e681398f8abc382c5ece467a117
15,271
cpp
C++
Modules/Classification/CLCore/src/mitkAbstractGlobalImageFeature.cpp
SVRTK/MITK
52252d60e42702e292d188e30f6717fe50c23962
[ "BSD-3-Clause" ]
null
null
null
Modules/Classification/CLCore/src/mitkAbstractGlobalImageFeature.cpp
SVRTK/MITK
52252d60e42702e292d188e30f6717fe50c23962
[ "BSD-3-Clause" ]
null
null
null
Modules/Classification/CLCore/src/mitkAbstractGlobalImageFeature.cpp
SVRTK/MITK
52252d60e42702e292d188e30f6717fe50c23962
[ "BSD-3-Clause" ]
null
null
null
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include <mitkAbstractGlobalImageFeature.h> #include <mitkImageCast.h> #include <mitkITKImageImport.h> #include <iterator> static void ExtractSlicesFromImages(mitk::Image::Pointer image, mitk::Image::Pointer mask, int direction, std::vector<mitk::Image::Pointer> &imageVector, std::vector<mitk::Image::Pointer> &maskVector) { typedef itk::Image< double, 2 > FloatImage2DType; typedef itk::Image< unsigned short, 2 > MaskImage2DType; typedef itk::Image< double, 3 > FloatImageType; typedef itk::Image< unsigned short, 3 > MaskImageType; FloatImageType::Pointer itkFloat = FloatImageType::New(); MaskImageType::Pointer itkMask = MaskImageType::New(); mitk::CastToItkImage(mask, itkMask); mitk::CastToItkImage(image, itkFloat); int idxA, idxB, idxC; switch (direction) { case 0: idxA = 1; idxB = 2; idxC = 0; break; case 1: idxA = 0; idxB = 2; idxC = 1; break; case 2: idxA = 0; idxB = 1; idxC = 2; break; default: idxA = 1; idxB = 2; idxC = 0; break; } auto imageSize = image->GetLargestPossibleRegion().GetSize(); FloatImageType::IndexType index3D; FloatImage2DType::IndexType index2D; FloatImage2DType::SpacingType spacing2D; spacing2D[0] = itkFloat->GetSpacing()[idxA]; spacing2D[1] = itkFloat->GetSpacing()[idxB]; for (unsigned int i = 0; i < imageSize[idxC]; ++i) { FloatImage2DType::RegionType region; FloatImage2DType::IndexType start; FloatImage2DType::SizeType size; start[0] = 0; start[1] = 0; size[0] = imageSize[idxA]; size[1] = imageSize[idxB]; region.SetIndex(start); region.SetSize(size); FloatImage2DType::Pointer image2D = FloatImage2DType::New(); image2D->SetRegions(region); image2D->Allocate(); MaskImage2DType::Pointer mask2D = MaskImage2DType::New(); mask2D->SetRegions(region); mask2D->Allocate(); unsigned long voxelsInMask = 0; for (unsigned int a = 0; a < imageSize[idxA]; ++a) { for (unsigned int b = 0; b < imageSize[idxB]; ++b) { index3D[idxA] = a; index3D[idxB] = b; index3D[idxC] = i; index2D[0] = a; index2D[1] = b; image2D->SetPixel(index2D, itkFloat->GetPixel(index3D)); mask2D->SetPixel(index2D, itkMask->GetPixel(index3D)); voxelsInMask += (itkMask->GetPixel(index3D) > 0) ? 1 : 0; } } image2D->SetSpacing(spacing2D); mask2D->SetSpacing(spacing2D); mitk::Image::Pointer tmpFloatImage = mitk::Image::New(); tmpFloatImage->InitializeByItk(image2D.GetPointer()); mitk::GrabItkImageMemory(image2D, tmpFloatImage); mitk::Image::Pointer tmpMaskImage = mitk::Image::New(); tmpMaskImage->InitializeByItk(mask2D.GetPointer()); mitk::GrabItkImageMemory(mask2D, tmpMaskImage); if (voxelsInMask > 0) { imageVector.push_back(tmpFloatImage); maskVector.push_back(tmpMaskImage); } } } std::vector<double> mitk::AbstractGlobalImageFeature::SplitDouble(std::string str, char delimiter) { std::vector<double> internal; std::stringstream ss(str); // Turn the string into a stream. std::string tok; double val; while (std::getline(ss, tok, delimiter)) { std::stringstream s2(tok); s2 >> val; internal.push_back(val); } return internal; } void mitk::AbstractGlobalImageFeature::AddQuantifierArguments(mitkCommandLineParser &parser) { std::string name = GetOptionPrefix(); parser.addArgument(name + "::minimum", name + "::min", mitkCommandLineParser::Float, "Minium Intensity for Quantification", "Defines the minimum Intensity used for Quantification", us::Any()); parser.addArgument(name + "::maximum", name + "::max", mitkCommandLineParser::Float, "Maximum Intensity for Quantification", "Defines the maximum Intensity used for Quantification", us::Any()); parser.addArgument(name + "::bins", name + "::bins", mitkCommandLineParser::Int, "Number of Bins", "Define the number of bins that is used ", us::Any()); parser.addArgument(name + "::binsize", name + "::binsize", mitkCommandLineParser::Float, "Binsize", "Define the size of the used bins", us::Any()); parser.addArgument(name + "::ignore-global-histogram", name + "::ignore-global-histogram", mitkCommandLineParser::Bool, "Ignore the global histogram Parameters", "Ignores the global histogram parameters", us::Any()); parser.addArgument(name + "::ignore-mask-for-histogram", name + "::ignore-mask", mitkCommandLineParser::Bool, "Ignore the global histogram Parameters", "Ignores the global histogram parameters", us::Any()); } void mitk::AbstractGlobalImageFeature::InitializeQuantifierFromParameters(const Image::Pointer & feature, const Image::Pointer &mask, unsigned int defaultBins) { unsigned int bins = 0; double binsize = 0; double minimum = 0; double maximum = 0; auto parsedArgs = GetParameter(); std::string name = GetOptionPrefix(); bool useGlobal = true; if (parsedArgs.count(name + "::ignore-global-histogram")) { useGlobal = false; SetUseMinimumIntensity(false); SetUseMaximumIntensity(false); SetUseBinsize(false); SetUseBins(false); } if (useGlobal) { if (parsedArgs.count("ignore-mask-for-histogram")) { bool tmp = us::any_cast<bool>(parsedArgs["ignore-mask-for-histogram"]); SetIgnoreMask(tmp); } if (parsedArgs.count("minimum-intensity")) { minimum = us::any_cast<float>(parsedArgs["minimum-intensity"]); SetMinimumIntensity(minimum); SetUseMinimumIntensity(true); } if (parsedArgs.count("maximum-intensity")) { maximum = us::any_cast<float>(parsedArgs["maximum-intensity"]); SetMaximumIntensity(maximum); SetUseMaximumIntensity(true); } if (parsedArgs.count("bins")) { bins = us::any_cast<int>(parsedArgs["bins"]); SetBins(bins); SetUseBins(true); } if (parsedArgs.count("binsize")) { binsize = us::any_cast<float>(parsedArgs["binsize"]); SetBinsize(binsize); SetUseBinsize(true); } } if (parsedArgs.count(name+"::ignore-mask-for-histogram")) { bool tmp = us::any_cast<bool>(parsedArgs[name+"::ignore-mask-for-histogram"]); SetIgnoreMask(tmp); } if (parsedArgs.count(name + "::minimum")) { minimum = us::any_cast<float>(parsedArgs[name + "::minimum"]); SetMinimumIntensity(minimum); SetUseMinimumIntensity(true); } if (parsedArgs.count(name + "::maximum")) { maximum = us::any_cast<float>(parsedArgs[name + "::maximum"]); SetMaximumIntensity(maximum); SetUseMaximumIntensity(true); } if (parsedArgs.count(name + "::bins")) { bins = us::any_cast<int>(parsedArgs[name + "::bins"]); SetBins(bins); } if (parsedArgs.count(name + "::binsize")) { binsize = us::any_cast<float>(parsedArgs[name + "::binsize"]); SetBinsize(binsize); SetUseBinsize(true); } InitializeQuantifier(feature, mask, defaultBins); } void mitk::AbstractGlobalImageFeature::InitializeQuantifier(const Image::Pointer & feature, const Image::Pointer &mask, unsigned int defaultBins) { m_Quantifier = IntensityQuantifier::New(); if (GetUseMinimumIntensity() && GetUseMaximumIntensity() && GetUseBinsize()) m_Quantifier->InitializeByBinsizeAndMaximum(GetMinimumIntensity(), GetMaximumIntensity(), GetBinsize()); else if (GetUseMinimumIntensity() && GetUseBins() && GetUseBinsize()) m_Quantifier->InitializeByBinsizeAndBins(GetMinimumIntensity(), GetBins(), GetBinsize()); else if (GetUseMinimumIntensity() && GetUseMaximumIntensity() && GetUseBins()) m_Quantifier->InitializeByMinimumMaximum(GetMinimumIntensity(), GetMaximumIntensity(), GetBins()); // Intialize from Image and Binsize else if (GetUseBinsize() && GetIgnoreMask() && GetUseMinimumIntensity()) m_Quantifier->InitializeByImageAndBinsizeAndMinimum(feature, GetMinimumIntensity(), GetBinsize()); else if (GetUseBinsize() && GetIgnoreMask() && GetUseMaximumIntensity()) m_Quantifier->InitializeByImageAndBinsizeAndMaximum(feature, GetMaximumIntensity(), GetBinsize()); else if (GetUseBinsize() && GetIgnoreMask()) m_Quantifier->InitializeByImageAndBinsize(feature, GetBinsize()); // Initialize form Image, Mask and Binsize else if (GetUseBinsize() && GetUseMinimumIntensity()) m_Quantifier->InitializeByImageRegionAndBinsizeAndMinimum(feature, mask, GetMinimumIntensity(), GetBinsize()); else if (GetUseBinsize() && GetUseMaximumIntensity()) m_Quantifier->InitializeByImageRegionAndBinsizeAndMaximum(feature, mask, GetMaximumIntensity(), GetBinsize()); else if (GetUseBinsize()) m_Quantifier->InitializeByImageRegionAndBinsize(feature, mask, GetBinsize()); // Intialize from Image and Bins else if (GetUseBins() && GetIgnoreMask() && GetUseMinimumIntensity()) m_Quantifier->InitializeByImageAndMinimum(feature, GetMinimumIntensity(), GetBins()); else if (GetUseBins() && GetIgnoreMask() && GetUseMaximumIntensity()) m_Quantifier->InitializeByImageAndMaximum(feature, GetMaximumIntensity(), GetBins()); else if (GetUseBins()) m_Quantifier->InitializeByImage(feature, GetBins()); // Intialize from Image, Mask and Bins else if (GetUseBins() && GetUseMinimumIntensity()) m_Quantifier->InitializeByImageRegionAndMinimum(feature, mask, GetMinimumIntensity(), GetBins()); else if (GetUseBins() && GetUseMaximumIntensity()) m_Quantifier->InitializeByImageRegionAndMaximum(feature, mask, GetMaximumIntensity(), GetBins()); else if (GetUseBins()) m_Quantifier->InitializeByImageRegion(feature, mask, GetBins()); // Default else if (GetIgnoreMask()) m_Quantifier->InitializeByImage(feature, GetBins()); else m_Quantifier->InitializeByImageRegion(feature, mask, defaultBins); } std::string mitk::AbstractGlobalImageFeature::GetCurrentFeatureEncoding() { return ""; } std::string mitk::AbstractGlobalImageFeature::FeatureDescriptionPrefix() { std::string output; output = m_FeatureClassName + "::"; if (m_EncodeParameters) { output += GetCurrentFeatureEncoding() + "::"; } return output; } std::string mitk::AbstractGlobalImageFeature::QuantifierParameterString() { std::stringstream ss; if (GetUseMinimumIntensity() && GetUseMaximumIntensity() && GetUseBinsize()) ss << "Min-" << GetMinimumIntensity() << "_Max-" << GetMaximumIntensity() << "_BS-" << GetBinsize(); else if (GetUseMinimumIntensity() && GetUseBins() && GetUseBinsize()) ss << "Min-" << GetMinimumIntensity() << "_Bins-" << GetBins() << "_BS-" << GetBinsize(); else if (GetUseMinimumIntensity() && GetUseMaximumIntensity() && GetUseBins()) ss << "Min-" << GetMinimumIntensity() << "_Max-" << GetMaximumIntensity() << "_Bins-" << GetBins(); // Intialize from Image and Binsize else if (GetUseBinsize() && GetIgnoreMask() && GetUseMinimumIntensity()) ss << "Min-" << GetMinimumIntensity() << "_BS-" << GetBinsize() << "_FullImage"; else if (GetUseBinsize() && GetIgnoreMask() && GetUseMaximumIntensity()) ss << "Max-" << GetMaximumIntensity() << "_BS-" << GetBinsize() << "_FullImage"; else if (GetUseBinsize() && GetIgnoreMask()) ss << "BS-" << GetBinsize() << "_FullImage"; // Initialize form Image, Mask and Binsize else if (GetUseBinsize() && GetUseMinimumIntensity()) ss << "Min-" << GetMinimumIntensity() << "_BS-" << GetBinsize(); else if (GetUseBinsize() && GetUseMaximumIntensity()) ss << "Max-" << GetMaximumIntensity() << "_BS-" << GetBinsize(); else if (GetUseBinsize()) ss << "BS-" << GetBinsize(); // Intialize from Image and Bins else if (GetUseBins() && GetIgnoreMask() && GetUseMinimumIntensity()) ss << "Min-" << GetMinimumIntensity() << "_Bins-" << GetBins() << "_FullImage"; else if (GetUseBins() && GetIgnoreMask() && GetUseMaximumIntensity()) ss << "Max-" << GetMaximumIntensity() << "_Bins-" << GetBins() << "_FullImage"; else if (GetUseBins()) ss << "Bins-" << GetBins() << "_FullImage"; // Intialize from Image, Mask and Bins else if (GetUseBins() && GetUseMinimumIntensity()) ss << "Min-" << GetMinimumIntensity() << "_Bins-" << GetBins(); else if (GetUseBins() && GetUseMaximumIntensity()) ss << "Max-" << GetMaximumIntensity() << "_Bins-" << GetBins(); else if (GetUseBins()) ss << "Bins-" << GetBins(); // Default else if (GetIgnoreMask()) ss << "Bins-" << GetBins() << "_FullImage"; else ss << "Bins-" << GetBins(); return ss.str(); } void mitk::AbstractGlobalImageFeature::CalculateFeaturesSliceWiseUsingParameters(const Image::Pointer & feature, const Image::Pointer &mask, int sliceID, FeatureListType &featureList) { m_CalculateWithParameter = true; auto result = CalculateFeaturesSlicewise(feature, mask, sliceID); featureList.insert(featureList.end(), result.begin(), result.end()); } mitk::AbstractGlobalImageFeature::FeatureListType mitk::AbstractGlobalImageFeature::CalculateFeaturesSlicewise(const Image::Pointer & feature, const Image::Pointer &mask, int sliceID) { std::vector<mitk::Image::Pointer> imageVector; std::vector<mitk::Image::Pointer> maskVector; ExtractSlicesFromImages(feature, mask,sliceID, imageVector, maskVector); std::vector<mitk::AbstractGlobalImageFeature::FeatureListType> statVector; for (std::size_t index = 0; index < imageVector.size(); ++index) { if (m_CalculateWithParameter) { FeatureListType stat; this->CalculateFeaturesUsingParameters(imageVector[index], maskVector[index], maskVector[index], stat); statVector.push_back(stat); } else { auto stat = this->CalculateFeatures(imageVector[index], maskVector[index]); statVector.push_back(stat); } } if (statVector.size() < 1) return FeatureListType(); FeatureListType statMean, statStd, result; for (std::size_t i = 0; i < statVector[0].size(); ++i) { auto cElement1 = statVector[0][i]; cElement1.first = "SliceWise Mean " + cElement1.first; cElement1.second = 0.0; auto cElement2 = statVector[0][i]; cElement2.first = "SliceWise Var. " + cElement2.first; cElement2.second = 0.0; statMean.push_back(cElement1); statStd.push_back(cElement2); } for (auto cStat : statVector) { for (std::size_t i = 0; i < cStat.size(); ++i) { statMean[i].second += cStat[i].second / (1.0*statVector.size()); } } for (auto cStat : statVector) { for (std::size_t i = 0; i < cStat.size(); ++i) { statStd[i].second += (cStat[i].second - statMean[i].second)*(cStat[i].second - statMean[i].second) / (1.0*statVector.size()); } } for (auto cStat : statVector) { std::copy(cStat.begin(), cStat.end(), std::back_inserter(result)); } std::copy(statMean.begin(), statMean.end(), std::back_inserter(result)); std::copy(statStd.begin(), statStd.end(), std::back_inserter(result)); return result; }
37.8933
218
0.677821
[ "vector" ]
c69071c0bb77539538006f1aa52de6c0b0f721c1
92,729
cpp
C++
HopsanGUI/GUIObjects/GUISystem.cpp
mjfwest/hopsan
77a0a1e69fd9588335b7e932f348972186cbdf6f
[ "Apache-2.0" ]
null
null
null
HopsanGUI/GUIObjects/GUISystem.cpp
mjfwest/hopsan
77a0a1e69fd9588335b7e932f348972186cbdf6f
[ "Apache-2.0" ]
null
null
null
HopsanGUI/GUIObjects/GUISystem.cpp
mjfwest/hopsan
77a0a1e69fd9588335b7e932f348972186cbdf6f
[ "Apache-2.0" ]
null
null
null
/*----------------------------------------------------------------------------- Copyright 2017 Hopsan Group This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. The full license is available in the file GPLv3. For details about the 'Hopsan Group' or information about Authors and Contributors see the HOPSANGROUP and AUTHORS files that are located in the Hopsan source code root directory. -----------------------------------------------------------------------------*/ //! //! @file GUISystem.cpp //! @author Flumes <flumes@lists.iei.liu.se> //! @date 2010-01-01 //! //! @brief Contains the GUI System class, representing system components //! //$Id$ #include <QMessageBox> #include <QFileDialog> #include <QInputDialog> #include "global.h" #include "GUISystem.h" #include "GraphicsView.h" #include "CoreAccess.h" #include "loadFunctions.h" #include "GUIConnector.h" #include "UndoStack.h" #include "version_gui.h" #include "LibraryHandler.h" #include "MessageHandler.h" #include "Widgets/ModelWidget.h" //#include "Dialogs/ContainerPropertiesDialog.h" #include "Utilities/GUIUtilities.h" #include "GUIObjects/GUIWidgets.h" #include "Widgets/PyDockWidget.h" #include "Configuration.h" #include "GUIContainerObject.h" #include "GUIComponent.h" #include "GUIPort.h" #include "Dialogs/ComponentPropertiesDialog3.h" #include "DesktopHandler.h" #include "GeneratorUtils.h" SystemContainer::SystemContainer(QPointF position, double rotation, const ModelObjectAppearance* pAppearanceData, ContainerObject *pParentContainer, SelectionStatusEnumT startSelected, GraphicsTypeEnumT gfxType) : ContainerObject(position, rotation, pAppearanceData, startSelected, gfxType, pParentContainer, pParentContainer) { this->mpModelWidget = pParentContainer->mpModelWidget; this->commonConstructorCode(); } //Root system specific constructor SystemContainer::SystemContainer(ModelWidget *parentModelWidget, QGraphicsItem *pParent) : ContainerObject(QPointF(0,0), 0, 0, Deselected, UserGraphics, 0, pParent) { this->mModelObjectAppearance = *(gpLibraryHandler->getModelObjectAppearancePtr(HOPSANGUISYSTEMTYPENAME)); //This will crash if Subsystem not already loaded this->mpModelWidget = parentModelWidget; this->commonConstructorCode(); this->mpUndoStack->newPost(); } void SystemContainer::deleteInHopsanCore() { this->setUndoEnabled(false, true); //The last true means DONT ASK //qDebug() << ",,,,,,,,,,,,,,,,,,,,,,,,,GUISystem destructor"; //First remove all contents this->clearContents(); if (mpParentContainerObject != 0) { mpParentContainerObject->getCoreSystemAccessPtr()->removeSubComponent(this->getName(), true); } else { mpCoreSystemAccess->deleteRootSystemPtr(); } delete mpCoreSystemAccess; } //! @brief This code is common among the two constructors, we use one function to avoid code duplication void SystemContainer::commonConstructorCode() { // Set default values mLoadType = "EMBEDED"; mNumberOfLogSamples = 2048; mLogStartTime = 0; mSaveUndoStack = false; //Do not save undo stack by default // Connect propagation signal when alias is changed connect(this, SIGNAL(aliasChanged(QString,QString)), mpModelWidget, SIGNAL(aliasChanged(QString,QString))); // Create the object in core, and update name if (this->mpParentContainerObject == 0) { //Create root system qDebug() << "creating ROOT access system"; mpCoreSystemAccess = new CoreSystemAccess(); this->setName("RootSystem"); //qDebug() << "the core root system name: " << mpCoreSystemAccess->getRootSystemName(); } else { //Create subsystem qDebug() << "creating subsystem and setting name in " << mpParentContainerObject->getCoreSystemAccessPtr()->getSystemName(); if(this->getTypeName() == HOPSANGUICONDITIONALSYSTEMTYPENAME) { mName = mpParentContainerObject->getCoreSystemAccessPtr()->createConditionalSubSystem(this->getName()); } else { mName = mpParentContainerObject->getCoreSystemAccessPtr()->createSubSystem(this->getName()); } refreshDisplayName(); qDebug() << "creating CoreSystemAccess for this subsystem, name: " << this->getName() << " parentname: " << mpParentContainerObject->getName(); mpCoreSystemAccess = new CoreSystemAccess(this->getName(), mpParentContainerObject->getCoreSystemAccessPtr()); } if(!isTopLevelContainer()) { refreshAppearance(); refreshExternalPortsAppearanceAndPosition(); refreshDisplayName(); //Make sure name window is correct size for center positioning } if(mpParentContainerObject) { connect(mpParentContainerObject, SIGNAL(showOrHideSignals(bool)), this, SLOT(setVisibleIfSignal(bool))); } } //! @brief This function sets the desired subsystem name //! @param [in] newName The new name void SystemContainer::setName(QString newName) { if (mpParentContainerObject == 0) { mName = mpCoreSystemAccess->setSystemName(newName); } else { mpParentContainerObject->renameModelObject(this->getName(), newName); } refreshDisplayName(); } //! Returns a string with the sub system type. QString SystemContainer::getTypeName() const { return mModelObjectAppearance.getTypeName(); } //! @brief Get the system cqs type //! @returns A string containing the CQS type QString SystemContainer::getTypeCQS() { return mpCoreSystemAccess->getSystemTypeCQS(); } //! @brief get The parameter names of this system //! @returns A QStringList containing the parameter names QStringList SystemContainer::getParameterNames() { return mpCoreSystemAccess->getSystemParameterNames(); } //! @brief Get a vector contain data from all parameters //! @param [out] rParameterDataVec A vector that will contain parameter data void SystemContainer::getParameters(QVector<CoreParameterData> &rParameterDataVec) { mpCoreSystemAccess->getSystemParameters(rParameterDataVec); } //! @brief Function that returns the specified parameter value //! @param name Name of the parameter to return value from QString SystemContainer::getParameterValue(const QString paramName) { return mpCoreSystemAccess->getSystemParameterValue(paramName); } bool SystemContainer::hasParameter(const QString &rParamName) { return mpCoreSystemAccess->hasSystemParameter(rParamName); } //! @brief Get parameter data for a specific parameter //! @param [out] rData The parameter data void SystemContainer::getParameter(const QString paramName, CoreParameterData &rData) { return mpCoreSystemAccess->getSystemParameter(paramName, rData); } //! @brief Get a pointer the the CoreSystemAccess object that this system is representing CoreSystemAccess* SystemContainer::getCoreSystemAccessPtr() { return mpCoreSystemAccess; } //! @brief Overloaded version that returns self if root system ContainerObject *SystemContainer::getParentContainerObject() { if (mpParentContainerObject==0) { return this; } else { return mpParentContainerObject; } } int SystemContainer::type() const { return Type; } QString SystemContainer::getHmfTagName() const { return HMF_SYSTEMTAG; } //! @brief Saves the System specific core data to XML DOM Element //! @param[in] rDomElement The DOM Element to save to void SystemContainer::saveCoreDataToDomElement(QDomElement &rDomElement, SaveContentsEnumT contents) { ModelObject::saveCoreDataToDomElement(rDomElement); if (mLoadType == "EXTERNAL" && contents == FullModel) { // Determine the relative path QFileInfo parentModelPath(mpParentContainerObject->getModelFilePath()); QString relPath = relativePath(getModelFilePath(), parentModelPath.absolutePath()); // This information should ONLY be used to indicate that a subsystem is external, it SHOULD NOT be included in the actual external system // If it would be, the load function will fail rDomElement.setAttribute( HMF_EXTERNALPATHTAG, relPath ); } if (mLoadType != "EXTERNAL" && contents == FullModel) { appendSimulationTimeTag(rDomElement, mpModelWidget->getStartTime().toDouble(), this->getTimeStep(), mpModelWidget->getStopTime().toDouble(), this->doesInheritTimeStep()); appendLogSettingsTag(rDomElement, getLogStartTime(), getNumberOfLogSamples()); } // Save the NumHop script if (!mNumHopScript.isEmpty()) { appendDomTextNode(rDomElement, HMF_NUMHOPSCRIPT, mNumHopScript); } // Save the parameter values for the system QVector<CoreParameterData> paramDataVector; this->getParameters(paramDataVector); QDomElement xmlParameters = appendDomElement(rDomElement, HMF_PARAMETERS); for(int i=0; i<paramDataVector.size(); ++i) { QDomElement xmlParameter = appendDomElement(xmlParameters, HMF_PARAMETERTAG); xmlParameter.setAttribute(HMF_NAMETAG, paramDataVector[i].mName); xmlParameter.setAttribute(HMF_VALUETAG, paramDataVector[i].mValue); xmlParameter.setAttribute(HMF_TYPE, paramDataVector[i].mType); if (!paramDataVector[i].mQuantity.isEmpty()) { xmlParameter.setAttribute(HMF_QUANTITY, paramDataVector[i].mQuantity); } if (!paramDataVector[i].mUnit.isEmpty()) { xmlParameter.setAttribute(HMF_UNIT, paramDataVector[i].mUnit); } if (!paramDataVector[i].mDescription.isEmpty()) { xmlParameter.setAttribute(HMF_DESCRIPTIONTAG, paramDataVector[i].mDescription); } } // Save the alias names in this system QDomElement xmlAliases = appendDomElement(rDomElement, HMF_ALIASES); QStringList aliases = getAliasNames(); //! @todo need one function that gets both alias and full maybe for (int i=0; i<aliases.size(); ++i) { QDomElement alias = appendDomElement(xmlAliases, HMF_ALIAS); alias.setAttribute(HMF_TYPE, "variable"); //!< @todo not manual type alias.setAttribute(HMF_NAMETAG, aliases[i]); QString fullName = getFullNameFromAlias(aliases[i]); appendDomTextNode(alias, "fullname",fullName ); } } //! @brief Defines the right click menu for container objects. void SystemContainer::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) { // This will prevent context menus from appearing automatically - they are started manually from mouse release event. if(event->reason() == QGraphicsSceneContextMenuEvent::Mouse) return; bool allowFullEditing = (!isLocallyLocked() && (getModelLockLevel() == NotLocked)); //bool allowLimitedEditing = (!isLocallyLocked() && (getModelLockLevel() <= LimitedLock)); QMenu menu; QAction *loadAction = menu.addAction(tr("Load Subsystem File")); QAction *saveAction = menu.addAction(tr("Save Subsystem As")); QAction *saveAsComponentAction = menu.addAction(tr("Save As Component")); QAction *enterAction = menu.addAction(tr("Enter Subsystem")); loadAction->setEnabled(allowFullEditing); if(!mModelFileInfo.filePath().isEmpty()) { loadAction->setDisabled(true); } if(isExternal()) { saveAction->setDisabled(true); saveAsComponentAction->setDisabled(true); } //qDebug() << "ContainerObject::contextMenuEvent"; QAction *pAction = this->buildBaseContextMenu(menu, event); if (pAction == loadAction) { QString modelFilePath = QFileDialog::getOpenFileName(gpMainWindowWidget, tr("Choose Subsystem File"), gpConfig->getStringSetting(CFG_SUBSYSTEMDIR), tr("Hopsan Model Files (*.hmf)")); if (!modelFilePath.isNull()) { QFile file; file.setFileName(modelFilePath); QFileInfo fileInfo(file); gpConfig->setStringSetting(CFG_SUBSYSTEMDIR, fileInfo.absolutePath()); bool doIt = true; if (mModelObjectMap.size() > 0) { QMessageBox clearAndLoadQuestionBox(QMessageBox::Warning, tr("Warning"),tr("All current contents of the system will be replaced. Do you want to continue?"), 0, 0); clearAndLoadQuestionBox.addButton(tr("&Yes"), QMessageBox::AcceptRole); clearAndLoadQuestionBox.addButton(tr("&No"), QMessageBox::RejectRole); clearAndLoadQuestionBox.setWindowIcon(gpMainWindowWidget->windowIcon()); doIt = (clearAndLoadQuestionBox.exec() == QMessageBox::AcceptRole); } if (doIt) { this->clearContents(); QDomDocument domDocument; QDomElement hmfRoot = loadXMLDomDocument(file, domDocument, HMF_ROOTTAG); if (!hmfRoot.isNull()) { //! @todo Check version numbers //! @todo check if we could load else give error message and don't attempt to load QDomElement systemElement = hmfRoot.firstChildElement(HMF_SYSTEMTAG); this->setModelFileInfo(file); //Remember info about the file from which the data was loaded QFileInfo fileInfo(file); this->setAppearanceDataBasePath(fileInfo.absolutePath()); this->loadFromDomElement(systemElement); } } } } else if(pAction == saveAction) { //Get file name QString modelFilePath; modelFilePath = QFileDialog::getSaveFileName(gpMainWindowWidget, tr("Save Subsystem As"), gpConfig->getStringSetting(CFG_LOADMODELDIR), tr("Hopsan Model Files (*.hmf)")); if(modelFilePath.isEmpty()) //Don't save anything if user presses cancel { return; } //! @todo Duplicated code, but we cannot use code from ModelWidget, because it can only save top level system... QFile file(modelFilePath); //Create a QFile object if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) //open file { gpMessageHandler->addErrorMessage("Could not open the file: "+file.fileName()+" for writing." ); return; } //Save xml document QDomDocument domDocument; QDomElement rootElement; rootElement = appendHMFRootElement(domDocument, HMF_VERSIONNUM, HOPSANGUIVERSION, getHopsanCoreVersion()); // Save the required external lib names QVector<QString> extLibNames; CoreLibraryAccess coreLibAccess; coreLibAccess.getLoadedLibNames(extLibNames); QDomElement reqDom = appendDomElement(rootElement, "requirements"); for (int i=0; i<extLibNames.size(); ++i) { appendDomTextNode(reqDom, "componentlibrary", extLibNames[i]); } //Save the model component hierarchy this->saveToDomElement(rootElement, FullModel); //Save to file QFile xmlFile(modelFilePath); if (!xmlFile.open(QIODevice::WriteOnly | QIODevice::Text)) //open file { gpMessageHandler->addErrorMessage("Could not save to file: " + modelFilePath); return; } QTextStream out(&xmlFile); appendRootXMLProcessingInstruction(domDocument); //The xml "comment" on the first line domDocument.save(out, XMLINDENTATION); //Close the file xmlFile.close(); // mpModelWidget->saveTo(modelFilePath, FullModel); } else if(pAction == saveAsComponentAction) { //Get file name QString cafFilePath; cafFilePath = QFileDialog::getSaveFileName(gpMainWindowWidget, tr("Save Subsystem As"), gpConfig->getStringSetting(CFG_LOADMODELDIR), tr("Hopsan Component Appearance Files (*.xml)")); if(cafFilePath.isEmpty()) //Don't save anything if user presses cancel { return; } QString iconFileName = QFileInfo(getIconPath(UserGraphics, Absolute)).fileName(); QString modelFileName = QFileInfo(cafFilePath).baseName()+".hmf"; //! @todo why is graphics copied twice QFile::copy(getIconPath(UserGraphics, Absolute), QFileInfo(cafFilePath).path()+"/"+iconFileName); QFile::copy(getIconPath(UserGraphics, Absolute), getAppearanceData()->getBasePath()+"/"+iconFileName); bool ok; QString subtype = QInputDialog::getText(gpMainWindowWidget, tr("Decide a unique Subtype"), tr("Decide a unique subtype name for this component:"), QLineEdit::Normal, QString(""), &ok); if (!ok || subtype.isEmpty()) { gpMessageHandler->addErrorMessage("You must specify a subtype name. Aborting!"); return; } //! @todo it would be better if this xml would only include hmffile attribute and all otehr info loaded from there QString cafStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; cafStr.append(QString("<hopsanobjectappearance version=\"0.3\">\n")); cafStr.append(QString(" <modelobject hmffile=\"%1\" displayname=\"%2\" typename=\"%3\" subtypename=\"%4\">\n").arg(modelFileName).arg(getName()).arg("Subsystem").arg(subtype)); cafStr.append(QString(" <icons>\n")); cafStr.append(QString(" <icon scale=\"1\" path=\"%1\" iconrotation=\"ON\" type=\"user\"/>\n").arg(iconFileName)); cafStr.append(QString(" </icons>\n")); cafStr.append(QString(" </modelobject>\n")); cafStr.append(QString("</hopsanobjectappearance>\n")); QFile cafFile(cafFilePath); if(!cafFile.open(QFile::Text | QFile::WriteOnly)) { gpMessageHandler->addErrorMessage("Could not open the file: "+cafFile.fileName()+" for writing."); return; } cafFile.write(cafStr.toUtf8()); cafFile.close(); QString modelFilePath = QFileInfo(cafFilePath).path()+"/"+QFileInfo(cafFilePath).baseName()+".hmf"; QString orgIconPath = this->getIconPath(UserGraphics, Relative); this->setIconPath(iconFileName, UserGraphics, Relative); //! @todo Duplicated code, but we cannot use code from ModelWidget, because it can only save top level system... QFile file(modelFilePath); //Create a QFile object if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) //open file { gpMessageHandler->addErrorMessage("Could not open the file: "+file.fileName()+" for writing." ); return; } //Save xml document QDomDocument domDocument; QDomElement rootElement; rootElement = appendHMFRootElement(domDocument, HMF_VERSIONNUM, HOPSANGUIVERSION, getHopsanCoreVersion()); // Save the required external lib names QVector<QString> extLibNames; CoreLibraryAccess coreLibAccess; coreLibAccess.getLoadedLibNames(extLibNames); QDomElement reqDom = appendDomElement(rootElement, "requirements"); for (int i=0; i<extLibNames.size(); ++i) { appendDomTextNode(reqDom, "componentlibrary", extLibNames[i]); } //Save the model component hierarchy QString old_subtype = this->getAppearanceData()->getSubTypeName(); this->getAppearanceData()->setSubTypeName(subtype); this->saveToDomElement(rootElement, FullModel); this->getAppearanceData()->setSubTypeName(old_subtype); //Save to file QFile xmlFile(modelFilePath); if (!xmlFile.open(QIODevice::WriteOnly | QIODevice::Text)) //open file { gpMessageHandler->addErrorMessage("Could not save to file: " + modelFilePath); return; } QTextStream out(&xmlFile); appendRootXMLProcessingInstruction(domDocument); //The xml "comment" on the first line domDocument.save(out, XMLINDENTATION); //Close the file xmlFile.close(); this->setIconPath(orgIconPath, UserGraphics, Relative); QFile::remove(getModelFilePath()+"/"+iconFileName); } else if (pAction == enterAction) { enterContainer(); } // Don't call GUIModelObject::contextMenuEvent as that will open an other menu after this one is closed } //! @brief Defines the double click event for container objects (used to enter containers). void SystemContainer::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) { QGraphicsWidget::mouseDoubleClickEvent(event); if (isExternal()) { openPropertiesDialog(); } else { enterContainer(); } } void SystemContainer::saveSensitivityAnalysisSettingsToDomElement(QDomElement &rDomElement) { QDomElement XMLsens = appendDomElement(rDomElement, HMF_SENSITIVITYANALYSIS); QDomElement XMLsetting = appendDomElement(XMLsens, HMF_SETTINGS); appendDomIntegerNode(XMLsetting, HMF_ITERATIONS, mSensSettings.nIter); if(mSensSettings.distribution == SensitivityAnalysisSettings::UniformDistribution) { appendDomTextNode(XMLsetting, HMF_DISTRIBUTIONTYPE, HMF_UNIFORMDIST); } else if(mSensSettings.distribution == SensitivityAnalysisSettings::NormalDistribution) { appendDomTextNode(XMLsetting, HMF_DISTRIBUTIONTYPE, HMF_NORMALDIST); } //Parameters QDomElement XMLparameters = appendDomElement(XMLsens, HMF_PARAMETERS); for(int i = 0; i < mSensSettings.parameters.size(); ++i) { QDomElement XMLparameter = appendDomElement(XMLparameters, HMF_PARAMETERTAG); appendDomTextNode(XMLparameter, HMF_COMPONENTTAG, mSensSettings.parameters.at(i).compName); appendDomTextNode(XMLparameter, HMF_PARAMETERTAG, mSensSettings.parameters.at(i).parName); appendDomValueNode2(XMLparameter, HMF_MINMAX, mSensSettings.parameters.at(i).min, mSensSettings.parameters.at(i).max); appendDomValueNode(XMLparameter, HMF_AVERAGE, mSensSettings.parameters.at(i).aver); appendDomValueNode(XMLparameter, HMF_SIGMA, mSensSettings.parameters.at(i).sigma); } //Variables QDomElement XMLobjectives = appendDomElement(XMLsens, HMF_PLOTVARIABLES); for(int i = 0; i < mSensSettings.variables.size(); ++i) { QDomElement XMLobjective = appendDomElement(XMLobjectives, HMF_PLOTVARIABLE); appendDomTextNode(XMLobjective, HMF_COMPONENTTAG, mSensSettings.variables.at(i).compName); appendDomTextNode(XMLobjective, HMF_PORTTAG, mSensSettings.variables.at(i).portName); appendDomTextNode(XMLobjective, HMF_PLOTVARIABLE, mSensSettings.variables.at(i).varName); } } void SystemContainer::loadSensitivityAnalysisSettingsFromDomElement(QDomElement &rDomElement) { qDebug() << rDomElement.toDocument().toString(); QDomElement settingsElement = rDomElement.firstChildElement(HMF_SETTINGS); if(!settingsElement.isNull()) { mSensSettings.nIter = parseDomIntegerNode(settingsElement.firstChildElement(HMF_ITERATIONS), mSensSettings.nIter); QDomElement distElement = settingsElement.firstChildElement(HMF_DISTRIBUTIONTYPE); if(!distElement.isNull() && distElement.text() == HMF_UNIFORMDIST) { mSensSettings.distribution = SensitivityAnalysisSettings::UniformDistribution; } else if(!distElement.isNull() && distElement.text() == HMF_NORMALDIST) { mSensSettings.distribution = SensitivityAnalysisSettings::NormalDistribution; } } QDomElement parametersElement = rDomElement.firstChildElement(HMF_PARAMETERS); if(!parametersElement.isNull()) { QDomElement parameterElement =parametersElement.firstChildElement(HMF_PARAMETERTAG); while (!parameterElement.isNull()) { SensitivityAnalysisParameter par; par.compName = parameterElement.firstChildElement(HMF_COMPONENTTAG).text(); par.parName = parameterElement.firstChildElement(HMF_PARAMETERTAG).text(); parseDomValueNode2(parameterElement.firstChildElement(HMF_MINMAX), par.min, par.max); par.aver = parseDomValueNode(parameterElement.firstChildElement(HMF_AVERAGE), 0); par.sigma = parseDomValueNode(parameterElement.firstChildElement(HMF_SIGMA), 0); mSensSettings.parameters.append(par); parameterElement = parameterElement.nextSiblingElement(HMF_PARAMETERTAG); } } QDomElement variablesElement = rDomElement.firstChildElement(HMF_PLOTVARIABLES); if(!variablesElement.isNull()) { QDomElement variableElement = variablesElement.firstChildElement(HMF_PLOTVARIABLE); while (!variableElement.isNull()) { SensitivityAnalysisVariable var; var.compName = variableElement.firstChildElement(HMF_COMPONENTTAG).text(); var.portName = variableElement.firstChildElement(HMF_PORTTAG).text(); var.varName = variableElement.firstChildElement(HMF_PLOTVARIABLE).text(); mSensSettings.variables.append(var); variableElement = variableElement.nextSiblingElement((HMF_PLOTVARIABLE)); } } } void SystemContainer::saveOptimizationSettingsToDomElement(QDomElement &rDomElement) { QDomElement XMLopt = appendDomElement(rDomElement, HMF_OPTIMIZATION); QDomElement XMLsetting = appendDomElement(XMLopt, HMF_SETTINGS); appendDomIntegerNode(XMLsetting, HMF_ITERATIONS, mOptSettings.mNiter); appendDomIntegerNode(XMLsetting, HMF_SEARCHPOINTS, mOptSettings.mNsearchp); appendDomValueNode(XMLsetting, HMF_REFLCOEFF, mOptSettings.mRefcoeff); appendDomValueNode(XMLsetting, HMF_RANDOMFACTOR, mOptSettings.mRandfac); appendDomValueNode(XMLsetting, HMF_FORGETTINGFACTOR, mOptSettings.mForgfac); appendDomValueNode(XMLsetting, HMF_PARTOL, mOptSettings.mPartol); appendDomBooleanNode(XMLsetting, HMF_PLOT, mOptSettings.mPlot); appendDomBooleanNode(XMLsetting, HMF_SAVECSV, mOptSettings.mSavecsv); appendDomBooleanNode(XMLsetting, HMF_SAVECSV, mOptSettings.mFinalEval); //Parameters appendDomBooleanNode(XMLsetting, HMF_LOGPAR, mOptSettings.mlogPar); QDomElement XMLparameters = appendDomElement(XMLopt, HMF_PARAMETERS); for(int i = 0; i < mOptSettings.mParamters.size(); ++i) { QDomElement XMLparameter = appendDomElement(XMLparameters, HMF_PARAMETERTAG); appendDomTextNode(XMLparameter, HMF_COMPONENTTAG, mOptSettings.mParamters.at(i).mComponentName); appendDomTextNode(XMLparameter, HMF_PARAMETERTAG, mOptSettings.mParamters.at(i).mParameterName); appendDomValueNode2(XMLparameter, HMF_MINMAX, mOptSettings.mParamters.at(i).mMin, mOptSettings.mParamters.at(i).mMax); } //Objective Functions QDomElement XMLobjectives = appendDomElement(XMLopt, HMF_OBJECTIVES); for(int i = 0; i < mOptSettings.mObjectives.size(); ++i) { QDomElement XMLobjective = appendDomElement(XMLobjectives, HMF_OBJECTIVE); appendDomTextNode(XMLobjective, HMF_FUNCNAME, mOptSettings.mObjectives.at(i).mFunctionName); appendDomValueNode(XMLobjective, HMF_WEIGHT, mOptSettings.mObjectives.at(i).mWeight); appendDomValueNode(XMLobjective, HMF_NORM, mOptSettings.mObjectives.at(i).mNorm); appendDomValueNode(XMLobjective, HMF_EXP, mOptSettings.mObjectives.at(i).mExp); QDomElement XMLObjectiveVariables = appendDomElement(XMLobjective, HMF_PLOTVARIABLES); if(!(mOptSettings.mObjectives.at(i).mVariableInfo.isEmpty())) { for(int j = 0; j < mOptSettings.mObjectives.at(i).mVariableInfo.size(); ++j) { QDomElement XMLObjectiveVariable = appendDomElement(XMLObjectiveVariables, HMF_PLOTVARIABLE); appendDomTextNode(XMLObjectiveVariable, HMF_COMPONENTTAG, mOptSettings.mObjectives.at(i).mVariableInfo.at(j).at(0)); appendDomTextNode(XMLObjectiveVariable, HMF_PORTTAG, mOptSettings.mObjectives.at(i).mVariableInfo.at(j).at(1)); appendDomTextNode(XMLObjectiveVariable, HMF_PLOTVARIABLE, mOptSettings.mObjectives.at(i).mVariableInfo.at(j).at(2)); } } if(!(mOptSettings.mObjectives.at(i).mData.isEmpty())) { QDomElement XMLdata = appendDomElement(XMLobjective, HMF_DATA); for(int j = 0; j < mOptSettings.mObjectives.at(i).mData.size(); ++j) { appendDomTextNode(XMLdata, HMF_PARAMETERTAG, mOptSettings.mObjectives.at(i).mData.at(j)); } } } } void SystemContainer::loadOptimizationSettingsFromDomElement(QDomElement &rDomElement) { qDebug() << rDomElement.toDocument().toString(); QDomElement settingsElement = rDomElement.firstChildElement(HMF_SETTINGS); if(!settingsElement.isNull()) { mOptSettings.mNiter = parseDomIntegerNode(settingsElement.firstChildElement(HMF_ITERATIONS), mOptSettings.mNiter); mOptSettings.mNsearchp = parseDomIntegerNode(settingsElement.firstChildElement(HMF_SEARCHPOINTS), mOptSettings.mNsearchp); mOptSettings.mRefcoeff = parseDomValueNode(settingsElement.firstChildElement(HMF_REFLCOEFF), mOptSettings.mRefcoeff); mOptSettings.mRandfac = parseDomValueNode(settingsElement.firstChildElement(HMF_RANDOMFACTOR), mOptSettings.mRandfac); mOptSettings.mForgfac = parseDomValueNode(settingsElement.firstChildElement(HMF_FORGETTINGFACTOR), mOptSettings.mForgfac); mOptSettings.mPartol = parseDomValueNode(settingsElement.firstChildElement(HMF_PARTOL), mOptSettings.mPartol); mOptSettings.mPlot = parseDomBooleanNode(settingsElement.firstChildElement(HMF_PLOT), mOptSettings.mPlot); mOptSettings.mSavecsv = parseDomBooleanNode(settingsElement.firstChildElement(HMF_SAVECSV), mOptSettings.mSavecsv); mOptSettings.mFinalEval = parseDomBooleanNode(settingsElement.firstChildElement(HMF_FINALEVAL), mOptSettings.mFinalEval); mOptSettings.mlogPar = parseDomBooleanNode(settingsElement.firstChildElement(HMF_LOGPAR), mOptSettings.mlogPar); } QDomElement parametersElement = rDomElement.firstChildElement(HMF_PARAMETERS); if(!parametersElement.isNull()) { QDomElement parameterElement = parametersElement.firstChildElement(HMF_PARAMETERTAG); while (!parameterElement.isNull()) { OptParameter parameter; parameter.mComponentName = parameterElement.firstChildElement(HMF_COMPONENTTAG).text(); parameter.mParameterName = parameterElement.firstChildElement(HMF_PARAMETERTAG).text(); parseDomValueNode2(parameterElement.firstChildElement(HMF_MINMAX), parameter.mMin, parameter.mMax); mOptSettings.mParamters.append(parameter); parameterElement = parameterElement.nextSiblingElement(HMF_PARAMETERTAG); } } QDomElement objectivesElement = rDomElement.firstChildElement(HMF_OBJECTIVES); if(!objectivesElement.isNull()) { QDomElement objElement = objectivesElement.firstChildElement(HMF_OBJECTIVE); while (!objElement.isNull()) { Objectives objectives; objectives.mFunctionName = objElement.firstChildElement(HMF_FUNCNAME).text(); objectives.mWeight = objElement.firstChildElement(HMF_WEIGHT).text().toDouble(); objectives.mNorm = objElement.firstChildElement(HMF_NORM).text().toDouble(); objectives.mExp = objElement.firstChildElement(HMF_EXP).text().toDouble(); QDomElement variablesElement = objElement.firstChildElement(HMF_PLOTVARIABLES); if(!variablesElement.isNull()) { QDomElement varElement = variablesElement.firstChildElement(HMF_PLOTVARIABLE); while (!varElement.isNull()) { QStringList variableInfo; variableInfo.append(varElement.firstChildElement(HMF_COMPONENTTAG).text()); variableInfo.append(varElement.firstChildElement(HMF_PORTTAG).text()); variableInfo.append(varElement.firstChildElement(HMF_PLOTVARIABLE).text()); objectives.mVariableInfo.append(variableInfo); varElement = varElement.nextSiblingElement(HMF_PLOTVARIABLE); } } QDomElement dataElement = objElement.firstChildElement(HMF_DATA); if(!dataElement.isNull()) { QDomElement parElement = dataElement.firstChildElement(HMF_PARAMETERTAG); while (!parElement.isNull()) { objectives.mData.append(parElement.text()); parElement = parElement.nextSiblingElement(HMF_PARAMETERTAG); } } objElement = objElement.nextSiblingElement(HMF_OBJECTIVE); mOptSettings.mObjectives.append(objectives); } } } void SystemContainer::getSensitivityAnalysisSettings(SensitivityAnalysisSettings &sensSettings) { sensSettings = mSensSettings; } void SystemContainer::setSensitivityAnalysisSettings(SensitivityAnalysisSettings &sensSettings) { mSensSettings = sensSettings; } void SystemContainer::getOptimizationSettings(OptimizationSettings &optSettings) { optSettings = mOptSettings; } void SystemContainer::setOptimizationSettings(OptimizationSettings &optSettings) { mOptSettings = optSettings; } //! @brief Saves the System specific GUI data to XML DOM Element //! @param[in] rDomElement The DOM Element to save to QDomElement SystemContainer::saveGuiDataToDomElement(QDomElement &rDomElement) { QDomElement guiStuff = ModelObject::saveGuiDataToDomElement(rDomElement); //Should we try to append appearancedata stuff, we don't want this in external systems as they contain their own appearance if (mLoadType!="EXTERNAL") { //Append system meta info QString author, email, affiliation, description; getModelInfo(author, email, affiliation, description); if (!(author.isEmpty() && email.isEmpty() && affiliation.isEmpty() && description.isEmpty())) { QDomElement infoElement = appendDomElement(guiStuff, HMF_INFOTAG); appendDomTextNode(infoElement, HMF_AUTHORTAG, author); appendDomTextNode(infoElement, HMF_EMAILTAG, email); appendDomTextNode(infoElement, HMF_AFFILIATIONTAG, affiliation); appendDomTextNode(infoElement, HMF_DESCRIPTIONTAG, description); } GraphicsViewPort vp = this->getGraphicsViewport(); appendViewPortTag(guiStuff, vp.mCenter.x(), vp.mCenter.y(), vp.mZoom); QDomElement portsHiddenElement = appendDomElement(guiStuff, HMF_PORTSTAG); portsHiddenElement.setAttribute("hidden", !mShowSubComponentPorts); QDomElement namesHiddenElement = appendDomElement(guiStuff, HMF_NAMESTAG); namesHiddenElement.setAttribute("hidden", !mShowSubComponentNames); QString gfxType = "iso"; if(mGfxType == UserGraphics) gfxType = "user"; QDomElement gfxTypeElement = appendDomElement(guiStuff, HMF_GFXTAG); gfxTypeElement.setAttribute("type", gfxType); QDomElement scriptFileElement = appendDomElement(guiStuff, HMF_SCRIPTFILETAG); scriptFileElement.setAttribute("path", mScriptFilePath); this->refreshExternalPortsAppearanceAndPosition(); QDomElement xmlApp = appendOrGetCAFRootTag(guiStuff); //Before we save the modelobjectappearance data we need to set the correct basepath, (we ask our parent it will know) if (this->getParentContainerObject() != 0) { this->mModelObjectAppearance.setBasePath(this->getParentContainerObject()->getAppearanceData()->getBasePath()); } this->mModelObjectAppearance.saveToDomElement(xmlApp); } saveOptimizationSettingsToDomElement(guiStuff); saveSensitivityAnalysisSettingsToDomElement(guiStuff); //Save undo stack if setting is activated if(mSaveUndoStack) { guiStuff.appendChild(mpUndoStack->toXml()); } return guiStuff; } //! @brief Overloaded special XML DOM save function for System Objects //! @param[in] rDomElement The DOM Element to save to void SystemContainer::saveToDomElement(QDomElement &rDomElement, SaveContentsEnumT contents) { //qDebug() << "Saving to dom node in: " << this->mModelObjectAppearance.getName(); QDomElement xmlSubsystem = appendDomElement(rDomElement, getHmfTagName()); //! @todo maybe use enums instead of strings //! @todo should not need to set this here if (mpParentContainerObject==0) { mLoadType = "ROOT"; //!< @todo this is a temporary hack for the xml save function (see bellow) } else if (!mModelFileInfo.filePath().isEmpty()) { mLoadType = "EXTERNAL"; } else { mLoadType = "EMBEDED"; } // Save Core related stuff this->saveCoreDataToDomElement(xmlSubsystem, contents); if(contents==FullModel) { // Save gui object stuff this->saveGuiDataToDomElement(xmlSubsystem); } //Replace volunector with connectors and component QList<Connector*> volunectorPtrs; QList<Connector*> tempConnectorPtrs; //To be removed later QList<ModelObject*> tempComponentPtrs; //To be removed later for(int i=0; i<mSubConnectorList.size(); ++i) { if(mSubConnectorList[i]->isVolunector()) { Connector *pVolunector = mSubConnectorList[i]; volunectorPtrs.append(pVolunector); mSubConnectorList.removeAll(pVolunector); --i; tempComponentPtrs.append(pVolunector->getVolunectorComponent()); tempConnectorPtrs.append(new Connector(this)); tempConnectorPtrs.last()->setStartPort(pVolunector->getStartPort()); tempConnectorPtrs.last()->setEndPort(tempComponentPtrs.last()->getPort("P1")); QVector<QPointF> points; QStringList geometries; points.append(pVolunector->mapToScene(pVolunector->getLine(0)->line().p1())); for(int j=0; j<pVolunector->getNumberOfLines(); ++j) { points.append(pVolunector->mapToScene(pVolunector->getLine(j)->line().p2())); if(pVolunector->getGeometry(j) == Horizontal) geometries.append("horizontal"); else if(pVolunector->getGeometry(j) == Vertical) geometries.append("vertical"); else geometries.append("diagonal"); } tempConnectorPtrs.last()->setPointsAndGeometries(points, geometries); tempConnectorPtrs.append(new Connector(this)); tempConnectorPtrs.last()->setStartPort(tempComponentPtrs.last()->getPort("P2")); tempConnectorPtrs.last()->setEndPort(pVolunector->getEndPort()); } for(int j=0; j<tempComponentPtrs.size(); ++j) { mModelObjectMap.insert(tempComponentPtrs[j]->getName(), tempComponentPtrs[j]); } } mSubConnectorList.append(tempConnectorPtrs); //Save all of the sub objects if (mLoadType=="EMBEDED" || mLoadType=="ROOT") { //Save subcomponents and subsystems QDomElement xmlObjects = appendDomElement(xmlSubsystem, HMF_OBJECTS); ModelObjectMapT::iterator it; for(it = mModelObjectMap.begin(); it!=mModelObjectMap.end(); ++it) { it.value()->saveToDomElement(xmlObjects, contents); if(tempComponentPtrs.contains(it.value())) { xmlObjects.lastChildElement().setAttribute("volunector", "true"); } } if(contents==FullModel) { //Save all widgets QMap<size_t, Widget *>::iterator itw; for(itw = mWidgetMap.begin(); itw!=mWidgetMap.end(); ++itw) { itw.value()->saveToDomElement(xmlObjects); } //Save the connectors QDomElement xmlConnections = appendDomElement(xmlSubsystem, HMF_CONNECTIONS); for(int i=0; i<mSubConnectorList.size(); ++i) { mSubConnectorList[i]->saveToDomElement(xmlConnections); } } } //Remove temporary connectors/components and re-add volunectors for(int i=0; i<tempConnectorPtrs.size(); ++i) { mSubConnectorList.removeAll(tempConnectorPtrs[i]); Connector *pConnector = tempConnectorPtrs[i]; Port *pStartPort = pConnector->getStartPort(); ModelObject *pStartComponent = pStartPort->getParentModelObject(); Port *pEndPort = pConnector->getEndPort(); ModelObject *pEndComponent = pEndPort->getParentModelObject(); pStartPort->forgetConnection(pConnector); pStartComponent->forgetConnector(pConnector); pEndPort->forgetConnection(pConnector); pEndComponent->forgetConnector(pConnector); delete(tempConnectorPtrs[i]); } for(int i=0; i<volunectorPtrs.size(); ++i) { mSubConnectorList.append(volunectorPtrs[i]); } for(int i=0; i<tempComponentPtrs.size(); ++i) { mModelObjectMap.remove(tempComponentPtrs[i]->getName()); } } //! @brief Loads a System from an XML DOM Element //! @param[in] rDomElement The element to load from void SystemContainer::loadFromDomElement(QDomElement domElement) { // Loop back up to root level to get version numbers QString hmfFormatVersion = domElement.ownerDocument().firstChildElement(HMF_ROOTTAG).attribute(HMF_VERSIONTAG, "0"); QString coreHmfVersion = domElement.ownerDocument().firstChildElement(HMF_ROOTTAG).attribute(HMF_HOPSANCOREVERSIONTAG, "0"); // Check if the subsystem is external or internal, and load appropriately QString external_path = domElement.attribute(HMF_EXTERNALPATHTAG); if (external_path.isEmpty()) { // Load embedded subsystem // 0. Load core and gui stuff //! @todo might need some error checking here in case some fields are missing // Now load the core specific data, might need inherited function for this this->setName(domElement.attribute(HMF_NAMETAG)); // Load the NumHop script setNumHopScript(parseDomStringNode(domElement.firstChildElement(HMF_NUMHOPSCRIPT), "")); // Begin loading GUI stuff like appearance data and viewport QDomElement guiStuff = domElement.firstChildElement(HMF_HOPSANGUITAG); mModelObjectAppearance.readFromDomElement(guiStuff.firstChildElement(CAF_ROOT).firstChildElement(CAF_MODELOBJECT)); refreshDisplayName(); // This must be done because in some occasions the loadAppearanceData line above will overwrite the correct name // Load system/model info QDomElement infoElement = domElement.parentNode().firstChildElement(HMF_INFOTAG); //!< @deprecated info tag is in the system from 0.7.5 an onwards, this line loads from old models if (infoElement.isNull()) { infoElement = guiStuff.firstChildElement(HMF_INFOTAG); } if(!infoElement.isNull()) { QString author, email, affiliation, description; QDomElement authorElement = infoElement.firstChildElement(HMF_AUTHORTAG); if(!authorElement.isNull()) { author = authorElement.text(); } QDomElement emailElement = infoElement.firstChildElement(HMF_EMAILTAG); if(!emailElement.isNull()) { email = emailElement.text(); } QDomElement affiliationElement = infoElement.firstChildElement(HMF_AFFILIATIONTAG); if(!affiliationElement.isNull()) { affiliation = affiliationElement.text(); } QDomElement descriptionElement = infoElement.firstChildElement(HMF_DESCRIPTIONTAG); if(!descriptionElement.isNull()) { description = descriptionElement.text(); } this->setModelInfo(author, email, affiliation, description); } // Now lets check if the icons were loaded successfully else we may want to ask the library widget for the graphics (components saved as subsystems) if (!mModelObjectAppearance.iconValid(UserGraphics) || !mModelObjectAppearance.iconValid(ISOGraphics)) { SharedModelObjectAppearanceT pApp = gpLibraryHandler->getModelObjectAppearancePtr(mModelObjectAppearance.getTypeName(), mModelObjectAppearance.getSubTypeName()); if (pApp) { // If our user graphics is invalid but library has valid data then set from library if (!mModelObjectAppearance.iconValid(UserGraphics) && pApp->iconValid(UserGraphics)) { setIconPath(pApp->getIconPath(UserGraphics, Absolute), UserGraphics, Absolute); } // If our iso graphics is invalid but library has valid data then set from library if (!mModelObjectAppearance.iconValid(ISOGraphics) && pApp->iconValid(ISOGraphics)) { setIconPath(pApp->getIconPath(ISOGraphics, Absolute), ISOGraphics, Absolute); } } } // Continue loading GUI stuff like appearance data and viewport this->mShowSubComponentNames = !parseAttributeBool(guiStuff.firstChildElement(HMF_NAMESTAG),"hidden",true); this->mShowSubComponentPorts = !parseAttributeBool(guiStuff.firstChildElement(HMF_PORTSTAG),"hidden",true); QString gfxType = guiStuff.firstChildElement(HMF_GFXTAG).attribute("type"); if(gfxType == "user") { mGfxType = UserGraphics; } else if(gfxType == "iso") { mGfxType = ISOGraphics; } //! @todo these two should not be set here gpToggleNamesAction->setChecked(mShowSubComponentNames); gpTogglePortsAction->setChecked(mShowSubComponentPorts); double x = guiStuff.firstChildElement(HMF_VIEWPORTTAG).attribute("x").toDouble(); double y = guiStuff.firstChildElement(HMF_VIEWPORTTAG).attribute("y").toDouble(); double zoom = guiStuff.firstChildElement(HMF_VIEWPORTTAG).attribute("zoom").toDouble(); setScriptFile(guiStuff.firstChildElement(HMF_SCRIPTFILETAG).attribute("path")); bool dontClearUndo = false; if(!guiStuff.firstChildElement(HMF_UNDO).isNull()) { QDomElement undoElement = guiStuff.firstChildElement(HMF_UNDO); mpUndoStack->fromXml(undoElement); dontClearUndo = true; mSaveUndoStack = true; //Set save undo stack setting to true if loading a hmf file with undo stack saved } // Only set viewport and zoom if the system being loaded is the one shown in the view // But make system remember the setting anyway this->setGraphicsViewport(GraphicsViewPort(x,y,zoom)); if (mpModelWidget->getViewContainerObject() == this) { mpModelWidget->getGraphicsView()->setViewPort(GraphicsViewPort(x,y,zoom)); } //Load simulation time QString startT,stepT,stopT; bool inheritTs; parseSimulationTimeTag(domElement.firstChildElement(HMF_SIMULATIONTIMETAG), startT, stepT, stopT, inheritTs); this->setTimeStep(stepT.toDouble()); mpCoreSystemAccess->setInheritTimeStep(inheritTs); // Load number of log samples parseLogSettingsTag(domElement.firstChildElement(HMF_SIMULATIONLOGSETTINGS), mLogStartTime, mNumberOfLogSamples); //! @deprecated 20131002 we keep this below for backwards compatibility for a while if(domElement.hasAttribute(HMF_LOGSAMPLES)) { mNumberOfLogSamples = domElement.attribute(HMF_LOGSAMPLES).toInt(); } // Only set start stop time for the top level system if (mpParentContainerObject == 0) { mpModelWidget->setTopLevelSimulationTime(startT,stepT,stopT); } //1. Load global parameters QDomElement xmlParameters = domElement.firstChildElement(HMF_PARAMETERS); QDomElement xmlSubObject = xmlParameters.firstChildElement(HMF_PARAMETERTAG); while (!xmlSubObject.isNull()) { loadSystemParameter(xmlSubObject, true, hmfFormatVersion, this); xmlSubObject = xmlSubObject.nextSiblingElement(HMF_PARAMETERTAG); } //2. Load all sub-components QList<ModelObject*> volunectorObjectPtrs; QDomElement xmlSubObjects = domElement.firstChildElement(HMF_OBJECTS); xmlSubObject = xmlSubObjects.firstChildElement(HMF_COMPONENTTAG); while (!xmlSubObject.isNull()) { verifyHmfComponentCompatibility(xmlSubObject, hmfFormatVersion, coreHmfVersion); ModelObject* pObj = loadModelObject(xmlSubObject, this, NoUndo); if(pObj == NULL) { gpMessageHandler->addErrorMessage(QString("Model contains component from a library that has not been loaded. TypeName: ") + xmlSubObject.attribute(HMF_TYPENAME) + QString(", Name: ") + xmlSubObject.attribute(HMF_NAMETAG)); // Insert missing component dummy instead xmlSubObject.setAttribute(HMF_TYPENAME, "MissingComponent"); pObj = loadModelObject(xmlSubObject, this, NoUndo); } else { //! @deprecated This StartValue load code is only kept for up converting old files, we should keep it here until we have some other way of up converting old formats //Load start values //Is not needed, start values are saved as ordinary parameters! This code snippet can probably be removed. QDomElement xmlStartValues = xmlSubObject.firstChildElement(HMF_STARTVALUES); QDomElement xmlStartValue = xmlStartValues.firstChildElement(HMF_STARTVALUE); while (!xmlStartValue.isNull()) { loadStartValue(xmlStartValue, pObj, NoUndo); xmlStartValue = xmlStartValue.nextSiblingElement(HMF_STARTVALUE); } } if(xmlSubObject.attribute("volunector") == "true") { volunectorObjectPtrs.append(pObj); } // if(pObj && pObj->getTypeName().startsWith("CppComponent")) // { // recompileCppComponents(pObj); // } xmlSubObject = xmlSubObject.nextSiblingElement(HMF_COMPONENTTAG); } //3. Load all text box widgets xmlSubObject = xmlSubObjects.firstChildElement(HMF_TEXTBOXWIDGETTAG); while (!xmlSubObject.isNull()) { loadTextBoxWidget(xmlSubObject, this, NoUndo); xmlSubObject = xmlSubObject.nextSiblingElement(HMF_TEXTBOXWIDGETTAG); } //5. Load all sub-systems xmlSubObject = xmlSubObjects.firstChildElement(HMF_SYSTEMTAG); while (!xmlSubObject.isNull()) { loadModelObject(xmlSubObject, this, NoUndo); xmlSubObject = xmlSubObject.nextSiblingElement(HMF_SYSTEMTAG); } //6. Load all system ports xmlSubObject = xmlSubObjects.firstChildElement(HMF_SYSTEMPORTTAG); while (!xmlSubObject.isNull()) { loadContainerPortObject(xmlSubObject, this, NoUndo); xmlSubObject = xmlSubObject.nextSiblingElement(HMF_SYSTEMPORTTAG); } //7. Load all connectors QDomElement xmlConnections = domElement.firstChildElement(HMF_CONNECTIONS); xmlSubObject = xmlConnections.firstChildElement(HMF_CONNECTORTAG); QList<QDomElement> failedConnections; while (!xmlSubObject.isNull()) { if(!loadConnector(xmlSubObject, this, NoUndo)) { // failedConnections.append(xmlSubObject); } xmlSubObject = xmlSubObject.nextSiblingElement(HMF_CONNECTORTAG); } // //If some connectors failed to load, it could mean that they were loaded in wrong order. // //Try again until they work, or abort if number of attempts are greater than maximum possible for success. // int stop=failedConnections.size()*(failedConnections.size()+1)/2; // int i=0; // while(!failedConnections.isEmpty()) // { // if(!loadConnector(failedConnections.first(), this, NoUndo)) // { // failedConnections.append(failedConnections.first()); // } // failedConnections.removeFirst(); // ++i; // if(i>stop) break; // } //8. Load favorite variables // QDomElement xmlFavVariables = guiStuff.firstChildElement(HMF_FAVORITEVARIABLES); // QDomElement xmlFavVariable = xmlFavVariables.firstChildElement(HMF_FAVORITEVARIABLETAG); // while (!xmlFavVariable.isNull()) // { // loadFavoriteVariable(xmlFavVariable, this); // xmlFavVariable = xmlFavVariable.nextSiblingElement(HMF_FAVORITEVARIABLETAG); // } //8. Load system parameters again in case we need to reregister system port start values xmlParameters = domElement.firstChildElement(HMF_PARAMETERS); xmlSubObject = xmlParameters.firstChildElement(HMF_PARAMETERTAG); while (!xmlSubObject.isNull()) { loadSystemParameter(xmlSubObject, false, hmfFormatVersion, this); xmlSubObject = xmlSubObject.nextSiblingElement(HMF_PARAMETERTAG); } //9. Load plot variable aliases QDomElement xmlAliases = domElement.firstChildElement(HMF_ALIASES); QDomElement xmlAlias = xmlAliases.firstChildElement(HMF_ALIAS); while (!xmlAlias.isNull()) { loadPlotAlias(xmlAlias, this); xmlAlias = xmlAlias.nextSiblingElement(HMF_ALIAS); } //9.1 Load plot variable aliases //! @deprecated Remove in the future when hmf format stabilized and everyone has upgraded xmlSubObject = xmlParameters.firstChildElement(HMF_ALIAS); while (!xmlSubObject.isNull()) { loadPlotAlias(xmlSubObject, this); xmlSubObject = xmlSubObject.nextSiblingElement(HMF_ALIAS); } //10. Load optimization settings xmlSubObject = guiStuff.firstChildElement(HMF_OPTIMIZATION); loadOptimizationSettingsFromDomElement(xmlSubObject); //11. Load sensitivity analysis settings xmlSubObject = guiStuff.firstChildElement(HMF_SENSITIVITYANALYSIS); loadSensitivityAnalysisSettingsFromDomElement(xmlSubObject); //Replace volunector components with volunectors for(int i=0; i<volunectorObjectPtrs.size(); ++i) { if(volunectorObjectPtrs[i]->getPort("P1")->isConnected() && volunectorObjectPtrs[i]->getPort("P2")->isConnected()) { Port *pP1 = volunectorObjectPtrs[i]->getPort("P1"); Port *pP2 = volunectorObjectPtrs[i]->getPort("P2"); Connector *pVolunector = pP1->getAttachedConnectorPtrs().first(); Connector *pExcessiveConnector = pP2->getAttachedConnectorPtrs().first(); Port *pEndPort = pExcessiveConnector->getEndPort(); ModelObject *pEndComponent = pEndPort->getParentModelObject(); ModelObject *pVolunectorObject = volunectorObjectPtrs[i]; //Forget and remove excessive connector mSubConnectorList.removeAll(pExcessiveConnector); pVolunectorObject->forgetConnector(pExcessiveConnector); //Start component pEndComponent->forgetConnector(pExcessiveConnector); //Start port pP2->forgetConnection(pExcessiveConnector); //End component pEndPort->forgetConnection(pExcessiveConnector); //End port delete(pExcessiveConnector); //Disconnect volunector from volunector component pVolunectorObject->forgetConnector(pVolunector); pP1->forgetConnection(pVolunector); //Re-connect volunector with end component pVolunector->setEndPort(pEndPort); //Make the connector a volunector pVolunector->makeVolunector(dynamic_cast<Component*>(pVolunectorObject)); //Remove volunector object parent container object mModelObjectMap.remove(pVolunectorObject->getName()); pVolunectorObject->setParent(0); //Re-draw connector object pVolunector->drawConnector(); } } //Refresh the appearance of the subsystem and create the GUIPorts based on the loaded portappearance information //! @todo This is a bit strange, refreshAppearance MUST be run before create ports or create ports will not know some necessary stuff this->refreshAppearance(); this->refreshExternalPortsAppearanceAndPosition(); //this->createPorts(); //Deselect all components this->deselectAll(); if(!dontClearUndo) { this->mpUndoStack->clear(); } //Only do this for the root system //! @todo maybe can do this for subsystems to (even if we don't see them right now) if (this->mpParentContainerObject == 0) { //mpParentModelWidget->getGraphicsView()->centerView(); mpModelWidget->getGraphicsView()->updateViewPort(); } this->mpModelWidget->setSaved(true); #ifdef USEPYTHONQT gpPythonTerminalWidget->runPyScript(mScriptFilePath); #endif emit systemParametersChanged(); // Make sure we refresh the syspar widget emit checkMessages(); } else { gpMessageHandler->addWarningMessage("A system you tried to load is taged as an external system, but the ContainerSystem load function only loads embeded systems"); } } void SystemContainer::exportToLabView() { QMessageBox::StandardButton reply; reply = QMessageBox::question(gpMainWindowWidget, tr("Export to LabVIEW/SIT"), "This will create source code for a LabVIEW/SIT DLL-file from current model. The HopsanCore source code is included but you will neee Visual Studio 2003 to compile it.\nContinue?", QMessageBox::Yes | QMessageBox::No); if (reply == QMessageBox::No) return; //Open file dialog and initialize the file stream QString filePath; filePath = QFileDialog::getSaveFileName(gpMainWindowWidget, tr("Export Project to HopsanRT Wrapper Code"), gpConfig->getStringSetting(CFG_LABVIEWEXPORTDIR), tr("C++ Source File (*.cpp)")); if(filePath.isEmpty()) return; //Don't save anything if user presses cancel QFileInfo file(filePath); gpConfig->setStringSetting(CFG_LABVIEWEXPORTDIR, file.absolutePath()); auto spGenerator = createDefaultGenerator(); if (!spGenerator->generateToLabViewSIT(filePath, mpCoreSystemAccess->getCoreSystemPtr())) { gpMessageHandler->addErrorMessage("LabView SIT export failed"); } } void SystemContainer::exportToFMU1_32() { exportToFMU("", 1, ArchitectureEnumT::x86); } void SystemContainer::exportToFMU1_64() { exportToFMU("", 1, ArchitectureEnumT::x64); } void SystemContainer::exportToFMU2_32() { exportToFMU("", 2, ArchitectureEnumT::x86); } void SystemContainer::exportToFMU2_64() { exportToFMU("", 2, ArchitectureEnumT::x64); } void SystemContainer::exportToFMU(QString savePath, int version, ArchitectureEnumT arch) { if(savePath.isEmpty()) { //Open file dialog and initialize the file stream QDir fileDialogSaveDir; savePath = QFileDialog::getExistingDirectory(gpMainWindowWidget, tr("Create Functional Mockup Unit"), gpConfig->getStringSetting(CFG_FMUEXPORTDIR), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); if(savePath.isEmpty()) return; //Don't save anything if user presses cancel QDir saveDir; saveDir.setPath(savePath); gpConfig->setStringSetting(CFG_FMUEXPORTDIR, saveDir.absolutePath()); saveDir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot); if(!saveDir.entryList().isEmpty()) { qDebug() << saveDir.entryList(); QMessageBox msgBox; msgBox.setWindowIcon(gpMainWindowWidget->windowIcon()); msgBox.setText(QString("Folder is not empty!")); msgBox.setInformativeText("Are you sure you want to export files here?"); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::No); int answer = msgBox.exec(); if(answer == QMessageBox::No) { return; } } } QDir saveDir(savePath); if(!saveDir.exists()) { QDir().mkpath(savePath); } saveDir.setFilter(QDir::NoFilter); if(!mpModelWidget->isSaved()) { QMessageBox::information(gpMainWindowWidget, "tr(Model not saved)", "tr(Please save your model before exporting an FMU)"); return; } //Save model to hmf in export directory mpModelWidget->saveTo(savePath+"/"+mModelFileInfo.fileName().replace(" ", "_")); auto spGenerator = createDefaultGenerator(); spGenerator->setCompilerPath(gpConfig->getCompilerPath(arch)); HopsanGeneratorGUI::TargetArchitectureT garch; if (arch == ArchitectureEnumT::x64) { garch = HopsanGeneratorGUI::TargetArchitectureT::x64; } else { garch = HopsanGeneratorGUI::TargetArchitectureT::x86; } auto pCoreSystem = mpCoreSystemAccess->getCoreSystemPtr(); auto fmuVersion = static_cast<HopsanGeneratorGUI::FmuVersionT>(version); if (!spGenerator->generateToFmu(savePath, pCoreSystem, fmuVersion, garch)) { gpMessageHandler->addErrorMessage("Failed to export FMU"); } } //void SystemContainer::exportToFMU() //{ // //Open file dialog and initialize the file stream // QDir fileDialogSaveDir; // QString savePath; // savePath = QFileDialog::getExistingDirectory(gpMainWindow, tr("Create Functional Mockup Unit"), // gConfig.getFmuExportDir(), // QFileDialog::ShowDirsOnly // | QFileDialog::DontResolveSymlinks); // if(savePath.isEmpty()) return; //Don't save anything if user presses cancel // QDir saveDir; // saveDir.setPath(savePath); // gConfig.setFmuExportDir(saveDir.absolutePath()); // saveDir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot); // if(!saveDir.entryList().isEmpty()) // { // qDebug() << saveDir.entryList(); // QMessageBox msgBox; // msgBox.setWindowIcon(gpMainWindow->windowIcon()); // msgBox.setText(QString("Folder is not empty!")); // msgBox.setInformativeText("Are you sure you want to export files here?"); // msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); // msgBox.setDefaultButton(QMessageBox::No); // int answer = msgBox.exec(); // if(answer == QMessageBox::No) // { // return; // } // } // saveDir.setFilter(QDir::NoFilter); // //Tells if user selected the gcc compiler or not (= visual studio) // //bool gccCompiler = mpExportFmuGccRadioButton->isChecked(); // //Write the FMU ID // int random = rand() % 1000; // QString randomString = QString().setNum(random); // QString ID = "{8c4e810f-3df3-4a00-8276-176fa3c9f"+randomString+"}"; //!< @todo How is this ID defined? // //Collect information about input ports // QStringList inputVariables; // QStringList inputComponents; // QStringList inputPorts; // QList<int> inputDatatypes; // ModelObjectMapT::iterator it; // for(it = mModelObjectMap.begin(); it!=mModelObjectMap.end(); ++it) // { // if(it.value()->getTypeName() == "SignalInputInterface") // { // inputVariables.append(it.value()->getName().remove(' ')); // inputComponents.append(it.value()->getName()); // inputPorts.append("out"); // inputDatatypes.append(0); // } // } // //Collect information about output ports // QStringList outputVariables; // QStringList outputComponents; // QStringList outputPorts; // QList<int> outputDatatypes; // for(it = mModelObjectMap.begin(); it!=mModelObjectMap.end(); ++it) // { // if(it.value()->getTypeName() == "SignalOutputInterface") // { // outputVariables.append(it.value()->getName().remove(' ')); // outputComponents.append(it.value()->getName()); // outputPorts.append("in"); // outputDatatypes.append(0); // } // } // //Create file objects for all files that shall be created // QFile modelSourceFile; // QString modelName = getModelFileInfo().fileName(); // modelName.chop(4); // QString realModelName = modelName; //Actual model name (used for hmf file) // modelName.replace(" ", "_"); //Replace white spaces with underscore, to avoid problems // modelSourceFile.setFileName(savePath + "/" + modelName + ".c"); // if(!modelSourceFile.open(QIODevice::WriteOnly | QIODevice::Text)) // { // gpMessageHandler->addErrorMessage("Failed to open " + modelName + ".c for writing."); // return; // } // QFile modelDescriptionFile; // modelDescriptionFile.setFileName(savePath + "/modelDescription.xml"); // if(!modelDescriptionFile.open(QIODevice::WriteOnly | QIODevice::Text)) // { // gpMessageHandler->addErrorMessage("Failed to open modelDescription.xml for writing."); // return; // } // QFile fmuHeaderFile; // fmuHeaderFile.setFileName(savePath + "/HopsanFMU.h"); // if(!fmuHeaderFile.open(QIODevice::WriteOnly | QIODevice::Text)) // { // gpMessageHandler->addErrorMessage("Failed to open HopsanFMU.h for writing."); // return; // } // QFile fmuSourceFile; // fmuSourceFile.setFileName(savePath + "/HopsanFMU.cpp"); // if(!fmuSourceFile.open(QIODevice::WriteOnly | QIODevice::Text)) // { // gpMessageHandler->addErrorMessage("Failed to open HopsanFMU.cpp for writing."); // return; // } //#ifdef _WIN32 // QFile clBatchFile; // clBatchFile.setFileName(savePath + "/compile.bat"); // if(!clBatchFile.open(QIODevice::WriteOnly | QIODevice::Text)) // { // gpMessageHandler->addErrorMessage("Failed to open compile.bat for writing."); // return; // } //#endif // //progressBar.setLabelText("Writing modelDescription.xml"); // //progressBar.setValue(1); // QTextStream modelDescriptionStream(&modelDescriptionFile); // modelDescriptionStream << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"; //!< @todo Encoding, should it be UTF-8? // modelDescriptionStream << "<fmiModelDescription\n"; // modelDescriptionStream << " fmiVersion=\"1.0\"\n"; // modelDescriptionStream << " modelName=\"" << modelName << "\"\n"; //!< @todo What's the difference between name and identifier? // modelDescriptionStream << " modelIdentifier=\"" << modelName << "\"\n"; // modelDescriptionStream << " guid=\"" << ID << "\"\n"; // modelDescriptionStream << " numberOfContinuousStates=\"" << inputVariables.size() + outputVariables.size() << "\"\n"; // modelDescriptionStream << " numberOfEventIndicators=\"0\">\n"; // modelDescriptionStream << "<ModelVariables>\n"; // int i, j; // for(i=0; i<inputVariables.size(); ++i) // { // QString refString = QString().setNum(i); // modelDescriptionStream << " <ScalarVariable name=\"" << inputVariables.at(i) << "\" valueReference=\""+refString+"\" description=\"input variable\" causality=\"input\">\n"; // modelDescriptionStream << " <Real start=\"0\" fixed=\"false\"/>\n"; // modelDescriptionStream << " </ScalarVariable>\n"; // } // for(j=0; j<outputVariables.size(); ++j) // { // QString refString = QString().setNum(i+j); // modelDescriptionStream << " <ScalarVariable name=\"" << outputVariables.at(j) << "\" valueReference=\""+refString+"\" description=\"output variable\" causality=\"output\">\n"; // modelDescriptionStream << " <Real start=\"0\" fixed=\"false\"/>\n"; // modelDescriptionStream << " </ScalarVariable>\n"; // } // modelDescriptionStream << "</ModelVariables>\n"; // modelDescriptionStream << "</fmiModelDescription>\n"; // modelDescriptionFile.close(); // //progressBar.setLabelText("Writing " + modelName + ".c"); // //progressBar.setValue(2); // QTextStream modelSourceStream(&modelSourceFile); // modelSourceStream << "// Define class name and unique id\n"; // modelSourceStream << " #define MODEL_IDENTIFIER " << modelName << "\n"; // modelSourceStream << " #define MODEL_GUID \"" << ID << "\"\n\n"; // modelSourceStream << " // Define model size\n"; // modelSourceStream << " #define NUMBER_OF_REALS " << inputVariables.size() + outputVariables.size() << "\n"; // modelSourceStream << " #define NUMBER_OF_INTEGERS 0\n"; // modelSourceStream << " #define NUMBER_OF_BOOLEANS 0\n"; // modelSourceStream << " #define NUMBER_OF_STRINGS 0\n"; // modelSourceStream << " #define NUMBER_OF_STATES "<< inputVariables.size() + outputVariables.size() << "\n"; //!< @todo Does number of variables equal number of states? // modelSourceStream << " #define NUMBER_OF_EVENT_INDICATORS 0\n\n"; // modelSourceStream << " // Include fmu header files, typedefs and macros\n"; // modelSourceStream << " #include \"fmuTemplate.h\"\n"; // modelSourceStream << " #include \"HopsanFMU.h\"\n\n"; // modelSourceStream << " // Define all model variables and their value references\n"; // for(i=0; i<inputVariables.size(); ++i) // modelSourceStream << " #define " << inputVariables.at(i) << "_ " << i << "\n\n"; // for(j=0; j<outputVariables.size(); ++j) // modelSourceStream << " #define " << outputVariables.at(j) << "_ " << j+i << "\n\n"; // modelSourceStream << " // Define state vector as vector of value references\n"; // modelSourceStream << " #define STATES { "; // i=0; // j=0; // if(!inputVariables.isEmpty()) // { // modelSourceStream << inputVariables.at(0) << "_"; // ++i; // } // else if(!outputVariables.isEmpty()) // { // modelSourceStream << outputVariables.at(0) << "_"; // ++j; // } // for(; i<inputVariables.size(); ++i) // modelSourceStream << ", " << inputVariables.at(i) << "_"; // for(; j<outputVariables.size(); ++j) // modelSourceStream << ", " << outputVariables.at(j) << "_"; // modelSourceStream << " }\n\n"; // modelSourceStream << " //Set start values\n"; // modelSourceStream << " void setStartValues(ModelInstance *comp) \n"; // modelSourceStream << " {\n"; // for(i=0; i<inputVariables.size(); ++i) // modelSourceStream << " r(" << inputVariables.at(i) << "_) = 0;\n"; //!< Fix start value handling // for(j=0; j<outputVariables.size(); ++j) // modelSourceStream << " r(" << outputVariables.at(j) << "_) = 0;\n"; //!< Fix start value handling // modelSourceStream << " }\n\n"; // modelSourceStream << " //Initialize\n"; // modelSourceStream << " void initialize(ModelInstance* comp, fmiEventInfo* eventInfo)\n"; // modelSourceStream << " {\n"; // modelSourceStream << " initializeHopsanWrapper(\""+realModelName+".hmf\");\n"; // modelSourceStream << " eventInfo->upcomingTimeEvent = fmiTrue;\n"; // modelSourceStream << " eventInfo->nextEventTime = 0.0005 + comp->time;\n"; // modelSourceStream << " }\n\n"; // modelSourceStream << " //Return variable of real type\n"; // modelSourceStream << " fmiReal getReal(ModelInstance* comp, fmiValueReference vr)\n"; // modelSourceStream << " {\n"; // modelSourceStream << " switch (vr) \n"; // modelSourceStream << " {\n"; // for(i=0; i<inputVariables.size(); ++i) // modelSourceStream << " case " << inputVariables.at(i) << "_: return getVariable(\"" << inputComponents.at(i) << "\", \"" << inputPorts.at(i) << "\", " << inputDatatypes.at(i) << ");\n"; // for(j=0; j<outputVariables.size(); ++j) // modelSourceStream << " case " << outputVariables.at(j) << "_: return getVariable(\"" << outputComponents.at(j) << "\", \"" << outputPorts.at(j) << "\", " << outputDatatypes.at(j) << ");\n"; // modelSourceStream << " default: return 1;\n"; // modelSourceStream << " }\n"; // modelSourceStream << " }\n\n"; // modelSourceStream << " void setReal(ModelInstance* comp, fmiValueReference vr, fmiReal value)\n"; // modelSourceStream << " {\n"; // modelSourceStream << " switch (vr) \n"; // modelSourceStream << " {\n"; // for(i=0; i<inputVariables.size(); ++i) // modelSourceStream << " case " << inputVariables.at(i) << "_: setVariable(\"" << inputComponents.at(i) << "\", \"" << inputPorts.at(i) << "\", " << inputDatatypes.at(i) << ", value);\n"; // for(j=0; j<outputVariables.size(); ++j) // modelSourceStream << " case " << outputVariables.at(j) << "_: setVariable(\"" << outputComponents.at(j) << "\", \"" << outputPorts.at(j) << "\", " << outputDatatypes.at(j) << ", value);\n"; // modelSourceStream << " default: return;\n"; // modelSourceStream << " }\n"; // modelSourceStream << " }\n\n"; // modelSourceStream << " //Update at time event\n"; // modelSourceStream << " void eventUpdate(ModelInstance* comp, fmiEventInfo* eventInfo)\n"; // modelSourceStream << " {\n"; // modelSourceStream << " simulateOneStep();\n"; // modelSourceStream << " eventInfo->upcomingTimeEvent = fmiTrue;\n"; // modelSourceStream << " eventInfo->nextEventTime = 0.0005 + comp->time;\n"; //!< @todo Hardcoded timestep // modelSourceStream << " }\n\n"; // modelSourceStream << " // Include code that implements the FMI based on the above definitions\n"; // modelSourceStream << " #include \"fmuTemplate.c\"\n"; // modelSourceFile.close(); // //progressBar.setLabelText("Writing HopsanFMU.h"); // //progressBar.setValue(4); // QTextStream fmuHeaderStream(&fmuHeaderFile); // QTextLineStream fmuHeaderLines(fmuHeaderStream); // fmuHeaderLines << "#ifndef HOPSANFMU_H"; // fmuHeaderLines << "#define HOPSANFMU_H"; // fmuHeaderLines << ""; // fmuHeaderLines << "#ifdef WRAPPERCOMPILATION"; // //fmuHeaderLines << " #define DLLEXPORT __declspec(dllexport)"; // fmuHeaderLines << " extern \"C\" {"; // fmuHeaderLines << "#else"; // fmuHeaderLines << " #define DLLEXPORT"; // fmuHeaderLines << "#endif"; // fmuHeaderLines << ""; // fmuHeaderLines << "DLLEXPORT void initializeHopsanWrapper(char* filename);"; // fmuHeaderLines << "DLLEXPORT void simulateOneStep();"; // fmuHeaderLines << "DLLEXPORT double getVariable(char* component, char* port, size_t idx);"; // fmuHeaderLines << ""; // fmuHeaderLines << "DLLEXPORT void setVariable(char* component, char* port, size_t idx, double value);"; // fmuHeaderLines << ""; // fmuHeaderLines << "#ifdef WRAPPERCOMPILATION"; // fmuHeaderLines << "}"; // fmuHeaderLines << "#endif"; // fmuHeaderLines << "#endif // HOPSANFMU_H"; // fmuHeaderFile.close(); // //progressBar.setLabelText("Writing HopsanFMU.cpp"); // //progressBar.setValue(5); // QTextStream fmuSourceStream(&fmuSourceFile); // QTextLineStream fmuSrcLines(fmuSourceStream); // fmuSrcLines << "#include <iostream>"; // fmuSrcLines << "#include <assert.h>"; // fmuSrcLines << "#include \"HopsanCore.h\""; // fmuSrcLines << "#include \"HopsanFMU.h\""; // //fmuSrcLines << "#include \"include/ComponentEssentials.h\""; // //fmuSrcLines << "#include \"include/ComponentUtilities.h\""; // fmuSrcLines << ""; // fmuSrcLines << "static double fmu_time=0;"; // fmuSrcLines << "static hopsan::ComponentSystem *spCoreComponentSystem;"; // fmuSrcLines << "static std::vector<std::string> sComponentNames;"; // fmuSrcLines << "hopsan::HopsanEssentials gHopsanCore;"; // fmuSrcLines << ""; // fmuSrcLines << "void initializeHopsanWrapper(char* filename)"; // fmuSrcLines << "{"; // fmuSrcLines << " double startT; //Dummy variable"; // fmuSrcLines << " double stopT; //Dummy variable"; // fmuSrcLines << " gHopsanCore.loadExternalComponentLib(\"../componentLibraries/defaultLibrary/components/libdefaultComponentLibrary.so\");"; // fmuSrcLines << " spCoreComponentSystem = gHopsanCore.loadHMFModel(filename, startT, stopT);\n"; // fmuSrcLines << " assert(spCoreComponentSystem);"; // fmuSrcLines << " spCoreComponentSystem->setDesiredTimestep(0.001);"; //!< @todo Time step should not be hard coded // fmuSrcLines << " spCoreComponentSystem->initialize(0,10);"; // fmuSrcLines << ""; // fmuSrcLines << " fmu_time = 0;"; // fmuSrcLines << "}"; // fmuSrcLines << ""; // fmuSrcLines << "void simulateOneStep()"; // fmuSrcLines << "{"; // fmuSrcLines << " if(spCoreComponentSystem->checkModelBeforeSimulation())"; // fmuSrcLines << " {"; // fmuSrcLines << " double timestep = spCoreComponentSystem->getDesiredTimeStep();"; // fmuSrcLines << " spCoreComponentSystem->simulate(fmu_time, fmu_time+timestep);"; // fmuSrcLines << " fmu_time = fmu_time+timestep;\n"; // fmuSrcLines << " }"; // fmuSrcLines << " else"; // fmuSrcLines << " {"; // fmuSrcLines << " std::cout << \"Simulation failed!\";"; // fmuSrcLines << " }"; // fmuSrcLines << "}"; // fmuSrcLines << ""; // fmuSrcLines << "double getVariable(char* component, char* port, size_t idx)"; // fmuSrcLines << "{"; // fmuSrcLines << " return spCoreComponentSystem->getSubComponentOrThisIfSysPort(component)->getPort(port)->readNode(idx);"; // fmuSrcLines << "}"; // fmuSrcLines << ""; // fmuSrcLines << "void setVariable(char* component, char* port, size_t idx, double value)"; // fmuSrcLines << "{"; // fmuSrcLines << " assert(spCoreComponentSystem->getSubComponentOrThisIfSysPort(component)->getPort(port) != 0);"; // fmuSrcLines << " return spCoreComponentSystem->getSubComponentOrThisIfSysPort(component)->getPort(port)->writeNode(idx, value);"; // fmuSrcLines << "}"; // fmuSourceFile.close(); //#ifdef _WIN32 // //progressBar.setLabelText("Writing to compile.bat"); // //progressBar.setValue(6); // //Write the compilation script file // QTextStream clBatchStream(&clBatchFile); //// if(gccCompiler) //// { // //! @todo Ship Mingw with Hopsan, or check if it exists in system and inform user if it does not. // clBatchStream << "g++ -DWRAPPERCOMPILATION -c -Wl,--rpath,'$ORIGIN/.' HopsanFMU.cpp -I./include\n"; // clBatchStream << "g++ -shared -Wl,--rpath,'$ORIGIN/.' -o HopsanFMU.dll HopsanFMU.o -L./ -lhopsancore"; //// } //// else //// { //// //! @todo Check that Visual Studio is installed, and warn user if not //// clBatchStream << "echo Compiling Visual Studio libraries...\n"; //// clBatchStream << "if defined VS90COMNTOOLS (call \"%VS90COMNTOOLS%\\vsvars32.bat\") else ^\n"; //// clBatchStream << "if defined VS80COMNTOOLS (call \"%VS80COMNTOOLS%\\vsvars32.bat\")\n"; //// clBatchStream << "cl -LD -nologo -DWIN32 -DWRAPPERCOMPILATION HopsanFMU.cpp /I \\. /I \\include\\HopsanCore.h HopsanCore.lib\n"; //// } // clBatchFile.close(); //#endif // //progressBar.setLabelText("Copying binary files"); // //progressBar.setValue(7); // //Copy binaries to export directory //#ifdef _WIN32 // QFile dllFile; // QFile libFile; // QFile expFile; //// if(gccCompiler) //// { // dllFile.setFileName(gDesktopHandler.getExecPath() + "HopsanCore.dll"); // dllFile.copy(savePath + "/HopsanCore.dll"); //// } //// else //// { //// //! @todo this seem a bit hardcoded //// dllFile.setFileName(gDesktopHandler.getMSVC2008X86Path() + "HopsanCore.dll"); //// dllFile.copy(savePath + "/HopsanCore.dll"); //// libFile.setFileName(gDesktopHandler.getMSVC2008X86Path() + "HopsanCore.lib"); //// libFile.copy(savePath + "/HopsanCore.lib"); //// expFile.setFileName(gDesktopHandler.getMSVC2008X86Path() + "HopsanCore.exp"); //// expFile.copy(savePath + "/HopsanCore.exp"); //// } //#elif linux // QFile soFile; // soFile.setFileName(gDesktopHandler.getExecPath() + "libhopsancore.so"); // soFile.copy(savePath + "/libhopsancore.so"); //#endif // //progressBar.setLabelText("Copying include files"); // //progressBar.setValue(8); // //Copy include files to export directory // copyIncludeFilesToDir(savePath); // progressBar.setLabelText("Writing "+realModelName+".hmf"); // progressBar.setValue(9); // //Save model to hmf in export directory // //! @todo This code is duplicated from ModelWidget::saveModel(), make it a common function somehow // QDomDocument domDocument; // QDomElement hmfRoot = appendHMFRootElement(domDocument, HMF_VERSIONNUM, HOPSANGUIVERSION, getHopsanCoreVersion()); // saveToDomElement(hmfRoot); // const int IndentSize = 4; // QFile xmlhmf(savePath + "/" + mModelFileInfo.fileName()); // if (!xmlhmf.open(QIODevice::WriteOnly | QIODevice::Text)) //open file // { // gpMainWindow->mpMessageWidget->printGUIErrorMessage("Unable to open "+savePath+"/"+mModelFileInfo.fileName()+" for writing."); // return; // } // QTextStream out(&xmlhmf); // appendRootXMLProcessingInstruction(domDocument); //The xml "comment" on the first line // domDocument.save(out, IndentSize); // CoreGeneratorAccess *pCoreAccess = new CoreGeneratorAccess(); // pCoreAccess->generateToFmu(savePath, this); // delete(pCoreAccess); //} void SystemContainer::exportToSimulink() { QDialog *pExportDialog = new QDialog(gpMainWindowWidget); pExportDialog->setWindowTitle("Create Simulink Source Files"); QLabel *pExportDialogLabel1 = new QLabel(tr("This will create source files for Simulink from the current model. These can be compiled into an S-function library by executing HopsanSimulinkCompile.m from Matlab console."), pExportDialog); pExportDialogLabel1->setWordWrap(true); // QGroupBox *pCompilerGroupBox = new QGroupBox(tr("Choose compiler:"), pExportDialog); // QRadioButton *pMSVC2008RadioButton = new QRadioButton(tr("Microsoft Visual Studio 2008")); // QRadioButton *pMSVC2010RadioButton = new QRadioButton(tr("Microsoft Visual Studio 2010")); // pMSVC2008RadioButton->setChecked(true); // QVBoxLayout *pCompilerLayout = new QVBoxLayout; // pCompilerLayout->addWidget(pMSVC2008RadioButton); // pCompilerLayout->addWidget(pMSVC2010RadioButton); // pCompilerLayout->addStretch(1); // pCompilerGroupBox->setLayout(pCompilerLayout); // QGroupBox *pArchitectureGroupBox = new QGroupBox(tr("Choose architecture:"), pExportDialog); // QRadioButton *p32bitRadioButton = new QRadioButton(tr("32-bit (x86)")); // QRadioButton *p64bitRadioButton = new QRadioButton(tr("64-bit (x64)")); // p32bitRadioButton->setChecked(true); // QVBoxLayout *pArchitectureLayout = new QVBoxLayout; // pArchitectureLayout->addWidget(p32bitRadioButton); // pArchitectureLayout->addWidget(p64bitRadioButton); // pArchitectureLayout->addStretch(1); // pArchitectureGroupBox->setLayout(pArchitectureLayout); // QLabel *pExportDialogLabel2 = new QLabel("Matlab must use the same compiler during compilation. ", pExportDialog); QCheckBox *pDisablePortLabels = new QCheckBox("Disable port labels (for older versions of Matlab)"); QDialogButtonBox *pExportButtonBox = new QDialogButtonBox(pExportDialog); QPushButton *pExportButtonOk = new QPushButton("Ok", pExportDialog); QPushButton *pExportButtonCancel = new QPushButton("Cancel", pExportDialog); pExportButtonBox->addButton(pExportButtonOk, QDialogButtonBox::AcceptRole); pExportButtonBox->addButton(pExportButtonCancel, QDialogButtonBox::RejectRole); QVBoxLayout *pExportDialogLayout = new QVBoxLayout(pExportDialog); pExportDialogLayout->addWidget(pExportDialogLabel1); // pExportDialogLayout->addWidget(pCompilerGroupBox); // pExportDialogLayout->addWidget(pArchitectureGroupBox); // pExportDialogLayout->addWidget(pExportDialogLabel2); pExportDialogLayout->addWidget(pDisablePortLabels); pExportDialogLayout->addWidget(pExportButtonBox); pExportDialog->setLayout(pExportDialogLayout); connect(pExportButtonBox, SIGNAL(accepted()), pExportDialog, SLOT(accept())); connect(pExportButtonBox, SIGNAL(rejected()), pExportDialog, SLOT(reject())); //connect(pExportButtonOk, SIGNAL(clicked()), pExportDialog, SLOT(accept())); //connect(pExportButtonCancel, SIGNAL(clicked()), pExportDialog, SLOT(reject())); if(pExportDialog->exec() == QDialog::Rejected) { return; } //QMessageBox::information(gpMainWindow, gpMainWindow->tr("Create Simulink Source Files"), // gpMainWindow->tr("This will create source files for Simulink from the current model. These can be compiled into an S-function library by executing HopsanSimulinkCompile.m from Matlab console.\n\nVisual Studio 2008 compiler is supported, although other versions might work as well..")); QString fileName; if(!mModelFileInfo.fileName().isEmpty()) { fileName = mModelFileInfo.fileName(); } else { fileName = "untitled.hmf"; } //Open file dialog and initialize the file stream QString savePath; savePath = QFileDialog::getExistingDirectory(gpMainWindowWidget, tr("Create Simulink Source Files"), gpConfig->getStringSetting(CFG_SIMULINKEXPORTDIR), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); if(savePath.isEmpty()) return; //Don't save anything if user presses cancel QFileInfo file(savePath); gpConfig->setStringSetting(CFG_SIMULINKEXPORTDIR, file.absolutePath()); // Save xml document mpModelWidget->saveTo(savePath+"/"+fileName); // int compiler; // if(pMSVC2008RadioButton->isChecked() && p32bitRadioButton->isChecked()) // { // compiler=0; // } // else if(pMSVC2008RadioButton->isChecked() && p64bitRadioButton->isChecked()) // { // compiler=1; // } // else if(pMSVC2010RadioButton->isChecked() && p32bitRadioButton->isChecked()) // { // compiler=2; // } // else/* if(pMSVC2010RadioButton->isChecked() && p64bitRadioButton->isChecked())*/ // { // compiler=3; // } auto spGenerator = createDefaultGenerator(); QString modelPath = getModelFileInfo().fileName(); auto pCoreSystem = mpCoreSystemAccess->getCoreSystemPtr(); auto portLabels = pDisablePortLabels->isChecked() ? HopsanGeneratorGUI::UsePortlablesT::DisablePortLables : HopsanGeneratorGUI::UsePortlablesT::EnablePortLabels; if (!spGenerator->generateToSimulink(savePath, modelPath, pCoreSystem, portLabels )) { gpMessageHandler->addErrorMessage("Simulink export generator failed"); } //Clean up widgets that do not have a parent delete(pDisablePortLabels); // delete(pMSVC2008RadioButton); // delete(pMSVC2010RadioButton); // delete(p32bitRadioButton); // delete(p64bitRadioButton); } //! @brief Sets the modelfile info from the file representing this system //! @param[in] rFile The QFile objects representing the file we want to information about //! @param[in] relModelPath Relative filepath to parent model file (model asset path) void SystemContainer::setModelFileInfo(QFile &rFile, const QString relModelPath) { mModelFileInfo.setFile(rFile); if (!relModelPath.isEmpty()) { getCoreSystemAccessPtr()->setExternalModelFilePath(relModelPath); } } void SystemContainer::loadParameterFile(const QString &path) { qDebug() << "loadParameterFile()"; QString parameterFileName = path; if(path.isEmpty()) { parameterFileName = QFileDialog::getOpenFileName(gpMainWindowWidget, tr("Load Parameter File"), gpConfig->getStringSetting(CFG_LOADMODELDIR), tr("Hopsan Parameter Files (*.hpf *.xml)")); } if(!parameterFileName.isEmpty()) { mpCoreSystemAccess->loadParameterFile(parameterFileName); QFileInfo fileInfo = QFileInfo(parameterFileName); gpConfig->setStringSetting(CFG_LOADMODELDIR, fileInfo.absolutePath()); } } //! @brief Function to set the time step of the current system void SystemContainer::setTimeStep(const double timeStep) { mpCoreSystemAccess->setDesiredTimeStep(timeStep); this->hasChanged(); } void SystemContainer::setVisibleIfSignal(bool visible) { if(this->getTypeCQS() == "S") { this->setVisible(visible); } } //! @brief Returns the time step value of the current project. double SystemContainer::getTimeStep() { return mpCoreSystemAccess->getDesiredTimeStep(); } //! @brief Check if the system inherits timestep from its parent bool SystemContainer::doesInheritTimeStep() { return mpCoreSystemAccess->doesInheritTimeStep(); } //! @brief Returns the number of samples value of the current project. //! @see setNumberOfLogSamples(double) size_t SystemContainer::getNumberOfLogSamples() { return mNumberOfLogSamples; } //! @brief Sets the number of samples value for the current project //! @see getNumberOfLogSamples() void SystemContainer::setNumberOfLogSamples(size_t nSamples) { mNumberOfLogSamples = nSamples; } double SystemContainer::getLogStartTime() const { return mLogStartTime; } void SystemContainer::setLogStartTime(const double logStartT) { mLogStartTime = logStartT; } OptimizationSettings::OptimizationSettings() { //Defaulf values mNiter=100; mNsearchp=8; mRefcoeff=1.3; mRandfac=.3; mForgfac=0.0; mPartol=.0001; mPlot=true; mSavecsv=false; mFinalEval=true; mlogPar = false; } SensitivityAnalysisSettings::SensitivityAnalysisSettings() { nIter = 100; distribution = UniformDistribution; }
42.751959
316
0.658305
[ "object", "vector", "model" ]
c6920ce4e2fc599b43071d7a2d9c3292e13f50c9
108
cpp
C++
src/model/Model.cpp
picardb/QtRemoteTestClient
d14665e7f3615df7078931b4ee7276549835023e
[ "MIT" ]
null
null
null
src/model/Model.cpp
picardb/QtRemoteTestClient
d14665e7f3615df7078931b4ee7276549835023e
[ "MIT" ]
null
null
null
src/model/Model.cpp
picardb/QtRemoteTestClient
d14665e7f3615df7078931b4ee7276549835023e
[ "MIT" ]
null
null
null
#include "Model.h" /* * Components definitions */ Network Model::m_network; Control Model::m_control;
12
26
0.703704
[ "model" ]
578deb598c847266d0d8083a3a79640204e851bd
4,560
cpp
C++
SOLVER/src/models3D/ocean_load/StructuredGridO3D.cpp
nicklinyi/AxiSEM-3D
cd11299605cd6b92eb867d4109d2e6a8f15e6b4d
[ "MIT" ]
8
2020-06-05T01:13:20.000Z
2022-02-24T05:11:50.000Z
SOLVER/src/models3D/ocean_load/StructuredGridO3D.cpp
nicklinyi/AxiSEM-3D
cd11299605cd6b92eb867d4109d2e6a8f15e6b4d
[ "MIT" ]
24
2020-10-21T19:03:38.000Z
2021-11-17T21:32:02.000Z
SOLVER/src/models3D/ocean_load/StructuredGridO3D.cpp
nicklinyi/AxiSEM-3D
cd11299605cd6b92eb867d4109d2e6a8f15e6b4d
[ "MIT" ]
5
2020-06-21T11:54:22.000Z
2021-06-23T01:02:39.000Z
// // StructuredGridO3D.cpp // AxiSEM3D // // Created by Kuangdai Leng on 4/15/20. // Copyright © 2020 Kuangdai Leng. All rights reserved. // // 3D ocean-load models based on structured grid #include "StructuredGridO3D.hpp" // constructor StructuredGridO3D:: StructuredGridO3D(const std::string &modelName, const std::string &fname, const std::array<std::string, 2> &crdVarNames, const std::array<int, 2> &shuffleData, bool sourceCentered, bool xy, bool ellipticity, double lengthUnit, double angleUnit, const std::string &dataVarName, double factor, bool superOnly): OceanLoad3D(modelName), mFileName(fname), mCrdVarNames(crdVarNames), mSourceCentered(sourceCentered), mXY(xy), mEllipticity(ellipticity), mDataVarName(dataVarName), mFactor(factor), mSuperOnly(superOnly) { ////////////// init grid ////////////// // info std::vector<std::pair<std::string, double>> dataInfo; dataInfo.push_back({mDataVarName, mFactor}); // lambda auto initGrid = [this, &dataInfo, &shuffleData, &lengthUnit, &angleUnit]() { // grid mGrid = std::make_unique<StructuredGrid<2, double>> (mFileName, mCrdVarNames, dataInfo, shuffleData); // coordinate units sg_tools::constructUnits(*mGrid, mSourceCentered, mXY, false, lengthUnit, angleUnit); // longitude range if (!mSourceCentered) { mLon360 = sg_tools::constructLon360(*mGrid, mModelName); } }; // data if (mSuperOnly) { // constructor of StructuredGrid uses root + broadcast to read // right: mpi::super() after mpi::enterSuper() // wrong: mpi::root() after mpi::enterInfer() mpi::enterSuper(); if (mpi::super()) { initGrid(); } mpi::enterWorld(); } else { initGrid(); } } // get sum(rho * depth) bool StructuredGridO3D::getSumRhoDepth(const eigen::DMatX3 &spz, const eigen::DMat24 &nodalSZ, eigen::DColX &sumRhoDepth) const { //////////////////////// coords //////////////////////// // check min/max const auto &gridCrds = mGrid->getGridCoords(); if (!inplaneScope(nodalSZ, mSourceCentered && (!mXY), gridCrds[0].front(), gridCrds[0].back(), false, 0., 0., false, false)) { return false; } // compute grid coords const eigen::DMatX3 &crdGrid = coordsFromMeshToModel(spz, mSourceCentered, mXY, mEllipticity, mLon360, false, false, mModelName); //////////////////////// values //////////////////////// // allocate and fill with zero int nCardinals = (int)spz.rows(); sumRhoDepth = eigen::DColX::Zero(nCardinals); // point loop static const double err = std::numeric_limits<double>::lowest(); bool oneInScope = false; for (int ipnt = 0; ipnt < nCardinals; ipnt++) { const eigen::DRow2 &horizontal = crdGrid.block(ipnt, 0, 1, 2); double val = mGrid->compute(horizontal, err); // check scope // ignore negative sum(rho * depth) if (val > 0.) { sumRhoDepth(ipnt) = val; oneInScope = true; } } return oneInScope; } // verbose std::string StructuredGridO3D::verbose() const { if (!mpi::root()) { // grid uninitialized on infer ranks return ""; } using namespace bstring; std::stringstream ss; // head ss << sg_tools::verboseHead(mModelName, "StructuredGridO3D", mFileName); // coords const auto &gcrds = mGrid->getGridCoords(); ss << sg_tools::verboseCoords(mSourceCentered, mXY, false, false, {mCrdVarNames[0], mCrdVarNames[1]}, {gcrds[0].front(), gcrds[1].front()}, {gcrds[0].back(), gcrds[1].back()}); // options if (!mSourceCentered) { ss << boxEquals(4, 22, "ellipticity correction", mEllipticity); } // data ss << boxSubTitle(2, "Data for sum(rho * depth)"); ss << boxEquals(4, 19, "NetCDF variable", mDataVarName); const auto &minMax = mGrid->getDataRange(); ss << boxEquals(4, 19, "data range", range(minMax(0, 0), minMax(0, 1))); ss << boxEquals(4, 19, "leader-only storage", mSuperOnly); return ss.str(); }
34.80916
76
0.556798
[ "vector", "3d" ]
5796e10a9d415fcc0a15c2d2eeec67c1bc56f779
24,836
cc
C++
chrome/browser/importer/firefox_importer_utils.cc
bluebellzhy/chromium
008c4fef2676506869a0404239da31e83fd6ccc7
[ "BSD-3-Clause" ]
1
2016-05-08T15:35:17.000Z
2016-05-08T15:35:17.000Z
chrome/browser/importer/firefox_importer_utils.cc
bluebellzhy/chromium
008c4fef2676506869a0404239da31e83fd6ccc7
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/importer/firefox_importer_utils.cc
bluebellzhy/chromium
008c4fef2676506869a0404239da31e83fd6ccc7
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/importer/firefox_importer_utils.h" #include <shlobj.h> #include "base/file_util.h" #include "base/logging.h" #include "base/registry.h" #include "base/string_util.h" #include "base/sys_string_conversions.h" #include "base/time.h" #include "chrome/browser/template_url.h" #include "chrome/browser/template_url_model.h" #include "chrome/browser/template_url_parser.h" #include "chrome/common/win_util.h" #include "googleurl/src/gurl.h" #include "net/base/base64.h" namespace { // NOTE: Keep these in order since we need test all those paths according // to priority. For example. One machine has multiple users. One non-admin // user installs Firefox 2, which causes there is a Firefox2 entry under HKCU. // One admin user installs Firefox 3, which causes there is a Firefox 3 entry // under HKLM. So when the non-admin user log in, we should deal with Firefox 2 // related data instead of Firefox 3. static const HKEY kFireFoxRegistryPaths[] = { HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE }; // FirefoxURLParameterFilter is used to remove parameter mentioning Firefox from // the search URL when importing search engines. class FirefoxURLParameterFilter : public TemplateURLParser::ParameterFilter { public: FirefoxURLParameterFilter() { } ~FirefoxURLParameterFilter() { } // TemplateURLParser::ParameterFilter method. virtual bool KeepParameter(const std::string& key, const std::string& value) { std::string low_value = StringToLowerASCII(value); if (low_value.find("mozilla") != -1 || low_value.find("firefox") != -1 || low_value.find("moz:") != -1 ) return false; return true; } private: DISALLOW_EVIL_CONSTRUCTORS(FirefoxURLParameterFilter); }; typedef BOOL (WINAPI* SetDllDirectoryFunc)(LPCTSTR lpPathName); // A helper class whose destructor calls SetDllDirectory(NULL) to undo the // effects of a previous SetDllDirectory call. class SetDllDirectoryCaller { public: explicit SetDllDirectoryCaller() : func_(NULL) { } ~SetDllDirectoryCaller() { if (func_) func_(NULL); } // Sets the SetDllDirectory function pointer to activates this object. void set_func(SetDllDirectoryFunc func) { func_ = func; } private: SetDllDirectoryFunc func_; }; } // namespace int GetCurrentFirefoxMajorVersion() { TCHAR ver_buffer[128]; DWORD ver_buffer_length = sizeof(ver_buffer); // When installing Firefox with admin account, the product keys will be // written under HKLM\Mozilla. Otherwise it the keys will be written under // HKCU\Mozilla. for (int i = 0; i < arraysize(kFireFoxRegistryPaths); ++i) { bool result = ReadFromRegistry(kFireFoxRegistryPaths[i], L"Software\\Mozilla\\Mozilla Firefox", L"CurrentVersion", ver_buffer, &ver_buffer_length); if (!result) continue; return _wtoi(ver_buffer); } return 0; } std::wstring GetProfilesINI() { // The default location of the profile folder containing user data is // under the "Application Data" folder in Windows XP. std::wstring ini_file; wchar_t buffer[MAX_PATH] = {0}; if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, buffer))) { ini_file = buffer; file_util::AppendToPath(&ini_file, L"Mozilla\\Firefox\\profiles.ini"); } if (!file_util::PathExists(ini_file)) ini_file.clear(); return ini_file; } std::wstring GetFirefoxInstallPath() { // Detects the path that Firefox is installed in. std::wstring registry_path = L"Software\\Mozilla\\Mozilla Firefox"; TCHAR buffer[MAX_PATH]; DWORD buffer_length = sizeof(buffer); bool result; result = ReadFromRegistry(HKEY_LOCAL_MACHINE, registry_path.c_str(), L"CurrentVersion", buffer, &buffer_length); if (!result) return std::wstring(); registry_path += L"\\" + std::wstring(buffer) + L"\\Main"; buffer_length = sizeof(buffer); result = ReadFromRegistry(HKEY_LOCAL_MACHINE, registry_path.c_str(), L"Install Directory", buffer, &buffer_length); if (!result) return std::wstring(); return buffer; } void ParseProfileINI(std::wstring file, DictionaryValue* root) { // Reads the whole INI file. std::string content; file_util::ReadFileToString(file, &content); ReplaceSubstringsAfterOffset(&content, 0, "\r\n", "\n"); std::vector<std::string> lines; SplitString(content, '\n', &lines); // Parses the file. root->Clear(); std::wstring current_section; for (size_t i = 0; i < lines.size(); ++i) { std::wstring line = UTF8ToWide(lines[i]); if (line.empty()) { // Skips the empty line. continue; } if (line[0] == L'#' || line[0] == L';') { // This line is a comment. continue; } if (line[0] == L'[') { // It is a section header. current_section = line.substr(1); size_t end = current_section.rfind(L']'); if (end != std::wstring::npos) current_section.erase(end); } else { std::wstring key, value; size_t equal = line.find(L'='); if (equal != std::wstring::npos) { key = line.substr(0, equal); value = line.substr(equal + 1); // Checks whether the section and key contain a '.' character. // Those sections and keys break DictionaryValue's path format, // so we discard them. if (current_section.find(L'.') == std::wstring::npos && key.find(L'.') == std::wstring::npos) root->SetString(current_section + L"." + key, value); } } } } bool CanImportURL(const GURL& url) { const char* kInvalidSchemes[] = {"wyciwyg", "place", "about", "chrome"}; // The URL is not valid. if (!url.is_valid()) return false; // Filter out the URLs with unsupported schemes. for (int i = 0; i < arraysize(kInvalidSchemes); ++i) { if (url.SchemeIs(kInvalidSchemes[i])) return false; } return true; } void ParseSearchEnginesFromXMLFiles(const std::vector<std::wstring>& xml_files, std::vector<TemplateURL*>* search_engines) { DCHECK(search_engines); std::map<std::wstring, TemplateURL*> search_engine_for_url; std::string content; // The first XML file represents the default search engine in Firefox 3, so we // need to keep it on top of the list. TemplateURL* default_turl = NULL; for (std::vector<std::wstring>::const_iterator iter = xml_files.begin(); iter != xml_files.end(); ++iter) { file_util::ReadFileToString(*iter, &content); TemplateURL* template_url = new TemplateURL(); FirefoxURLParameterFilter param_filter; if (TemplateURLParser::Parse( reinterpret_cast<const unsigned char*>(content.data()), content.length(), &param_filter, template_url) && template_url->url()) { std::wstring url = template_url->url()->url(); std::map<std::wstring, TemplateURL*>::iterator iter = search_engine_for_url.find(url); if (iter != search_engine_for_url.end()) { // We have already found a search engine with the same URL. We give // priority to the latest one found, as GetSearchEnginesXMLFiles() // returns a vector with first Firefox default search engines and then // the user's ones. We want to give priority to the user ones. delete iter->second; search_engine_for_url.erase(iter); } // Give this a keyword to facilitate tab-to-search, if possible. template_url->set_keyword(TemplateURLModel::GenerateKeyword(GURL(url), false)); template_url->set_show_in_default_list(true); search_engine_for_url[url] = template_url; if (!default_turl) default_turl = template_url; } else { delete template_url; } content.clear(); } // Put the results in the |search_engines| vector. std::map<std::wstring, TemplateURL*>::iterator t_iter; for (t_iter = search_engine_for_url.begin(); t_iter != search_engine_for_url.end(); ++t_iter) { if (t_iter->second == default_turl) search_engines->insert(search_engines->begin(), default_turl); else search_engines->push_back(t_iter->second); } } bool ReadPrefFile(const std::wstring& path_name, const std::wstring& file_name, std::string* content) { if (content == NULL) return false; std::wstring file = path_name; file_util::AppendToPath(&file, file_name.c_str()); file_util::ReadFileToString(file, content); if (content->empty()) { NOTREACHED() << L"Firefox preference file " << file_name.c_str() << L" is empty."; return false; } return true; } std::string ReadBrowserConfigProp(const std::wstring& app_path, const std::string& pref_key) { std::string content; if (!ReadPrefFile(app_path, L"browserconfig.properties", &content)) return ""; // This file has the syntax: key=value. size_t prop_index = content.find(pref_key + "="); if (prop_index == -1) return ""; size_t start = prop_index + pref_key.length(); size_t stop = -1; if (start != -1) stop = content.find("\n", start + 1); if (start == -1 || stop == -1 || (start == stop)) { NOTREACHED() << "Firefox property " << pref_key << " could not be parsed."; return ""; } return content.substr(start + 1, stop - start - 1); } std::string ReadPrefsJsValue(const std::wstring& profile_path, const std::string& pref_key) { std::string content; if (!ReadPrefFile(profile_path, L"prefs.js", &content)) return ""; // This file has the syntax: user_pref("key", value); std::string search_for = std::string("user_pref(\"") + pref_key + std::string("\", "); size_t prop_index = content.find(search_for); if (prop_index == -1) return ""; size_t start = prop_index + search_for.length(); size_t stop = -1; if (start != -1) stop = content.find(")", start + 1); if (start == -1 || stop == -1) { NOTREACHED() << "Firefox property " << pref_key << " could not be parsed."; return ""; } // String values have double quotes we don't need to return to the caller. if (content[start] == '\"' && content[stop - 1] == '\"') { ++start; --stop; } return content.substr(start, stop - start); } int GetFirefoxDefaultSearchEngineIndex( const std::vector<TemplateURL*>& search_engines, const std::wstring& profile_path) { // The default search engine is contained in the file prefs.js found in the // profile directory. // It is the "browser.search.selectedEngine" property. if (search_engines.empty()) return -1; std::wstring default_se_name = UTF8ToWide( ReadPrefsJsValue(profile_path, "browser.search.selectedEngine")); if (default_se_name.empty()) { // browser.search.selectedEngine does not exist if the user has not changed // from the default (or has selected the default). // TODO: should fallback to 'browser.search.defaultengine' if selectedEngine // is empty. return -1; } int default_se_index = -1; for (std::vector<TemplateURL*>::const_iterator iter = search_engines.begin(); iter != search_engines.end(); ++iter) { if (default_se_name == (*iter)->short_name()) { default_se_index = static_cast<int>(iter - search_engines.begin()); break; } } if (default_se_index == -1) { NOTREACHED() << "Firefox default search engine not found in search engine list"; } return default_se_index; } GURL GetHomepage(const std::wstring& profile_path) { std::string home_page_list = ReadPrefsJsValue(profile_path, "browser.startup.homepage"); size_t seperator = home_page_list.find_first_of('|'); if (seperator == std::string::npos) return GURL(home_page_list); return GURL(home_page_list.substr(0, seperator)); } bool IsDefaultHomepage(const GURL& homepage, const std::wstring& app_path) { if (!homepage.is_valid()) return false; std::string default_homepages = ReadBrowserConfigProp(app_path, "browser.startup.homepage"); size_t seperator = default_homepages.find_first_of('|'); if (seperator == std::string::npos) return homepage.spec() == GURL(default_homepages).spec(); // Crack the string into separate homepage urls. std::vector<std::string> urls; SplitString(default_homepages, '|', &urls); for (size_t i = 0; i < urls.size(); ++i) { if (homepage.spec() == GURL(urls[i]).spec()) return true; } return false; } // class NSSDecryptor. // static const wchar_t NSSDecryptor::kNSS3Library[] = L"nss3.dll"; const wchar_t NSSDecryptor::kSoftokn3Library[] = L"softokn3.dll"; const wchar_t NSSDecryptor::kPLDS4Library[] = L"plds4.dll"; const wchar_t NSSDecryptor::kNSPR4Library[] = L"nspr4.dll"; NSSDecryptor::NSSDecryptor() : NSS_Init(NULL), NSS_Shutdown(NULL), PK11_GetInternalKeySlot(NULL), PK11_CheckUserPassword(NULL), PK11_FreeSlot(NULL), PK11_Authenticate(NULL), PK11SDR_Decrypt(NULL), SECITEM_FreeItem(NULL), PL_ArenaFinish(NULL), PR_Cleanup(NULL), nss3_dll_(NULL), softokn3_dll_(NULL), is_nss_initialized_(false) { } NSSDecryptor::~NSSDecryptor() { Free(); } bool NSSDecryptor::Init(const std::wstring& dll_path, const std::wstring& db_path) { // We call SetDllDirectory to work around a Purify bug (GetModuleHandle // fails inside Purify under certain conditions). SetDllDirectory only // exists on Windows XP SP1 or later, so we look up its address at run time. HMODULE kernel32_dll = GetModuleHandle(L"kernel32.dll"); if (kernel32_dll == NULL) return false; SetDllDirectoryFunc set_dll_directory = (SetDllDirectoryFunc)GetProcAddress(kernel32_dll, "SetDllDirectoryW"); SetDllDirectoryCaller caller; if (set_dll_directory != NULL) { if (!set_dll_directory(dll_path.c_str())) return false; caller.set_func(set_dll_directory); nss3_dll_ = LoadLibrary(kNSS3Library); if (nss3_dll_ == NULL) return false; } else { // Fall back on LoadLibraryEx if SetDllDirectory isn't available. We // actually prefer this method because it doesn't change the DLL search // path, which is a process-wide property. std::wstring path = dll_path; file_util::AppendToPath(&path, kNSS3Library); nss3_dll_ = LoadLibraryEx(path.c_str(), NULL, LOAD_WITH_ALTERED_SEARCH_PATH); if (nss3_dll_ == NULL) return false; // Firefox 2 uses NSS 3.11. Firefox 3 uses NSS 3.12. NSS 3.12 has two // changes in its DLLs: // 1. nss3.dll is not linked with softokn3.dll at build time, but rather // loads softokn3.dll using LoadLibrary in NSS_Init. // 2. softokn3.dll has a new dependency sqlite3.dll. // NSS_Init's LoadLibrary call has trouble finding sqlite3.dll. To help // it out, we preload softokn3.dll using LoadLibraryEx with the // LOAD_WITH_ALTERED_SEARCH_PATH flag. This helps because LoadLibrary // doesn't load a DLL again if it's already loaded. This workaround is // harmless for NSS 3.11. path = dll_path; file_util::AppendToPath(&path, kSoftokn3Library); softokn3_dll_ = LoadLibraryEx(path.c_str(), NULL, LOAD_WITH_ALTERED_SEARCH_PATH); if (softokn3_dll_ == NULL) { Free(); return false; } } // NSPR DLLs are already loaded now. HMODULE plds4_dll = GetModuleHandle(kPLDS4Library); HMODULE nspr4_dll = GetModuleHandle(kNSPR4Library); if (plds4_dll == NULL || nspr4_dll == NULL) { Free(); return false; } // Gets the function address. NSS_Init = (NSSInitFunc)GetProcAddress(nss3_dll_, "NSS_Init"); NSS_Shutdown = (NSSShutdownFunc)GetProcAddress(nss3_dll_, "NSS_Shutdown"); PK11_GetInternalKeySlot = (PK11GetInternalKeySlotFunc) GetProcAddress(nss3_dll_, "PK11_GetInternalKeySlot"); PK11_FreeSlot = (PK11FreeSlotFunc)GetProcAddress(nss3_dll_, "PK11_FreeSlot"); PK11_Authenticate = (PK11AuthenticateFunc) GetProcAddress(nss3_dll_, "PK11_Authenticate"); PK11SDR_Decrypt = (PK11SDRDecryptFunc) GetProcAddress(nss3_dll_, "PK11SDR_Decrypt"); SECITEM_FreeItem = (SECITEMFreeItemFunc) GetProcAddress(nss3_dll_, "SECITEM_FreeItem"); PL_ArenaFinish = (PLArenaFinishFunc) GetProcAddress(plds4_dll, "PL_ArenaFinish"); PR_Cleanup = (PRCleanupFunc)GetProcAddress(nspr4_dll, "PR_Cleanup"); if (NSS_Init == NULL || NSS_Shutdown == NULL || PK11_GetInternalKeySlot == NULL || PK11_FreeSlot == NULL || PK11_Authenticate == NULL || PK11SDR_Decrypt == NULL || SECITEM_FreeItem == NULL || PL_ArenaFinish == NULL || PR_Cleanup == NULL) { Free(); return false; } SECStatus result = NSS_Init(base::SysWideToNativeMB(db_path).c_str()); if (result != SECSuccess) { Free(); return false; } is_nss_initialized_ = true; return true; } void NSSDecryptor::Free() { if (is_nss_initialized_) { NSS_Shutdown(); PL_ArenaFinish(); PR_Cleanup(); is_nss_initialized_ = false; } if (softokn3_dll_ != NULL) FreeLibrary(softokn3_dll_); softokn3_dll_ = NULL; if (nss3_dll_ != NULL) FreeLibrary(nss3_dll_); nss3_dll_ = NULL; NSS_Init = NULL; NSS_Shutdown = NULL; PK11_GetInternalKeySlot = NULL; PK11_FreeSlot = NULL; PK11_Authenticate = NULL; PK11SDR_Decrypt = NULL; SECITEM_FreeItem = NULL; PL_ArenaFinish = NULL; PR_Cleanup = NULL; } // This method is based on some Firefox code in // security/manager/ssl/src/nsSDR.cpp // The license block is: /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the Netscape security libraries. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1994-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ std::wstring NSSDecryptor::Decrypt(const std::string& crypt) const { // Do nothing if NSS is not loaded. if (!nss3_dll_) return std::wstring(); std::string plain; // The old style password is encoded in base64. They are identified // by a leading '~'. Otherwise, we should decrypt the text. if (crypt[0] != '~') { std::string decoded_data; net::Base64Decode(crypt, &decoded_data); PK11SlotInfo* slot = NULL; slot = PK11_GetInternalKeySlot(); SECStatus result = PK11_Authenticate(slot, PR_TRUE, NULL); if (result != SECSuccess) { PK11_FreeSlot(slot); return std::wstring(); } SECItem request; request.data = reinterpret_cast<unsigned char*>( const_cast<char*>(decoded_data.data())); request.len = static_cast<unsigned int>(decoded_data.size()); SECItem reply; reply.data = NULL; reply.len = 0; result = PK11SDR_Decrypt(&request, &reply, NULL); if (result == SECSuccess) plain.assign(reinterpret_cast<char*>(reply.data), reply.len); SECITEM_FreeItem(&reply, PR_FALSE); PK11_FreeSlot(slot); } else { // Deletes the leading '~' before decoding. net::Base64Decode(crypt.substr(1), &plain); } return UTF8ToWide(plain); } // There are three versions of password filess. They store saved user // names and passwords. // References: // http://kb.mozillazine.org/Signons.txt // http://kb.mozillazine.org/Signons2.txt // http://kb.mozillazine.org/Signons3.txt void NSSDecryptor::ParseSignons(const std::string& content, std::vector<PasswordForm>* forms) { forms->clear(); // Splits the file content into lines. std::vector<std::string> lines; SplitString(content, '\n', &lines); // The first line is the file version. We skip the unknown versions. if (lines.empty()) return; int version; if (lines[0] == "#2c") version = 1; else if (lines[0] == "#2d") version = 2; else if (lines[0] == "#2e") version = 3; else return; GURL::Replacements rep; rep.ClearQuery(); rep.ClearRef(); rep.ClearUsername(); rep.ClearPassword(); // Reads never-saved list. Domains are stored one per line. size_t i; for (i = 1; i < lines.size() && lines[i].compare(".") != 0; ++i) { PasswordForm form; form.origin = GURL(lines[i]).ReplaceComponents(rep); form.signon_realm = form.origin.GetOrigin().spec(); form.blacklisted_by_user = true; forms->push_back(form); } ++i; // Reads saved passwords. The information is stored in blocks // seperated by lines that only contain a dot. We find a block // by the seperator and parse them one by one. while (i < lines.size()) { size_t begin = i; size_t end = i + 1; while (end < lines.size() && lines[end].compare(".") != 0) ++end; i = end + 1; // A block has at least five lines. if (end - begin < 5) continue; PasswordForm form; // The first line is the site URL. // For HTTP authentication logins, the URL may contain http realm, // which will be in bracket: // sitename:8080 (realm) GURL url; std::string realm; const char kRealmBracketBegin[] = " ("; const char kRealmBracketEnd[] = ")"; if (lines[begin].find(kRealmBracketBegin) != std::string::npos) { // In this case, the scheme may not exsit. We assume that the // scheme is HTTP. if (lines[begin].find("://") == std::string::npos) lines[begin] = "http://" + lines[begin]; size_t start = lines[begin].find(kRealmBracketBegin); url = GURL(lines[begin].substr(0, start)); start += std::string(kRealmBracketBegin).size(); size_t end = lines[begin].rfind(kRealmBracketEnd); realm = lines[begin].substr(start, end - start); } else { // Don't have http realm. It is the URL that the following passwords // belong to. url = GURL(lines[begin]); } // Skips this block if the URL is not valid. if (!url.is_valid()) continue; form.origin = url.ReplaceComponents(rep); form.signon_realm = form.origin.GetOrigin().spec(); if (!realm.empty()) form.signon_realm += realm; form.ssl_valid = form.origin.SchemeIsSecure(); ++begin; // There may be multiple username/password pairs for this site. // In this case, they are saved in one block without a seperated // line (contains a dot). while (begin + 4 < end) { // The user name. form.username_element = UTF8ToWide(lines[begin++]); form.username_value = Decrypt(lines[begin++]); // The element name has a leading '*'. if (lines[begin].at(0) == '*') { form.password_element = UTF8ToWide(lines[begin++].substr(1)); form.password_value = Decrypt(lines[begin++]); } else { // Maybe the file is bad, we skip to next block. break; } // The action attribute from the form element. This line exists // in versin 2 or above. if (version >= 2) { if (begin < end) form.action = GURL(lines[begin]).ReplaceComponents(rep); ++begin; } // Version 3 has an extra line for further use. if (version == 3) { ++begin; } forms->push_back(form); } } }
33.744565
80
0.664398
[ "object", "vector" ]
579a632942adaa580f65635942cf173961b67f74
42,623
cpp
C++
Dark Basic Public Shared/Dark Basic Pro SDK/Shared/Multiplayer/CMultiplayerC.cpp
domydev/Dark-Basic-Pro
237fd8d859782cb27b9d5994f3c34bc5372b6c04
[ "MIT" ]
231
2018-01-28T00:06:56.000Z
2022-03-31T21:39:56.000Z
Dark Basic Public Shared/Dark Basic Pro SDK/Shared/Multiplayer/CMultiplayerC.cpp
domydev/Dark-Basic-Pro
237fd8d859782cb27b9d5994f3c34bc5372b6c04
[ "MIT" ]
9
2016-02-10T10:46:16.000Z
2017-12-06T17:27:51.000Z
Dark Basic Public Shared/Dark Basic Pro SDK/Shared/Multiplayer/CMultiplayerC.cpp
domydev/Dark-Basic-Pro
237fd8d859782cb27b9d5994f3c34bc5372b6c04
[ "MIT" ]
66
2018-01-28T21:54:52.000Z
2022-02-16T22:50:57.000Z
// // Multiplayer DLL // ////////////////////////////////////////////////////////////////////////////////// // INCLUDES / LIBS /////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// #ifdef DARKSDK_COMPILE #pragma comment ( lib, "dplayx.lib" ) #endif // Includes #include ".\..\error\cerror.h" #include ".\..\core\globstruct.h" #include "network\CNetwork.h" #include "network\NetQueue.h" #ifdef DARKSDK_COMPILE #include ".\..\..\..\DarkGDK\Code\Include\DarkSDKBitmap.h" #include ".\..\..\..\DarkGDK\Code\Include\DarkSDKImage.h" #include ".\..\..\..\DarkGDK\Code\Include\DarkSDKSound.h" #include ".\..\..\..\DarkGDK\Code\Include\DarkSDKBasic3D.h" #include ".\..\..\..\DarkGDK\Code\Include\DarkSDKMemblocks.h" #endif #include "cmultiplayerc.h" ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// // GLOBALS /////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// // leefix - 131108 - DarkGDK does not want another global instance #ifdef DARKSDK_COMPILE #define DBPRO_GLOBAL static #endif // Global Shared Data Pointer (passed in from core) DBPRO_GLOBAL GlobStruct* g_pGlob = NULL; DBPRO_GLOBAL PTR_FuncCreateStr g_pCreateDeleteStringFunction = NULL; // Global Internal Data DBPRO_GLOBAL char m_pWorkString[256]; DBPRO_GLOBAL CNetwork* pCNetwork = NULL; DWORD gInternalErrorCode = 0; DBPRO_GLOBAL bool gbAlwaysHaveFocus = false; // Used to call memblockDLL for memblock return ptr function typedef int ( *MEMBLOCKS_GetMemblockExist ) ( int ); typedef DWORD ( *MEMBLOCKS_GetMemblockPtr ) ( int ); typedef DWORD ( *MEMBLOCKS_GetMemblockSize ) ( int ); typedef void ( *MEMBLOCKS_MemblockFromMedia ) ( int, int ); typedef void ( *MEMBLOCKS_MediaFromMemblock ) ( int, int ); typedef void ( *MEMBLOCKS_MakeMemblock ) ( int, int ); typedef void ( *MEMBLOCKS_DeleteMemblock ) ( int ); DBPRO_GLOBAL MEMBLOCKS_GetMemblockExist g_Memblock_GetMemblockExist; DBPRO_GLOBAL MEMBLOCKS_GetMemblockPtr g_Memblock_GetMemblockPtr; DBPRO_GLOBAL MEMBLOCKS_GetMemblockSize g_Memblock_GetMemblockSize; DBPRO_GLOBAL MEMBLOCKS_MemblockFromMedia g_Memblock_MemblockFromImage; DBPRO_GLOBAL MEMBLOCKS_MemblockFromMedia g_Memblock_MemblockFromBitmap; DBPRO_GLOBAL MEMBLOCKS_MemblockFromMedia g_Memblock_MemblockFromSound; DBPRO_GLOBAL MEMBLOCKS_MemblockFromMedia g_Memblock_MemblockFromMesh; DBPRO_GLOBAL MEMBLOCKS_MediaFromMemblock g_Memblock_ImageFromMemblock; DBPRO_GLOBAL MEMBLOCKS_MediaFromMemblock g_Memblock_BitmapFromMemblock; DBPRO_GLOBAL MEMBLOCKS_MediaFromMemblock g_Memblock_SoundFromMemblock; DBPRO_GLOBAL MEMBLOCKS_MediaFromMemblock g_Memblock_MeshFromMemblock; DBPRO_GLOBAL MEMBLOCKS_MakeMemblock g_Memblock_MakeMemblock; DBPRO_GLOBAL MEMBLOCKS_DeleteMemblock g_Memblock_DeleteMemblock; // Used to call mediaDLLs typedef int ( *MEDIA_GetExist ) ( int ); DBPRO_GLOBAL MEDIA_GetExist g_Image_GetExist; DBPRO_GLOBAL MEDIA_GetExist g_Bitmap_GetExist; DBPRO_GLOBAL MEDIA_GetExist g_Sound_GetExist; DBPRO_GLOBAL MEDIA_GetExist g_Basic3D_GetExist; // local checklist work vars DBPRO_GLOBAL bool g_bCreateChecklistNow = false; DBPRO_GLOBAL DWORD g_dwMaxStringSizeInEnum = 0; // Internal Data DBV1 DBPRO_GLOBAL bool gbNetDataExists=false; DBPRO_GLOBAL int gdwNetDataType=0; DBPRO_GLOBAL DWORD gdwNetDataPlayerFrom=0; DBPRO_GLOBAL DWORD gdwNetDataPlayerTo=0; DBPRO_GLOBAL DWORD gpNetDataDWORD=NULL; DBPRO_GLOBAL DWORD gpNetDataDWORDSize=0; DBPRO_GLOBAL int gPlayerIDDatabase[256]; DBPRO_GLOBAL bool gbPlayerIDDatabaseFlagged[256]; // External Data DBV1 extern CNetQueue* gpNetQueue; extern int gGameSessionActive; extern bool gbSystemSessionLost; extern int gSystemPlayerCreated; extern int gSystemPlayerDestroyed; extern int gSystemSessionIsNowHosting; ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// // // Internal Functions // DARKSDK void Constructor ( void ) { gpNetDataDWORD = NULL; //pCNetwork = NULL; } DARKSDK void FreeNet ( void ) { if(gdwNetDataType>=3 && gpNetDataDWORD) { //delete (char*)gpNetDataDWORD; // mike - 250604 delete [ ] ( char* ) gpNetDataDWORD; gpNetDataDWORD=NULL; } if(pCNetwork) { pCNetwork->CloseNetGame(); delete pCNetwork; pCNetwork=NULL; } } DARKSDK void Destructor ( void ) { FreeNet(); } DARKSDK void RefreshD3D ( int iMode ) { } DARKSDK void SetErrorHandler ( LPVOID pErrorHandlerPtr ) { // Update error handler pointer g_pErrorHandler = (CRuntimeErrorHandler*)pErrorHandlerPtr; } DARKSDK void PassCoreData( LPVOID pGlobPtr ) { // Held in Core, used here.. g_pGlob = (GlobStruct*)pGlobPtr; g_pCreateDeleteStringFunction = g_pGlob->CreateDeleteString; #ifndef DARKSDK_COMPILE // memblock DLL ptrs g_Memblock_GetMemblockExist = ( MEMBLOCKS_GetMemblockExist ) GetProcAddress ( g_pGlob->g_Memblocks, "?MemblockExist@@YAHH@Z" ); g_Memblock_GetMemblockPtr = ( MEMBLOCKS_GetMemblockPtr ) GetProcAddress ( g_pGlob->g_Memblocks, "?GetMemblockPtr@@YAKH@Z" ); g_Memblock_GetMemblockSize = ( MEMBLOCKS_GetMemblockSize ) GetProcAddress ( g_pGlob->g_Memblocks, "?GetMemblockSize@@YAHH@Z" ); g_Memblock_MemblockFromImage = ( MEMBLOCKS_MemblockFromMedia ) GetProcAddress ( g_pGlob->g_Memblocks, "?CreateMemblockFromImage@@YAXHH@Z" ); g_Memblock_MemblockFromBitmap = ( MEMBLOCKS_MemblockFromMedia ) GetProcAddress ( g_pGlob->g_Memblocks, "?CreateMemblockFromBitmap@@YAXHH@Z" ); g_Memblock_MemblockFromSound = ( MEMBLOCKS_MemblockFromMedia ) GetProcAddress ( g_pGlob->g_Memblocks, "?CreateMemblockFromSound@@YAXHH@Z" ); g_Memblock_MemblockFromMesh = ( MEMBLOCKS_MemblockFromMedia ) GetProcAddress ( g_pGlob->g_Memblocks, "?CreateMemblockFromMesh@@YAXHH@Z" ); g_Memblock_ImageFromMemblock = ( MEMBLOCKS_MediaFromMemblock ) GetProcAddress ( g_pGlob->g_Memblocks, "?CreateImageFromMemblock@@YAXHH@Z" ); g_Memblock_BitmapFromMemblock = ( MEMBLOCKS_MediaFromMemblock ) GetProcAddress ( g_pGlob->g_Memblocks, "?CreateBitmapFromMemblock@@YAXHH@Z" ); g_Memblock_SoundFromMemblock = ( MEMBLOCKS_MediaFromMemblock ) GetProcAddress ( g_pGlob->g_Memblocks, "?CreateSoundFromMemblock@@YAXHH@Z" ); g_Memblock_MeshFromMemblock = ( MEMBLOCKS_MediaFromMemblock ) GetProcAddress ( g_pGlob->g_Memblocks, "?CreateMeshFromMemblock@@YAXHH@Z" ); g_Memblock_MakeMemblock = ( MEMBLOCKS_MakeMemblock ) GetProcAddress ( g_pGlob->g_Memblocks, "?MakeMemblock@@YAXHH@Z" ); g_Memblock_DeleteMemblock = ( MEMBLOCKS_DeleteMemblock ) GetProcAddress ( g_pGlob->g_Memblocks, "?DeleteMemblock@@YAXH@Z" ); // media DLL ptrs g_Image_GetExist = ( MEDIA_GetExist ) GetProcAddress ( g_pGlob->g_Image, "?GetExistEx@@YAHH@Z" ); g_Bitmap_GetExist = ( MEDIA_GetExist ) GetProcAddress ( g_pGlob->g_Bitmap, "?BitmapExist@@YAHH@Z" ); g_Sound_GetExist = ( MEDIA_GetExist ) GetProcAddress ( g_pGlob->g_Sound, "?GetSoundExist@@YAHH@Z" ); g_Basic3D_GetExist = ( MEDIA_GetExist ) GetProcAddress ( g_pGlob->g_Basic3D, "?GetMeshExist@@YAHH@Z" ); #else g_Memblock_GetMemblockExist = dbMemblockExist; g_Memblock_GetMemblockPtr = dbGetMemblockPtr; g_Memblock_GetMemblockSize = ( MEMBLOCKS_GetMemblockSize )dbGetMemblockSize; g_Memblock_MemblockFromImage = dbMakeMemblockFromImage; g_Memblock_MemblockFromBitmap = dbMakeMemblockFromBitmap; g_Memblock_MemblockFromSound = dbMakeMemblockFromSound; g_Memblock_MemblockFromMesh = dbMakeMemblockFromMesh; g_Memblock_ImageFromMemblock = dbMakeImageFromMemblock; g_Memblock_BitmapFromMemblock = dbMakeBitmapFromMemblock; g_Memblock_SoundFromMemblock = dbMakeSoundFromMemblock; g_Memblock_MeshFromMemblock = dbMakeMeshFromMemblock; g_Memblock_MakeMemblock = dbMakeMemblock; g_Memblock_DeleteMemblock = dbDeleteMemblock; g_Image_GetExist = dbImageExist; g_Bitmap_GetExist =dbBitmapExist; g_Sound_GetExist = dbSoundExist; g_Basic3D_GetExist =dbObjectExist; #endif } DBPRO_GLOBAL LPSTR GetReturnStringFromWorkString(void) { LPSTR pReturnString=NULL; if(m_pWorkString) { DWORD dwSize=strlen(m_pWorkString); g_pCreateDeleteStringFunction((DWORD*)&pReturnString, dwSize+1); strcpy(pReturnString, m_pWorkString); } return pReturnString; } DARKSDK bool QuickStartInit(int* sessionnumber) { bool bCreationValid=true; if(pCNetwork==NULL) { pCNetwork = new CNetwork; if(pCNetwork->SetNetConnections(-1)!=0) { if(pCNetwork->FindNetSessions("")!=0) { if(pCNetwork->SetNetSessions(1)!=0) { // QuickStart Success - reassign session number to 1 if(sessionnumber) *sessionnumber=0; } else { RunTimeWarning(RUNTIMEERROR_MPFAILEDTOSETSESSION); bCreationValid=false; } } else { RunTimeWarning(RUNTIMEERROR_MPFAILEDTOFINDSESSION); bCreationValid=false; } } else { RunTimeWarning(RUNTIMEERROR_MPFAILEDTOCONNECT); bCreationValid=false; } } return bCreationValid; } DARKSDK int findseqidindatabase(int dpid) { int free=-1, got=-1; for(int s=1; s<256; s++) { if(gPlayerIDDatabase[s]==0 && free==-1) free=s; if(gPlayerIDDatabase[s]==dpid) { got=s; break; } } if(got==-1) { if(free!=-1) { gPlayerIDDatabase[free]=dpid; return free; } else return -1; } else return got; } DARKSDK void CoreSendNetMsg(int type, int playerid, DWORD* pMessageData, DWORD dwSize, int guarenteed) { if(pCNetwork && gGameSessionActive>0) { // Get Player Id bool bSendValid=true; if(playerid==0) playerid=ALLPLAYERS; if(playerid!=0) { // Find player ID from database playerid=gPlayerIDDatabase[playerid]; if(playerid==0) { // Player not exist - send nothing bSendValid=false; } } // If send is valid if(bSendValid) { // Build MSG Data DWORD size; char* pData; char* pStr; switch(type) { // Integer Message case 1 : size = 4; pData = (char*)GlobalAlloc(GMEM_FIXED, sizeof(int) + sizeof(DWORD) + size); memcpy(pData, &type, sizeof(int)); memcpy(pData+sizeof(int), &size, sizeof(DWORD)); memcpy(pData+sizeof(int)+sizeof(DWORD), pMessageData, size); break; // Float Message case 2 : size = 4; pData = (char*)GlobalAlloc(GMEM_FIXED, sizeof(int) + sizeof(DWORD) + size); memcpy(pData, &type, sizeof(int)); memcpy(pData+sizeof(int), &size, sizeof(DWORD)); memcpy(pData+sizeof(int)+sizeof(DWORD), pMessageData, size); break; // String Message case 3 : pStr = (char*)pMessageData; size = strlen(pStr) + 1; pData = (char*)GlobalAlloc(GMEM_FIXED, sizeof(int) + sizeof(DWORD) + size); memcpy(pData, &type, sizeof(int)); memcpy(pData+sizeof(int), &size, sizeof(DWORD)); memcpy(pData+sizeof(int)+sizeof(DWORD), pStr, size); break; // Memblock Message case 4 : case 5 : case 6 : case 7 : case 8 : size = dwSize; pData = (char*)GlobalAlloc(GMEM_FIXED, sizeof(int) + sizeof(DWORD) + size); memcpy(pData, &type, sizeof(int)); memcpy(pData+sizeof(int), &size, sizeof(DWORD)); memcpy(pData+sizeof(int)+sizeof(DWORD), pMessageData, size); break; } if(guarenteed==1) { if(pCNetwork->SendNetMsgGUA(playerid, (tagNetData*)pData)==0) RunTimeWarning(RUNTIMEERROR_MPFAILEDTOSENDMESSAGE); } else { if(pCNetwork->SendNetMsg(playerid, (tagNetData*)pData)==0) RunTimeWarning(RUNTIMEERROR_MPFAILEDTOSENDMESSAGE); } // Free MSG Data if(pData) { GlobalFree(pData); pData=NULL; } } else RunTimeWarning(RUNTIMEERROR_MPPLAYERNOTEXIST); } else RunTimeWarning(RUNTIMEERROR_MPNOTINSESSION); } // // Command Functions // DARKSDK void CreateNetGame(LPSTR gamename, LPSTR name, int playermax) { if(gGameSessionActive==0) { // lee - 220306 - u6b4 - validation check, prevent crashing if ( gamename==NULL || name==NULL ) { RunTimeWarning(RUNTIMEERROR_MPFAILEDTOCREATEGAME); return; } // Easy Quick-Start if connection and session not set.. bool bCreationValid=QuickStartInit(NULL); // Net Game Creation Here if(bCreationValid) { if(strcmp(gamename,"")!=0) { if(strcmp(name,"")!=0) { if(playermax>=2 && playermax<=255) { if(pCNetwork->CreateNetGame(gamename, name, playermax, DPSESSION_MIGRATEHOST)!=0) { // Clear PlayerID Database gGameSessionActive=1; ZeroMemory(gPlayerIDDatabase, sizeof(gPlayerIDDatabase)); } else RunTimeWarning(RUNTIMEERROR_MPFAILEDTOCREATEGAME); } else RunTimeError(RUNTIMEERROR_MPCREATEBETWEEN2AND255); } else RunTimeError(RUNTIMEERROR_MPMUSTGIVEPLAYERNAME); } else RunTimeError(RUNTIMEERROR_MPMUSTGIVEGAMENAME); } else RunTimeWarning(RUNTIMEERROR_MPFAILEDTOCREATEGAME); } else RunTimeWarning(RUNTIMEERROR_MPSESSIONEXISTS); } DARKSDK void CreateNetGameEx(LPSTR gamename, LPSTR name, int playermax, int flagnum) { if(gGameSessionActive==0) { // lee - 220306 - u6b4 - validation check, prevent crashing if ( gamename==NULL || name==NULL ) { RunTimeWarning(RUNTIMEERROR_MPFAILEDTOCREATEGAME); return; } // Easy Quick-Start if connection and session not set.. bool bCreationValid=QuickStartInit(NULL); // Net Game Creation Here if(bCreationValid) { if(strcmp(gamename,"")!=0) { if(strcmp(name,"")!=0) { if(playermax>=2 && playermax<=255) { DWORD flags=0; if(flagnum==1) flags |= DPSESSION_MIGRATEHOST; if(flagnum==2) flags |= DPSESSION_CLIENTSERVER; if(pCNetwork->CreateNetGame(gamename, name, playermax, flags)!=0) { // Clear PlayerID Database gGameSessionActive=1; ZeroMemory(gPlayerIDDatabase, sizeof(gPlayerIDDatabase)); } else RunTimeWarning(RUNTIMEERROR_MPFAILEDTOCREATEGAME); } else RunTimeError(RUNTIMEERROR_MPCREATEBETWEEN2AND255); } else RunTimeError(RUNTIMEERROR_MPMUSTGIVEPLAYERNAME); } else RunTimeError(RUNTIMEERROR_MPMUSTGIVEGAMENAME); } else RunTimeWarning(RUNTIMEERROR_MPFAILEDTOCREATEGAME); } else RunTimeWarning(RUNTIMEERROR_MPSESSIONEXISTS); } DARKSDK void JoinNetGame(int sessionnum, LPSTR name) { if(gGameSessionActive==0) { // lee - 220306 - u6b4 - validation check, prevent crashing if ( name==NULL ) { RunTimeError(RUNTIMEERROR_MPMUSTGIVEPLAYERNAME); return; } // Easy Quick-Start if connection and session not set.. sessionnum-=1; bool bCreationValid=QuickStartInit(&sessionnum); // Net Game Creation Here if(bCreationValid) { if(sessionnum>=0 && sessionnum<MAX_SESSIONS) { if(pCNetwork->SetNetSessions(sessionnum)!=0) { if(strcmp(name,"")!=0) { int iResult = pCNetwork->JoinNetGame(name); if(iResult==1) { // Clear PlayerID Database gGameSessionActive=2; ZeroMemory(gPlayerIDDatabase, sizeof(gPlayerIDDatabase)); } else { if(iResult==2) RunTimeWarning(RUNTIMEERROR_MPNOTCREATEDPLAYER); else { if(iResult==3) RunTimeWarning(RUNTIMEERROR_MPTOOMANYPLAYERS); else RunTimeWarning(RUNTIMEERROR_MPFAILEDTOJOINGAME); } } } else RunTimeError(RUNTIMEERROR_MPMUSTGIVEPLAYERNAME); } else RunTimeWarning(RUNTIMEERROR_MPFAILEDTOSETSESSION); } else RunTimeError(RUNTIMEERROR_MPSESSIONNUMINVALID); } else RunTimeWarning(RUNTIMEERROR_MPFAILEDTOJOINGAME); } else RunTimeWarning(RUNTIMEERROR_MPSESSIONEXISTS); } DARKSDK void InternalJoinNetGame(int sessionnum, LPSTR name) { if(gGameSessionActive==0) { // lee - 220306 - u6b4 - validation check, prevent crashing if ( name==NULL ) return; // Easy Quick-Start if connection and session not set.. sessionnum-=1; bool bCreationValid=QuickStartInit(&sessionnum); // Net Game Creation Here if(bCreationValid) { if(sessionnum>=0 && sessionnum<MAX_SESSIONS) { if(pCNetwork->SetNetSessions(sessionnum)!=0) { if(strcmp(name,"")!=0) { int iResult = pCNetwork->JoinNetGame(name); if(iResult==1) { // Clear PlayerID Database gGameSessionActive=2; ZeroMemory(gPlayerIDDatabase, sizeof(gPlayerIDDatabase)); } } } } } } } DARKSDK void CloseNetGame(void) { // Clear PlayerID Database gGameSessionActive=0; ZeroMemory(gPlayerIDDatabase, sizeof(gPlayerIDDatabase)); // General network termination FreeNet(); } DARKSDK void PerformChecklistForNetConnections(void) { if(pCNetwork==NULL) pCNetwork = new CNetwork; char* data[MAX_CONNECTIONS]; ZeroMemory(data, sizeof(data)); // Generate Checklist g_pGlob->checklistqty=0; g_pGlob->checklistexists=true; g_pGlob->checklisthasvalues=false; g_pGlob->checklisthasstrings=true; if(pCNetwork->GetNetConnections(data)) { g_dwMaxStringSizeInEnum=0; g_bCreateChecklistNow=false; for(int pass=0; pass<2; pass++) { if(pass==1) { // Ensure checklist is large enough g_bCreateChecklistNow=true; for(int c=0; c<g_pGlob->checklistqty; c++) GlobExpandChecklist(c, g_dwMaxStringSizeInEnum); } // Run through... DWORD ci=0; for(DWORD i=0; i<MAX_CONNECTIONS; i++) { if(g_bCreateChecklistNow==true) strcpy(g_pGlob->checklist[i].string, ""); if(data[i]) { if(g_bCreateChecklistNow==true) { if(ci<g_pGlob->dwChecklistArraySize) { strcpy(g_pGlob->checklist[i].string, data[i]); if(i+1>ci) ci=i+1; } } else { DWORD dwSize = strlen(data[i]); if(dwSize>g_dwMaxStringSizeInEnum) g_dwMaxStringSizeInEnum=dwSize; if(i+1>ci) ci=i+1; } } } g_pGlob->checklistqty=ci; } } else g_pGlob->checklistqty=0; } DARKSDK void SetNetConnections(int index) { if(pCNetwork==NULL) pCNetwork = new CNetwork; index-=1; if(index>=0 && index<MAX_CONNECTIONS) { if(pCNetwork->SetNetConnections(index)!=0) { if(pCNetwork->FindNetSessions("")==0) RunTimeWarning(RUNTIMEERROR_MPFAILEDTOFINDSESSION); } else RunTimeWarning(RUNTIMEERROR_MPFAILEDTOCONNECT); } else RunTimeError(RUNTIMEERROR_MPCONNECTIONNUMINVALID); } DARKSDK void SetNetConnectionsEx(int index, LPSTR ipaddress) { if(pCNetwork==NULL) pCNetwork = new CNetwork; index-=1; if(index>=0 && index<MAX_CONNECTIONS) { if(pCNetwork->SetNetConnections(index)!=0) { if(pCNetwork->FindNetSessions(ipaddress)==0) RunTimeWarning(RUNTIMEERROR_MPFAILEDTOFINDSESSION); } else RunTimeWarning(RUNTIMEERROR_MPFAILEDTOCONNECT); } else RunTimeError(RUNTIMEERROR_MPCONNECTIONNUMINVALID); } DARKSDK void PerformChecklistForNetSessions(void) { if(pCNetwork==NULL) pCNetwork = new CNetwork; char* data[MAX_SESSIONS]; ZeroMemory(data, sizeof(data)); // Generate Checklist g_pGlob->checklistqty=0; g_pGlob->checklistexists=true; g_pGlob->checklisthasvalues=false; g_pGlob->checklisthasstrings=true; if(pCNetwork->GetNetSessions(data)) { g_dwMaxStringSizeInEnum=0; g_bCreateChecklistNow=false; for(int pass=0; pass<2; pass++) { if(pass==1) { // Ensure checklist is large enough g_bCreateChecklistNow=true; for(int c=0; c<g_pGlob->checklistqty; c++) GlobExpandChecklist(c, g_dwMaxStringSizeInEnum); } DWORD ci=0; for(DWORD i=0; i<MAX_SESSIONS; i++) { if(g_bCreateChecklistNow==true) { // ensure only validf checklist items are cleared if( i <g_pGlob->dwChecklistArraySize) strcpy ( g_pGlob->checklist[i].string, "" ); if(data[i]) { if(ci<g_pGlob->dwChecklistArraySize) { strcpy(g_pGlob->checklist[i].string, data[i]); if(i+1>ci) ci=i+1; //// mike - 250604 - stores extra data g_pGlob->checklisthasvalues=true; g_pGlob->checklist [ i ].valuea = netSession[i].iPlayers; g_pGlob->checklist [ i ].valueb = netSession[i].iMaxPlayers; } } } else { if(data[i]) if(i+1>ci) ci=i+1; } } g_pGlob->checklistqty=ci; } } else g_pGlob->checklistqty=0; } DARKSDK void PerformChecklistForNetPlayers(void) { DPID dpids[256]; char* data[256]; ZeroMemory(dpids, sizeof(dpids)); ZeroMemory(data, sizeof(data)); g_pGlob->checklistqty=0; g_pGlob->checklistexists=true; g_pGlob->checklisthasvalues=true; g_pGlob->checklisthasstrings=true; if(gGameSessionActive>0) { // Update checklist with player names and ids DWORD playernum=pCNetwork->GetNetPlayers(data, dpids); if(playernum>255) playernum=255; if(playernum>0) { // Reset lafs for player removal ZeroMemory(gbPlayerIDDatabaseFlagged, sizeof(gbPlayerIDDatabaseFlagged)); g_pGlob->checklistqty=playernum; for(int c=0; c<g_pGlob->checklistqty; c++) { if ( data [ c ] ) { GlobExpandChecklist(c, 255); strcpy(g_pGlob->checklist[c].string, ""); //strcpy(g_pGlob->checklist[c].string, "bob"); g_pGlob->checklist[c].valuea = findseqidindatabase(dpids[c]); gbPlayerIDDatabaseFlagged[g_pGlob->checklist[c].valuea]=true; g_pGlob->checklist[c].valueb = dpids[c]; g_pGlob->checklist[c].valuec = 0; g_pGlob->checklist[c].valued = 0; if(dpids[c]==pCNetwork->GetLocalPlayerDPID()) g_pGlob->checklist[c].valuec = 1; if(dpids[c]==pCNetwork->GetServerPlayerDPID()) g_pGlob->checklist[c].valued = 1; strcpy(g_pGlob->checklist[c].string, data[c]); } } for(int s=1; s<256; s++) if(gbPlayerIDDatabaseFlagged[s]==false) gPlayerIDDatabase[s]=0; } } /* DPID dpids[256]; char* data[256]; ZeroMemory(dpids, sizeof(dpids)); ZeroMemory(data, sizeof(data)); // Generate Checklist g_pGlob->checklistqty=0; g_pGlob->checklistexists=true; g_pGlob->checklisthasvalues=true; g_pGlob->checklisthasstrings=true; if(gGameSessionActive>0) { // Update checklist with player names and ids DWORD playernum=pCNetwork->GetNetPlayers(data, dpids); if(playernum>255) playernum=255; if(playernum>0) { // Reset lafs for player removal ZeroMemory(gbPlayerIDDatabaseFlagged, sizeof(gbPlayerIDDatabaseFlagged)); g_dwMaxStringSizeInEnum=0; g_bCreateChecklistNow=false; for(int pass=0; pass<2; pass++) { if(pass==1) { // Ensure checklist is large enough g_bCreateChecklistNow=true; for(int c=0; c<g_pGlob->checklistqty; c++) GlobExpandChecklist(c, g_dwMaxStringSizeInEnum); } DWORD ci=0; for(DWORD i=0; i<playernum; i++) { if(g_bCreateChecklistNow==true) { strcpy(g_pGlob->checklist[i].string, ""); if(data[i]) { if(ci<g_pGlob->dwChecklistArraySize) { g_pGlob->checklist[i].valuea = findseqidindatabase(dpids[i]); gbPlayerIDDatabaseFlagged[g_pGlob->checklist[i].valuea]=true; g_pGlob->checklist[i].valueb = dpids[i]; g_pGlob->checklist[i].valuec = 0; g_pGlob->checklist[i].valued = 0; if(dpids[i]==pCNetwork->GetLocalPlayerDPID()) g_pGlob->checklist[i].valuec = 1; if(dpids[i]==pCNetwork->GetServerPlayerDPID()) g_pGlob->checklist[i].valued = 1; strcpy(g_pGlob->checklist[i].string, data[i]); if(i+1>ci) ci=i+1; } } } else { if(data[i]) if(i+1>ci) ci=i+1; } } g_pGlob->checklistqty=ci; } // Delete players from database no longer in list for(int s=1; s<256; s++) if(gbPlayerIDDatabaseFlagged[s]==false) gPlayerIDDatabase[s]=0; } else g_pGlob->checklistqty=0; } else g_pGlob->checklistqty=0; */ } DARKSDK void CreatePlayer(LPSTR playername) { if(pCNetwork && gGameSessionActive>0) { if(pCNetwork->CreatePlayer(playername)==0) RunTimeWarning(RUNTIMEERROR_MPNOTCREATEDPLAYER); } else RunTimeWarning(RUNTIMEERROR_MPNOTINSESSION); } DARKSDK int CreatePlayerEx(LPSTR playername) { int playerid=0; if(pCNetwork && gGameSessionActive>0) { if((playerid=pCNetwork->CreatePlayer(playername))!=0) { // Return sequenced id from dpid playerid = findseqidindatabase(playerid); } else RunTimeWarning(RUNTIMEERROR_MPNOTCREATEDPLAYER); } else RunTimeWarning(RUNTIMEERROR_MPNOTINSESSION); return playerid; } DARKSDK void DestroyPlayer(int playerid) { if(pCNetwork && gGameSessionActive>0) { if(playerid>=1 && playerid<=256) { int playerindex = gPlayerIDDatabase[playerid]; if(playerindex!=0) { if(pCNetwork->DestroyPlayer(playerindex)) { gPlayerIDDatabase[playerid]=0; } else RunTimeWarning(RUNTIMEERROR_MPCANNOTDELETEPLAYER); } else RunTimeWarning(RUNTIMEERROR_MPPLAYERNOTEXIST); } else RunTimeError(RUNTIMEERROR_MPPLAYERNUMINVALID); } else RunTimeWarning(RUNTIMEERROR_MPNOTINSESSION); } DARKSDK void SendNetMsgL(int playerid, int MessageData) { CoreSendNetMsg(1, playerid, (DWORD*)&MessageData, 0, 0); } DARKSDK void SendNetMsgF(int playerid, DWORD MessageData) { CoreSendNetMsg(2, playerid, &MessageData, 0, 0); } DARKSDK void SendNetMsgS(int playerid, LPSTR pMessageData) { CoreSendNetMsg(3, playerid, (DWORD*)pMessageData, 0, 0); } DARKSDK void SendNetMsgMemblock(int playerid, int mbi) { if(mbi>=1 && mbi<=255) { LPSTR pMemblockData = (LPSTR)g_Memblock_GetMemblockPtr(mbi); if(pMemblockData) { DWORD dwMemblockSize = g_Memblock_GetMemblockSize(mbi); CoreSendNetMsg(4, playerid, (DWORD*)pMemblockData, dwMemblockSize, 0); } else RunTimeError(RUNTIMEERROR_MEMBLOCKNOTEXIST); } else RunTimeError(RUNTIMEERROR_MEMBLOCKRANGEILLEGAL); } DARKSDK void SendNetMsgMemblockEx(int playerid, int mbi, int gua) { if(mbi>=1 && mbi<=255) { LPSTR pMemblockData = (LPSTR)g_Memblock_GetMemblockPtr(mbi); if(pMemblockData) { DWORD dwMemblockSize = g_Memblock_GetMemblockSize(mbi); CoreSendNetMsg(4, playerid, (DWORD*)pMemblockData, dwMemblockSize, gua); } else RunTimeError(RUNTIMEERROR_MEMBLOCKNOTEXIST); } else RunTimeError(RUNTIMEERROR_MEMBLOCKRANGEILLEGAL); } DARKSDK void SendNetMsgImage(int playerid, int imageindex, int gua) { if(imageindex>=1 && imageindex<=MAXIMUMVALUE) { if ( g_Image_GetExist(imageindex) ) { int mbi=257; g_Memblock_MemblockFromImage(mbi, imageindex); DWORD* pPtr = (DWORD*)g_Memblock_GetMemblockPtr(mbi); DWORD dwSize = g_Memblock_GetMemblockSize(mbi); CoreSendNetMsg(5, playerid, pPtr, dwSize, gua); } else RunTimeError(RUNTIMEERROR_IMAGENOTEXIST); } else RunTimeError(RUNTIMEERROR_IMAGEILLEGALNUMBER); } DARKSDK void SendNetMsgBitmap(int playerid, int bitmapindex, int gua) { if(bitmapindex>=0 && bitmapindex<MAXIMUMVALUE) { if(bitmapindex==0 || g_Bitmap_GetExist(bitmapindex)) { int mbi=257; g_Memblock_MemblockFromBitmap(mbi, bitmapindex); DWORD* pPtr = (DWORD*)g_Memblock_GetMemblockPtr(mbi); DWORD dwSize = g_Memblock_GetMemblockSize(mbi); CoreSendNetMsg(6, playerid, pPtr, dwSize, gua); } else RunTimeError(RUNTIMEERROR_BITMAPNOTEXIST); } else RunTimeError(RUNTIMEERROR_BITMAPILLEGALNUMBER); } DARKSDK void SendNetMsgSound(int playerid, int soundindex, int gua) { if(soundindex>=1 && soundindex<MAXIMUMVALUE) { if(g_Sound_GetExist(soundindex)) { int mbi=257; g_Memblock_MemblockFromSound(mbi, soundindex); DWORD* pPtr = (DWORD*)g_Memblock_GetMemblockPtr(mbi); DWORD dwSize = g_Memblock_GetMemblockSize(mbi); CoreSendNetMsg(7, playerid, pPtr, dwSize, gua); } else RunTimeError(RUNTIMEERROR_SOUNDNOTEXIST); } else RunTimeError(RUNTIMEERROR_SOUNDNUMBERILLEGAL); } DARKSDK void SendNetMsgMesh(int playerid, int meshindex, int gua) { if(meshindex>0 && meshindex<MAXIMUMVALUE) { if(g_Basic3D_GetExist(meshindex)) { int mbi=257; g_Memblock_MemblockFromMesh(mbi, meshindex); DWORD* pPtr = (DWORD*)g_Memblock_GetMemblockPtr(mbi); DWORD dwSize = g_Memblock_GetMemblockSize(mbi); CoreSendNetMsg(8, playerid, pPtr, dwSize, gua); } else RunTimeError(RUNTIMEERROR_B3DMESHNOTEXIST); } else RunTimeError(RUNTIMEERROR_B3DMESHNUMBERILLEGAL); } DARKSDK void GetNetMsg(void) { if(pCNetwork && gGameSessionActive>0) { QueuePacketStruct packet; packet.pMsg=NULL; if(pCNetwork->GetOneNetMsgOffQueue(&packet)!=0) { if(packet.pMsg) { // Remove old data if(gdwNetDataType>=3 && gpNetDataDWORD) { delete (char*)gpNetDataDWORD; gpNetDataDWORD=NULL; } // Prepare new data gbNetDataExists=true; gdwNetDataType=packet.pMsg->id; gdwNetDataPlayerFrom=packet.idFrom; gdwNetDataPlayerTo=packet.idTo; // Create Data switch(gdwNetDataType) { case 1 : // Integer memcpy((int*)&gpNetDataDWORD, &packet.pMsg->msg, 4); break; case 2 : // Float memcpy((float*)&gpNetDataDWORD, &packet.pMsg->msg, 4); break; case 3 : // String if(packet.pMsg->size>0) { gpNetDataDWORD=(DWORD)new char[packet.pMsg->size]; memcpy((char*)gpNetDataDWORD, &packet.pMsg->msg, packet.pMsg->size); } break; case 4 : // Memblock gpNetDataDWORDSize=packet.pMsg->size; if(gpNetDataDWORDSize>0) { gpNetDataDWORD=(DWORD)new char[gpNetDataDWORDSize]; memcpy((char*)gpNetDataDWORD, &packet.pMsg->msg, gpNetDataDWORDSize); } break; case 5 : // Image case 6 : // Bitmap case 7 : // Sound case 8 : // Mesh gpNetDataDWORDSize=packet.pMsg->size; if(gpNetDataDWORDSize>0) { gpNetDataDWORD=(DWORD)new char[gpNetDataDWORDSize]; memcpy((char*)gpNetDataDWORD, &packet.pMsg->msg, gpNetDataDWORDSize); } break; } // Free MSG Data if(packet.pMsg) { GlobalFree(packet.pMsg); packet.pMsg=NULL; } } else { gdwNetDataType=0; gbNetDataExists=false; } } else { gdwNetDataType=0; gbNetDataExists=false; } } else RunTimeWarning(RUNTIMEERROR_MPNOTINSESSION); } DARKSDK int NetMsgExists(void) { int iResult=0; if(pCNetwork && gGameSessionActive>0) iResult=(int)gbNetDataExists; return iResult; } DARKSDK int NetMsgType(void) { return gdwNetDataType; } DARKSDK int NetMsgPlayerFrom(void) { return findseqidindatabase(gdwNetDataPlayerFrom); } DARKSDK int NetMsgPlayerTo(void) { return findseqidindatabase(gdwNetDataPlayerTo); } DARKSDK int NetMsgInteger(void) { if(gdwNetDataType==1) return *(int*)&gpNetDataDWORD; return 0; } DARKSDK DWORD NetMsgFloat(void) { if(gdwNetDataType==2) return gpNetDataDWORD; return 0; } DARKSDK DWORD NetMsgString(DWORD pDestStr) { strcpy(m_pWorkString, ""); if(pCNetwork && gpNetDataDWORD && gGameSessionActive>0 && gdwNetDataType==3) strcpy(m_pWorkString, (char*)gpNetDataDWORD); // Create and return string if(pDestStr) g_pCreateDeleteStringFunction((DWORD*)&pDestStr, 0); LPSTR pReturnString=GetReturnStringFromWorkString(); // mike - 250604 - clear delete (char*)gpNetDataDWORD; gpNetDataDWORD = NULL; return (DWORD)pReturnString; } DARKSDK void NetMsgMemblock(int mbi) { if(gdwNetDataType==4) { if(mbi>=1 && mbi<=255) { if(gpNetDataDWORDSize>0) { // Free existing memblock if(g_Memblock_GetMemblockExist(mbi)) g_Memblock_DeleteMemblock(mbi); // Create memblock g_Memblock_MakeMemblock ( mbi, gpNetDataDWORDSize ); if(g_Memblock_GetMemblockExist(mbi)) { // Put message in memblock LPSTR pMemblockData = (LPSTR)g_Memblock_GetMemblockPtr(mbi); DWORD dwMemblockSize = g_Memblock_GetMemblockSize(mbi); memcpy(pMemblockData, (char*)gpNetDataDWORD, gpNetDataDWORDSize); // mike - 250604 - clear delete (char*)gpNetDataDWORD; gpNetDataDWORD = NULL; } else RunTimeError(RUNTIMEERROR_MEMBLOCKCREATIONFAILED); } else RunTimeError(RUNTIMEERROR_MEMBLOCKCREATIONFAILED); } else RunTimeError(RUNTIMEERROR_MEMBLOCKRANGEILLEGAL); } } DARKSDK void NetMsgImage(int imageindex) { if(gdwNetDataType==5) { int mbi=257; if(imageindex>=1 && imageindex<=MAXIMUMVALUE) { if(gpNetDataDWORDSize>0) { // Free existing memblock if(g_Memblock_GetMemblockExist(mbi)) g_Memblock_DeleteMemblock(mbi); // Create memblock g_Memblock_MakeMemblock ( mbi, gpNetDataDWORDSize ); if(g_Memblock_GetMemblockExist(mbi)) { // Put message in memblock LPSTR pMemblockData = (LPSTR)g_Memblock_GetMemblockPtr(mbi); DWORD dwMemblockSize = g_Memblock_GetMemblockSize(mbi); memcpy(pMemblockData, (char*)gpNetDataDWORD, gpNetDataDWORDSize); // Turn memblock into media g_Memblock_ImageFromMemblock(imageindex,mbi); } else RunTimeError(RUNTIMEERROR_B3DERROR); } } else RunTimeError(RUNTIMEERROR_IMAGEILLEGALNUMBER); } } DARKSDK void NetMsgBitmap(int bitmapindex) { if(gdwNetDataType==6) { int mbi=257; if(bitmapindex>=0 && bitmapindex<MAXIMUMVALUE) { if(gpNetDataDWORDSize>0) { // Free existing memblock if(g_Memblock_GetMemblockExist(mbi)) g_Memblock_DeleteMemblock(mbi); // Create memblock g_Memblock_MakeMemblock ( mbi, gpNetDataDWORDSize ); if(g_Memblock_GetMemblockExist(mbi)) { // Put message in memblock LPSTR pMemblockData = (LPSTR)g_Memblock_GetMemblockPtr(mbi); DWORD dwMemblockSize = g_Memblock_GetMemblockSize(mbi); memcpy(pMemblockData, (char*)gpNetDataDWORD, gpNetDataDWORDSize); // Turn memblock into media g_Memblock_BitmapFromMemblock(bitmapindex,mbi); } else RunTimeError(RUNTIMEERROR_B3DERROR); } } else RunTimeError(RUNTIMEERROR_BITMAPILLEGALNUMBER); } } DARKSDK void NetMsgSound(int soundindex) { if(gdwNetDataType==7) { int mbi=257; if(soundindex>=1 && soundindex<MAXIMUMVALUE) { if(gpNetDataDWORDSize>0) { // Free existing memblock if(g_Memblock_GetMemblockExist(mbi)) g_Memblock_DeleteMemblock(mbi); // Create memblock g_Memblock_MakeMemblock ( mbi, gpNetDataDWORDSize ); if(g_Memblock_GetMemblockExist(mbi)) { // Put message in memblock LPSTR pMemblockData = (LPSTR)g_Memblock_GetMemblockPtr(mbi); DWORD dwMemblockSize = g_Memblock_GetMemblockSize(mbi); memcpy(pMemblockData, (char*)gpNetDataDWORD, gpNetDataDWORDSize); // Turn memblock into media g_Memblock_SoundFromMemblock(soundindex,mbi); } else RunTimeError(RUNTIMEERROR_SOUNDERROR); } } else RunTimeError(RUNTIMEERROR_SOUNDNUMBERILLEGAL); } } DARKSDK void NetMsgMesh(int meshindex) { if(gdwNetDataType==8) { int mbi=257; if(meshindex>0 && meshindex<MAXIMUMVALUE) { if(gpNetDataDWORDSize>0) { // Free existing memblock if(g_Memblock_GetMemblockExist(mbi)) g_Memblock_DeleteMemblock(mbi); // Create memblock g_Memblock_MakeMemblock ( mbi, gpNetDataDWORDSize ); if(g_Memblock_GetMemblockExist(mbi)) { // Put message in memblock LPSTR pMemblockData = (LPSTR)g_Memblock_GetMemblockPtr(mbi); DWORD dwMemblockSize = g_Memblock_GetMemblockSize(mbi); memcpy(pMemblockData, (char*)gpNetDataDWORD, gpNetDataDWORDSize); // Turn memblock into media g_Memblock_MeshFromMemblock(meshindex,mbi); } else RunTimeError(RUNTIMEERROR_B3DERROR); } } else RunTimeError(RUNTIMEERROR_B3DMESHNUMBERILLEGAL); } } DARKSDK int NetSessionExists(void) { if(gGameSessionActive>0) return 1; return 0; } DARKSDK int NetSessionLost(void) { int iValue=(int)gbSystemSessionLost; if(pCNetwork) pCNetwork->GetSysNetMsgIfAny(); gbSystemSessionLost=false; return iValue; } DARKSDK int NetPlayerCreated(void) { int iValue=0; if(pCNetwork) pCNetwork->GetSysNetMsgIfAny(); if(gSystemPlayerCreated>0) { iValue=findseqidindatabase(gSystemPlayerCreated); gSystemPlayerCreated=0; } return iValue; } DARKSDK int NetPlayerDestroyed(void) { int iValue=0; if(pCNetwork) pCNetwork->GetSysNetMsgIfAny(); if(gSystemPlayerDestroyed>0) { iValue=findseqidindatabase(gSystemPlayerDestroyed); gSystemPlayerDestroyed=0; } return iValue; } DARKSDK int NetSessionIsNowHosting(void) { int iValue; if(pCNetwork) pCNetwork->GetSysNetMsgIfAny(); iValue=gSystemSessionIsNowHosting; gSystemSessionIsNowHosting=0; return iValue; } /* void AlwaysActiveOn(void) { // Not Implemented in DBPRO V1 RELEASE RunTimeError(RUNTIMEERROR_COMMANDNOWOBSOLETE); } void AlwaysActiveOff(void) { // Not Implemented in DBPRO V1 RELEASE RunTimeError(RUNTIMEERROR_COMMANDNOWOBSOLETE); } */ // // New Multiplayer Commands // DARKSDK int MagicNetGame(DWORD lpGameName, DWORD lpPlayerName, int PlayerMax, int FlagNum ) { // Player Num is returned int iPlayerNumber=0; // First try to join InternalJoinNetGame(1, (LPSTR)lpPlayerName); if(gGameSessionActive==0) { // Ok, create as fresh host to new game CreateNetGameEx( (LPSTR)lpGameName, (LPSTR)lpPlayerName, PlayerMax, FlagNum ); iPlayerNumber=findseqidindatabase(pCNetwork->m_LocalPlayerDPID); } else { // In Magic creation, Order of players handled by ore-filling existing players char* data[256]; DPID dpids[256]; ZeroMemory(data, sizeof(data)); ZeroMemory(dpids, sizeof(dpids)); DWORD playernum=pCNetwork->GetNetPlayers(data, dpids); for(DWORD i=0; i<playernum; i++) if(data[i]) if(pCNetwork->m_LocalPlayerDPID!=dpids[i]) int ExistingPlayerNumber = findseqidindatabase(dpids[i]); // Get number if this player iPlayerNumber=findseqidindatabase(pCNetwork->m_LocalPlayerDPID); } return iPlayerNumber; } DARKSDK int NetBufferSize(void) { if(gpNetQueue) return gpNetQueue->QueueSize(); else return 0; } ////////////////////////////////////////////////////////////////////////////////// // DARK SDK SECTION ////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// #ifdef DARKSDK_COMPILE void ConstructorMultiplayer ( void ) { Constructor ( ); } void DestructorMultiplayer ( void ) { Destructor ( ); } void SetErrorHandlerMultiplayer ( LPVOID pErrorHandlerPtr ) { SetErrorHandler ( pErrorHandlerPtr ); } void PassCoreDataMultiplayer ( LPVOID pGlobPtr ) { PassCoreData ( pGlobPtr ); } void RefreshD3DMultiplayer ( int iMode ) { RefreshD3D ( iMode ); } void dbCreateNetGame(LPSTR gamename, LPSTR name, int playermax) { CreateNetGame( gamename, name, playermax); } void dbCreateNetGame (LPSTR gamename, LPSTR name, int playermax, int flagnum) { CreateNetGameEx( gamename, name, playermax, flagnum); } void dbJoinNetGame(int sessionnum, LPSTR name) { JoinNetGame( sessionnum, name); } void dbFreeNetGame(void) { CloseNetGame(); } void dbPerformChecklistForNetConnections(void) { PerformChecklistForNetConnections(); } void dbSetNetConnections(int index) { SetNetConnections(index); } void dbSetNetConnections(int index, LPSTR ipaddress) { SetNetConnectionsEx( index, ipaddress); } void dbPerformChecklistForNetSessions(void) { PerformChecklistForNetSessions(); } void dbPerformChecklistForNetPlayers(void) { PerformChecklistForNetPlayers(); } void dbCreateNetPlayer(LPSTR playername) { CreatePlayer( playername); } int dbCreateNetPlayerEx(LPSTR playername) { return CreatePlayerEx( playername); } void dbDestroyNetPlayer(int playerid) { DestroyPlayer( playerid); } void dbSendNetMessageInteger(int playerid, int MessageData) { SendNetMsgL( playerid, MessageData); } void dbSendNetMessageFloat(int playerid, float MessageData) { SendNetMsgF( playerid, ( DWORD ) MessageData); } void dbSendNetMessageString(int playerid, LPSTR pMessageData) { SendNetMsgS( playerid, pMessageData); } void dbSendNetMessageMemblock(int playerid, int mbi) { SendNetMsgMemblock( playerid, mbi); } void dbSendNetMessageMemblock(int playerid, int mbi, int gua) { SendNetMsgMemblockEx( playerid, mbi, gua); } void dbSendNetMessageImage(int playerid, int imageindex, int gua) { SendNetMsgImage( playerid, imageindex, gua); } void dbSendNetMessageBitmap(int playerid, int bitmapindex, int gua) { SendNetMsgBitmap( playerid, bitmapindex, gua); } void dbSendNetMessageSound(int playerid, int soundindex, int gua) { SendNetMsgSound( playerid, soundindex, gua); } void dbSendNetMessageMesh(int playerid, int meshindex, int gua) { SendNetMsgMesh( playerid, meshindex, gua); } void dbGetNetMessage(void) { GetNetMsg ( ); } int dbNetMessageInteger(void) { return NetMsgInteger ( ); } float dbNetMessageFloat(void) { DWORD dwReturn = NetMsgFloat ( ); return *( float* ) &dwReturn; } char* dbNetMessageString(void) { static char* szReturn = NULL; DWORD dwReturn = NetMsgString ( NULL ); szReturn = ( char* ) dwReturn; return szReturn; } void dbNetMessageMemblock(int mbi) { NetMsgMemblock( mbi); } void dbNetMessageImage(int imageindex) { NetMsgImage( imageindex); } void dbNetMessageBitmap(int bitmapindex) { NetMsgBitmap( bitmapindex); } void dbNetMessageSound(int soundindex) { NetMsgSound( soundindex); } void dbNetMessageMesh(int meshindex) { NetMsgMesh( meshindex); } int dbNetMessageExists(void) { return NetMsgExists(); } int dbNetMessageType(void) { return NetMsgType ( ); } int dbNetMessagePlayerFrom(void) { return NetMsgPlayerFrom(); } int dbNetMessagePlayerTo(void) { return NetMsgPlayerTo(); } int dbNetSessionExists(void) { return NetSessionExists(); } int dbNetSessionLost(void) { return NetSessionLost(); } int dbNetPlayerCreated(void) { return NetPlayerCreated(); } int dbNetPlayerDestroyed(void) { // lee - 300706 - fixed recursive error return NetPlayerDestroyed(); } int dbNetGameNowHosting(void) { return NetSessionIsNowHosting(); } int dbDefaultNetGame(char* lpGameName, char* lpPlayerName, int PlayerMax, int FlagNum ) { return MagicNetGame( ( DWORD ) lpGameName, ( DWORD ) lpPlayerName, PlayerMax, FlagNum ); } int dbNetBufferSize(void) { return NetBufferSize (); } // lee - 300706 - GDK fixes void dbFreeNetPlayer ( int playerid ) { dbDestroyNetPlayer ( playerid ); } void dbSetNetConnection ( int index ) { SetNetConnections ( index ); } void dbSetNetConnection ( int index, LPSTR ipaddress ) { dbSetNetConnections ( index, ipaddress ); } int dbNetGameExists ( void ) { return dbNetSessionExists (); } int dbNetGameLost ( void ) { return dbNetSessionLost (); } #endif ////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////
24.723318
144
0.696971
[ "mesh" ]
579d18d5db5a320f2346b6048981c7d1b8ad2ecb
5,409
cpp
C++
2015/day22/p1/main.cpp
jbaldwin/adventofcode2019
bdc333330dd5e36458a49f0b7cd64d462c9988c7
[ "MIT" ]
null
null
null
2015/day22/p1/main.cpp
jbaldwin/adventofcode2019
bdc333330dd5e36458a49f0b7cd64d462c9988c7
[ "MIT" ]
null
null
null
2015/day22/p1/main.cpp
jbaldwin/adventofcode2019
bdc333330dd5e36458a49f0b7cd64d462c9988c7
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <string> #include <optional> #include <set> #include <map> #include <lib/file_util.hpp> #include <chain/chain.hpp> struct Spell { Spell( std::string _name, int64_t _mana_cost, int64_t _hp, int64_t _mp, int64_t _dmg, int64_t _armor, int64_t _duration ) : name(std::move(_name)) , mana_cost(_mana_cost) , hp(_hp) , mp(_mp) , dmg(_dmg) , armor(_armor) , duration(_duration) { } std::string name; int64_t mana_cost; int64_t hp; int64_t mp; int64_t dmg; int64_t armor; int64_t duration; }; struct Character { Character( std::string _name, int64_t _hit_points, int64_t _mana_points, int64_t _damage ) : name(std::move(name)) , hit_points(_hit_points) , mana_points(_mana_points) , damage(_damage) { } std::string name; int64_t hit_points{0}; int64_t mana_points{0}; int64_t armor{0}; int64_t damage{0}; }; static int64_t g_min_mana_used = std::numeric_limits<int64_t>::max(); auto fight( Character player, Character boss, const std::vector<Spell>& spells, std::map<std::string, Spell> active_spells, int64_t mana_used, bool players_turn, bool hard_mode ) -> void { if(hard_mode && players_turn) { player.hit_points--; if(player.hit_points <= 0) { return; } } player.armor = 0; // Reset so it doesn't continuously apply armor via Shield // Apply active spells { std::map<std::string, Spell> active_spells_copy{}; for(auto& [active_spell_name, active_spell] : active_spells) { player.hit_points += active_spell.hp; player.mana_points += active_spell.mp; boss.hit_points -= active_spell.dmg; player.armor += active_spell.armor; active_spell.duration--; if(active_spell.duration > 0) { active_spells_copy.emplace(active_spell_name, active_spell); } } active_spells.swap(active_spells_copy); } if(boss.hit_points <= 0) { if(mana_used < g_min_mana_used) { g_min_mana_used = mana_used; } return; } // No point exploring trees that cost too much mana. if(mana_used > g_min_mana_used) { return; } if(players_turn) { for(const auto& spell : spells) { if(auto in_use = active_spells.find(spell.name); in_use == active_spells.end()) { if(spell.mana_cost <= player.mana_points) { auto new_active_spells = active_spells; new_active_spells.emplace(spell.name, spell); auto new_player = player; new_player.mana_points -= spell.mana_cost; fight( std::move(new_player), boss, spells, std::move(new_active_spells), mana_used + spell.mana_cost, false, hard_mode ); } } } } else { player.hit_points -= boss.damage - player.armor; if(player.hit_points <= 0) { return; } fight(player, boss, spells, std::move(active_spells), mana_used, true, hard_mode); } } int main(int argc, char* argv[]) { std::vector<std::string> args{argv, argv + argc}; if(args.size() != 2) { std::cout << args[0] << " <input_file>" << std::endl; return 0; } auto contents = file::read(args[1]); auto parts = chain::str::split(contents, '\n'); auto boss_hp = std::stol(std::string{chain::str::split(parts[0], ':')[1]}); auto boss_damage = std::stol(std::string{chain::str::split(parts[1], ':')[1]}); auto player_hp = std::stol(std::string{chain::str::split(parts[2], ':')[1]}); auto player_mana = std::stol(std::string{chain::str::split(parts[3], ':')[1]}); std::cout << "Boss hp " << boss_hp << " boss damage " << boss_damage << "\n"; std::cout << "Player hp " << player_hp << " player mana " << player_mana << "\n"; const std::vector<Spell> spells { // cost hp mp dmg arm duration Spell{"Magic Missle", 53, 0, 0, 4, 0, 0}, Spell{"Drain", 73, 2, 0, 2, 0, 0}, Spell{"Shield", 113, 0, 0, 0, 7, 6}, Spell{"Poison", 173, 0, 0, 3, 0, 6}, Spell{"Recharge", 229, 0, 101, 0, 0, 5} }; const Character boss{"Boss", boss_hp, 0, boss_damage}; const Character player{"Player", player_hp, player_mana, 0}; fight(player, boss, spells, {}, 0, true, false); std::cout << "Min mana used " << g_min_mana_used << "\n"; g_min_mana_used = std::numeric_limits<int64_t>::max(); fight(player, boss, spells, {}, 0, true, true); std::cout << "Min mana used (HARD) " << g_min_mana_used << "\n"; // Harder example spells casts for minimum mana used. // recharge // shield // drain // poison // magic missle return 0; }
25.635071
91
0.530043
[ "vector" ]
579f16ed30a2de4fd3045296b9c2e02f8fd82030
2,186
cpp
C++
Codeforces/B_String_Problem.cpp
ANONYMOUS609/Competitive-Programming
d3753eeee24a660963f1d8911bf887c8f41f5677
[ "MIT" ]
2
2019-01-30T12:45:18.000Z
2021-05-06T19:02:51.000Z
Codeforces/B_String_Problem.cpp
ANONYMOUS609/Competitive-Programming
d3753eeee24a660963f1d8911bf887c8f41f5677
[ "MIT" ]
null
null
null
Codeforces/B_String_Problem.cpp
ANONYMOUS609/Competitive-Programming
d3753eeee24a660963f1d8911bf887c8f41f5677
[ "MIT" ]
3
2020-10-02T15:42:04.000Z
2022-03-27T15:14:16.000Z
#include<bits/stdc++.h> using namespace std; #define fast ios::sync_with_stdio(false);cin.tie(0) #define pb push_back #define digit(x) floor(log10(x))+1 #define mod 1000000007 #define endl "\n" #define int long long #define matrix vector<vector<int> > #define vi vector<int> #define pii pair<int,inr> #define vs vector<string> #define vp vector<pair<int,int> > #define test() int t;cin>>t;while(t--) #define all(x) x.begin(),x.end() #define debug(x) cerr << #x << " is " << x << endl; int dx[] = {0, 0, 1, -1}; int dy[] = {1, -1, 0, 0}; //=================================================================// int A[26][26]; void floydWarshal() { for (int k = 0; k < 26; k++) { for (int i = 0; i < 26; i++) { for (int j = 0; j < 26; j++) { A[i][j] = min(A[i][j], A[i][k] + A[k][j]); } } } } #undef int int main(){ #define int long long fast; string s, t; cin >> s >> t; if (s.length() != t.length()) { cout << -1; } else { for (int i = 0; i < 26; i++) { for (int j = 0; j < 26; j++) { if(i==j) A[i][j] = 0; else A[i][j] = INT_MAX; } } int n; cin >> n; while (n--) { char u, v; int w; cin >> u >> v >> w; A[u - 'a'][v - 'a'] = min(w,A[u - 'a'][v - 'a']); } floydWarshal(); bool ok = 1; int ans = 0; string res = s; for (int i = 0; i < s.length(); i++) { if(s[i] == t[i]) continue; int muchmin = INT_MAX; for (char ch = 'a'; ch <= 'z';ch++) { int tmp = muchmin; muchmin = min(A[s[i] - 'a'][ch - 'a'] + A[t[i] - 'a'][ch - 'a'], muchmin); if(muchmin < tmp) { res[i] = ch; } } if(muchmin==INT_MAX) { ok = 0; break; } ans += muchmin; } if(ok){ cout << ans << endl; cout << res << endl; } else cout << "-1" << endl; } return 0; }
25.418605
90
0.381519
[ "vector" ]
579fdaaef7f561c081cdc2f9f6b0e994e429b907
836
cpp
C++
source/universe/systems/node_renderer.cpp
tkgamegroup/flame
f1628100cc66e13f84ea3047ea33af019caeb01b
[ "MIT" ]
25
2018-02-28T05:59:50.000Z
2022-03-18T03:11:52.000Z
source/universe/systems/node_renderer.cpp
tkgamegroup/flame
f1628100cc66e13f84ea3047ea33af019caeb01b
[ "MIT" ]
null
null
null
source/universe/systems/node_renderer.cpp
tkgamegroup/flame
f1628100cc66e13f84ea3047ea33af019caeb01b
[ "MIT" ]
5
2018-05-17T04:16:30.000Z
2021-12-22T04:02:02.000Z
#include "node_renderer_private.h" namespace flame { int sNodeRendererPrivate::set_mesh_res(int idx, graphics::Mesh* mesh) { return -1; } int sNodeRendererPrivate::find_mesh_res(graphics::Mesh* mesh) const { return -1; } uint sNodeRendererPrivate::add_mesh_transform(const mat4& mat, const mat3& nor) { return 0; } uint sNodeRendererPrivate::add_mesh_armature(const mat4* bones, uint count) { return 0; } void sNodeRendererPrivate::draw_mesh(uint id, uint mesh_id, uint skin, ShadingFlags flags) { } void sNodeRendererPrivate::update() { } struct sNodeRendererCreatePrivate : sNodeRenderer::Create { sNodeRendererPtr operator()() override { return new sNodeRendererPrivate(); } }sNodeRenderer_create_private; sNodeRenderer::Create& sNodeRenderer::create = sNodeRenderer_create_private; }
19
91
0.748804
[ "mesh" ]
57abda7aed3bfbe16a2b5b50ee98ee5c83da1fc4
2,735
cpp
C++
src/codegen/model_builder.cpp
annosoo/nncase
898bd4075a0f246bca7b62a912051af3d890aff4
[ "Apache-2.0" ]
1
2021-07-29T11:50:27.000Z
2021-07-29T11:50:27.000Z
src/codegen/model_builder.cpp
annosoo/nncase
898bd4075a0f246bca7b62a912051af3d890aff4
[ "Apache-2.0" ]
3
2021-05-27T06:08:30.000Z
2021-06-02T10:39:35.000Z
src/codegen/model_builder.cpp
annosoo/nncase
898bd4075a0f246bca7b62a912051af3d890aff4
[ "Apache-2.0" ]
null
null
null
/* Copyright 2019-2021 Canaan Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <nncase/codegen/model_builder.h> #include <nncase/runtime/model.h> #include <nncase/targets/target.h> using namespace nncase; using namespace nncase::codegen; using namespace nncase::ir; using namespace nncase::schedule; using namespace nncase::runtime; model_builder::model_builder(target &target, const schedule::schedule_result &sched) : target_(target), sched_(sched), dump_asm_(false) { } void model_builder::config_dump(const std::filesystem::path &dump_dir, bool dump_asm) { dump_dir_ = dump_dir; dump_asm_ = dump_asm; } build_model_result model_builder::build(std::ostream &output) { binary_writer writer(output); auto begin_pos = writer.position(); model_header header {}; header.identifier = MODEL_IDENTIFIER; header.version = MODEL_VERSION; header.flags = 0; header.alignment = 8; header.modules = (uint32_t)sched_.modules.size(); // Skip model header auto header_pos = writer.position(); writer.skip(sizeof(header)); uint32_t main_module_id = 0; for (auto &graph : sched_.graph_orders) { auto &mod = sched_.modules.at(graph); module_builder_params params { sched_, mod }; auto builder = target_.create_module_builder(graph->module_type(), graph->name(), params); builder->config_dump(dump_dir_ / graph->escaped_name(), dump_asm_); builder->build(writer); header.alignment = std::max(header.alignment, builder->alignment()); if (graph == sched_.main_module) header.main_module = main_module_id; main_module_id++; } auto end_pos = writer.position(); // header writer.position(header_pos); writer.write(header); writer.position(end_pos); build_model_result result; result.model_size = (size_t)(end_pos - begin_pos); return result; } size_t model_builder::max_usage(memory_location_t location) const { size_t usage = 0; for (auto &mod : sched_.modules) { auto it = mod.second.max_usages.find(location); if (it != mod.second.max_usages.end()) usage += it->second; } return usage; }
30.388889
98
0.69543
[ "model" ]
57b214abc9c744c90369943c39412e64e5138e41
10,746
cpp
C++
problem-solver/cxx/rulesApplicationModule/model/StatementsCheckResult.cpp
NikitaZotov/ostis-inference
6c5c7ca37668e6b22ba1cf261101e12e1e46589d
[ "Apache-2.0" ]
null
null
null
problem-solver/cxx/rulesApplicationModule/model/StatementsCheckResult.cpp
NikitaZotov/ostis-inference
6c5c7ca37668e6b22ba1cf261101e12e1e46589d
[ "Apache-2.0" ]
null
null
null
problem-solver/cxx/rulesApplicationModule/model/StatementsCheckResult.cpp
NikitaZotov/ostis-inference
6c5c7ca37668e6b22ba1cf261101e12e1e46589d
[ "Apache-2.0" ]
null
null
null
/* * This source file is part of an OSTIS project. For the latest info, see http://ostis.net * Distributed under the MIT License * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) */ #include "StatementsCheckResult.hpp" #include <sc-memory/sc_addr.hpp> #include <sc-agents-common/utils/GenerationUtils.hpp> #include "searcher/RuleConstructionsSearcher.hpp" #include "utils/RuleCheckResultUtils.hpp" using namespace std; using namespace rulesApplicationModule; using namespace utils; StatementsCheckResult::StatementsCheckResult() = default; void StatementsCheckResult::add( ScMemoryContext * context, ScAddr const & atomicStatement, SearchWithContentResult const & searchResult, ScTemplateParams const & params) { Replacements otherReplacements = createReplacements(context, atomicStatement, searchResult, params); addByReplacements(otherReplacements); } void StatementsCheckResult::add( ScMemoryContext * context, ScAddr const & atomicStatement, ScTemplateGenResult const & genResult) { Replacements otherReplacements = createReplacements(context, atomicStatement, genResult); addByReplacements(otherReplacements); } void StatementsCheckResult::addByReplacements(Replacements const & otherReplacements) { if (!replacements.empty() && !replacementsKeysIsEqual(replacements, otherReplacements)) throw runtime_error("StatementsCheckResult: cannot add gen result - different set of variables."); size_t replacementsCombinationNumber = RuleCheckResultUtils::getReplacementCombinationsNumber(replacements); size_t otherReplacementsCombinationNumber = RuleCheckResultUtils::getReplacementCombinationsNumber( otherReplacements); size_t sizeToReserve = replacementsCombinationNumber + otherReplacementsCombinationNumber; for (auto const & otherReplacement : otherReplacements) { replacements[otherReplacement.first].reserve(sizeToReserve); replacements[otherReplacement.first].insert( replacements[otherReplacement.first].end(), otherReplacement.second.begin(), otherReplacement.second.end()); } } bool StatementsCheckResult::extend(StatementsCheckResult const & other) { notFoundStructures.insert(other.notFoundStructures.begin(), other.notFoundStructures.end()); notSearchedStructures.insert(other.notSearchedStructures.begin(), other.notSearchedStructures.end()); return update(other.replacements); } bool StatementsCheckResult::extend( ScMemoryContext * context, ScAddr const & atomicStatement, size_t const & nestingLevel, SearchWithContentResult const & searchResult, ScTemplateParams const & params) // replace with extend from ScTemplateSearchResult { Replacements otherReplacements = createReplacements(context, atomicStatement, searchResult, params); if (otherReplacements.empty()) notFoundStructures.insert({ atomicStatement, nestingLevel }); return update(otherReplacements); } Replacements StatementsCheckResult::getUniqueReplacements(vector<string> const & identifiers) const { vector<string> existingKeys; for (auto const & identifier : identifiers) { if (replacements.find(identifier) != replacements.end()) existingKeys.push_back(identifier); } Replacements replacementsSubset; size_t replacementsCombinationsNum = RuleCheckResultUtils::getReplacementCombinationsNumber(replacements); for (size_t checkedCombinationIndex = 0; checkedCombinationIndex < replacementsCombinationsNum; checkedCombinationIndex++) { size_t combinationToCompareIndex = checkedCombinationIndex + 1; bool isUnique = true; while (combinationToCompareIndex < replacementsCombinationsNum && isUnique) { isUnique = replacementCombinationsForKeysAreDifferent( checkedCombinationIndex, combinationToCompareIndex, existingKeys); combinationToCompareIndex++; } if (isUnique) { for (auto const & key : existingKeys) replacementsSubset[key].push_back(replacements.at(key)[checkedCombinationIndex]); } } return replacementsSubset; } bool StatementsCheckResult::replacementCombinationsForKeysAreDifferent( size_t const & firstCombinationIndex, size_t const & secondCombinationIndex, vector<string> const & keys) const { bool replacementAreDifferent = false; for (auto const & key : keys) { if (replacements.at(key)[firstCombinationIndex] != replacements.at(key)[secondCombinationIndex]) { replacementAreDifferent = true; break; } } return replacementAreDifferent; } vector<string> StatementsCheckResult::getCommonVariablesIdtf(Replacements const & otherReplacements) { vector<string> commonKeys; for (auto const & replacement : replacements) { auto other_it = otherReplacements.find(replacement.first); if (other_it != otherReplacements.end()) { commonKeys.push_back(replacement.first); } } return commonKeys; } Replacements StatementsCheckResult::createReplacements( ScMemoryContext * context, ScAddr const & atomicStatement, ScTemplateGenResult const & genResult) { Replacements otherReplacements; RuleConstructionsSearcher ruleConstructionsSearcher(context); vector<string> variableIdentifiers = ruleConstructionsSearcher.getVariablesNodesSystemIdentifiers(atomicStatement); for (auto const & identifier : variableIdentifiers) otherReplacements[identifier].push_back(genResult[identifier]); return otherReplacements; } Replacements StatementsCheckResult::createReplacements( ScMemoryContext * context, ScAddr const & atomicStatement, SearchWithContentResult const & searchResult, ScTemplateParams const & params) { Replacements otherReplacements; if (!searchResult.empty()) { RuleConstructionsSearcher ruleConstructionsSearcher(context); vector<string> variableIdentifiers = ruleConstructionsSearcher.getVariablesNodesSystemIdentifiers(atomicStatement); for (auto const & searchResultItem : searchResult) { for (auto const & identifier : variableIdentifiers) { ScAddr replacement; if (params.Get(identifier, replacement)) otherReplacements[identifier].push_back(replacement); else otherReplacements[identifier].push_back(searchResultItem[identifier]); } } } return otherReplacements; } bool StatementsCheckResult::update(Replacements const & otherReplacements) { bool result; vector<string> commonKeys = getCommonVariablesIdtf(otherReplacements); if (commonKeys.empty()) result = updateWithoutKeys(otherReplacements); else result = updateWithCommonKeys(commonKeys, otherReplacements); return result; } bool StatementsCheckResult::updateWithCommonKeys( std::vector<std::string> const & commonKeys, Replacements const & otherReplacements) { bool result = false; Replacements updatedReplacements; size_t replacementsSize = RuleCheckResultUtils::getReplacementCombinationsNumber(replacements); size_t otherReplacementsSize = RuleCheckResultUtils::getReplacementCombinationsNumber(otherReplacements); vector<string> additionalKeys = getAdditionalKeys(otherReplacements); for (size_t replacementIndex = 0; replacementIndex < replacementsSize; replacementIndex++) { for (size_t otherReplacementIndex = 0; otherReplacementIndex < otherReplacementsSize; otherReplacementIndex++) { bool commonReplacementsAreEqual = commonKeysInReplacementsCombinationAreEqual( commonKeys, otherReplacements, otherReplacementIndex, replacementIndex); if (commonReplacementsAreEqual) { for (auto const & pair : replacements) updatedReplacements[pair.first].push_back(pair.second[replacementIndex]); for (auto const & additionalKey : additionalKeys) updatedReplacements[additionalKey].push_back(otherReplacements.at(additionalKey)[otherReplacementIndex]); } } } // All common variable replacements are different - the two structures are independent // The structure we found is not a continuation of the previous one - nothing to merge. if (!updatedReplacements.empty()) { replacements = updatedReplacements; result = true; } return result; } bool StatementsCheckResult::commonKeysInReplacementsCombinationAreEqual( std::vector<std::string> const & commonKeys, Replacements const & otherReplacements, size_t const & otherReplacementsCombinationIndex, size_t const & replacementsCombinationIndex) { bool commonReplacementsAreEqual = true; for (auto & commonKey: commonKeys) { if (replacements[commonKey][replacementsCombinationIndex] != otherReplacements.at(commonKey)[otherReplacementsCombinationIndex]) { commonReplacementsAreEqual = false; break; } } return commonReplacementsAreEqual; } vector<string> StatementsCheckResult::getAdditionalKeys(Replacements const & otherReplacements) { vector<string> additionalKeys; for (auto const & pair : otherReplacements) { if (replacements.find(pair.first) == replacements.end()) additionalKeys.push_back(pair.first); } return additionalKeys; } bool StatementsCheckResult::updateWithoutKeys(Replacements const & otherReplacements) { bool result = false; if (replacements.empty()) { replacements = otherReplacements; result = true; } else if (!otherReplacements.empty()) { Replacements updatedReplacements; size_t replacementsCombinationsNum = RuleCheckResultUtils::getReplacementCombinationsNumber(replacements); size_t otherReplacementsCombinationsNum = RuleCheckResultUtils::getReplacementCombinationsNumber(otherReplacements); for (size_t replacementIndex = 0; replacementIndex < replacementsCombinationsNum; replacementIndex++) { for (size_t otherReplacementIndex = 0; otherReplacementIndex < otherReplacementsCombinationsNum; otherReplacementIndex++) { for (auto const & pair : replacements) updatedReplacements[pair.first].push_back(pair.second[replacementIndex]); for (auto const & pair : otherReplacements) updatedReplacements[pair.first].push_back(pair.second[otherReplacementIndex]); } } replacements = updatedReplacements; result = true; } return result; } bool StatementsCheckResult::replacementsKeysIsEqual( Replacements const & first, Replacements const & second) { auto pred = [](auto a, auto b) { return a.first == b.first; }; return first.size() == second.size() && equal(first.begin(), first.end(), second.begin(), pred); }
33.899054
120
0.751722
[ "vector" ]
57b4979b6c5a10f1e37e95af779afba539cf8962
1,028
cpp
C++
RenderEngine/geometry_instance/Transform.cpp
igui/OppositeRenderer
2442741792b3f0f426025c2015002694fab692eb
[ "MIT" ]
9
2016-06-25T15:52:05.000Z
2020-01-15T17:31:49.000Z
RenderEngine/geometry_instance/Transform.cpp
igui/OppositeRenderer
2442741792b3f0f426025c2015002694fab692eb
[ "MIT" ]
null
null
null
RenderEngine/geometry_instance/Transform.cpp
igui/OppositeRenderer
2442741792b3f0f426025c2015002694fab692eb
[ "MIT" ]
2
2018-10-17T18:33:37.000Z
2022-03-14T20:17:30.000Z
/* * Copyright (c) 2013 Opposite Renderer * For the full copyright and license information, please view the LICENSE.txt * file that was distributed with this source code. */ #include "Transform.h" Transform::Transform() { this->arr[0] = 1; this->arr[1] = 0; this->arr[2] = 0; this->arr[3] = 0; this->arr[4] = 0; this->arr[5] = 1; this->arr[6] = 0; this->arr[7] = 0; this->arr[8] = 0; this->arr[9] = 0; this->arr[10] = 1; this->arr[11] = 0; this->arr[12] = 0; this->arr[13] = 0; this->arr[14] = 0; this->arr[15] = 1; } optix::Transform Transform::getOptixTransform( optix::Context& context ) { optix::Transform t = context->createTransform(); t->setMatrix(false, this->arr, NULL); return t; } void Transform::translate( float x, float y, float z ) { this->arr[3] += x; this->arr[7] += y; this->arr[11] += z; } void Transform::scale( float scale ) { this->arr[0] *= scale; this->arr[5] *= scale; this->arr[10] *= scale; }
21.416667
78
0.567121
[ "transform" ]
57c02f26f393f80b4b9c88fc2363bc2e96bc35f7
1,286
cpp
C++
USACOTasks/Section 3.4 Raucous Rockers/rockers.cpp
zombiecry/AlgorithmPractice
f42933883bd62a86aeef9740356f5010c6c9bebf
[ "MIT" ]
null
null
null
USACOTasks/Section 3.4 Raucous Rockers/rockers.cpp
zombiecry/AlgorithmPractice
f42933883bd62a86aeef9740356f5010c6c9bebf
[ "MIT" ]
null
null
null
USACOTasks/Section 3.4 Raucous Rockers/rockers.cpp
zombiecry/AlgorithmPractice
f42933883bd62a86aeef9740356f5010c6c9bebf
[ "MIT" ]
null
null
null
/* ID: yezhiyo1 PROG: rockers LANG: C++ */ #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <queue> #include <stack> #include <map> #include <set> #include <string> #include <algorithm> #include <cmath> #include <memory.h> using namespace std; ifstream fin("rockers.in"); ofstream fout("rockers.out"); const int MAX_N = 20; const int MAX_M = 20; int N,T,M; std::vector <bool> inserted; std::vector <int> songs; int a[MAX_N][MAX_N]; //[i,j) int c[MAX_M+1][MAX_N+1]; int Calc(int start,int len){ std::vector <int> nums; nums.resize(len); for (int i=0;i<len;i++){ nums[i]=songs[i+start]; } std::sort(nums.begin(),nums.end()); int count=0; int left=T; for (int i=0;i<len;i++){ if (left>=nums[i]){ left-=nums[i]; count++; } else{ break; } } return count; } int main (){ fin>>N>>T>>M; inserted.resize(N,false); songs.resize(N); for (int i=0;i<N;i++){ fin>>songs[i]; } for (int j=1;j<=N;j++){ for (int i=0;i<N;i++){ if (i+j<=N){ a[i][j]=Calc(i,j); } } } for (int i=0;i<N;i++){ c[1][i]=a[0][i+1]; } for (int i=2;i<=M;i++){ for (int j=0;j<N;j++){ c[i][j]=c[i-1][j]; for (int k=0;k<j;k++){ c[i][j]=std::max(c[i][j],c[i-1][k]+a[k+1][j-k]); } } } fout<<c[M][N-1]<<endl; return 0; }
16.701299
52
0.561431
[ "vector" ]
57c729e634d893ef860609f72545e1d9b9d72066
4,117
cpp
C++
src/tcp/server/server.cpp
adsniper-tech/rtb_perf_servers
5052177fe93ea30db4bde353e81c95ccd9fe6562
[ "Apache-2.0" ]
null
null
null
src/tcp/server/server.cpp
adsniper-tech/rtb_perf_servers
5052177fe93ea30db4bde353e81c95ccd9fe6562
[ "Apache-2.0" ]
null
null
null
src/tcp/server/server.cpp
adsniper-tech/rtb_perf_servers
5052177fe93ea30db4bde353e81c95ccd9fe6562
[ "Apache-2.0" ]
null
null
null
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com /* * Copyright (c) 2019, AdSniper, Oleg Romanenko (oleg@romanenko.ro) * * 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 <csignal> #include <sniper/event/Loop.h> #include <sniper/event/Sig.h> #include <sniper/event/Timer.h> #include <sniper/http/Server.h> #include <sniper/log/log.h> #include <sniper/std/check.h> #include <sniper/std/vector.h> #include <sniper/threads/Stop.h> #include <thread> #include "Config.h" using namespace sniper; void stop_signal(const event::loop_ptr& loop) { log_warn("Stop signal. Exiting"); threads::Stop::get().stop(); loop->break_loop(ev::ALL); } static void sigsegv_handler(int sig) { log_err("Error: signal {} ({})", strsignal(sig), sig); log_err("{}", stacktrace_to_string(boost::stacktrace::stacktrace())); exit(1); } class Node final { public: explicit Node(const tcp_test::server::Config& config) : _config(config) { for (unsigned i = 0; i < _config.threads_count(); i++) { _t.emplace_back([this] { try { worker(); } catch (std::exception& e) { log_err(e.what()); } catch (...) { log_err("[Node] non std::exception occured"); } }); } } ~Node() { for (auto& w : _t) if (w.joinable()) w.join(); } private: void worker() { auto loop = event::make_loop(); http::Server http_server(loop, _config.http_server_config()); check(http_server.bind(_config.ip(), _config.port()), "[Node] cannot bind to {}:{}", _config.ip(), _config.port()); string data; if (_config.response_size()) data.resize(_config.response_size()); http_server.set_cb_request([&](const auto& conn, const auto& req, const auto& resp) { if (!data.empty()) resp->set_data_nocopy(data); resp->code = http::ResponseStatus::OK; conn->send(resp); }); event::TimerRepeat timer_stop(loop, 1s, [&loop] { if (threads::Stop::get().is_stopped()) loop->break_loop(ev::ALL); }); loop->run(); } const tcp_test::server::Config& _config; vector<std::thread> _t; }; int main(int argc, char** argv) { if (argc != 2) { log_info("{}, build {}, {} UTC, rev {}", APP_NAME, __DATE__, __TIME__, GIT_SHA1); log_err("Run: {} config.conf", APP_NAME); return EXIT_FAILURE; } std::signal(SIGPIPE, SIG_IGN); std::signal(SIGSEGV, sigsegv_handler); std::signal(SIGABRT, sigsegv_handler); try { log_info("{} init", APP_NAME); auto loop = event::make_loop(); if (!loop) { log_err("Main: cannot init event loop"); return EXIT_FAILURE; } tcp_test::server::Config config(argv[1]); Node node(config); event::Sig sig_int(loop, SIGINT, stop_signal); event::Sig sig_iterm(loop, SIGTERM, stop_signal); log_info("{} started", APP_NAME); loop->run(); } catch (std::exception& e) { log_err(e.what()); return EXIT_FAILURE; } catch (...) { log_err("Non std::exception occured"); return EXIT_FAILURE; } log_info("{} stopped", APP_NAME); return EXIT_SUCCESS; }
27.446667
106
0.580034
[ "vector" ]
57c93a9a8e498805ff400f37e0bc1769233a8c0e
829
hpp
C++
src/whenifier.hpp
gregdionne/mcbasic
bdf8892068bab7dc552b92e473b835721ef0c354
[ "MIT" ]
5
2021-02-02T18:44:13.000Z
2022-03-08T16:53:09.000Z
src/whenifier.hpp
gregdionne/mcbasic
bdf8892068bab7dc552b92e473b835721ef0c354
[ "MIT" ]
6
2021-01-28T04:38:48.000Z
2021-04-05T03:06:33.000Z
src/whenifier.hpp
gregdionne/mcbasic
bdf8892068bab7dc552b92e473b835721ef0c354
[ "MIT" ]
3
2021-01-18T04:13:25.000Z
2021-10-29T23:25:49.000Z
// Copyright (C) 2022 Greg Dionne // Distributed under MIT License #ifndef WHENIFIER_HPP #define WHENIFIER_HPP #include "program.hpp" // replace IF .. THEN GOTO/GOSUB at end of line // with WHEN .. GOTO/GOSUB // // This provides a hint to the compiler that // the alternate branch can be omitted in favor // of fallthrough to the next BASIC line. class StatementWhenifier : public StatementOp { public: StatementWhenifier() = default; void operate(If &s) override; using StatementOp::operate; bool result{false}; bool isSub{false}; std::unique_ptr<NumericExpr> predicate; int lineNumber{0}; }; class Whenifier : public ProgramOp { public: Whenifier() = default; void operate(Program &p) override; void operate(Line &l) override; std::vector<std::unique_ptr<Line>>::iterator itCurrentLine; }; #endif
21.815789
61
0.727382
[ "vector" ]
57cac0c19b974ac44367d9c1fa633e160cdddc71
3,917
cpp
C++
src/lib/graphics/graphics/DrawLine.cpp
Adnn/Graphics
335d54bdbb5d8d6042c9adfb9e47ccb14f612cf8
[ "MIT" ]
null
null
null
src/lib/graphics/graphics/DrawLine.cpp
Adnn/Graphics
335d54bdbb5d8d6042c9adfb9e47ccb14f612cf8
[ "MIT" ]
null
null
null
src/lib/graphics/graphics/DrawLine.cpp
Adnn/Graphics
335d54bdbb5d8d6042c9adfb9e47ccb14f612cf8
[ "MIT" ]
null
null
null
#include "DrawLine.h" #include "shaders.h" #include <renderer/Error.h> #include <renderer/Uniforms.h> #include <renderer/VertexSpecification.h> namespace ad { namespace graphics { namespace { // // Per vertex data // struct VertexData { Position2<GLfloat> mPosition; }; constexpr AttributeDescriptionList gVertexDescription{ {0, 2, offsetof(VertexData, mPosition), MappedGL<GLfloat>::enumerator}, }; constexpr std::size_t gVerticesCount = 4; // Note: X is used for origin(0) or end(1). // Y is used for width. +normal(1) or -normal(-1). constexpr VertexData gVertices[gVerticesCount]{ {{0.0f, 1.0f}}, {{0.0f, -1.0f}}, {{1.0f, 1.0f}}, {{1.0f, -1.0f}}, }; // // Per instance data // constexpr AttributeDescriptionList gInstanceDescription{ { 1, 3, offsetof(DrawLine::Line, mOrigin), MappedGL<GLfloat>::enumerator}, { 2, 3, offsetof(DrawLine::Line, mEnd), MappedGL<GLfloat>::enumerator}, { 3, 1, offsetof(DrawLine::Line, mWidth_screen), MappedGL<GLfloat>::enumerator}, {{4, Attribute::Access::Float, true}, 4, offsetof(DrawLine::Line, mColor), MappedGL<GLubyte>::enumerator}, }; VertexSpecification make_VertexSpecification() { VertexSpecification specification; appendToVertexSpecification(specification, gVertexDescription, gsl::span{gVertices}); appendToVertexSpecification<DrawLine::Line>(specification, gInstanceDescription, {}, 1); return specification; } Program make_Program() { return makeLinkedProgram({ {GL_VERTEX_SHADER, drawline::gSolidColorLineVertexShader}, {GL_FRAGMENT_SHADER, gTrivialFragmentShaderOpacity}, }); } } // anonymous namespace DrawLine::DrawLine(std::shared_ptr<AppInterface> aAppInterface) : mDrawContext{ make_VertexSpecification(), make_Program() }, mListenWindowSize{aAppInterface->listenWindowResize( std::bind(&DrawLine::setWindowResolution, this, std::placeholders::_1))} { setWindowResolution(aAppInterface->getWindowSize()); setCameraTransformation(math::AffineMatrix<4, GLfloat>::Identity()); setProjectionTransformation(math::AffineMatrix<4, GLfloat>::Identity()); } void DrawLine::clearShapes() { mInstances.clear(); } void DrawLine::addLine(Line aLineData) { mInstances.push_back(std::move(aLineData)); } void DrawLine::render() const { activate(mDrawContext); auto scopedDepthTest = graphics::scopeFeature(GL_DEPTH_TEST, false); auto scopedBlend = graphics::scopeFeature(GL_BLEND, true); // // Stream vertex attributes // // The last vertex buffer added to the specification is the per instance data. respecifyBuffer(mDrawContext.mVertexSpecification.mVertexBuffers.back(), gsl::span<const Line>{mInstances}); // // Draw // glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, gVerticesCount, static_cast<GLsizei>(mInstances.size())); } void DrawLine::setCameraTransformation(const math::AffineMatrix<4, GLfloat> & aTransformation) { setUniform(mDrawContext.mProgram, "u_view", aTransformation); } void DrawLine::setProjectionTransformation(const math::Matrix<4, 4, GLfloat> & aTransformation) { setUniform(mDrawContext.mProgram, "u_projection", aTransformation); } void DrawLine::setWindowResolution(Size2<int> aNewResolution) { GLint location = glGetUniformLocation(mDrawContext.mProgram, "in_BufferResolution"); glProgramUniform2iv(mDrawContext.mProgram, location, 1, aNewResolution.data()); } } // namespace graphics } // namespace ad
27.978571
121
0.64769
[ "render" ]
57d5e1d62c2a42b301663a09dd29bddea97e0af6
30,141
cpp
C++
src/Reservoir.cpp
necst/Echobay
923e16f796d5019daa039a5b131061270746d429
[ "Apache-2.0" ]
9
2019-09-04T15:10:14.000Z
2021-09-21T10:14:33.000Z
src/Reservoir.cpp
necst/Echobay
923e16f796d5019daa039a5b131061270746d429
[ "Apache-2.0" ]
null
null
null
src/Reservoir.cpp
necst/Echobay
923e16f796d5019daa039a5b131061270746d429
[ "Apache-2.0" ]
null
null
null
#include "Reservoir.hpp" #include "Eigen/StdVector" #include "Quantizer.hpp" #ifdef USE_TBB #ifndef COUT_MU tbb::mutex cout_mutex; #endif #endif using namespace std::chrono; using namespace Eigen; using namespace Spectra; class WrException: public std::exception { virtual const char* what() const throw() { return "Wr: bad_alloc"; } } WrEx; /** * @brief Construct a Reservoir class with a given topology, number of layers and inputs * * @param nLayers Number of layers in deep reservoirs (= 1 in shallow networks) * @param Nu Number of input channels * @param type Topology of the network see also EchoBay::esn_config(const Eigen::VectorXd &optParams, YAML::Node confParams, int Nu, const std::string folder) * for details */ EchoBay::Reservoir::Reservoir(const int nLayers, const int Nu, const int type) { // Save layers _nLayers = nLayers; // Save input _Nu = Nu; // Save type _type = type; // Reserve vectors WinLayers.reserve(_nLayers); WrLayers.reserve(_nLayers); stateMat.reserve(_nLayers); _layerConfig.reserve(_nLayers); } /** * @brief Destroy the Reservoir object cleaning internal layers * */ EchoBay::Reservoir::~Reservoir() { // Free vectors _layerConfig.clear(); _layerConfig.shrink_to_fit(); WinLayers.clear(); WinLayers.shrink_to_fit(); WrLayers.clear(); WrLayers.shrink_to_fit(); stateMat.clear(); stateMat.shrink_to_fit(); } /** * @brief Initialize the reservoir according to internal topology * */ void EchoBay::Reservoir::init_network() { // Initialize Win switch(_type) { case 0: this->init_WinLayers(); break; case 1: this->init_WinLayers_swt(); break; case 2: this->init_WinLayers_crj(); break; } // Initialize Wr this->init_WrLayers(); // Initialize stateMat this->init_stateMat(); } /** * @brief Initialize random input layers * */ void EchoBay::Reservoir::init_WinLayers() { // Reset Win WinLayers.clear(); // Determine the input scaling rule int countScale = _layerConfig[0].scaleInput.size(); // TO DO: Not correct way for determining countscale // Homogeneous scaling if (countScale == 1) { WinLayers.push_back(_layerConfig[0].scaleInput[0] * MatrixBO::Random(_layerConfig[0].Nr, _Nu)); } else { // Differentiated input scaling MatrixBO Win(_layerConfig[0].Nr, _Nu); for (int cols = _Nu - 1; cols >= 0; cols--) { Win.col(cols) = _layerConfig[0].scaleInput[cols] * MatrixBO::Random(_layerConfig[0].Nr, 1); } WinLayers.push_back(Win); } // Fill subsequent layers for (int i = 1; i < _nLayers; ++i) { WinLayers.push_back(_layerConfig[i].scaleInput[0] * MatrixBO::Random(_layerConfig[i].Nr, _layerConfig[i - 1].Nr + 1)); } } /** * @brief Initialize input layers according to Small World Topology selection * */ void EchoBay::Reservoir::init_WinLayers_swt() { // Reset Win WinLayers.clear(); // Determine the input scaling rule int countScale = _layerConfig[0].scaleInput.size();//-1; std::vector<ArrayI> NIindex = _WinIndex; std::vector<ArrayI> NOIndex = _WoutIndex; int NiCount = NIindex[0].size(); int NoCount; // Homogeneous scaling if (countScale == 1) { MatrixBO temp = MatrixBO::Zero(_layerConfig[0].Nr, _Nu); temp.block(0,0,NiCount, _Nu) = _layerConfig[0].scaleInput[0] * MatrixBO::Random(NiCount, _Nu); WinLayers.push_back(temp); } else { // Differentiated input scaling MatrixBO Win(_layerConfig[0].Nr, _Nu); for (int cols = _Nu - 1; cols >= 0; cols--) { MatrixBO temp = MatrixBO::Zero(_layerConfig[0].Nr, 1); // Select a block of inputs temp.block(0,0,NiCount, 1) = _layerConfig[0].scaleInput[cols] * MatrixBO::Random(NiCount, 1); Win.col(cols) = temp; } WinLayers.push_back(Win); } // Fill subsequent layers for (int i = 1; i < _nLayers; ++i) { MatrixBO temp = MatrixBO::Zero(_layerConfig[i].Nr, _layerConfig[i-1].Nr + 1); NiCount = NIindex[i].size(); NoCount = NOIndex[i-1].size(); temp.block(0,floor(_layerConfig[i-1].Nr/2),NiCount, NoCount) = _layerConfig[i].scaleInput[0] * MatrixBO::Random(NiCount, NoCount); temp.block(0,_layerConfig[i-1].Nr,NiCount, 1) = _layerConfig[i].scaleInput[0] * MatrixBO::Random(NiCount, 1); WinLayers.push_back(temp); // MatrixBO temp(_layerConfig[i].Nr, _layerConfig[i-1].Nr + 1); // WinLayers.push_back(_layerConfig[i].scaleInput[0] * MatrixBO::Random(_layerConfig[i].Nr, _layerConfig[i - 1].Nr + 1)); } } /** * @brief Initialize input layers according to Cyclic Reservoir Jumps selection * */ void EchoBay::Reservoir::init_WinLayers_crj() { // Reset Win WinLayers.clear(); // Determine the input scaling rule int countScale = _layerConfig[0].scaleInput.size();//-1; // Initialize random engine unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); std::default_random_engine gen(seed); std::bernoulli_distribution probability(0.5); // Determine Win sign auto opSign = [&](void){return probability(gen) ? 1 : -1;}; MatrixBO temp = MatrixBO::NullaryExpr(_layerConfig[0].Nr, _Nu, opSign); // Apply value using lambda // Homogeneous scaling if (countScale == 1) { WinLayers.push_back(_layerConfig[0].scaleInput[0] * temp); } else { // Differentiated input scaling MatrixBO Win(_layerConfig[0].Nr, _Nu); for (int cols = _Nu - 1; cols >= 0; cols--) { Win.col(cols) = _layerConfig[0].scaleInput[cols] * temp.col(cols); } WinLayers.push_back(Win); } // Fill subsequent layers for (int i = 1; i < _nLayers; ++i) { temp = MatrixBO::NullaryExpr(_layerConfig[i].Nr, _layerConfig[i - 1].Nr + 1, opSign); WinLayers.push_back(_layerConfig[i].scaleInput[0] * temp); } } /** * @brief Reset state matrix * */ void EchoBay::Reservoir::init_stateMat() { // Clear state vector stateMat.clear(); for (const auto& layer: _layerConfig) { stateMat.push_back(ArrayBO::Zero((layer.Nr))); } } /** * @brief Initialize the weights of the Reservoir * */ void EchoBay::Reservoir::init_WrLayers() { // Clear Wr vector WrLayers.clear(); // Fill layers for(const auto& layer: _layerConfig) { WrLayers.push_back(init_Wr(layer.Nr, layer.density, layer.desiredRho, layer.leaky, layer.edgesJumps)); } } #if !defined(ESP_PLATFORM) /** * @brief Load the whole Reservoir from files * * @param folder Path to the folder containing the files */ void EchoBay::Reservoir::load_network(const std::string &folder) { // Initialize Win this->load_WinLayers(folder); // Initialize Wr this->load_WrLayers(folder); // Initialize stateMat this->load_stateMat(folder); } /** * @brief Load input layers from files * * @param folder Path to the folder containing the files */ void EchoBay::Reservoir::load_WinLayers(const std::string &folder) { MatrixBO Win; std::string tempName; for (int i = 0; i < _nLayers; ++i) { tempName = folder + "/Win_eigen" + std::to_string(i) + ".mtx"; read_matrix(tempName, Win); WinLayers.push_back(Win); } } /** * @brief Load Reservoir's weight layers from files * * @param folder Path to the folder containing the files */ void EchoBay::Reservoir::load_WrLayers(const std::string &folder) { SparseMatrix<floatBO, 0x1> Wr; std::string tempName; for (int i = 0; i < _nLayers; ++i) { tempName = folder + "/Wr_eigen" + std::to_string(i) + ".mtx"; loadMarket(Wr, tempName); WrLayers.push_back(Wr); } } /** * @brief Load Reservoir's states from files * * @param folder Path to the folder containing the files */ void EchoBay::Reservoir::load_stateMat(const std::string &folder) { // First layer ArrayBO state; std::string tempName; for (int i = 0; i < _nLayers; ++i) { tempName = folder + "/State_eigen" + std::to_string(i) + ".mtx"; read_matrix(tempName, state); stateMat.push_back(state); } } #endif /** * @brief Fill the reservoir with random initialization * * @param Wr Eigen SparseMatrix of the weights * @param Nr Layer dimension * @param active_units Number of active units to be allocated randomly * @param valid_idx_hash [Not used] keep track of the active units indexes */ void EchoBay::Reservoir::wr_random_fill(SparseBO &Wr, int Nr, int active_units, std::unordered_set<std::pair<int, int>, pair_hash> &valid_idx_hash) { // Initialize random generator unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); std::default_random_engine gen(seed); std::uniform_real_distribution<double> values(-1.0, 1.0); std::uniform_real_distribution<double> indexes(0.0, 1.0); std::vector<TripletBO> tripletList; tripletList.reserve(active_units); std::pair<UOMIterator, bool> result; // Fill Wr matrix int i, j, k; floatBO value; for (k = 0; k < active_units;) { i = floor(indexes(gen) * Nr); j = floor(indexes(gen) * Nr); value = values(gen); // Inserting an element through value_type result = valid_idx_hash.insert({i, j}); if (result.second == true) { tripletList.push_back(TripletBO(i, j, value)); k++; } } try { Wr.setFromTriplets(tripletList.begin(), tripletList.end()); } catch (const std::exception &e) { throw WrEx; } } /** * @brief Fill the reservoir with a Small World Topology * * @param Wr Eigen SparseMatrix of the weights * @param Nr Layer dimension * @param edges Number of edges connected to each unit TODO add reference * @param valid_idx_hash [Not used] keep track of the active units indexes */ void EchoBay::Reservoir::wr_swt_fill(SparseBO &Wr, int Nr, int edges, std::unordered_set<std::pair<int, int>, pair_hash> &valid_idx_hash) { // Initialize random generator unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); std::default_random_engine gen(seed); std::uniform_real_distribution<double> values(-1.0, 1.0); std::bernoulli_distribution probability(0.1); std::uniform_real_distribution<double> indexToReassign(0, Nr-1); // Allocate triplet list std::vector<TripletBO> tripletList; std::pair<UOMIterator, bool> result; // Fill Wr matrix int i, j; floatBO value; // Check on maximum number of edges if(edges >= ceil(Nr/4)) { std::cout << "WARNING! Limiting SWT Edges to Nr/4 to avoid bad rewiring." << std::endl; edges = ceil(Nr/4); } // Allocate fixed connections for ( i = 0; i < Nr; ++i) { for (j = 1 ; j <= edges; ++j) { // Pick value value = values(gen); int tempIndex = i + j; tempIndex = tempIndex > Nr-1 ? tempIndex - Nr : tempIndex; tripletList.push_back(TripletBO(i, tempIndex, value)); tripletList.push_back(TripletBO( tempIndex, i, value)); } } // Set initial Wr try { Wr.setFromTriplets(tripletList.begin(), tripletList.end()); } catch (const std::exception &e) { throw WrEx; } // Move edges according to rewiring probability for ( j = 1; j <= edges; ++j) { // int tempIndexLeft = i - j; // tempIndexLeft = tempIndexLeft < 0 ? tempIndexLeft + Nr : tempIndexLeft; for ( i = 0; i < Nr; ++i ) { int tempIndexRight = i + j; tempIndexRight = tempIndexRight > Nr-1 ? tempIndexRight - Nr : tempIndexRight; if(probability(gen)){ Wr.coeffRef(i,tempIndexRight) = 0; Wr.coeffRef(tempIndexRight,i) = 0; int newConnection = ceil(indexToReassign(gen)); while(Wr.coeffRef(i, newConnection)) { while (Wr.coeffRef(i,newConnection) != 0) { newConnection = ceil(indexToReassign(gen)); } } // Move connection value = values(gen); if (!Wr.coeffRef(i, newConnection)) { Wr.coeffRef(i, newConnection) = value; Wr.coeffRef(newConnection,i) = value; }else{ Wr.insert(i, newConnection) = value; Wr.insert(newConnection, i) = value; } } } } } /** * @brief Fill the reservoir with a Cyclic Reservoir Jump topology * * @param Wr Eigen SparseMatrix of the weights * @param Nr Layer dimension * @param jumps Number of jumps in the connections * @param valid_idx_hash [Not used] keep track of the active units indexes */ void EchoBay::Reservoir::wr_crj_fill(SparseBO &Wr, int Nr, int jumps, std::unordered_set<std::pair<int, int>, pair_hash> &valid_idx_hash) { // Initialize random generator unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); std::default_random_engine gen(seed); std::uniform_real_distribution<double> values(-1.0, 1.0); std::bernoulli_distribution probability(0); std::uniform_real_distribution<double> indexToReassign(0, Nr-1); // Allocate triplet list std::vector<TripletBO> tripletList; std::pair<UOMIterator, bool> result; // Fill Wr matrix int i; floatBO value; // Create Circle value = values(gen); tripletList.push_back(TripletBO( 0, Nr-1, value)); //tripletList.push_back(TripletBO( Nr-1, 0, value)); // Initial fill for(i = 0; i < Nr-1; i++){ tripletList.push_back(TripletBO( i+1, i, value)); //tripletList.push_back(TripletBO( i, i+1, value)); } // Create Jumps value = values(gen); if (jumps > 0) { for (i = 0; i < Nr; i = i + jumps){ int tempindex = i + jumps; tempindex = tempindex > Nr-1 ? tempindex - Nr : tempindex; tripletList.push_back(TripletBO( i, tempindex, value)); tripletList.push_back(TripletBO( tempindex, i, value)); } } // Allocate Wr try { Wr.setFromTriplets(tripletList.begin(), tripletList.end()); } catch (const std::exception &e) { throw WrEx; } } /** * @brief Calculate Spectral Radius of weight matrix * * @param Wr Eigen SparseMatrix of the weights * @param scalingFactor Additional custom scaling factor * @return floatBO Scale radius */ floatBO EchoBay::Reservoir::wr_scale_radius(SparseBO &Wr, const double scalingFactor) { // Spectra solver for eigenvalues SparseGenMatProd<floatBO, 0x1> op(Wr); int param = 6 > Wr.rows() ? Wr.rows() : 6; VComplexBO evalues; floatBO scale_radius; int nconv; // General case with Nr > 2 if(Wr.rows() > 2) { do { GenEigsSolver<floatBO, LARGEST_MAGN, SparseGenMatProd<floatBO, 0x1>> eigs(&op, 1, param); eigs.init(); nconv = eigs.compute(); param = (param + 10 > Wr.rows()) ? Wr.rows() : param + 10; if (nconv > 0){ //ok == SUCCESSFUL) evalues = eigs.eigenvalues(); } } while (nconv < 1); //ok == NOT_CONVERGING); // Rescale Wr matrix with desired rho value floatBO spectral_radius = sqrt(pow(std::real(evalues[0]), 2) + pow(std::imag(evalues[0]), 2)); scale_radius = scalingFactor / spectral_radius; } else // 2-by-2 matrix { // Find trace and determinant floatBO trace = Wr.coeff(0,0) + Wr.coeff(1,1); floatBO determinant = Wr.coeff(0,0)*Wr.coeff(1,1) - Wr.coeff(1,0)*Wr.coeff(0,1); // Calculate the two eigenvalues VComplexBO eigens = VComplexBO::Zero(2,1); eigens(0) = (trace + sqrt(trace*trace - 4.0*determinant))/2.0; eigens(1) = (trace - sqrt(trace*trace - 4.0*determinant))/2.0; floatBO magEigen[2] = {0}; magEigen[0] = sqrt(eigens(0).real()*eigens(0).real() + eigens(0).imag()*eigens(0).imag()); magEigen[1] = sqrt(eigens(1).real()*eigens(1).real() + eigens(1).imag()*eigens(1).imag()); scale_radius = magEigen[0] > magEigen[1] ? scalingFactor/magEigen[0] : scalingFactor/magEigen[1]; } return scale_radius; } /** * @brief Initialize the Reservoir's weights according to user-defined parameters * * @param Nr Reservoir size * @param density Reservoir density * @param scalingFactor Custom scaling factor TODO add reference * @param leaky Leaky factor * @param extraParam Extra parameter defining edges (SW topology) or jumps (CRJ topology) * @return SparseBO Scaled Wr */ SparseBO EchoBay::Reservoir::init_Wr(const int Nr, const double density, const double scalingFactor, const double leaky,const int extraParam) { // Fixed Parameters int non_zero_units = ceil(Nr * Nr * density); // Wr declaration SparseMatrix<floatBO, 0x1> Wr(Nr, Nr); Wr.reserve(non_zero_units); Wr.setZero(); Wr.data().squeeze(); SparseMatrix<floatBO, 0x1> Eye(Nr, Nr); Eye.setIdentity(); Eye = Eye * (1 - leaky); // Accumulate valid indexes std::unordered_set<std::pair<int, int>, pair_hash> valid_idx_hash; // Initialize Wr according to desired topology switch(_type) { // Random topology case 0: wr_random_fill(Wr, Nr, non_zero_units, valid_idx_hash); break; // Small World topology case 1: wr_swt_fill(Wr, Nr, extraParam, valid_idx_hash); break; // Cyclid Reservoir Jump topology case 2: wr_crj_fill(Wr, Nr, extraParam, valid_idx_hash); break; } // Perform spectral radius scaling if (_reservoirInizialization == "radius") { Wr = Wr * leaky + Eye; // Get scale radius for Echo State Property floatBO scale_radius = wr_scale_radius(Wr, scalingFactor); // Rescale Wr Wr = (Wr * scale_radius - Eye) / leaky; } else { // Rescaling according to Gallicchio 2019 paper (see documentation for details) floatBO scaling = 6/sqrt(density * Nr * 12) * scalingFactor; Wr = Wr * leaky + Eye; Wr = (Wr * scaling - Eye) / leaky; } // Quantization // Quantizer quant(8, false); // quant.quantize_matrix<SparseBO>(Wr); return Wr; } /** * @brief Initialize configuration structure according to optimization vector and parameters file * * @param optParams Eigen Vector used by Limbo to define hyper-parameters * @param confParams YAML Node containing hyper-parameters at high level */ void EchoBay::Reservoir::init_LayerConfig(const Eigen::VectorXd &optParams, const YAML::Node confParams) { // Reset layerConfig _layerConfig.clear(); int nLayers = parse_config<int>("Nl", 0, 0, optParams, confParams, 1); int countScale = 1; int NrTemporary; // if (confParams["scaleIn"]["count"]) // { // countScale = confParams["scaleIn"]["count"].as<int>(); // } std::string scaleInType = confParams["scaleIn"]["type"].as<std::string>(); if (scaleInType == "dynamic") { if(confParams["scaleIn"]["count"]){ // Check count minimum size countScale = confParams["scaleIn"]["count"].as<int>() >= 2 ? confParams["scaleIn"]["count"].as<int>() : 2; }else{ countScale = 2; } }else{ countScale = 1; } // Get reservoir scaling type if (confParams["rho"]["scaling"]) { _reservoirInizialization = confParams["rho"]["scaling"].as<std::string>(); } int scaleSize; for (int i = 0; i < nLayers; i++) { layerParameter layerTemp; NrTemporary = parse_config<int>("Nr", i, 0, optParams, confParams, 400); layerTemp.Nr = NrTemporary >= 2 ? NrTemporary : 2; layerTemp.density = parse_config<double>("density", i, 0, optParams, confParams, 1); layerTemp.desiredRho = parse_config<double>("rho", i, 0, optParams, confParams, 0.9); layerTemp.leaky = parse_config<double>("leaky", i, 0, optParams, confParams, 0.9); layerTemp.edgesJumps = parse_config<int>("edgesJumps", i, 0, optParams, confParams, 0); // scaleInput management scaleSize = (i == 0) ? _Nu : 1; layerTemp.scaleInput.resize(scaleSize); layerTemp.scaleInput[0] = parse_config<double>("scaleIn", i, 0, optParams, confParams, 1); for (int j = 1; (j < countScale) && (i == 0); j++) { layerTemp.scaleInput[j] = parse_config<double>("scaleIn", nLayers, j, optParams, confParams, 1); } for (int j = countScale; (j < _Nu) && (i == 0); j++) { layerTemp.scaleInput[j] = layerTemp.scaleInput[countScale - 1]; } _layerConfig.push_back(layerTemp); } // Manage Small World topology if (_type == 1) { int elementsToCopy; ArrayI InIndex; ArrayI OutIndex; for (int i = 0; i < nLayers; ++i) { elementsToCopy = (int) floor(_layerConfig[i].Nr /5.0); InIndex.resize(elementsToCopy); OutIndex.resize(elementsToCopy); for (int j = 0; j < elementsToCopy; ++j) { InIndex[j] = j; OutIndex[j] = j + (int) floor(_layerConfig[i].Nr /2.0); } _WinIndex.push_back(InIndex); _WoutIndex.push_back(OutIndex); } } } /** * @brief Initialize configuration structure according to vector of key/value pairs * * @param paramValue vector of stringdouble_t pairs with key and value */ void EchoBay::Reservoir::init_LayerConfig(std::vector<stringdouble_t> paramValue) // TO DO, if necessary, updated with different types { _layerConfig.clear(); int nLayers = paramValue[0]["Nl"](0); int countScale = paramValue[0]["scaleInCount"](0); int scaleSize; for (int i = 0; i < nLayers; i++) { layerParameter layerTemp; layerTemp.Nr = paramValue[i]["Nr"](0); layerTemp.density = paramValue[i]["density"](0); layerTemp.desiredRho = paramValue[i]["rho"](0); layerTemp.leaky = paramValue[i]["leaky"](0); // scaleInput management scaleSize = (i == 0) ? _Nu : 1; layerTemp.scaleInput.resize(scaleSize); layerTemp.scaleInput[0] = paramValue[i]["scaleIn"](0); for (int j = 1; (j < countScale) && (i == 0); j++) { layerTemp.scaleInput[j] = paramValue[i]["scaleIn"](j); } for (int j = countScale; (j < _Nu) && (i == 0); j++) { layerTemp.scaleInput[j] = layerTemp.scaleInput[countScale - 1]; } _layerConfig.push_back(layerTemp); } } std::unordered_set<int> EchoBay::Reservoir::pickSet(int N, int k, std::mt19937& gen) { std::unordered_set<int> elems; for (int r = N - k; r < N; ++r) { int v = std::uniform_int_distribution<>(1, r)(gen); // there are two cases. // v is not in candidates ==> add it // v is in candidates ==> well, r is definitely not, because // this is the first iteration in the loop that we could've // picked something that big. if (!elems.insert(v).second) { elems.insert(r); } } return elems; } ArrayI EchoBay::Reservoir::pick(int Nr, int k) { std::random_device rd; std::mt19937 gen(rd()); //int k = 2 * floor(Nr/5); std::unordered_set<int> elems = pickSet(Nr, k, gen); // ok, now we have a set of k elements. but now // it's in a [unknown] deterministic order. // so we have to shuffle it: std::vector<int> result(elems.begin(), elems.end()); std::shuffle(result.begin(), result.end(), gen); ArrayI output = Eigen::Map<ArrayI, Eigen::Unaligned>(result.data(), result.size()); return output; } /** * @brief Getter function for Reservoir type * * @return int internal Reservoir type */ int EchoBay::Reservoir::get_ReservoirType() const { return _type; } /** * @brief Getter function for layerConfig as vector of layerParameter * * @return std::vector<layerParameter> Layers configuration */ std::vector<layerParameter> EchoBay::Reservoir::get_LayerConfig() const { return _layerConfig; } /** * @brief Getter function for SWT WinIndex * * @return std::vector<int> Number of layers */ int EchoBay::Reservoir::get_nLayers() const { return _nLayers; } /** * @brief Return the sum of Nr across layers * * @param layer number of layers. Default -1 counts all layers * @return int sum of Nr across layers */ int EchoBay::Reservoir::get_fullNr(const int layer) const { auto sumNr = [](int sum, const layerParameter& curr){return sum + curr.Nr;}; auto finalLayer = (layer == -1) ? _layerConfig.end() : _layerConfig.begin() + layer; return 1 + std::accumulate(_layerConfig.begin(), finalLayer, 0, sumNr); } /** * @brief Getter function for SWT WinIndex * * @return std::vector<std::vector<int>> Win Index */ std::vector<ArrayI> EchoBay::Reservoir::get_WinIndex() const { return _WinIndex; } /** * @brief Getter function for SWT WoutIndex * * @return std::vector<std::vector<int>> Wout Index */ std::vector<ArrayI> EchoBay::Reservoir::get_WoutIndex() const { return _WoutIndex; } /** * @brief Return the sum of Nr across layers for SWT topology * * @param layer number of layers. Default -1 counts all layers * @return int sum of SWT Nr across layers */ int EchoBay::Reservoir::get_NrSWT(const int layer) const { auto sumNrSWT = [](int sum, const ArrayI curr){return sum + curr.size();}; auto finalLayer = (layer == -1) ? _WoutIndex.end() : _WoutIndex.begin() + layer; return 1 + std::accumulate(_WoutIndex.begin(), finalLayer, 0, sumNrSWT); } /** * @brief Return memory occupation of the Reservoir object * * @params confParams YAML Node containing hyper-parameters at high level * @return floatBO The sum along all the layers of the product between Nr and Density */ floatBO EchoBay::Reservoir::return_net_dimension(const YAML::Node confParams) const { int optNr = 0,optDensity = 0; floatBO NrUpper, NrLower, densityUpper, densityLower; if (confParams["Nr"]["type"].as<std::string>() == "dynamic") { optNr = 1; NrUpper = confParams["Nr"]["upper_bound"].as<int>(); NrLower = confParams["Nr"]["lower_bound"].as<int>(); } if (confParams["density"]["type"].as<std::string>() == "dynamic") { optDensity = 1; densityUpper = confParams["density"]["upper_bound"].as<floatBO>(); densityLower = confParams["density"]["lower_bound"].as<floatBO>(); } floatBO count; count = (optNr + optDensity) * _nLayers == 0 ? 1 : (optNr + optDensity) * _nLayers; floatBO memory = 0; for (int i = 0; i < _nLayers; ++i) { floatBO tempNr, tempDensity; if(optNr){ tempNr = (_layerConfig[i].Nr - NrLower)/(NrUpper - NrLower); memory += tempNr; } if(optDensity){ tempDensity = (_layerConfig[i].density - densityLower)/(densityUpper - densityLower); memory += tempDensity; } } return memory/count; } /** * @brief Print optimizable parameters with a pretty table * * @param nLayers Number of layers * @param nWashout Sample washout * @param lambda Ridge regression factor see also EchoBay::Wout_ridge(int rows, int cols, double lambda, Eigen::Ref<MatrixBO> biasedState, Eigen::Ref<MatrixBO> target) * for details */ void EchoBay::Reservoir::print_params(const int nLayers, const int nWashout, const double lambda) { //std::cout << "\n"; #ifdef USE_TBB cout_mutex.lock(); #endif std::cout << "Nr" << std::string(14, ' '); // Switch topology switch(_type) { case 0: std::cout << "density" << std::string(9, ' '); break; case 1: std::cout << "edges" << std::string(11, ' '); break; case 2: std::cout << "jump" << std::string(12, ' '); break; } std::cout << "scaleInput" << std::string(8 * (_layerConfig[0].scaleInput.size() - 1) + 1, ' ') << "leaky" << std::string(11, ' ') << "rho" << std::endl; int active_units = 0; for (int i = 0; i < nLayers; i++) { std::cout << std::setprecision(5) << std::fixed << _layerConfig[i].Nr << "\t\t"; // Switch topology if(_type == 0) { std::cout << std::fixed << _layerConfig[i].density << "\t\t"; } else { std::cout << std::fixed << _layerConfig[i].edgesJumps << "\t\t"; } // Sum active_units ATTENTION the network must be configured before print_params active_units += WrLayers[i].nonZeros(); for (size_t countScale = 0; countScale < _layerConfig[i].scaleInput.size(); countScale++) { std::cout << std::fixed << _layerConfig[i].scaleInput[countScale] << " "; } std::cout << std::string(8 * (i != 0) * (_layerConfig[0].scaleInput.size() - 1) + 3, ' '); std::cout << std::fixed << _layerConfig[i].leaky << std::string(9, ' ') << std::fixed << _layerConfig[i].desiredRho << std::endl; } // Print general values std::cout << "washout\t" << nWashout << std::endl; std::cout << "lambda\t" << lambda << std::endl; std::cout << "active units\t" << active_units << std::endl; #ifdef USE_TBB cout_mutex.unlock(); #endif }
30.693483
167
0.605919
[ "object", "vector" ]
57dd84752261292b4b326842d6e12d9e77e2954f
3,438
cpp
C++
Engine/src/Source/Common/Core/Game.cpp
DanielParra159/EngineAndGame
45af7439633054aa6c9a8e75dd0453f9ce297626
[ "CC0-1.0" ]
1
2017-04-08T14:33:04.000Z
2017-04-08T14:33:04.000Z
Engine/src/Source/Common/Core/Game.cpp
DanielParra159/EngineAndGame
45af7439633054aa6c9a8e75dd0453f9ce297626
[ "CC0-1.0" ]
1
2017-04-05T01:56:28.000Z
2017-04-05T01:56:28.000Z
Engine/src/Source/Common/Core/Game.cpp
DanielParra159/EngineAndGame
45af7439633054aa6c9a8e75dd0453f9ce297626
[ "CC0-1.0" ]
null
null
null
#include "Core/Game.h" #include "Core/GameDescription.h" #include "Core/IGameState.h" #include "Core/Log.h" #include "System/Time.h" #include "Graphics/RenderManager.h" #include "Input/InputManager.h" #include "UI/MenuManager.h" #include "Audio/AudioManager.h" #include "IO/FileSystem.h" #include "Script/ScriptManager.h" #include "Physics/PhysicsManager.h" #include "Logic/World.h" #include "Logic/ComponentFactory.h" #include "Defs.h" #include <SDL.h> namespace core { SINGLETON_BODY(Game); BOOL Game::Init(const int8* title, const GameDescription& aGameDescription) { logic::ComponentFactory::Instance()->Init(); io::FileSystem::Instance()->Init(aGameDescription.mRootDir); physics::PhysicsManager::Instance()->Init(aGameDescription.mPhysicsGravity); graphics::RenderManager::Instance()->Init(title, aGameDescription.mScreenSize, aGameDescription.mScreenPosition, aGameDescription.mClearColor, aGameDescription.mFullScreen); input::InputManager::Instance()->Init(); ui::MenuManager::Instance()->Init(); script::ScriptManager::Instance()->Init(); audio::AudioManager::Instance()->Init(1.0f); sys::Time::Instance()->Init(aGameDescription.mPhysicUpdatedFrequency); srand(sys::Time::Instance()->GetCurrentMili()); mAccumulatePhysicTime = 0.0f; mNumPhysicUpdateLoops = 0; return TRUE; } void Game::Run() { mRunning = TRUE; sys::Time::Instance()->Update(); while (mRunning) { mAccumulatePhysicTime += sys::Time::Instance()->Update(); while (mAccumulatePhysicTime > sys::Time::Instance()->mFixedDeltaSec && mNumPhysicUpdateLoops < mMaxmNumPhysicUpdateLoops) { physics::PhysicsManager::Instance()->Update(); FixedUpdate(); mAccumulatePhysicTime -= sys::Time::Instance()->mFixedDeltaSec; ++mNumPhysicUpdateLoops; } mNumPhysicUpdateLoops = 0; input::InputManager::Instance()->Update(); ui::MenuManager::Instance()->Update(); Update(); audio::AudioManager::Instance()->Update(); Render(); } Release(); } void Game::Update() { if (mNextGameState) { SetGameState(mNextGameState); mNextGameState = 0; mAccumulatePhysicTime = 0.0f; mNumPhysicUpdateLoops = 0; } else if (mCurrentGameState) mRunning = mCurrentGameState->Update(); } void Game::FixedUpdate() { if (mCurrentGameState) mCurrentGameState->FixedUpdate(); } void Game::Render() { if (mCurrentGameState) mCurrentGameState->Render(); } void Game::Release() { if (mCurrentGameState) mCurrentGameState->Release(); audio::AudioManager::Instance()->Release(); script::ScriptManager::Instance()->Release(); ui::MenuManager::Instance()->Release(); input::InputManager::Instance()->Release(); graphics::RenderManager::Instance()->Release(); physics::PhysicsManager::Instance()->Release(); io::FileSystem::Instance()->Release(); logic::ComponentFactory::Instance()->Release(); SDL_Quit(); } BOOL Game::SetGameState(IGameState* aGameState) { if (mCurrentGameState) { mCurrentGameState->Release(); delete mCurrentGameState; } mCurrentGameState = aGameState; return aGameState->Init(); } void Game::ChangeGameState(IGameState* aGameState) { mNextGameState = aGameState; } } // namespace core
21.898089
126
0.668121
[ "render" ]
57ddacc875bc675eb1d04786c7d20f3d5882fc2c
72,976
cpp
C++
3rd_party_libs/chai3d-2.1/src/files/CFileLoader3DS.cpp
atp42/jks-ros-pkg
367fc00f2a9699f33d05c7957d319a80337f1ed4
[ "FTL" ]
3
2017-02-02T13:27:45.000Z
2018-06-17T11:52:13.000Z
3rd_party_libs/chai3d-2.1/src/files/CFileLoader3DS.cpp
salisbury-robotics/jks-ros-pkg
367fc00f2a9699f33d05c7957d319a80337f1ed4
[ "FTL" ]
null
null
null
3rd_party_libs/chai3d-2.1/src/files/CFileLoader3DS.cpp
salisbury-robotics/jks-ros-pkg
367fc00f2a9699f33d05c7957d319a80337f1ed4
[ "FTL" ]
null
null
null
//=========================================================================== /* This file is part of the CHAI 3D visualization and haptics libraries. Copyright (C) 2003-2010 by CHAI 3D. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License("GPL") version 2 as published by the Free Software Foundation. For using the CHAI 3D libraries with software that can not be combined with the GNU GPL, and for taking advantage of the additional benefits of our support services, please contact CHAI 3D about acquiring a Professional Edition License. \author <http://www.chai3d.org> \author Lev Povalahev \author Dan Morris \version 2.1.0 $Rev: 322 $ */ //=========================================================================== //--------------------------------------------------------------------------- #include "files/CFileLoader3DS.h" //--------------------------------------------------------------------------- #include <algorithm> #include <cstring> #include <map> //--------------------------------------------------------------------------- #ifndef DOXYGEN_SHOULD_SKIP_THIS //--------------------------------------------------------------------------- // define snprintf alternative in non-posix environments #if defined(_WIN32) #define snprintf _snprintf #endif /* #if defined(_LINUX) || defined(_MACOSX) #define _snprintf(x,y,...) sprintf(x,__VA_ARGS__) #endif */ //--------------------------------------------------------------------------- typedef std::map<unsigned int, unsigned int> uint_uint_map; bool g_3dsLoaderShouldGenerateExtraVertices = false; //--------------------------------------------------------------------------- #endif // DOXYGEN_SHOULD_SKIP_THIS //--------------------------------------------------------------------------- //=========================================================================== /*! Load a 3d studio max 3ds file format image into a mesh. \fn bool cLoadFile3DS(cMesh* a_mesh, const string& a_fileName) \param a_mesh Mesh in which image file is loaded \param a_fileName Name of image file. \return Return \b true if image was loaded successfully, otherwise return \b false. */ //=========================================================================== bool cLoadFile3DS(cMesh* a_mesh, const string& a_fileName) { int k; // Instantiate a loader L3DS loader; const char* fname = a_fileName.c_str(); if (loader.LoadFile(fname) == false) return false; cWorld* world = a_mesh->getParentWorld(); // clear all vertices and triangles of the current mesh a_mesh->clear(); // Global rendering flags that we'll use to mark the root mesh usefully bool transparency_enabled = false; bool materials_enabled = false; // get information about file // The number of meshes loaded from this file int num_file_meshes = loader.GetMeshCount(); // Create a child mesh for each mesh we found in the file, // and load its information for(int current_file_mesh=0; current_file_mesh<num_file_meshes; current_file_mesh++) { LMesh& cur_mesh = loader.GetMesh(current_file_mesh); // This CHAI mesh corresponds to the 3ds submesh cMesh* sub_mesh = a_mesh->createMesh(); // Assign a name to this mesh strncpy(sub_mesh->m_objectName,(const char*)(cur_mesh.GetName().c_str()),CHAI_SIZE_NAME); // Create a vertex map for each submesh sub_mesh->m_userData = new uint_uint_map; a_mesh->addChild(sub_mesh); // For each mesh in the file, we're going to create an additional mesh for // each material, since in CHAI each mesh has a specific material int num_materials = cur_mesh.GetMaterialCount(); // We'll put material-specific submeshes here if we find them... cMesh** newMeshes = 0; // Process materials if there are any... if (num_materials > 0) { materials_enabled = true; newMeshes = new cMesh*[num_materials]; // Create the new meshes and add them to the submesh we're working on now for(int i=0; i<num_materials; i++) { newMeshes[i] = a_mesh->createMesh(); cMesh* newMesh = newMeshes[i]; // Assign a name to this mesh if (num_materials > 1) snprintf(newMesh->m_objectName,CHAI_SIZE_NAME,"%s (mat %d)", (const char*)(cur_mesh.GetName().c_str()),i); else snprintf(newMesh->m_objectName,CHAI_SIZE_NAME,"%s", (const char*)(cur_mesh.GetName().c_str())); newMesh->m_userData = new uint_uint_map; sub_mesh->addChild(newMesh); // Set up material properties for each mesh // Get the global material id for each material used in this mesh int global_material_id = cur_mesh.GetMaterial(i); LMaterial& cur_material = loader.GetMaterial(global_material_id); // Does this material have a texture? Note that we only // support one texture per material right now. LMap& curmap = cur_material.GetTextureMap1(); if (strlen(curmap.mapName) > 0) { cTexture2D *newTexture = world->newTexture(); int result = newTexture->loadFromFile(curmap.mapName); // If this didn't work out, try again in the 3ds file's path if (result == 0) { char model_dir[1024]; find_directory(model_dir,fname); char new_texture_path[1024]; sprintf(new_texture_path,"%s/%s",model_dir,curmap.mapName); result = newTexture->loadFromFile(new_texture_path); } if (result) { newMeshes[i]->setTexture(newTexture,1); newMeshes[i]->setUseTexture(true); } // We really failed to load a texture... else { #if defined(_WIN32) // CHAI_DEBUG_PRINT("Could not load texture map %s\n",curmap.mapName); #endif } } // Get transparency double transparency = cur_material.GetTransparency(); float alpha = 1.0f - (float)(transparency); if (alpha < 1.0) { transparency_enabled = true; newMesh->setUseTransparency(true, false); } float shininess = cur_material.GetShininess(); newMesh->m_material.setShininess(int(shininess * 255.0)); // get ambient component: LColor3 ambient = cur_material.GetAmbientColor(); newMesh->m_material.m_ambient.setR((float)ambient.r); newMesh->m_material.m_ambient.setG((float)ambient.g); newMesh->m_material.m_ambient.setB((float)ambient.b); newMesh->m_material.m_ambient.setA(alpha); // get diffuse component: LColor3 diffuse = cur_material.GetDiffuseColor(); newMesh->m_material.m_diffuse.setR((float)diffuse.r); newMesh->m_material.m_diffuse.setG((float)diffuse.g); newMesh->m_material.m_diffuse.setB((float)diffuse.b); newMesh->m_material.m_diffuse.setA(alpha); // get specular component: LColor3 specular = cur_material.GetSpecularColor(); newMesh->m_material.m_specular.setR((float)specular.r); newMesh->m_material.m_specular.setG((float)specular.g); newMesh->m_material.m_specular.setB((float)specular.b); newMesh->m_material.m_specular.setA(alpha); // get shininess newMesh->m_material.setShininess((GLuint)(128.0 * cur_material.GetShininess())); } // For every material in this mesh } // If this submesh has materials // Local copy of the material list, for quick lookup vector<uint> materials = cur_mesh.m_materials; // Now loop over all the triangles in this mesh and put them in the right // place in our CHAI meshes... unsigned int num_triangles = cur_mesh.GetTriangleCount(); for(unsigned int cur_tri_index=0; cur_tri_index<num_triangles; cur_tri_index++) { // Get all the information about this triangle // LTriangle2& cur_tri = cur_mesh.GetTriangle2(cur_tri_index); // Get the vertex indices for this triangle... const LTriangle& cur_indexed_tri = cur_mesh.GetTriangle(cur_tri_index); // Which CHAI mesh are we going to insert this triangle into? cMesh* cur_chai_mesh; // Default to the material-independent submesh cur_chai_mesh = sub_mesh; // Look for a material-specific submesh for this triangle if there is one... if (num_materials > 0) { int curMaterialId = cur_mesh.m_tris[cur_tri_index].materialId; // This material id is in terms of the global material id, but we need the // local material id to find the right CHAI mesh... int global_mat_id = curMaterialId; int local_mat_id = -1; // So we look it up in the list for(unsigned int k=0; k<materials.size(); k++) { if ((int)(materials[k]) == global_mat_id) { local_mat_id = k; break; } } if (local_mat_id == -1) { // Error finding the right mesh to put this triangle in // continue; // If there's no material, put it in the material-independent sub-mesh cur_chai_mesh = sub_mesh; } else cur_chai_mesh = newMeshes[local_mat_id]; } unsigned int indexTriangle = 0; if (g_3dsLoaderShouldGenerateExtraVertices == false) { uint_uint_map* vertex_map = (uint_uint_map*)cur_chai_mesh->m_userData; unsigned short indices[3]; unsigned short* pindex = (unsigned short*)(&cur_indexed_tri); uint_uint_map::iterator viter; // For each vertex indexed by this triangle... for(int k=0; k<3; k++) { indices[k] = pindex[k]; viter = vertex_map->find(indices[k]); LVector4 v = cur_mesh.GetVertex(indices[k]); // If we've never seen this vertex before... if (viter == vertex_map->end()) { // Create a new vertex and put him in this map int newVertexIndex = cur_chai_mesh->newVertex(v.x,v.y,v.z); (*vertex_map)[(indices[k])] = newVertexIndex; indices[k] = newVertexIndex; } else { // Otherwise just grab his index... indices[k] = (*viter).second; } } // Create the new triangle... indexTriangle = cur_chai_mesh->newTriangle(indices[0],indices[1],indices[2]); } if (g_3dsLoaderShouldGenerateExtraVertices == true) { LVector4 v0 = cur_mesh.GetVertex(cur_indexed_tri.a); LVector4 v1 = cur_mesh.GetVertex(cur_indexed_tri.b); LVector4 v2 = cur_mesh.GetVertex(cur_indexed_tri.c); cVector3d vert0(v0.x,v0.y,v0.z); cVector3d vert1(v1.x,v1.y,v1.z); cVector3d vert2(v2.x,v2.y,v2.z); indexTriangle = cur_chai_mesh->newTriangle(vert0,vert1,vert2); } cTriangle* curTriangle = cur_chai_mesh->getTriangle(indexTriangle); double transparency = cur_chai_mesh->m_material.m_diffuse.getA(); // Give properties to each vertex of this triangle unsigned short* pindex = (unsigned short*)(&cur_indexed_tri); for(k=0; k<3; k++) { unsigned short curindex = pindex[k]; LVector3 norm = cur_mesh.GetNormal(curindex); LVector2 uv = cur_mesh.GetUV(curindex); LColor3 color = cur_mesh.GetColor(curindex); cVertex* vertex = curTriangle->getVertex(k); vertex->setNormal(norm.x,norm.y,norm.z); vertex->setTexCoord(uv.x, 1.0 - uv.y); vertex->setColor(color.r,color.g,color.b,(float)transparency); } } // For every triangle in this 3ds mesh // We're now done with all the vertex maps for this mesh... for(int i=0; i<num_materials; i++) { cMesh* curMesh = newMeshes[i]; uint_uint_map* pmap = (uint_uint_map*)curMesh->m_userData; delete pmap; } if (newMeshes) delete [] newMeshes; uint_uint_map* pmap = (uint_uint_map*)sub_mesh->m_userData; delete pmap; } // For every mesh in the 3ds file // Copy relevant rendering state as generally useful flags in the main mesh. // // Don't over-write the "real" variables in other submeshes a_mesh->setUseTransparency(transparency_enabled,false); a_mesh->setUseMaterial(materials_enabled,false); a_mesh->setUseVertexColors(!materials_enabled,false); // compute boundary boxes a_mesh->computeBoundaryBox(true); // update global position in world if (world != 0) world->computeGlobalPositions(true); // return result return (true); } //--------------------------------------------------------------------------- #ifndef DOXYGEN_SHOULD_SKIP_THIS //--------------------------------------------------------------------------- //=========================================================================== /* The remainder of this file comes from Lev Povalahev's l3ds.cpp copyright (c) 2001-2002 Lev Povalahev */ //=========================================================================== typedef unsigned long ulong; #define SEEK_START 1900 #define SEEK_CURSOR 1901 // common chunks // colors #define COLOR_F 0x0010 #define COLOR_24 0x0011 #define LIN_COLOR_24 0x0012 #define LIN_COLOR_F 0x0013 // percentage #define INT_PERCENTAGE 0x0030 #define FLOAT_PERCENTAGE 0x0031 // ambient light #define AMBIENT_LIGHT 0x2100 #define MAIN3DS 0x4D4D #define EDIT3DS 0x3D3D // this is the start of the editor config // keyframer chunk ids #define KFDATA 0xB000 // the keyframer section #define KFHDR 0xB00A #define OBJECT_NODE_TAG 0xB002 #define NODE_HDR 0xB010 #define PIVOT 0xB013 #define POS_TRACK_TAG 0xB020 #define ROT_TRACK_TAG 0xB021 #define SCL_TRACK_TAG 0xB022 // material entries #define MAT_ENTRY 0xAFFF #define MAT_NAME 0xA000 #define MAT_AMBIENT 0xA010 #define MAT_DIFFUSE 0xA020 #define MAT_SPECULAR 0xA030 #define MAT_SHININESS 0xA040 #define MAT_SHIN2PCT 0xA041 #define MAT_TRANSPARENCY 0xA050 #define MAT_SHADING 0xA100 #define MAT_TWO_SIDE 0xA081 #define MAT_ADDITIVE 0xA083 #define MAT_WIRE 0xA085 #define MAT_FACEMAP 0xA088 #define MAT_WIRESIZE 0xA087 #define MAT_DECAL 0xA082 #define MAT_TEXMAP 0xA200 #define MAT_MAPNAME 0xA300 #define MAT_MAP_TILING 0xA351 #define MAT_MAP_USCALE 0xA354 #define MAT_MAP_VSCALE 0xA356 #define MAT_MAP_UOFFSET 0xA358 #define MAT_MAP_VOFFSET 0xA35A #define MAT_MAP_ANG 0xA35C #define MAT_TEX2MAP 0xA33A #define MAT_OPACMAP 0xA210 #define MAT_BUMPMAP 0xA230 #define MAT_SPECMAP 0xA204 #define MAT_SHINMAP 0xA33C #define MAT_REFLMAP 0xA220 #define MAT_ACUBIC 0xA310 #define EDIT_OBJECT 0x4000 #define OBJ_TRIMESH 0x4100 #define OBJ_LIGHT 0x4600 #define OBJ_CAMERA 0x4700 #define CAM_RANGES 0x4720 #define LIT_OFF 0x4620 #define LIT_SPOT 0x4610 #define LIT_INRANGE 0x4659 #define LIT_OUTRANGE 0x465A #define TRI_VERTEXLIST 0x4110 #define TRI_VERTEXOPTIONS 0x4111 #define TRI_FACELIST 0x4120 #define TRI_MAT_GROUP 0x4130 #define TRI_SMOOTH_GROUP 0x4150 #define TRI_FACEMAPPING 0x4140 #define TRI_MATRIX 0x4160 #define SPOTLIGHT 0x4610 //--------------------------------------------------------------------------- #define MAX_SHARED_TRIS 100 // the error reporting routine void ErrorMsg(const char *msg) { /* char buf[1000]; sprintf(buf,"%s\n",msg); CHAI_DEBUG_PRINT(buf); */ } //--------------------------------------------------------------------------- LColor3 black = {0, 0, 0}; LVector3 zero3(0,0,0); LVector4 zero4 = {0, 0, 0, 0}; LMap emptyMap = {0, "", 1, 1, 0, 0, 0}; //--------------------------------------------------------------------------- LVector3 _4to3(const LVector4 &vec) { LVector3 t; t.x = vec.x; t.y = vec.y; t.z = vec.z; return t; } //--------------------------------------------------------------------------- LVector3 AddVectors(const LVector3 &a, const LVector3 &b) { LVector3 t; t.x = a.x+b.x; t.y = a.y+b.y; t.z = a.z+b.z; return t; } //--------------------------------------------------------------------------- LVector3 SubtractVectors(const LVector3 &a, const LVector3 &b) { LVector3 t; t.x = a.x-b.x; t.y = a.y-b.y; t.z = a.z-b.z; return t; } //--------------------------------------------------------------------------- float VectorLength(const LVector3 &vec) { return (float)sqrt(vec.x*vec.x + vec.y*vec.y+vec.z*vec.z); } LVector3 NormalizeVector(const LVector3 &vec) { float a = VectorLength(vec); if (a == 0) return vec; float b = 1/a; LVector3 v; v.x = vec.x*b; v.y = vec.y*b; v.z = vec.z*b; return v; } //--------------------------------------------------------------------------- LVector3 CrossProduct(const LVector3 &a, const LVector3 &b) { LVector3 v; v.x = a.y*b.z - a.z*b.y; v.y = a.z*b.x - a.x*b.z; v.z = a.x*b.y - a.y*b.x; return v; } //--------------------------------------------------------------------------- void LoadIdentityMatrix(LMatrix4 &m) { m._11 = 1.0f; m._12 = 0.0f; m._13 = 0.0f; m._14 = 0.0f; m._21 = 0.0f; m._22 = 1.0f; m._23 = 0.0f; m._24 = 0.0f; m._31 = 0.0f; m._32 = 0.0f; m._33 = 1.0f; m._34 = 0.0f; m._41 = 0.0f; m._42 = 0.0f; m._43 = 1.0f; m._44 = 0.0f; } //--------------------------------------------------------------------------- LVector4 VectorByMatrix(const LMatrix4 &m, const LVector4 &vec) { LVector4 res; res.x = m._11*vec.x + m._12*vec.y + m._13*vec.z + m._14*vec.w; res.y = m._21*vec.x + m._22*vec.y + m._23*vec.z + m._24*vec.w; res.z = m._31*vec.x + m._32*vec.y + m._33*vec.z + m._34*vec.w; res.w = m._41*vec.x + m._42*vec.y + m._43*vec.z + m._44*vec.w; if (res.w != 0) { float b = 1/res.w; res.x *= b; res.y *= b; res.z *= b; res.w = 1; } else res.w = 1; return res; } //--------------------------------------------------------------------------- void QuatToMatrix(const LVector4 &quat, LMatrix4 &m) { } //--------------------------------------------------------------------------- // Lobject CLASS IMPLEMENTATION //--------------------------------------------------------------------------- LObject::LObject() { m_name = "";//.clear(); } //--------------------------------------------------------------------------- LObject::~LObject() { // nothing here } //--------------------------------------------------------------------------- void LObject::SetName(const string& value) { m_name = value; } //--------------------------------------------------------------------------- const string& LObject::GetName() { return m_name; } //--------------------------------------------------------------------------- bool LObject::IsObject(const string &name) { return (m_name == name); } //--------------------------------------------------------------------------- // LMaterial CLASS IMPLEMENTATION //--------------------------------------------------------------------------- LMaterial::LMaterial() : LObject() { m_id = 0; m_texMap1 = emptyMap; m_texMap2 = emptyMap; m_opacMap = emptyMap; m_bumpMap = emptyMap; m_reflMap = emptyMap; m_specMap = emptyMap; m_ambient = black; m_diffuse = black; m_specular = black; m_shading = sGouraud; m_shininess = 0; m_transparency = 0; } //--------------------------------------------------------------------------- LMaterial::~LMaterial() { } //--------------------------------------------------------------------------- uint LMaterial::GetID() { return m_id; } //--------------------------------------------------------------------------- LMap& LMaterial::GetTextureMap1() { return m_texMap1; } //--------------------------------------------------------------------------- LMap& LMaterial::GetTextureMap2() { return m_texMap2; } //--------------------------------------------------------------------------- LMap& LMaterial::GetOpacityMap() { return m_opacMap; } //--------------------------------------------------------------------------- LMap& LMaterial::GetSpecularMap() { return m_specMap; } //--------------------------------------------------------------------------- LMap& LMaterial::GetBumpMap() { return m_bumpMap; } //--------------------------------------------------------------------------- LMap& LMaterial::GetReflectionMap() { return m_reflMap; } //--------------------------------------------------------------------------- LColor3 LMaterial::GetAmbientColor() { return m_ambient; } //--------------------------------------------------------------------------- LColor3 LMaterial::GetDiffuseColor() { return m_diffuse; } //--------------------------------------------------------------------------- LColor3 LMaterial::GetSpecularColor() { return m_specular; } //--------------------------------------------------------------------------- float LMaterial::GetShininess() { return m_shininess; } //--------------------------------------------------------------------------- float LMaterial::GetTransparency() { return m_transparency; } //--------------------------------------------------------------------------- LShading LMaterial::GetShadingType() { return m_shading; } //--------------------------------------------------------------------------- void LMaterial::SetID(uint value) { m_id = value; } //--------------------------------------------------------------------------- void LMaterial::SetAmbientColor(const LColor3 &color) { m_ambient = color; } //--------------------------------------------------------------------------- void LMaterial::SetDiffuseColor(const LColor3 &color) { m_diffuse = color; } //--------------------------------------------------------------------------- void LMaterial::SetSpecularColor(const LColor3 &color) { m_specular = color; } //--------------------------------------------------------------------------- void LMaterial::SetShininess(float value) { m_shininess = value; if (m_shininess < 0) m_shininess = 0; if (m_shininess > 1) m_shininess = 1; } //--------------------------------------------------------------------------- void LMaterial::SetTransparency(float value) { m_transparency = value; if (m_transparency < 0) m_transparency = 0; if (m_transparency > 1) m_transparency = 1; } //--------------------------------------------------------------------------- void LMaterial::SetShadingType(LShading shading) { m_shading = shading; } //--------------------------------------------------------------------------- // LMesh CLASS IMPLEMENTATION //--------------------------------------------------------------------------- LMesh::LMesh() : LObject() { Clear(); } //--------------------------------------------------------------------------- LMesh::~LMesh() { Clear(); } //--------------------------------------------------------------------------- void LMesh::Clear() { m_vertices.clear(); m_normals.clear(); m_uv.clear(); m_colors.clear(); m_tangents.clear(); m_binormals.clear(); m_triangles.clear(); m_tris.clear(); m_materials.clear(); LoadIdentityMatrix(m_matrix); } //--------------------------------------------------------------------------- uint LMesh::GetVertexCount() { return m_vertices.size(); } //--------------------------------------------------------------------------- void LMesh::SetVertexArraySize(uint value) { m_vertices.resize(value); m_normals.resize(value); m_uv.resize(value); m_colors.resize(value); m_tangents.resize(value); m_binormals.resize(value); } //--------------------------------------------------------------------------- uint LMesh::GetTriangleCount() { return m_triangles.size(); } //--------------------------------------------------------------------------- void LMesh::SetTriangleArraySize(uint value) { m_triangles.reserve(value); m_tris.reserve(value); m_tris.resize(value); m_triangles.resize(value); } //--------------------------------------------------------------------------- const LVector4& LMesh::GetVertex(uint index) { return m_vertices[index]; } //--------------------------------------------------------------------------- const LVector3& LMesh::GetNormal(uint index) { return m_normals[index]; } //--------------------------------------------------------------------------- LColor3& LMesh::GetColor(uint index) { return m_colors[index]; } //--------------------------------------------------------------------------- const LVector2& LMesh::GetUV(uint index) { return m_uv[index]; } //--------------------------------------------------------------------------- const LVector3& LMesh::GetTangent(uint index) { return m_tangents[index]; } //--------------------------------------------------------------------------- const LVector3& LMesh::GetBinormal(uint index) { return m_binormals[index]; } //--------------------------------------------------------------------------- void LMesh::SetVertex(const LVector4 &vec, uint index) { if (index >= m_vertices.size()) return; m_vertices[index] = vec; } //--------------------------------------------------------------------------- void LMesh::SetNormal(const LVector3 &vec, uint index) { if (index >= m_vertices.size()) return; m_normals[index] = vec; } //--------------------------------------------------------------------------- void LMesh::SetUV(const LVector2 &vec, uint index) { if (index >= m_vertices.size()) return; m_uv[index] = vec; } //--------------------------------------------------------------------------- void LMesh::SetColor(const LColor3 &vec, uint index) { if (index >= m_vertices.size()) return; m_colors[index] = vec; } //--------------------------------------------------------------------------- void LMesh::SetTangent(const LVector3 &vec, uint index) { if (index >= m_vertices.size()) return; m_tangents[index] = vec; } //--------------------------------------------------------------------------- void LMesh::SetBinormal(const LVector3 &vec, uint index) { if (index >= m_vertices.size()) return; m_binormals[index] = vec; } //--------------------------------------------------------------------------- const LTriangle& LMesh::GetTriangle(uint index) { return m_triangles[index]; } //--------------------------------------------------------------------------- LTriangle2 LMesh::GetTriangle2(uint index) { LTriangle2 f; LTriangle t = GetTriangle(index); f.vertices[0] = GetVertex(t.a); f.vertices[1] = GetVertex(t.b); f.vertices[2] = GetVertex(t.c); f.vertexNormals[0] = GetNormal(t.a); f.vertexNormals[1] = GetNormal(t.b); f.vertexNormals[2] = GetNormal(t.c); f.textureCoords[0] = GetUV(t.a); f.textureCoords[1] = GetUV(t.b); f.textureCoords[2] = GetUV(t.c); f.color[0] = GetColor(t.a); f.color[1] = GetColor(t.b); f.color[2] = GetColor(t.c); LVector3 a, b; a = SubtractVectors(_4to3(f.vertices[1]), _4to3(f.vertices[0])); b = SubtractVectors(_4to3(f.vertices[1]), _4to3(f.vertices[2])); f.faceNormal = CrossProduct(b, a); f.faceNormal = NormalizeVector(f.faceNormal); f.materialId = m_tris[index].materialId; return f; } //--------------------------------------------------------------------------- LMatrix4 LMesh::GetMatrix() { return m_matrix; } //--------------------------------------------------------------------------- void LMesh::SetMatrix(LMatrix4 m) { m_matrix = m; } //--------------------------------------------------------------------------- void LMesh::TransformVertices() { for (uint i=0; i<m_vertices.size(); i++) m_vertices[i] = VectorByMatrix(m_matrix, m_vertices[i]); } //--------------------------------------------------------------------------- void LMesh::CalcNormals(bool useSmoothingGroups) { unsigned int i; // first calculate the face normals for (i=0; i<m_triangles.size(); i++) { LVector3 a, b; a = SubtractVectors(_4to3(m_vertices[m_tris[i].b]), _4to3(m_vertices[m_tris[i].a])); b = SubtractVectors(_4to3(m_vertices[m_tris[i].b]), _4to3(m_vertices[m_tris[i].c])); m_tris[i].normal = NormalizeVector(CrossProduct(b, a)); } vector< vector<int> > array; array.resize(m_vertices.size()); for (i=0; i<m_triangles.size(); i++) { uint k = m_tris[i].a; array[k].push_back(i); k = m_tris[i].b; array[k].push_back(i); k = m_tris[i].c; array[k].push_back(i); } LVector3 temp; if (!useSmoothingGroups) { // now calculate the normals without using smoothing groups for (i=0; i<m_vertices.size(); i++) { temp = zero3; int t = array[i].size(); for (int k=0; k<t; k++) { temp.x += m_tris[array[i][k]].normal.x; temp.y += m_tris[array[i][k]].normal.y; temp.z += m_tris[array[i][k]].normal.z; } m_normals[i] = NormalizeVector(temp); } } else { // now calculate the normals _USING_ smoothing groups // I'm assuming a triangle can only belong to one smoothing group at a time! vector<ulong> smGroups; vector< vector <uint> > smList; uint loop_size = m_vertices.size(); for (i=0; i<loop_size; i++) { int t = array[i].size(); if (t == 0) continue; smGroups.clear(); smList.clear(); smGroups.push_back(m_tris[array[i][0]].smoothingGroups); smList.resize(smGroups.size()); smList[smGroups.size()-1].push_back(array[i][0]); // first build a list of smoothing groups for the vertex for (int k=0; k<t; k++) { bool found = false; for (uint j=0; j<smGroups.size(); j++) { if (m_tris[array[i][k]].smoothingGroups == smGroups[j]) { smList[j].push_back(array[i][k]); found = true; } } if (!found) { smGroups.push_back(m_tris[array[i][k]].smoothingGroups); smList.resize(smGroups.size()); smList[smGroups.size()-1].push_back(array[i][k]); } } // now we have the list of faces for the vertex sorted by smoothing groups // now duplicate the vertices so that there's only one smoothing group "per vertex" if (smGroups.size() > 1) for (uint j=1; j< smGroups.size(); j++) { m_vertices.push_back(m_vertices[i]); m_normals.push_back(m_normals[i]); m_uv.push_back(m_uv[i]); m_colors.push_back(m_colors[i]); m_tangents.push_back(m_tangents[i]); m_binormals.push_back(m_binormals[i]); uint t = m_vertices.size()-1; for (uint h=0; h<smList[j].size(); h++) { if (m_tris[smList[j][h]].a == (int)i) m_tris[smList[j][h]].a = t; if (m_tris[smList[j][h]].b == (int)i) m_tris[smList[j][h]].b = t; if (m_tris[smList[j][h]].c == (int)i) m_tris[smList[j][h]].c = t; } } } // now rebuild a face list for each vertex, since the old one is invalidated for (i=0; i<array.size(); i++) array[i].clear(); array.clear(); array.resize(m_vertices.size()); for (i=0; i<m_triangles.size(); i++) { uint k = m_tris[i].a; array[k].push_back(i); k = m_tris[i].b; array[k].push_back(i); k = m_tris[i].c; array[k].push_back(i); } // now compute the normals for (i=0; i<m_vertices.size(); i++) { temp = zero3; int t = array[i].size(); for (int k=0; k<t; k++) { temp.x += m_tris[array[i][k]].normal.x; temp.y += m_tris[array[i][k]].normal.y; temp.z += m_tris[array[i][k]].normal.z; } m_normals[i] = NormalizeVector(temp); } } // copy m_tris to m_triangles for (i=0; i<m_triangles.size(); i++) { m_triangles[i].a = m_tris[i].a; m_triangles[i].b = m_tris[i].b; m_triangles[i].c = m_tris[i].c; } } //--------------------------------------------------------------------------- void LMesh::CalcTextureSpace() { // a understandable description of how to do that can be found here: // http://members.rogers.com/deseric/tangentspace.htm // first calculate the tangent for each triangle LVector3 x_vec, y_vec, z_vec; LVector3 v1, v2; uint i; for ( i=0; i<m_triangles.size(); i++) { v1.x = m_vertices[m_tris[i].b].x - m_vertices[m_tris[i].a].x; v1.y = m_uv[m_tris[i].b].x - m_uv[m_tris[i].a].x; v1.z = m_uv[m_tris[i].b].y - m_uv[m_tris[i].a].y; v2.x = m_vertices[m_tris[i].c].x - m_vertices[m_tris[i].a].x; v2.y = m_uv[m_tris[i].c].x - m_uv[m_tris[i].a].x; v2.z = m_uv[m_tris[i].c].y - m_uv[m_tris[i].a].y; x_vec = CrossProduct(v1, v2); v1.x = m_vertices[m_tris[i].b].y - m_vertices[m_tris[i].a].y; v1.y = m_uv[m_tris[i].b].x - m_uv[m_tris[i].a].x; v1.z = m_uv[m_tris[i].b].y - m_uv[m_tris[i].a].y; v2.x = m_vertices[m_tris[i].c].y - m_vertices[m_tris[i].a].y; v2.y = m_uv[m_tris[i].c].x - m_uv[m_tris[i].a].x; v2.z = m_uv[m_tris[i].c].y - m_uv[m_tris[i].a].y; y_vec = CrossProduct(v1, v2); v1.x = m_vertices[m_tris[i].b].z - m_vertices[m_tris[i].a].z; v1.y = m_uv[m_tris[i].b].x - m_uv[m_tris[i].a].x; v1.z = m_uv[m_tris[i].b].y - m_uv[m_tris[i].a].y; v2.x = m_vertices[m_tris[i].c].z - m_vertices[m_tris[i].a].z; v2.y = m_uv[m_tris[i].c].x - m_uv[m_tris[i].a].x; v2.z = m_uv[m_tris[i].c].y - m_uv[m_tris[i].a].y; z_vec = CrossProduct(v1, v2); m_tris[i].tangent.x = -(x_vec.y/x_vec.x); m_tris[i].tangent.y = -(y_vec.y/y_vec.x); m_tris[i].tangent.z = -(z_vec.y/z_vec.x); m_tris[i].binormal.x = -(x_vec.z/x_vec.x); m_tris[i].binormal.y = -(y_vec.z/y_vec.x); m_tris[i].binormal.z = -(z_vec.z/z_vec.x); } // now for each vertex build a list of face that share this vertex vector< vector<int> > array; array.resize(m_vertices.size()); for (i=0; i<m_triangles.size(); i++) { uint k = m_tris[i].a; array[k].push_back(i); k = m_tris[i].b; array[k].push_back(i); k = m_tris[i].c; array[k].push_back(i); } // now average the tangents and compute the binormals as (tangent X normal) for (i=0; i<m_vertices.size(); i++) { v1 = zero3; v2 = zero3; int t = array[i].size(); for (int k=0; k<t; k++) { v1.x += m_tris[array[i][k]].tangent.x; v1.y += m_tris[array[i][k]].tangent.y; v1.z += m_tris[array[i][k]].tangent.z; v2.x += m_tris[array[i][k]].binormal.x; v2.y += m_tris[array[i][k]].binormal.y; v2.z += m_tris[array[i][k]].binormal.z; } m_tangents[i] = NormalizeVector(v1); //m_binormals[i] = NormalizeVector(v2); m_binormals[i] = NormalizeVector(CrossProduct(m_tangents[i], m_normals[i])); } } //--------------------------------------------------------------------------- void LMesh::Optimize(LOptimizationLevel value) { switch (value) { case oNone: //TransformVertices(); break; case oSimple: //TransformVertices(); CalcNormals(false); break; case oFull: //TransformVertices(); CalcNormals(true); CalcTextureSpace(); break; } } //--------------------------------------------------------------------------- void LMesh::SetTri(const LTri &tri, uint index) { if (index >= m_triangles.size()) return; m_tris[index] = tri; } //--------------------------------------------------------------------------- LTri& LMesh::GetTri(uint index) { return m_tris[index]; } //--------------------------------------------------------------------------- uint LMesh::GetMaterial(uint index) { return m_materials[index]; } //--------------------------------------------------------------------------- uint LMesh::AddMaterial(uint id) { m_materials.push_back(id); return m_materials.size()-1; } //--------------------------------------------------------------------------- uint LMesh::GetMaterialCount() { return m_materials.size(); } //--------------------------------------------------------------------------- // LCamera CLASS IMPLENTATION //--------------------------------------------------------------------------- LCamera::LCamera() : LObject() { Clear(); } //--------------------------------------------------------------------------- LCamera::~LCamera() { } //--------------------------------------------------------------------------- void LCamera::Clear() { m_pos.x = m_pos.y = m_pos.z = 0.0f; m_target.x = m_target.y = m_target.z = 0.0f; m_fov = 80; m_bank = 0;; m_near = 10; m_far = 10000; } //--------------------------------------------------------------------------- void LCamera::SetPosition(LVector3 vec) { m_pos = vec; } //--------------------------------------------------------------------------- LVector3 LCamera::GetPosition() { return m_pos; } void LCamera::SetTarget(LVector3 target) { m_target = target; } //--------------------------------------------------------------------------- LVector3 LCamera::GetTarget() { return m_target; } //--------------------------------------------------------------------------- void LCamera::SetFOV(float value) { m_fov = value; } //--------------------------------------------------------------------------- float LCamera::GetFOV() { return m_fov; } //--------------------------------------------------------------------------- void LCamera::SetBank(float value) { m_bank = value; } //--------------------------------------------------------------------------- float LCamera::GetBank() { return m_bank; } //--------------------------------------------------------------------------- void LCamera::SetNearplane(float value) { m_near = value; } //--------------------------------------------------------------------------- float LCamera::GetNearplane() { return m_near; } //--------------------------------------------------------------------------- void LCamera::SetFarplane(float value) { m_far = value; } //--------------------------------------------------------------------------- float LCamera::GetFarplane() { return m_far; } //--------------------------------------------------------------------------- // LLight CLASS IMPLEMENTATION //--------------------------------------------------------------------------- LLight::LLight() : LObject() { Clear(); } //--------------------------------------------------------------------------- LLight::~LLight() { } //--------------------------------------------------------------------------- void LLight::Clear() { m_pos.x = m_pos.y = m_pos.z = 0.0f; m_color.r = m_color.g = m_color.b = 0.0f; m_spotlight = false; m_attenuationend = 100; m_attenuationstart = 1000; } //--------------------------------------------------------------------------- void LLight::SetPosition(LVector3 vec) { m_pos = vec; } //--------------------------------------------------------------------------- LVector3 LLight::GetPosition() { return m_pos; } //--------------------------------------------------------------------------- void LLight::SetColor(LColor3 color) { m_color = color; } //--------------------------------------------------------------------------- LColor3 LLight::GetColor() { return m_color; } //--------------------------------------------------------------------------- void LLight::SetSpotlight(bool value) { m_spotlight = value; } //--------------------------------------------------------------------------- bool LLight::GetSpotlight() { return m_spotlight; } //--------------------------------------------------------------------------- void LLight::SetTarget(LVector3 target) { m_target = target; } //--------------------------------------------------------------------------- LVector3 LLight::GetTarget() { return m_target; } //--------------------------------------------------------------------------- void LLight::SetHotspot(float value) { m_hotspot = value; } //--------------------------------------------------------------------------- float LLight::GetHotspot() { return m_hotspot; } //--------------------------------------------------------------------------- void LLight::SetFalloff(float value) { m_falloff = value; } //--------------------------------------------------------------------------- float LLight::GetFalloff() { return m_falloff; } //--------------------------------------------------------------------------- void LLight::SetAttenuationstart(float value) { m_attenuationend = value; } //--------------------------------------------------------------------------- float LLight::GetAttenuationstart() { return m_attenuationend; } //--------------------------------------------------------------------------- void LLight::SetAttenuationend(float value) { m_attenuationstart = value; } //--------------------------------------------------------------------------- float LLight::GetAttenuationend() { return m_attenuationstart; } //--------------------------------------------------------------------------- // LImporter CLASS IMPLEMENTATION //--------------------------------------------------------------------------- LImporter::LImporter() { Clear(); } //--------------------------------------------------------------------------- LImporter::~LImporter() { Clear(); } //--------------------------------------------------------------------------- uint LImporter::GetMeshCount() { return m_meshes.size(); } //--------------------------------------------------------------------------- uint LImporter::GetLightCount() { return m_lights.size(); } //--------------------------------------------------------------------------- uint LImporter::GetMaterialCount() { return m_materials.size(); } //--------------------------------------------------------------------------- uint LImporter::GetCameraCount() { return m_cameras.size(); } //--------------------------------------------------------------------------- LMesh& LImporter::GetMesh(uint index) { return m_meshes[index]; } //--------------------------------------------------------------------------- LLight& LImporter::GetLight(uint index) { return m_lights[index]; } //--------------------------------------------------------------------------- LMaterial& LImporter::GetMaterial(uint index) { return m_materials[index]; } //--------------------------------------------------------------------------- LCamera& LImporter::GetCamera(uint index) { return m_cameras[index]; } //--------------------------------------------------------------------------- LMaterial* LImporter::FindMaterial(const string& name) { for (uint i=0; i<m_materials.size(); i++) if (m_materials[i].IsObject(name)) return &m_materials[i]; return 0; } //--------------------------------------------------------------------------- LMesh* LImporter::FindMesh(const string& name) { for (uint i=0; i<m_meshes.size(); i++) if (m_meshes[i].IsObject(name)) return &m_meshes[i]; return 0; } //--------------------------------------------------------------------------- LLight* LImporter::FindLight(const string& name) { for (uint i=0; i<m_lights.size(); i++) if (m_lights[i].IsObject(name)) return &m_lights[i]; return 0; } //--------------------------------------------------------------------------- void LImporter::Clear() { m_meshes.clear(); m_lights.clear(); m_materials.clear(); m_optLevel = oSimple; } //--------------------------------------------------------------------------- void LImporter::SetOptimizationLevel(LOptimizationLevel value) { m_optLevel = value; } //--------------------------------------------------------------------------- LOptimizationLevel LImporter::GetOptimizationLevel() { return m_optLevel; } //--------------------------------------------------------------------------- // L3DS CLASS IMPLEMENTATION //--------------------------------------------------------------------------- L3DS::L3DS() : LImporter() { m_buffer = 0; m_bufferSize = 0; m_pos = 0; m_eof = false; } //--------------------------------------------------------------------------- L3DS::L3DS(const char *filename) : LImporter() { m_buffer = 0; m_bufferSize = 0; m_pos = 0; m_eof = false; LoadFile(filename); } //--------------------------------------------------------------------------- L3DS::~L3DS() { if (m_bufferSize > 0) free(m_buffer); } //--------------------------------------------------------------------------- bool L3DS::LoadFile(const char *filename) { FILE *f; f = fopen(filename, "rb"); if (f == 0) { ErrorMsg("L3DS::LoadFile - cannot open file"); return false; } fseek(f, 0, SEEK_END); m_bufferSize = ftell(f); fseek(f, 0, SEEK_SET); m_buffer = (unsigned char*) calloc(m_bufferSize, 1); if (m_buffer == 0) { ErrorMsg("L3DS::LoadFile - not enough memory (malloc failed)"); return false; } if (fread(m_buffer, m_bufferSize, 1, f) != 1) { fclose(f); free(m_buffer); m_bufferSize = 0; ErrorMsg("L3DS::LoadFile - error reading from file"); return false; } fclose(f); Clear(); bool res = Read3DS(); free(m_buffer); m_buffer = 0; m_bufferSize = 0; /*** Added by Dan Morris. Populates the vertex color list from the material array, using diffuse colors, to approximate the correct colors. ***/ if (this->GetMaterialCount() > 0) { uint last_mat = 0; // Now build colors for each triangle... for (uint i= 0; i<this->GetMeshCount(); i++) { LMesh &mesh = this->GetMesh(i); // For each triangle for (uint j=0; j<mesh.m_tris.size(); j++) { uint mat_id = mesh.m_tris[j].materialId; if (mat_id >= this->GetMaterialCount()) { mat_id = last_mat; } last_mat = mat_id; LMaterial& mat = this->GetMaterial(mat_id); LColor3 c = mat.GetDiffuseColor(); // Set each vertex's color mesh.SetColor(c, mesh.m_tris[j].a); mesh.SetColor(c, mesh.m_tris[j].b); mesh.SetColor(c, mesh.m_tris[j].c); } } } return res; } //--------------------------------------------------------------------------- short L3DS::ReadShort() { if ((m_buffer!=0) && (m_bufferSize != 0) && ((m_pos+2)<m_bufferSize)) { short *w = (short*)(m_buffer+m_pos); short s = *w; //(short)*(m_buffer+m_pos); m_pos += 2; return s; } m_eof = true; return 0; } //--------------------------------------------------------------------------- int L3DS::ReadInt() { if ((m_buffer!=0) && (m_bufferSize != 0) && ((m_pos+4)<m_bufferSize)) { int *w = (int*)(m_buffer+m_pos); int s = *w;//(int)*(m_buffer+m_pos); m_pos += 4; return s; } m_eof = true; return 0; } //--------------------------------------------------------------------------- char L3DS::ReadChar() { if ((m_buffer!=0) && (m_bufferSize != 0) && ((m_pos+1)<m_bufferSize)) { char s = (char)*(m_buffer+m_pos); m_pos += 1; return s; } m_eof = true; return 0; } //--------------------------------------------------------------------------- float L3DS::ReadFloat() { if ((m_buffer!=0) && (m_bufferSize != 0) && ((m_pos+4)<m_bufferSize)) { float *w = (float*)(m_buffer+m_pos); float s = *w;//(float)*(m_buffer+m_pos); m_pos += 4; return s; } m_eof = true; return 0.0; } //--------------------------------------------------------------------------- byte L3DS::ReadByte() { if ((m_buffer!=0) && (m_bufferSize != 0) && ((m_pos+1)<m_bufferSize)) { byte s = (byte)*(m_buffer+m_pos); m_pos += 1; return s; } m_eof = true; return 0; } //--------------------------------------------------------------------------- int L3DS::ReadASCIIZ(char *buf, int max_count) { int count; if ((m_buffer==0) || (m_bufferSize == 0) || (m_pos>=m_bufferSize)) { count = 0; m_eof = true; return count; } count = 0; char c = ReadChar(); while ((c!=0) && (count<max_count-1)) { buf[count] = c; count ++; c = ReadChar(); } buf[count] = 0; return count; } //--------------------------------------------------------------------------- void L3DS::Seek(int offset, int origin) { if (origin == SEEK_START) { m_pos = (std::max)(0,offset); } if (origin == SEEK_CURSOR) { if (offset < 0 && (uint)(abs(offset)) > m_pos) m_pos = 0; else m_pos += offset; } if (m_pos >= m_bufferSize) { m_pos = m_bufferSize-1; } m_eof = false; } //--------------------------------------------------------------------------- uint L3DS::Pos() { return m_pos; } //--------------------------------------------------------------------------- LChunk L3DS::ReadChunk() { LChunk chunk; chunk.id = ReadShort(); int a = ReadInt(); chunk.start = Pos(); chunk.end = chunk.start+a-6; return chunk; } //--------------------------------------------------------------------------- bool L3DS::FindChunk(LChunk &target, const LChunk &parent) { if (Pos() >= parent.end) return false; LChunk chunk; chunk = ReadChunk(); while (( chunk.id != target.id) && (chunk.end <= parent.end)) { SkipChunk(chunk); if (chunk.end >= parent.end) break; chunk = ReadChunk(); } if (chunk.id == target.id) { target.start = chunk.start; target.end = chunk.end; return true; } return false; } //--------------------------------------------------------------------------- void L3DS::SkipChunk(const LChunk &chunk) { Seek(chunk.end, SEEK_START); } //--------------------------------------------------------------------------- void L3DS::GotoChunk(const LChunk &chunk) { Seek(chunk.start, SEEK_START); } //--------------------------------------------------------------------------- LColor3 L3DS::ReadColor(const LChunk &chunk) { LColor3 col = black; GotoChunk(chunk); switch (chunk.id) { case COLOR_F: col.r = ReadFloat(); col.g = ReadFloat(); col.b = ReadFloat(); break; case COLOR_24: col.r = ReadByte()/255.0f; col.g = ReadByte()/255.0f; col.b = ReadByte()/255.0f; break; case LIN_COLOR_F: col.r = ReadFloat(); col.g = ReadFloat(); col.b = ReadFloat(); break; case LIN_COLOR_24: col.r = ReadByte()/255.0f; col.g = ReadByte()/255.0f; col.b = ReadByte()/255.0f; break; default: ErrorMsg("L3DS::ReadColor - error this is not a color chunk"); } return col; } //--------------------------------------------------------------------------- float L3DS::ReadPercentage(const LChunk &chunk) { GotoChunk(chunk); switch (chunk.id) { case INT_PERCENTAGE: return (ReadShort()/100.0f); case FLOAT_PERCENTAGE: return ReadFloat(); } ErrorMsg("L3DS::ReadPercentage - error, the chunk is not a percentage chunk"); return 0; } //--------------------------------------------------------------------------- bool L3DS::Read3DS() { LChunk mainchunk; LChunk edit; edit.id = EDIT3DS; mainchunk = ReadChunk(); if (mainchunk.id != MAIN3DS) { ErrorMsg("L3DS::Read3DS - wrong file format"); return false; } if (!FindChunk(edit, mainchunk)) return false; LChunk obj; LChunk ml; GotoChunk(edit); obj.id = MAT_ENTRY; while (FindChunk(obj, edit)) { ReadMaterial(obj); SkipChunk(obj); } GotoChunk(edit); obj.id = EDIT_OBJECT; { while (FindChunk(obj, edit)) { ReadASCIIZ(m_objName, 99); ml = ReadChunk(); if (ml.id == OBJ_TRIMESH) { ReadMesh(ml); } else if (ml.id == OBJ_LIGHT) { ReadLight(ml); } else if (ml.id == OBJ_CAMERA) { ReadCamera(ml); } SkipChunk(obj); } } // read the keyframer data here to find out correct object orientation LChunk keyframer; keyframer.id = KFDATA; LChunk objtrack; objtrack.id = OBJECT_NODE_TAG; GotoChunk(mainchunk); if (FindChunk(keyframer, mainchunk)) { // keyframer chunk is present GotoChunk(keyframer); while (FindChunk(objtrack, keyframer)) { ReadKeyframeData(objtrack); SkipChunk(objtrack); } } for (uint i=0; i<m_meshes.size(); i++) m_meshes[i].Optimize(m_optLevel); m_pos = 0; strcpy(m_objName, ""); return true; } //--------------------------------------------------------------------------- void L3DS::ReadLight(const LChunk &parent) { float t; LVector3 v; LLight light; light.SetName(m_objName); v.x = ReadFloat(); v.y = ReadFloat(); v.z = ReadFloat(); light.SetPosition(v); LChunk chunk = ReadChunk(); while (chunk.end <= parent.end) { switch (chunk.id) { case COLOR_24: case COLOR_F: case LIN_COLOR_F: case LIN_COLOR_24: light.SetColor(ReadColor(chunk)); break; case SPOTLIGHT: v.x = ReadFloat(); v.y = ReadFloat(); v.z = ReadFloat(); light.SetTarget(v); t = ReadFloat(); light.SetHotspot(t); t = ReadFloat(); light.SetFalloff(t); break; case LIT_INRANGE: light.SetAttenuationstart(ReadFloat()); break; case LIT_OUTRANGE: light.SetAttenuationend(ReadFloat()); break; default: break; } SkipChunk(chunk); if (chunk.end >= parent.end) break; chunk = ReadChunk(); } m_lights.push_back(light); } //--------------------------------------------------------------------------- void L3DS::ReadCamera(const LChunk &parent) { LVector3 v,t; LCamera camera; camera.SetName(m_objName); v.x = ReadFloat(); v.y = ReadFloat(); v.z = ReadFloat(); t.x = ReadFloat(); t.y = ReadFloat(); t.z = ReadFloat(); camera.SetPosition(v); camera.SetTarget(t); camera.SetBank(ReadFloat()); camera.SetFOV(2400.0f/ReadFloat()); LChunk chunk = ReadChunk(); while (chunk.end <= parent.end) { switch (chunk.id) { case CAM_RANGES: camera.SetNearplane(ReadFloat()); camera.SetFarplane(ReadFloat()); break; default: break; } SkipChunk(chunk); if (chunk.end >= parent.end) break; chunk = ReadChunk(); } m_cameras.push_back(camera); } //--------------------------------------------------------------------------- void L3DS::ReadMesh(const LChunk &parent) { unsigned short count, i; LVector4 p; LMatrix4 m; LVector2 t; p.w = 1.0f; LMesh mesh; mesh.SetName(m_objName); GotoChunk(parent); LChunk chunk = ReadChunk(); while (chunk.end <= parent.end) { switch (chunk.id) { case TRI_VERTEXLIST: count = ReadShort(); mesh.SetVertexArraySize(count); for (i=0; i < count; i++) { p.x = ReadFloat(); p.y = ReadFloat(); p.z = ReadFloat(); mesh.SetVertex(p, i); } break; case TRI_FACEMAPPING: count = ReadShort(); if (mesh.GetVertexCount() == 0) mesh.SetVertexArraySize(count); for (i=0; i < count; i++) { t.x = ReadFloat(); t.y = ReadFloat(); mesh.SetUV(t, i); } break; case TRI_FACELIST: ReadFaceList(chunk, mesh); break; case TRI_MATRIX: m._11 = ReadFloat(); m._12 = ReadFloat(); m._13 = ReadFloat(); m._21 = ReadFloat(); m._22 = ReadFloat(); m._23 = ReadFloat(); m._31 = ReadFloat(); m._32 = ReadFloat(); m._33 = ReadFloat(); /* m._41 = ReadFloat(); m._42 = ReadFloat(); m._43 = ReadFloat(); */ m._41 = 0.0; m._42 = 0.0; m._43 = 0.0; m._14 = 0.0f; m._24 = 0.0f; m._34 = 0.0f; m._44 = 1.0f; mesh.SetMatrix(m); break; default: break; } SkipChunk(chunk); if (chunk.end >= parent.end) break; chunk = ReadChunk(); } m_meshes.push_back(mesh); } //--------------------------------------------------------------------------- void L3DS::ReadFaceList(const LChunk &chunk, LMesh &mesh) { // variables unsigned short count, t; uint i; LTri tri; LChunk ch; char str[20]; //uint mat; // consistency checks if (chunk.id != TRI_FACELIST) { ErrorMsg("L3DS::ReadFaceList - internal error: wrong chunk passed as parameter"); return; } GotoChunk(chunk); tri.smoothingGroups = 1; // read the number of faces count = ReadShort(); mesh.SetTriangleArraySize(count); for (i=0; i<(unsigned int)count; i++) { tri.a = ReadShort(); tri.b = ReadShort(); tri.c = ReadShort(); ReadShort(); mesh.SetTri(tri, i); } // now read the optional chunks ch = ReadChunk(); int mat_id = 0; while (ch.end <= chunk.end) { LMaterial* mat; switch (ch.id) { case TRI_MAT_GROUP: ReadASCIIZ(str, 20); mat = FindMaterial(str); if (mat) { mat_id = mat->GetID(); mesh.AddMaterial(mat_id); } count = ReadShort(); for (i=0; i<(unsigned int)count; i++) { t = ReadShort(); if (mat) mesh.GetTri(t).materialId = mat_id; } break; case TRI_SMOOTH_GROUP: for (i=0; i<mesh.GetTriangleCount(); i++) mesh.GetTri(i).smoothingGroups = (ulong) ReadInt(); break; } SkipChunk(ch); ch = ReadChunk(); } } //--------------------------------------------------------------------------- void L3DS::ReadMaterial(const LChunk &parent) { // variables LChunk chunk; LChunk child; char str[30]; LMaterial mat; short sh; GotoChunk(parent); chunk = ReadChunk(); while (chunk.end <= parent.end) { switch (chunk.id) { case MAT_NAME: ReadASCIIZ(str, 30); mat.SetName(str); break; case MAT_AMBIENT: child = ReadChunk(); mat.SetAmbientColor(ReadColor(child)); break; case MAT_DIFFUSE: child = ReadChunk(); mat.SetDiffuseColor(ReadColor(child)); break; case MAT_SPECULAR: child = ReadChunk(); mat.SetSpecularColor(ReadColor(child)); break; case MAT_SHININESS: child = ReadChunk(); mat.SetShininess(ReadPercentage(child)); break; case MAT_TRANSPARENCY: child = ReadChunk(); mat.SetTransparency(ReadPercentage(child)); break; case MAT_SHADING: sh = ReadShort(); switch (sh) { case 0: mat.SetShadingType(sWireframe); break; case 1: mat.SetShadingType(sFlat); break; case 2: mat.SetShadingType(sGouraud); break; case 3: mat.SetShadingType(sPhong); break; case 4: mat.SetShadingType(sMetal); break; } break; case MAT_WIRE: mat.SetShadingType(sWireframe); break; case MAT_TEXMAP: ReadMap(chunk, mat.GetTextureMap1()); break; case MAT_TEX2MAP: ReadMap(chunk, mat.GetTextureMap2()); break; case MAT_OPACMAP: ReadMap(chunk, mat.GetOpacityMap()); break; case MAT_BUMPMAP: ReadMap(chunk, mat.GetBumpMap()); break; case MAT_SPECMAP: ReadMap(chunk, mat.GetSpecularMap()); break; case MAT_REFLMAP: child = ReadChunk(); mat.GetReflectionMap().strength = ReadPercentage(child); SkipChunk(child); child = ReadChunk(); if (child.id != MAT_MAPNAME) { ErrorMsg("L3DS::ReadMaterial - error, expected chunk not found"); return; } ReadASCIIZ(str, 30); if (strcmp(str, "") == 0) strcpy(mat.GetReflectionMap().mapName, "auto"); break; } SkipChunk(chunk); chunk = ReadChunk(); } m_materials.push_back(mat); m_materials[m_materials.size()-1].SetID(m_materials.size()-1); } //--------------------------------------------------------------------------- void L3DS::ReadMap(const LChunk &chunk, LMap& lmap) { LChunk child; char str[20]; GotoChunk(chunk); child = ReadChunk(); while (child.end <= chunk.end) { switch (child.id) { case INT_PERCENTAGE: lmap.strength = ReadPercentage(child); break; case MAT_MAPNAME: ReadASCIIZ(str, 20); strcpy(lmap.mapName, str); break; case MAT_MAP_USCALE: lmap.uScale = ReadFloat(); break; case MAT_MAP_VSCALE: lmap.vScale = ReadFloat(); break; case MAT_MAP_UOFFSET: lmap.uOffset = ReadFloat(); break; case MAT_MAP_VOFFSET: lmap.vOffset = ReadFloat(); break; case MAT_MAP_ANG: lmap.angle = ReadFloat(); break; } SkipChunk(child); child = ReadChunk(); } } //--------------------------------------------------------------------------- void L3DS::ReadKeyframeData(const LChunk &parent) { uint frames = 0; LChunk node_hdr; node_hdr.id = NODE_HDR; char str[20]; LMesh *mesh; GotoChunk(parent); if (!FindChunk(node_hdr, parent)) return; GotoChunk(node_hdr); ReadASCIIZ(str, 19); mesh = FindMesh(str); if (mesh == 0) return; GotoChunk(parent); // read the pivot LVector3 pivot = zero3; LChunk pivotchunk; pivotchunk.id = PIVOT; if (FindChunk(pivotchunk, parent)) { GotoChunk(pivotchunk); pivot.x = ReadFloat(); pivot.y = ReadFloat(); pivot.z = ReadFloat(); } GotoChunk(parent); // read frame 0 from the position track LVector3 pos = zero3; frames = 0; LChunk poschunk; poschunk.id = POS_TRACK_TAG; if (FindChunk(poschunk, parent)) { GotoChunk(poschunk); // read the trackheader structure ReadShort(); ReadInt(); ReadInt(); frames = ReadInt(); if (frames > 0) { ReadKeyheader(); pos.x = ReadFloat(); pos.y = ReadFloat(); pos.z = ReadFloat(); } } GotoChunk(parent); // now read the rotation track LVector4 rot = zero4; LChunk rotchunk; rotchunk.id = ROT_TRACK_TAG; frames = 0; if (FindChunk(rotchunk, parent)) { GotoChunk(rotchunk); // read the trackheader structure ReadShort(); ReadInt(); ReadInt(); frames = ReadInt(); if (frames > 0) { ReadKeyheader(); rot.x = ReadFloat(); rot.y = ReadFloat(); rot.z = ReadFloat(); rot.w = ReadFloat(); } } GotoChunk(parent); // now read the scaling chunk LVector3 scale; scale.x = 1; scale.y = 1; scale.z = 1; LChunk scalechunk; scalechunk.id = SCL_TRACK_TAG; frames = 0; if (FindChunk(scalechunk, parent)) { GotoChunk(scalechunk); // read the trackheader structure ReadShort(); ReadInt(); ReadInt(); frames = ReadInt(); if (frames > 0) { ReadKeyheader(); scale.x = ReadFloat(); scale.y = ReadFloat(); scale.z = ReadFloat(); } } GotoChunk(parent); } //--------------------------------------------------------------------------- long L3DS::ReadKeyheader() { long frame; frame = ReadInt(); short opts = ReadShort(); if (opts & 32768) // 32768 is 1000000000000000 binary { // tension is present ReadFloat(); } if (opts & 16384) // 16384 is 0100000000000000 binary { // continuity is present ReadFloat(); } if (opts & 8192) { // bias info present ReadFloat(); } if (opts & 4096) { // "ease to" present ReadFloat(); } if (opts & 2048) { // "ease from" present ReadFloat(); } return frame; } //--------------------------------------------------------------------------- #endif // DOXYGEN_SHOULD_SKIP_THIS //---------------------------------------------------------------------------
27.008142
98
0.428908
[ "mesh", "object", "vector", "3d" ]
57e3416bd494660d89a4b9ae857c520084c313bf
3,557
cpp
C++
src/examples/mc_att_control_multiplatform/mc_att_control_main.cpp
wms124/PX4_1.4.1_Back-up
9d6d903a8f46346281ae11104c47f1904da05e37
[ "BSD-3-Clause" ]
69
2016-05-05T10:59:40.000Z
2021-06-15T07:58:43.000Z
src/examples/mc_att_control_multiplatform/mc_att_control_main.cpp
wms124/PX4_1.4.1_Back-up
9d6d903a8f46346281ae11104c47f1904da05e37
[ "BSD-3-Clause" ]
30
2015-01-01T19:52:52.000Z
2016-03-14T15:44:06.000Z
src/examples/mc_att_control_multiplatform/mc_att_control_main.cpp
wms124/PX4_1.4.1_Back-up
9d6d903a8f46346281ae11104c47f1904da05e37
[ "BSD-3-Clause" ]
347
2015-01-01T08:13:46.000Z
2016-03-21T01:13:55.000Z
/**************************************************************************** * * Copyright (c) 2013, 2014 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file mc_att_control_main.cpp * Multicopter attitude controller. * * @author Tobias Naegeli <naegelit@student.ethz.ch> * @author Lorenz Meier <lm@inf.ethz.ch> * @author Anton Babushkin <anton.babushkin@me.com> * @author Thomas Gubler <thomasgubler@gmail.com> * @author Julian Oes <julian@oes.ch> * @author Roman Bapst <bapstr@ethz.ch> * * The controller has two loops: P loop for angular error and PD loop for angular rate error. * Desired rotation calculated keeping in mind that yaw response is normally slower than roll/pitch. * For small deviations controller rotates copter to have shortest path of thrust vector and independently rotates around yaw, * so actual rotation axis is not constant. For large deviations controller rotates copter around fixed axis. * These two approaches fused seamlessly with weight depending on angular error. * When thrust vector directed near-horizontally (e.g. roll ~= PI/2) yaw setpoint ignored because of singularity. * Controller doesn't use Euler angles for work, they generated only for more human-friendly control and logging. * If rotation matrix setpoint is invalid it will be generated from Euler angles for compatibility with old position controllers. */ #include "mc_att_control.h" bool mc_att_control_thread_running = false; /**< Deamon status flag */ #if defined(__PX4_ROS) int main(int argc, char **argv) #else int mc_att_control_start_main(int argc, char **argv); // Prototype for missing declearation error with nuttx int mc_att_control_start_main(int argc, char **argv) #endif { px4::init(argc, argv, "mc_att_control_m"); PX4_INFO("starting"); MulticopterAttitudeControlMultiplatform attctl; mc_att_control_thread_running = true; attctl.spin(); PX4_INFO("exiting."); mc_att_control_thread_running = false; return 0; }
45.025316
129
0.732359
[ "vector" ]
57e4c15f3cc5637b2d00174c06b6da0898aa2522
9,178
cpp
C++
src/mongo/db/pipeline/process_interface/common_process_interface.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/db/pipeline/process_interface/common_process_interface.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/db/pipeline/process_interface/common_process_interface.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2018-present MongoDB, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * <http://www.mongodb.com/licensing/server-side-public-license>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the Server Side Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #include "mongo/platform/basic.h" #include "mongo/db/pipeline/process_interface/common_process_interface.h" #include "mongo/bson/mutable/document.h" #include "mongo/config.h" #include "mongo/db/auth/authorization_manager.h" #include "mongo/db/auth/authorization_session.h" #include "mongo/db/client.h" #include "mongo/db/curop.h" #include "mongo/db/operation_context.h" #include "mongo/db/operation_time_tracker.h" #include "mongo/db/pipeline/expression_context.h" #include "mongo/db/repl/repl_client_info.h" #include "mongo/db/repl/replication_coordinator.h" #include "mongo/db/service_context.h" #include "mongo/platform/atomic_word.h" #include "mongo/platform/mutex.h" #include "mongo/s/grid.h" #include "mongo/util/net/socket_utils.h" #ifndef MONGO_CONFIG_USE_RAW_LATCHES #include "mongo/util/diagnostic_info.h" #endif #define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kDefault namespace mongo { std::vector<BSONObj> CommonProcessInterface::getCurrentOps( const boost::intrusive_ptr<ExpressionContext>& expCtx, CurrentOpConnectionsMode connMode, CurrentOpSessionsMode sessionMode, CurrentOpUserMode userMode, CurrentOpTruncateMode truncateMode, CurrentOpCursorMode cursorMode, CurrentOpBacktraceMode backtraceMode) const { OperationContext* opCtx = expCtx->opCtx; AuthorizationSession* ctxAuth = AuthorizationSession::get(opCtx->getClient()); std::vector<BSONObj> ops; #ifndef MONGO_CONFIG_USE_RAW_LATCHES auto blockedOpGuard = DiagnosticInfo::maybeMakeBlockedOpForTest(opCtx->getClient()); #endif for (ServiceContext::LockedClientsCursor cursor(opCtx->getClient()->getServiceContext()); Client* client = cursor.next();) { invariant(client); stdx::lock_guard<Client> lk(*client); // If auth is disabled, ignore the allUsers parameter. if (ctxAuth->getAuthorizationManager().isAuthEnabled() && userMode == CurrentOpUserMode::kExcludeOthers && !ctxAuth->isCoauthorizedWithClient(client, lk)) { continue; } // Ignore inactive connections unless 'idleConnections' is true. if (connMode == CurrentOpConnectionsMode::kExcludeIdle && !client->hasAnyActiveCurrentOp()) { continue; } // Delegate to the mongoD- or mongoS-specific implementation of _reportCurrentOpForClient. ops.emplace_back(_reportCurrentOpForClient(opCtx, client, truncateMode, backtraceMode)); } // If 'cursorMode' is set to include idle cursors, retrieve them and add them to ops. if (cursorMode == CurrentOpCursorMode::kIncludeCursors) { for (auto&& cursor : getIdleCursors(expCtx, userMode)) { BSONObjBuilder cursorObj; cursorObj.append("type", "idleCursor"); cursorObj.append("host", getHostNameCachedAndPort()); // First, extract fields which need to go at the top level out of the GenericCursor. auto ns = cursor.getNs(); cursorObj.append("ns", ns->toString()); if (auto lsid = cursor.getLsid()) { cursorObj.append("lsid", lsid->toBSON()); } if (auto planSummaryData = cursor.getPlanSummary()) { // Not present on mongos. cursorObj.append("planSummary", *planSummaryData); } // Next, append the stripped-down version of the generic cursor. This will avoid // duplicating information reported at the top level. cursorObj.append("cursor", CurOp::truncateAndSerializeGenericCursor(&cursor, boost::none)); ops.emplace_back(cursorObj.obj()); } } // If we need to report on idle Sessions, defer to the mongoD or mongoS implementations. if (sessionMode == CurrentOpSessionsMode::kIncludeIdle) { _reportCurrentOpsForIdleSessions(opCtx, userMode, &ops); } if (!ctxAuth->getAuthorizationManager().isAuthEnabled() || userMode == CurrentOpUserMode::kIncludeAll) { _reportCurrentOpsForTransactionCoordinators( opCtx, sessionMode == MongoProcessInterface::CurrentOpSessionsMode::kIncludeIdle, &ops); _reportCurrentOpsForPrimaryOnlyServices(opCtx, connMode, sessionMode, &ops); } return ops; } std::vector<FieldPath> CommonProcessInterface::collectDocumentKeyFieldsActingAsRouter( OperationContext* opCtx, const NamespaceString& nss) const { const auto cm = uassertStatusOK(Grid::get(opCtx)->catalogCache()->getCollectionRoutingInfo(opCtx, nss)); if (cm.isSharded()) { return _shardKeyToDocumentKeyFields(cm.getShardKeyPattern().getKeyPatternFields()); } // We have no evidence this collection is sharded, so the document key is just _id. return {"_id"}; } void CommonProcessInterface::updateClientOperationTime(OperationContext* opCtx) const { // In order to support causal consistency in a replica set or a sharded cluster when reading // with secondary read preference, the secondary must propagate the primary's operation time // to the client so that when the client attempts to read, the secondary will block until it // has replicated the primary's writes. As such, the 'operationTime' returned from the // primary is explicitly set on the given opCtx's client. // // Note that the operationTime is attached even when a command fails because writes may succeed // while the command fails (such as in a $merge where 'whenMatched' is set to fail). This // guarantees that the operation time returned to the client reflects the most recent // successful write executed by this client. auto replCoord = repl::ReplicationCoordinator::get(opCtx); if (replCoord) { auto operationTime = OperationTimeTracker::get(opCtx)->getMaxOperationTime(); repl::ReplClientInfo::forClient(opCtx->getClient()) .setLastProxyWriteTimestampForward(operationTime.asTimestamp()); } } bool CommonProcessInterface::keyPatternNamesExactPaths(const BSONObj& keyPattern, const std::set<FieldPath>& uniqueKeyPaths) { size_t nFieldsMatched = 0; for (auto&& elem : keyPattern) { if (!elem.isNumber()) { return false; } if (uniqueKeyPaths.find(elem.fieldNameStringData()) == uniqueKeyPaths.end()) { return false; } ++nFieldsMatched; } return nFieldsMatched == uniqueKeyPaths.size(); } boost::optional<ChunkVersion> CommonProcessInterface::refreshAndGetCollectionVersion( const boost::intrusive_ptr<ExpressionContext>& expCtx, const NamespaceString& nss) const { const auto cm = uassertStatusOK(Grid::get(expCtx->opCtx) ->catalogCache() ->getCollectionRoutingInfoWithRefresh(expCtx->opCtx, nss)); return cm.isSharded() ? boost::make_optional(cm.getVersion()) : boost::none; } std::vector<FieldPath> CommonProcessInterface::_shardKeyToDocumentKeyFields( const std::vector<std::unique_ptr<FieldRef>>& keyPatternFields) const { std::vector<FieldPath> result; bool gotId = false; for (auto& field : keyPatternFields) { result.emplace_back(field->dottedField()); gotId |= (result.back().fullPath() == "_id"); } if (!gotId) { // If not part of the shard key, "_id" comes last. result.emplace_back("_id"); } return result; } std::string CommonProcessInterface::getHostAndPort(OperationContext* opCtx) const { return getHostNameCachedAndPort(); } } // namespace mongo
42.294931
100
0.694923
[ "vector" ]
57e7c27a1aeeb229713384e2ce4880ee70fe21e2
8,616
cpp
C++
test/performance-regression/full-apps/qmcpack/src/QMCWaveFunctions/Fermion/DiracDeterminantIterative.cpp
JKChenFZ/hclib
50970656ac133477c0fbe80bb674fe88a19d7177
[ "BSD-3-Clause" ]
55
2015-07-28T01:32:58.000Z
2022-02-27T16:27:46.000Z
test/performance-regression/full-apps/qmcpack/src/QMCWaveFunctions/Fermion/DiracDeterminantIterative.cpp
JKChenFZ/hclib
50970656ac133477c0fbe80bb674fe88a19d7177
[ "BSD-3-Clause" ]
66
2015-06-15T20:38:19.000Z
2020-08-26T00:11:43.000Z
test/performance-regression/full-apps/qmcpack/src/QMCWaveFunctions/Fermion/DiracDeterminantIterative.cpp
JKChenFZ/hclib
50970656ac133477c0fbe80bb674fe88a19d7177
[ "BSD-3-Clause" ]
26
2015-10-26T22:11:51.000Z
2021-03-02T22:09:15.000Z
////////////////////////////////////////////////////////////////// // (c) Copyright 1998-2002,2003- by Jeongnim Kim ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// // Jeongnim Kim // National Center for Supercomputing Applications & // Materials Computation Center // University of Illinois, Urbana-Champaign // Urbana, IL 61801 // e-mail: jnkim@ncsa.uiuc.edu // // Supported by // National Center for Supercomputing Applications, UIUC // Materials Computation Center, UIUC ////////////////////////////////////////////////////////////////// // -*- C++ -*- #include "QMCWaveFunctions/Fermion/DiracDeterminantIterative.h" #include "Numerics/DeterminantOperators.h" #include "Numerics/OhmmsBlas.h" //extern "C"{ //#include "ILUGMRESInterface.h" //} namespace qmcplusplus { /** constructor *@param spos the single-particle orbital set *@param first index of the first particle */ DiracDeterminantIterative::DiracDeterminantIterative(SPOSetBasePtr const &spos, int first): DiracDeterminantBase(spos,first) { } ///default destructor DiracDeterminantIterative::~DiracDeterminantIterative() {} DiracDeterminantIterative& DiracDeterminantIterative::operator=(const DiracDeterminantIterative& s) { NP=0; resize(s.NumPtcls, s.NumOrbitals); return *this; } DiracDeterminantIterative::DiracDeterminantIterative(const DiracDeterminantIterative& s): DiracDeterminantBase(s) { this->resize(s.NumPtcls,s.NumOrbitals); } void DiracDeterminantIterative::set(int first, int nel) { APP_ABORT("DiracDeterminantIterative::set"); } void DiracDeterminantIterative::set_iterative(int first, int nel,double &temp_cutoff) { cutoff=temp_cutoff; FirstIndex = first; resize(nel,nel); } void DiracDeterminantIterative::resize(int nel, int morb) { particleLists.resize(nel); DiracDeterminantBase::resize(nel,morb); } void DiracDeterminantIterative::SparseToCSR(vector<int> &Arp, vector<int> &Ari,vector<double> &Arx) { int systemSize=LastIndex-FirstIndex; int nnz_index=0; Arp.push_back(0); // cerr<<"Particle list size is "<<particleLists.size()<<endl; for (int ptcl=0; ptcl<particleLists.size(); ptcl++) { for (list<pair<int,double> >::iterator orb=particleLists[ptcl].begin(); orb!=particleLists[ptcl].end(); orb++) { pair<int,double> myPair=*orb; int orbitalIndex=myPair.first; double value=myPair.second; // if (abs(myValue)>=cutoff){ Ari.push_back(orbitalIndex); Arx.push_back(value); nnz_index++; } // } Arp.push_back(nnz_index); } // cerr<<"Ari size is "<<Ari.size()<<endl; } DiracDeterminantBase::ValueType DiracDeterminantIterative::ratio(ParticleSet& P, int iat) { // cerr<<"Using local ratio "<<TestMe()<<endl; UpdateMode=ORB_PBYP_RATIO; WorkingIndex = iat-FirstIndex; assert(FirstIndex==0); Phi->evaluate(P, iat, psiV); // cerr<<"Preparing stuff"<<endl; vector<int> Arp; vector<int> Ari; vector<double> Arx; SparseToCSR(Arp,Ari,Arx); vector<int> Arp2(Arp.size()); vector<int> Ari2(Ari.size()); vector<double> Arx2(Arx.size()); Arp2=Arp; Ari2=Ari; Arx2=Arx; int particleMoved=iat; int systemSize=LastIndex-FirstIndex; int nnzUpdatedPassed=Ari.size(); vector<double> uPassed(psiV.size()); double detRatio_ILU=0; for (int i=0; i<uPassed.size(); i++) uPassed[i]=psiV[i]; // cerr<<"Calling stuff"<<systemSize<<" "<<Arp.size()<<endl; assert(systemSize+1==Arp.size()); assert(Ari.size()<=nnzUpdatedPassed); // cerr<<"Entering"<<endl; //HACK TO GET TO COMPILE calcDeterminantILUGMRES(&particleMoved, &systemSize, &nnzUpdatedPassed, uPassed.data(), Arp.data(), Ari.data(), Arx.data(), Arp2.data(), Ari2.data(), Arx2.data(), &detRatio_ILU); // int *Arp_ptr; int *Ari_ptr; double *Arx_ptr; // DenseToCSR(psiM_actual,Arp_ptr,Ari_ptr,Arx_ptr); // cerr<<"The size of my particle list is "<<particleLists[iat].size()<<" "<<cutoff<<endl; oldPtcl.clear(); assert(iat<particleLists.size()); particleLists[iat].swap(oldPtcl); for (int i=0; i<psiV.size(); i++) { if (abs(psiV(i))>=cutoff) { pair <int,double> temp(i,psiV(i)); particleLists[iat].push_back(temp); } } #ifdef DIRAC_USE_BLAS curRatio = BLAS::dot(NumOrbitals,psiM[iat-FirstIndex],&psiV[0]); // cerr<<"RATIOS: "<<curRatio<<" "<<detRatio_ILU<<endl; return curRatio; #else curRatio = DetRatio(psiM, psiV.begin(),iat-FirstIndex); // cerr<<"RATIOS: "<<curRatio<<" "<<detRatio_ILU<<endl; return curRatio; #endif } DiracDeterminantBase::ValueType DiracDeterminantIterative::ratio(ParticleSet& P, int iat, ParticleSet::ParticleGradient_t& dG, ParticleSet::ParticleLaplacian_t& dL) { // cerr<<"doing large update"<<endl; UpdateMode=ORB_PBYP_ALL; Phi->evaluate(P, iat, psiV, dpsiV, d2psiV); WorkingIndex = iat-FirstIndex; #ifdef DIRAC_USE_BLAS curRatio = BLAS::dot(NumOrbitals,psiM_temp[WorkingIndex],&psiV[0]); #else curRatio= DetRatio(psiM_temp, psiV.begin(),WorkingIndex); #endif if(abs(curRatio)<numeric_limits<RealType>::epsilon()) { UpdateMode=ORB_PBYP_RATIO; //singularity! do not update inverse return 0.0; } //update psiM_temp with the row substituted DetUpdate(psiM_temp,psiV,workV1,workV2,WorkingIndex,curRatio); //update dpsiM_temp and d2psiM_temp for(int j=0; j<NumOrbitals; j++) { dpsiM_temp(WorkingIndex,j)=dpsiV[j]; d2psiM_temp(WorkingIndex,j)=d2psiV[j]; } int kat=FirstIndex; const ValueType* restrict yptr=psiM_temp.data(); const ValueType* restrict d2yptr=d2psiM_temp.data(); const GradType* restrict dyptr=dpsiM_temp.data(); for(int i=0; i<NumPtcls; i++,kat++) { //This mimics gemm with loop optimization GradType rv; ValueType lap=0.0; for(int j=0; j<NumOrbitals; j++,yptr++) { rv += *yptr * *dyptr++; lap += *yptr * *d2yptr++; } //using inline dot functions //GradType rv=dot(psiM_temp[i],dpsiM_temp[i],NumOrbitals); //ValueType lap=dot(psiM_temp[i],d2psiM_temp[i],NumOrbitals); //Old index: This is not pretty //GradType rv =psiM_temp(i,0)*dpsiM_temp(i,0); //ValueType lap=psiM_temp(i,0)*d2psiM_temp(i,0); //for(int j=1; j<NumOrbitals; j++) { // rv += psiM_temp(i,j)*dpsiM_temp(i,j); // lap += psiM_temp(i,j)*d2psiM_temp(i,j); //} lap -= dot(rv,rv); dG[kat] += rv - myG[kat]; myG_temp[kat]=rv; dL[kat] += lap -myL[kat]; myL_temp[kat]=lap; } return curRatio; } DiracDeterminantBase::RealType DiracDeterminantIterative::evaluateLog(ParticleSet& P, PooledData<RealType>& buf) { return DiracDeterminantBase::evaluateLog(P,buf); } DiracDeterminantBase::RealType DiracDeterminantIterative::evaluateLog(ParticleSet& P, ParticleSet::ParticleGradient_t& G, ParticleSet::ParticleLaplacian_t& L) { Phi->evaluate(P, FirstIndex, LastIndex, psiM,dpsiM, d2psiM); ///I think at this point psiM has particles as the first index for (int ptcl=0; ptcl<psiM.extent(1); ptcl++) { particleLists[ptcl].clear(); for (int orbital=0; orbital<psiM.extent(0); orbital++) { if (abs(psiM(orbital,ptcl))>=cutoff) { pair<int,double> temp(orbital,psiM(orbital,ptcl)); particleLists[ptcl].push_back(temp); } } } if(NumPtcls==1) { //CurrentDet=psiM(0,0); ValueType det=psiM(0,0); ValueType y=1.0/det; psiM(0,0)=y; GradType rv = y*dpsiM(0,0); G(FirstIndex) += rv; L(FirstIndex) += y*d2psiM(0,0) - dot(rv,rv); LogValue = evaluateLogAndPhase(det,PhaseValue); } else { LogValue=InvertWithLog(psiM.data(),NumPtcls,NumOrbitals,WorkSpace.data(),Pivot.data(),PhaseValue); const ValueType* restrict yptr=psiM.data(); const ValueType* restrict d2yptr=d2psiM.data(); const GradType* restrict dyptr=dpsiM.data(); for(int i=0, iat=FirstIndex; i<NumPtcls; i++, iat++) { GradType rv; ValueType lap=0.0; for(int j=0; j<NumOrbitals; j++,yptr++) { rv += *yptr * *dyptr++; lap += *yptr * *d2yptr++; } G(iat) += rv; L(iat) += lap - dot(rv,rv); } } return LogValue; } } /*************************************************************************** * $RCSfile$ $Author: jnkim $ * $Revision: 3265 $ $Date: 2008-10-15 09:20:33 -0500 (Wed, 15 Oct 2008) $ * $Id: DiracDeterminantIterative.cpp 3265 2008-10-15 14:20:33Z jnkim $ ***************************************************************************/
30.020906
208
0.63533
[ "vector" ]
57ee4311229acf610e4941f29dda9483b41067a1
13,324
cc
C++
centreon-engine/tests/downtimes/downtime_finder.cc
centreon/centreon-collect
e63fc4d888a120d588a93169e7d36b360616bdee
[ "Unlicense" ]
8
2020-07-26T09:12:02.000Z
2022-03-30T17:24:29.000Z
centreon-engine/tests/downtimes/downtime_finder.cc
centreon/centreon-collect
e63fc4d888a120d588a93169e7d36b360616bdee
[ "Unlicense" ]
47
2020-06-18T12:11:37.000Z
2022-03-16T10:28:56.000Z
centreon-engine/tests/downtimes/downtime_finder.cc
centreon/centreon-collect
e63fc4d888a120d588a93169e7d36b360616bdee
[ "Unlicense" ]
5
2020-06-29T14:22:02.000Z
2022-03-17T10:34:10.000Z
/* ** Copyright 2016 Centreon ** ** This file is part of Centreon Engine. ** ** Centreon Engine is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Engine 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 Centreon Engine. If not, see ** <http://www.gnu.org/licenses/>. */ #include "com/centreon/engine/downtimes/downtime_finder.hh" #include <gtest/gtest.h> #include <map> #include <memory> #include "com/centreon/clib.hh" #include "com/centreon/engine/downtimes/downtime.hh" #include "com/centreon/engine/downtimes/downtime_manager.hh" #include "com/centreon/engine/downtimes/service_downtime.hh" #include "helper.hh" using namespace com::centreon; using namespace com::centreon::engine; using namespace com::centreon::engine::downtimes; class DowntimeFinderFindMatchingAllTest : public ::testing::Test { public: void SetUp() override { init_config_state(); downtime_manager::instance().clear_scheduled_downtimes(); downtime_manager::instance().initialize_downtime_data(); new_downtime(0, "test_host", "", 234567891, 134567892, 1, 0, 84, "other_author", "test_comment"); new_downtime(1, "first_host", "test_service", 123456789, 134567892, 1, 0, 42, "test_author", "other_comment"); new_downtime(2, "other_host", "other_service", 123456789, 345678921, 0, 1, 42, "", "test_comment"); new_downtime(3, "test_host", "test_service", 234567891, 345678921, 0, 1, 84, "test_author", ""); new_downtime(4, "other_host", "test_service", 123456789, 134567892, 1, 1, 42, "test_author", "test_comment"); new_downtime(5, "out_host", "out_service", 7265943625, 7297479625, 1, 2, 31626500, "out_author", "out_comment"); _dtf.reset(new downtime_finder( downtime_manager::instance().get_scheduled_downtimes())); } void TearDown() override { _dtf.reset(); downtime_manager::instance().clear_scheduled_downtimes(); downtime_manager::instance().initialize_downtime_data(); deinit_config_state(); } /*downtime**/ void new_downtime(uint64_t downtime_id, std::string const& host_name, std::string const& service_description, time_t start, time_t end, int fixed, unsigned long triggered_by, int32_t duration, std::string const& author, std::string const& comment) { downtime_manager::instance().schedule_downtime( downtime::service_downtime, host_name, service_description, start, author.c_str(), comment.c_str(), start, end, fixed, triggered_by, duration, &downtime_id); } protected: std::unique_ptr<downtime_finder> _dtf; downtime* dtl; downtime_finder::criteria_set criterias; downtime_finder::result_set result; downtime_finder::result_set expected; }; // Given a downtime_finder object with a NULL downtime list // When find_matching_all() is called // Then an empty result_set is returned TEST_F(DowntimeFinderFindMatchingAllTest, NullDowntimeList) { std::multimap<time_t, std::shared_ptr<downtime>> map; downtime_finder local_dtf(map); criterias.push_back(downtime_finder::criteria("host", "test_host")); result = local_dtf.find_matching_all(criterias); ASSERT_TRUE(result.empty()); } // Given a downtime_finder object with the test downtime list // And a downtime of the test list has a null host_name // When find_matching_all() is called with criteria ("host", "anyhost") // Then an empty result_set is returned TEST_F(DowntimeFinderFindMatchingAllTest, NullHostNotFound) { criterias.push_back(downtime_finder::criteria("host", "anyhost")); result = _dtf->find_matching_all(criterias); ASSERT_TRUE(result.empty()); } // Given a downtime finder object with the test downtime list // And a downtime of the test list has a null service_description // When find_matching_all() is called with criteria ("service", "anyservice") // Then an empty result_set is returned TEST_F(DowntimeFinderFindMatchingAllTest, NullServiceNotFound) { criterias.push_back(downtime_finder::criteria("service", "anyservice")); result = _dtf->find_matching_all(criterias); ASSERT_TRUE(result.empty()); } // Given a downtime finder object with the test downtime list // And a downtime the test list has a null service_description // When find_matching_all() is called with the criteria ("service", "") // Then the result_set contains the downtime TEST_F(DowntimeFinderFindMatchingAllTest, NullServiceFound) { criterias.push_back(downtime_finder::criteria("service", "")); result = _dtf->find_matching_all(criterias); ASSERT_TRUE(result.empty()); } // Given a downtime_finder object with the test downtime list // And a downtime of the test list has a null author // When find_matching_all() is called with the criteria ("author", "anyauthor") // Then an empty result_set is returned TEST_F(DowntimeFinderFindMatchingAllTest, NullAuthorNotFound) { criterias.push_back(downtime_finder::criteria("author", "anyauthor")); result = _dtf->find_matching_all(criterias); ASSERT_TRUE(result.empty()); } // Given a downtime_finder object with the test downtime list // And a downtime of the test list has a null author // When find_matching_all() is called with the criteria ("author", "") // Then the result_set contains the downtime TEST_F(DowntimeFinderFindMatchingAllTest, NullAuthorFound) { criterias.push_back(downtime_finder::criteria("author", "")); result = _dtf->find_matching_all(criterias); expected.push_back(2); ASSERT_EQ(result, expected); } // Given a downtime_finder object with the test downtime list // And a downtime of the test list has a null comment // When find_matching_all() is called with the criteria ("comment", // "anycomment") Then an empty result_set is returned TEST_F(DowntimeFinderFindMatchingAllTest, NullCommentNotFound) { criterias.push_back(downtime_finder::criteria("comment", "anycomment")); result = _dtf->find_matching_all(criterias); ASSERT_TRUE(result.empty()); } // Given a downtime_finder object with the test downtime list // And a downtime of the test list has a null comment // When find_matching_all() is called with the criteria ("comment", "") // Then the result_set contains the downtime TEST_F(DowntimeFinderFindMatchingAllTest, NullCommentFound) { criterias.push_back(downtime_finder::criteria("comment", "")); result = _dtf->find_matching_all(criterias); expected.push_back(3); ASSERT_EQ(result, expected); } // Given a downtime_finder object with the test downtime list // When find_matching_all() is called with the criteria ("host", "test_host") // Then all downtimes of host /test_host/ are returned TEST_F(DowntimeFinderFindMatchingAllTest, MultipleHosts) { criterias.push_back(downtime_finder::criteria("host", "test_host")); result = _dtf->find_matching_all(criterias); expected.push_back(3); ASSERT_EQ(result, expected); } // Given a downtime_finder object with the test downtime list // When find_matching_all() is called with the criteria ("service", // "test_service") Then all downtimes of service /test_service/ are returned TEST_F(DowntimeFinderFindMatchingAllTest, MultipleServices) { criterias.push_back(downtime_finder::criteria("service", "test_service")); result = _dtf->find_matching_all(criterias); expected.push_back(1); expected.push_back(4); expected.push_back(3); ASSERT_EQ(result, expected); } // Given a downtime_finder object with the test downtime list // When find_matching_all() is called with the criteria ("start", "123456789") // Then all downtimes with 123456789 as start time are returned TEST_F(DowntimeFinderFindMatchingAllTest, MultipleStart) { criterias.push_back(downtime_finder::criteria("start", "123456789")); result = _dtf->find_matching_all(criterias); expected.push_back(1); expected.push_back(2); expected.push_back(4); ASSERT_EQ(result, expected); } // Given a downtime_finder object with the test downtime list // When find_matching_all() is called with the criteria ("end", "134567892") // Then all downtimes with 134567892 as end time are returned TEST_F(DowntimeFinderFindMatchingAllTest, MultipleEnd) { criterias.push_back(downtime_finder::criteria("end", "134567892")); result = _dtf->find_matching_all(criterias); expected.push_back(1); expected.push_back(4); ASSERT_EQ(result, expected); } // Given a downtime_finder object with the test downtime list // When find_matching_all() is called with the criteria ("fixed", "0") // Then all downtimes that are not fixed are returned TEST_F(DowntimeFinderFindMatchingAllTest, MultipleFixed) { criterias.push_back(downtime_finder::criteria("fixed", "0")); result = _dtf->find_matching_all(criterias); expected.push_back(2); expected.push_back(3); ASSERT_EQ(result, expected); } // Given a downtime_finder object with the test downtime list // When find_matching_all() is called with the criteria ("triggered_by", "0") // Then all downtimes that are not triggered by other downtimes are returned TEST_F(DowntimeFinderFindMatchingAllTest, MultipleTriggeredBy) { criterias.push_back(downtime_finder::criteria("triggered_by", "0")); result = _dtf->find_matching_all(criterias); expected.push_back(1); ASSERT_EQ(result, expected); } // Given a downtime_finder object with the test downtime list // When find_matching_all() is called with the criteria ("duration", "42") // Then all downtimes with a duration of 42 seconds are returned TEST_F(DowntimeFinderFindMatchingAllTest, MultipleDuration) { criterias.push_back(downtime_finder::criteria("duration", "42")); result = _dtf->find_matching_all(criterias); expected.push_back(1); expected.push_back(2); expected.push_back(4); ASSERT_EQ(result, expected); } // Given a downtime_finder object with the test downtime list // When find_matching_all() is called with the criteria ("author", // "test_author") Then all downtimes from author /test_author/ are returned TEST_F(DowntimeFinderFindMatchingAllTest, MultipleAuthor) { criterias.push_back(downtime_finder::criteria("author", "test_author")); result = _dtf->find_matching_all(criterias); expected.push_back(1); expected.push_back(4); expected.push_back(3); ASSERT_EQ(result, expected); } // Given a downtime_finder object with the test downtime list // When find_matching_all() is called with the criteria ("comment", // "test_comment") Then all downtimes with comment "test_comment" are returned TEST_F(DowntimeFinderFindMatchingAllTest, MultipleComment) { criterias.push_back(downtime_finder::criteria("comment", "test_comment")); result = _dtf->find_matching_all(criterias); expected.push_back(2); expected.push_back(4); ASSERT_EQ(result, expected); } // Given a downtime_finder object with the test downtime list // When findMatchinAll() is called with criterias ("author", "test_author"), // ("duration", "42") and ("comment", "test_comment") Then all downtimes // matching the criterias are returned TEST_F(DowntimeFinderFindMatchingAllTest, MultipleCriterias) { criterias.push_back(downtime_finder::criteria("author", "test_author")); criterias.push_back(downtime_finder::criteria("duration", "42")); criterias.push_back(downtime_finder::criteria("comment", "test_comment")); result = _dtf->find_matching_all(criterias); expected.push_back(4); ASSERT_EQ(result, expected); } // Given a downtime_finder object with the test downtime list // When find_matching_all() is called with the criteria ("end", "4102441200") // Then all downtimes with 4102441200 as end time are returned TEST_F(DowntimeFinderFindMatchingAllTest, OutOfRangeEnd) { criterias.push_back(downtime_finder::criteria("end", "4102441200")); result = _dtf->find_matching_all(criterias); expected.push_back(5); ASSERT_EQ(result, expected); } // Given a downtime_finder object with the test downtime list // When find_matching_all() is called with the criteria ("start", "4102441200") // Then all downtimes with 4102441200 as end time are returned TEST_F(DowntimeFinderFindMatchingAllTest, OutOfRangeStart) { criterias.push_back(downtime_finder::criteria("start", "4102441200")); result = _dtf->find_matching_all(criterias); expected.push_back(5); ASSERT_EQ(result, expected); } // Given a downtime_finder object with the test downtime list // When find_matching_all() is called with the criteria ("duration", // "4102441200") Then all downtimes with 31622400 as end time are returned TEST_F(DowntimeFinderFindMatchingAllTest, OutOfRangeDuration) { criterias.push_back(downtime_finder::criteria("duration", "31622400")); result = _dtf->find_matching_all(criterias); expected.push_back(5); ASSERT_EQ(result, expected); }
42.56869
80
0.740693
[ "object" ]
57fc6e5aca84bb301130b6737765729b59766a42
3,382
hpp
C++
core/include/ast.hpp
BaronKhan/gitgudcommit
cfc5f20339c61f3928871bea375608f7eefb8138
[ "MIT" ]
1
2021-02-22T15:06:39.000Z
2021-02-22T15:06:39.000Z
core/include/ast.hpp
BaronKhan/gitgudcommit
cfc5f20339c61f3928871bea375608f7eefb8138
[ "MIT" ]
null
null
null
core/include/ast.hpp
BaronKhan/gitgudcommit
cfc5f20339c61f3928871bea375608f7eefb8138
[ "MIT" ]
1
2021-02-22T15:06:41.000Z
2021-02-22T15:06:41.000Z
#ifndef AST_HPP_ #define AST_HPP_ #include <string> #include <vector> #include <utility> namespace GitGud { class MessageNode; enum NodeType { SUMMARY, BLANK, BODY, POINT }; // Stores the internal representation of a commit message as a vector of nodes class Ast { private: std::vector<MessageNode*> m_nodes; std::vector<std::pair<unsigned, std::string>> m_suggestions; std::vector<std::string> m_suggestions_full; double m_score; void parseMessage(const std::string &message); void calculateCommitScore(); public: static void addFilename(const std::string & filename); static void resetFilenames(); static std::vector<std::string> split(const std::string &s, char delim); static std::string ltrim(const std::string& s); static std::string rtrim(const std::string& s); static std::string trim(const std::string& s); Ast(const std::string &message); std::vector<MessageNode*> & getNodes(); std::vector<std::pair<unsigned, std::string>> & getSuggestions(); std::vector<std::string> getSuggestionsFull(); double getCommitScore(); void addSuggestion(unsigned line_number, const std::string & suggestion); ~Ast(); }; ////////////////////////////////////////////////////////////////////////////// class MessageNode { private: Ast * m_owner; public: MessageNode(Ast *owner); virtual const std::string & getData() = 0; virtual double getScore() const = 0; virtual NodeType getType() const = 0; void addSuggestion(unsigned line_number, const std::string & suggestion) const; bool wordIsFilename(const std::string & word) const; void checkSentence(double & score, const std::string & sentence, unsigned line_number, bool limit_words=false) const; virtual ~MessageNode() {} }; ////////////////////////////////////////////////////////////////////////////// class SummaryNode : public MessageNode { private: std::string m_summary; public: SummaryNode(Ast *owner, const std::string &title); virtual const std::string & getData(); virtual double getScore() const; virtual NodeType getType() const; }; ////////////////////////////////////////////////////////////////////////////// class BlankNode : public MessageNode { private: unsigned m_line_number; std::string m_blank; public: BlankNode(Ast *owner, unsigned line_number); virtual const std::string & getData(); virtual double getScore() const; virtual NodeType getType() const; }; ////////////////////////////////////////////////////////////////////////////// class BodyNode : public MessageNode { private: unsigned m_line_number; std::string m_line; public: BodyNode(Ast *owner, unsigned line_number, const std::string &line); virtual const std::string & getData(); virtual double getScore() const; virtual NodeType getType() const; }; ////////////////////////////////////////////////////////////////////////////// class PointNode : public MessageNode { private: unsigned m_line_number; std::string m_point; public: PointNode(Ast *owner, unsigned line_number, const std::string &point); virtual const std::string & getData(); virtual double getScore() const; virtual NodeType getType() const; }; } #endif
24.686131
83
0.596393
[ "vector" ]
57ff95cd409ca05f325be1992ec737ece954448f
14,406
cpp
C++
src/asiAlgo/interop/asiAlgo_ReadSTEPWithMeta.cpp
sasobadovinac/AnalysisSitus
304d39c64258d4fcca888eb8e68144eca50e785a
[ "BSD-3-Clause" ]
3
2021-11-04T01:36:56.000Z
2022-03-10T07:11:01.000Z
src/asiAlgo/interop/asiAlgo_ReadSTEPWithMeta.cpp
sasobadovinac/AnalysisSitus
304d39c64258d4fcca888eb8e68144eca50e785a
[ "BSD-3-Clause" ]
null
null
null
src/asiAlgo/interop/asiAlgo_ReadSTEPWithMeta.cpp
sasobadovinac/AnalysisSitus
304d39c64258d4fcca888eb8e68144eca50e785a
[ "BSD-3-Clause" ]
1
2021-09-25T18:14:30.000Z
2021-09-25T18:14:30.000Z
//----------------------------------------------------------------------------- // Created on: 02 June 2019 //----------------------------------------------------------------------------- // Copyright (c) 2019-present, Sergey Slyadnev // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the copyright holder(s) nor the // names of all contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- // Own include #include <asiAlgo_ReadSTEPWithMeta.h> // OpenCascade includes #include <Interface_EntityIterator.hxx> #include <Interface_Graph.hxx> #include <STEPControl_Controller.hxx> #include <STEPConstruct.hxx> #include <STEPConstruct_Styles.hxx> #include <StepRepr_NextAssemblyUsageOccurrence.hxx> #include <StepRepr_ProductDefinitionShape.hxx> #include <StepRepr_RepresentedDefinition.hxx> #include <StepRepr_SpecifiedHigherUsageOccurrence.hxx> #include <StepShape_ShapeDefinitionRepresentation.hxx> #include <StepShape_ShapeRepresentation.hxx> #include <StepVisual_PresentationStyleByContext.hxx> #include <StepVisual_StyledItem.hxx> #include <TopoDS_Iterator.hxx> #include <Transfer_TransientProcess.hxx> #include <TransferBRep.hxx> #include <XSControl_TransferReader.hxx> #include <XSControl_WorkSession.hxx> //----------------------------------------------------------------------------- asiAlgo_ReadSTEPWithMeta::asiAlgo_ReadSTEPWithMeta(ActAPI_ProgressEntry progress, ActAPI_PlotterEntry plotter) : ActAPI_IAlgorithm (progress, plotter), m_bColorMode (true) { STEPControl_Controller::Init(); } //----------------------------------------------------------------------------- asiAlgo_ReadSTEPWithMeta::asiAlgo_ReadSTEPWithMeta(const Handle(XSControl_WorkSession)& WS, const bool scratch, ActAPI_ProgressEntry progress, ActAPI_PlotterEntry plotter) : ActAPI_IAlgorithm (progress, plotter), m_bColorMode (true) { STEPControl_Controller::Init(); this->Init(WS, scratch); } //----------------------------------------------------------------------------- void asiAlgo_ReadSTEPWithMeta::Init(const Handle(XSControl_WorkSession)& WS, const bool scratch) { m_reader.SetWS(WS, scratch); } //----------------------------------------------------------------------------- IFSelect_ReturnStatus asiAlgo_ReadSTEPWithMeta::ReadFile(const char* filename) { return m_reader.ReadFile(filename); } //----------------------------------------------------------------------------- int asiAlgo_ReadSTEPWithMeta::GetNbRootsForTransfer() { return m_reader.NbRootsForTransfer(); } //----------------------------------------------------------------------------- bool asiAlgo_ReadSTEPWithMeta::TransferOneRoot(const int num) { TDF_LabelSequence Lseq; return this->transfer(m_reader, num); } //----------------------------------------------------------------------------- bool asiAlgo_ReadSTEPWithMeta::Transfer() { TDF_LabelSequence Lseq; return this->transfer(m_reader, 0); } //----------------------------------------------------------------------------- bool asiAlgo_ReadSTEPWithMeta::Perform(const char* filename) { if ( this->ReadFile(filename) != IFSelect_RetDone ) return false; return this->Transfer(); } //----------------------------------------------------------------------------- bool asiAlgo_ReadSTEPWithMeta::Perform(const TCollection_AsciiString& filename) { if ( this->ReadFile( filename.ToCString() ) != IFSelect_RetDone ) return false; return this->Transfer(); } //----------------------------------------------------------------------------- STEPControl_Reader& asiAlgo_ReadSTEPWithMeta::ChangeReader() { return m_reader; } //----------------------------------------------------------------------------- const STEPControl_Reader& asiAlgo_ReadSTEPWithMeta::GetReader() const { return m_reader; } //----------------------------------------------------------------------------- void asiAlgo_ReadSTEPWithMeta::SetColorMode(const bool colormode) { m_bColorMode = colormode; } //----------------------------------------------------------------------------- bool asiAlgo_ReadSTEPWithMeta::GetColorMode() const { return m_bColorMode; } //----------------------------------------------------------------------------- static void FillShapesMap(const TopoDS_Shape& S, TopTools_MapOfShape& map) { TopoDS_Shape S0 = S; TopLoc_Location loc; S0.Location(loc); map.Add(S0); if ( S.ShapeType() != TopAbs_COMPOUND ) return; for ( TopoDS_Iterator it(S); it.More(); it.Next() ) FillShapesMap(it.Value(), map); } //----------------------------------------------------------------------------- bool asiAlgo_ReadSTEPWithMeta::transfer(STEPControl_Reader& reader, const int nroot, const bool asOne) { reader.ClearShapes(); int i; // Read all shapes int num = reader.NbRootsForTransfer(); if (num <= 0) return false; if (nroot) { if (nroot > num) return false; reader.TransferOneRoot(nroot); } else { for (i = 1; i <= num; i++) reader.TransferOneRoot(i); } num = reader.NbShapes(); if (num <= 0) return false; // Fill a map of (top-level) shapes resulting from that transfer // Only these shapes will be considered further TopTools_MapOfShape ShapesMap, NewShapesMap; for (i = 1; i <= num; i++) FillShapesMap(reader.Shape(i), ShapesMap); // Collect information on shapes originating from SDRs // this will be used to distinguish compounds representing assemblies // from the ones representing hybrid models and shape sets STEPCAFControl_DataMapOfShapePD ShapePDMap; STEPCAFControl_DataMapOfPDExternFile PDFileMap; Handle(Interface_InterfaceModel) Model = reader.Model(); const Handle(Transfer_TransientProcess) &TP = reader.WS()->TransferReader()->TransientProcess(); int nb = Model->NbEntities(); Handle(TColStd_HSequenceOfTransient) SeqPDS = new TColStd_HSequenceOfTransient; for (i = 1; i <= nb; i++) { Handle(Standard_Transient) enti = Model->Value(i); if (enti->IsKind(STANDARD_TYPE(StepRepr_ProductDefinitionShape))) { // sequence for acceleration ReadMaterials SeqPDS->Append(enti); } if (enti->IsKind(STANDARD_TYPE(StepBasic_ProductDefinition))) { Handle(StepBasic_ProductDefinition) PD = Handle(StepBasic_ProductDefinition)::DownCast(enti); int index = TP->MapIndex(PD); if (index > 0) { Handle(Transfer_Binder) binder = TP->MapItem(index); TopoDS_Shape S = TransferBRep::ShapeResult(binder); if (!S.IsNull() && ShapesMap.Contains(S)) { NewShapesMap.Add(S); ShapePDMap.Bind(S, PD); //Handle(STEPCAFControl_ExternFile) EF; //PDFileMap.Bind(PD, EF); } } } if (enti->IsKind(STANDARD_TYPE(StepShape_ShapeRepresentation))) { int index = TP->MapIndex(enti); if (index > 0) { Handle(Transfer_Binder) binder = TP->MapItem(index); TopoDS_Shape S = TransferBRep::ShapeResult(binder); if (!S.IsNull() && ShapesMap.Contains(S)) NewShapesMap.Add(S); } } } // Add shape to the document. if ( asOne ) m_output->SetShape( reader.OneShape() ); // Set shape in the output. else { m_progress.SendLogMessage(LogErr(Normal) << "Transferring several shapes into assemblies is not currently supported."); return false; } // Read colors. if ( m_bColorMode ) this->readColors( reader.WS() ); return true; } //----------------------------------------------------------------------------- static void findStyledSR(const Handle(StepVisual_StyledItem)& style, Handle(StepShape_ShapeRepresentation)& aSR) { // search Shape Represenatation for component styled item for (int j = 1; j <= style->NbStyles(); j++) { Handle(StepVisual_PresentationStyleByContext) PSA = Handle(StepVisual_PresentationStyleByContext)::DownCast(style->StylesValue(j)); if (PSA.IsNull()) continue; StepVisual_StyleContextSelect aStyleCntxSlct = PSA->StyleContext(); Handle(StepShape_ShapeRepresentation) aCurrentSR = Handle(StepShape_ShapeRepresentation)::DownCast(aStyleCntxSlct.Representation()); if (aCurrentSR.IsNull()) continue; aSR = aCurrentSR; break; } } //----------------------------------------------------------------------------- bool asiAlgo_ReadSTEPWithMeta::readColors(const Handle(XSControl_WorkSession)& WS) const { STEPConstruct_Styles Styles(WS); if ( !Styles.LoadStyles() ) { m_progress.SendLogMessage(LogNotice(Normal) << "No styles are found in the model."); return false; } // searching for invisible items in the model Handle(TColStd_HSequenceOfTransient) aHSeqOfInvisStyle = new TColStd_HSequenceOfTransient; Styles.LoadInvisStyles(aHSeqOfInvisStyle); // parse and search for color attributes int nb = Styles.NbStyles(); for (int i = 1; i <= nb; i++) { Handle(StepVisual_StyledItem) style = Styles.Style(i); if (style.IsNull()) continue; bool IsVisible = true; // check the visibility of styled item. for (int si = 1; si <= aHSeqOfInvisStyle->Length(); si++) { if (style != aHSeqOfInvisStyle->Value(si)) continue; // found that current style is invisible. IsVisible = false; break; } Handle(StepVisual_Colour) SurfCol, BoundCol, CurveCol; // check if it is component style bool IsComponent = false; if (!Styles.GetColors(style, SurfCol, BoundCol, CurveCol, IsComponent) && IsVisible) continue; // find shape NCollection_Vector<Handle(Standard_Transient)> anItems; if (!style->Item().IsNull()) { anItems.Append(style->Item()); } else if (!style->ItemAP242().Representation().IsNull()) { //special case for AP242: item can be Reprsentation Handle(StepRepr_Representation) aRepr = style->ItemAP242().Representation(); for (int j = 1; j <= aRepr->Items()->Length(); j++) anItems.Append(aRepr->Items()->Value(j)); } for (int itemIt = 0; itemIt < anItems.Length(); itemIt++) { TopoDS_Shape S = STEPConstruct::FindShape(Styles.TransientProcess(), Handle(StepRepr_RepresentationItem)::DownCast(anItems.Value(itemIt))); bool isSkipSHUOstyle = false; // take shape with real location. while (IsComponent) { // take SR of NAUO Handle(StepShape_ShapeRepresentation) aSR; findStyledSR(style, aSR); // search for SR along model if (aSR.IsNull()) break; Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings(aSR); Handle(StepShape_ShapeDefinitionRepresentation) aSDR; for (subs.Start(); subs.More(); subs.Next()) { aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value()); if (aSDR.IsNull()) continue; StepRepr_RepresentedDefinition aPDSselect = aSDR->Definition(); Handle(StepRepr_ProductDefinitionShape) PDS = Handle(StepRepr_ProductDefinitionShape)::DownCast(aPDSselect.PropertyDefinition()); if (PDS.IsNull()) continue; StepRepr_CharacterizedDefinition aCharDef = PDS->Definition(); Handle(StepRepr_AssemblyComponentUsage) ACU = Handle(StepRepr_AssemblyComponentUsage)::DownCast(aCharDef.ProductDefinitionRelationship()); if (ACU.IsNull()) continue; // PTV 10.02.2003 skip styled item that refer to SHUO if (ACU->IsKind(STANDARD_TYPE(StepRepr_SpecifiedHigherUsageOccurrence))) { isSkipSHUOstyle = true; break; } Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO = Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(ACU); if (NAUO.IsNull()) continue; } break; } if (isSkipSHUOstyle) continue; // skip styled item which refer to SHUO if (S.IsNull()) continue; if (!SurfCol.IsNull() || !BoundCol.IsNull() || !CurveCol.IsNull()) { Quantity_Color aSCol, aBCol, aCCol; if ( !SurfCol.IsNull() ) { Styles.DecodeColor(SurfCol, aSCol); // m_output->SetColor(S, aSCol); } if ( !BoundCol.IsNull() ) { Styles.DecodeColor(BoundCol, aBCol); // m_output->SetColor(S, aBCol); } if ( !CurveCol.IsNull() ) { Styles.DecodeColor(CurveCol, aCCol); // m_output->SetColor(S, aBCol); } } } } return true; }
35.482759
123
0.597806
[ "shape", "model" ]
648e2aa551a4fdb97ff2a2e9aaeecb59554ccbfe
1,763
hh
C++
isaac_variant_caller/src/lib/blt_util/vcf_record.hh
sequencing/isaac_variant_caller
ed24e20b097ee04629f61014d3b81a6ea902c66b
[ "BSL-1.0" ]
21
2015-01-09T01:11:28.000Z
2019-09-04T03:48:21.000Z
isaac_variant_caller/src/lib/blt_util/vcf_record.hh
sequencing/isaac_variant_caller
ed24e20b097ee04629f61014d3b81a6ea902c66b
[ "BSL-1.0" ]
4
2015-07-23T09:38:39.000Z
2018-02-01T05:37:26.000Z
isaac_variant_caller/src/lib/blt_util/vcf_record.hh
sequencing/isaac_variant_caller
ed24e20b097ee04629f61014d3b81a6ea902c66b
[ "BSL-1.0" ]
13
2015-01-29T16:41:26.000Z
2021-06-25T02:42:32.000Z
// -*- mode: c++; indent-tabs-mode: nil; -*- // // Copyright (c) 2009-2013 Illumina, Inc. // // This software is provided under the terms and conditions of the // Illumina Open Source Software License 1. // // You should have received a copy of the Illumina Open Source // Software License 1 along with this program. If not, see // <https://github.com/sequencing/licenses/> // /// \file /// \author Chris Saunders /// #pragma once #include "blt_util/seq_util.hh" #include "boost/foreach.hpp" #include <iosfwd> #include <string> #include <vector> struct vcf_record { vcf_record() : pos(0) { clear(); } // set record from record string s, return false on error bool set(const char* s); void clear() { chrom=""; pos=0; ref=""; alt.clear(); } bool is_valid() const { if (! is_valid_seq(ref.c_str())) return false; BOOST_FOREACH(const std::string& alt_allele, alt) { if (! is_valid_seq(alt_allele.c_str())) return false; } return true; } bool is_indel() const { if (! is_valid()) return false; if ((ref.size()>1) && (alt.size()>0)) return true; BOOST_FOREACH(const std::string& alt_allele, alt) { if (alt_allele.size()>1) return true; } return false; } bool is_snv() const { if (! is_valid()) return false; if (1 != ref.size()) return false; BOOST_FOREACH(const std::string& alt_allele, alt) { if (1 != alt_allele.size()) return false; } return true; } std::string chrom; int pos; std::string ref; std::vector<std::string> alt; }; std::ostream& operator<<(std::ostream& os, const vcf_record& vcfr);
22.0375
67
0.583097
[ "vector" ]
64a302a6847209fc64ccf1d89185883818f3677b
2,778
cc
C++
tests/plm_test.cc
dlekkas/comm_detect
65a4acc49668d7973104129c39b1eb5dc6445145
[ "Apache-2.0" ]
null
null
null
tests/plm_test.cc
dlekkas/comm_detect
65a4acc49668d7973104129c39b1eb5dc6445145
[ "Apache-2.0" ]
1
2020-11-30T06:24:43.000Z
2020-11-30T06:24:43.000Z
tests/plm_test.cc
dlekkas/comm_detect
65a4acc49668d7973104129c39b1eb5dc6445145
[ "Apache-2.0" ]
1
2020-05-17T11:55:12.000Z
2020-05-17T11:55:12.000Z
#include "../include/graph.h" #include "../include/plm.h" #include "../include/modularity.h" #include <vector> #include <sys/time.h> #include <omp.h> #include <chrono> #include <math.h> int main(int argc, char* argv[]) { if (argc != 2) { std::cerr << "Usage: " << argv[0] << " <input-file>" << std::endl; std::exit(1); } std::string file_name = argv[1]; int threads = omp_get_max_threads(); #pragma omp parallel num_threads(threads) { /* Obtain thread number */ int tid = omp_get_thread_num(); if (tid == 0) { std::cout << "algo: PLM, threads: " << omp_get_num_threads() << ", "; } } /* initialize graph based on file and confirm correct parsing */ GraphComm test_g; //test_g.PrintNetwork(); auto start = std::chrono::system_clock::now(); test_g.Net_init(file_name); auto end = std::chrono::system_clock::now(); auto total_time = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count(); cout << "Read file succesfully after " << total_time / 1000.0 << "s" << std::endl; /* detect communities of graph */ PLM test_plm {&test_g }; /* benchmark time of community detection */ start = std::chrono::system_clock::now(); test_plm.DetectCommunities(); end = std::chrono::system_clock::now(); total_time = std::chrono::duration_cast< std::chrono::milliseconds>(end - start).count(); std::cout << "time (in sec): " << total_time / 1000.0 << endl; // Modularity! // /*int comms = *max_element(std::begin(test_plm.graph->communities), std::end(test_plm.graph->communities)) + 1; std::vector<int> w(comms, 0); std::vector<int> v(comms, 0); for (int i=0; i<test_plm.graph->n; i++) { int c_u = test_plm.graph->communities[i]; v[c_u] += test_plm.graph->volumes[i]; vector<pair<node_id, weight>> neighbors = test_plm.graph->net[i]; for (auto it=neighbors.begin(); it<neighbors.end(); ++it) { int c_j = test_plm.graph->communities[it->first]; if (c_u == c_j) w[c_u] += it->second; } } cout << "comm size: " << comms << endl; cout << "network weight: " << test_plm.graph->weight_net << endl; test_plm.graph->weight_sq = pow(test_plm.graph->weight_net, 2); float mod=0.0; for (int i=0; i<(int) comms; i++) { float a = (float) w[i] / test_plm.graph->weight_net; float b = (float) (v[i] * v[i]) / test_plm.graph->weight_sq; float mod_comm = a - b; mod += mod_comm; } //mod = compute_modularity(cs, &test_g); cout << "modularity: " << mod << endl;*/ return 0; }
30.195652
112
0.565875
[ "vector" ]
64a40fe6404b1cbb576d6a84685bcc31ba884954
6,254
hpp
C++
Phoenix/Client/Include/Client/Graphics/ShaderPipeline.hpp
NicolasRicard/Phoenix
5eae2bd716a933fd405487d93c0e91e5ca56b3e4
[ "BSD-3-Clause" ]
1
2020-05-02T14:46:39.000Z
2020-05-02T14:46:39.000Z
Phoenix/Client/Include/Client/Graphics/ShaderPipeline.hpp
NicolasRicard/Phoenix
5eae2bd716a933fd405487d93c0e91e5ca56b3e4
[ "BSD-3-Clause" ]
null
null
null
Phoenix/Client/Include/Client/Graphics/ShaderPipeline.hpp
NicolasRicard/Phoenix
5eae2bd716a933fd405487d93c0e91e5ca56b3e4
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019-20 Genten Studios // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. /** * @file ShaderPipeline.hpp * @brief The rendering pipeline paired with shaders. * * @copyright Copyright (c) 2019-20 Genten Studios */ #pragma once #include <Common/Math/Math.hpp> #include <string> #include <vector> namespace phx::gfx { /** * @brief The layout for shader vertex locations. * * A shader has a layout in which vertices and data in general is sent * to it in, this makes sure that all renderer objects can specify * their own layout to allow better compatibility. * * @paragraph Usage * @code * std::vector<ShaderLayout> attributes; * attributes.emplace_back("a_Vertex", 0); * attributes.emplace_back("a_UV", 1); * * ShaderPipeline pipeline; * pipeline.prepare("myvert.shader", "myfrag.shader", attributes); * @endcode */ struct ShaderLayout { ShaderLayout(const std::string& attribName, int desiredIndex) : attribName(attribName), desiredIndex(desiredIndex) { } std::string attribName; int desiredIndex = -1; }; /** * @brief The Pipeline through which basic rendering occurs. * * This class provides the ability to use shaders while rendering - and * you need shaders to render anything more than a triangle so this is a * necessity. Shaders must be written with ambiguous location parameters * on inputs but will be set through this class, to allow for maximum * compatibility. * * The activate method must be called before rendering the system * associated with this pipeline, otherwise you may render without or * with the wrong shaders. * * The set* methods are to set uniform data, for example the MVP * matrices from the camera. * * @paragraph Usage * @code * // using the chunk renderer as an example. * ShaderPipeline pipeline; * pipeline.prepare("myvert.shader", "myfrag.shader", * ChunkRenderer::getRequiredShaderLayout()); * * mainGameLoop() * { * // individually activate since we have another shader that could be * active. pipeline.activate(); pipeline.setMatrix(myViewMatrix); * pipeline.setMatrix(myProjectionMatrix); * world.render(); * * // lets say we made this for a ui element * pipeline2.activate(); * ui.render(); * } * @endcode */ class ShaderPipeline { public: ShaderPipeline() = default; ~ShaderPipeline() = default; /** * @brief Prepares a pipeline with the provided shaders and layout. * @param vertShaderPath Path to vertex shader. * @param fragShaderPath Path to fragment/pixel shader. * @param layout The required layout for the shaders to adhere to. */ void prepare(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::vector<ShaderLayout>& layout); /** * @brief Activates the pipeline, prepared shaders are activated. * * This must be called before calling the render method for * associated objects, otherwise you may render with the wrong * shader, or just without an active shader. If you don't plan on * changing shaders at any point, this can be called once beforehand * and never again. */ void activate(); /** * @brief Sets a uniform location to a float. * @param location The location being set. * @param value The value to set provided location. */ void setFloat(const std::string& location, float value); /** * @brief Sets a uniform location to a 2 component vector. * @param location The location being set. * @param value The value to set provided location. */ void setVector2(const std::string& location, math::vec2 value); /** * @brief Sets a uniform location to a 3 component vector. * @param location The unique identifier for the uniform. * @param value The value to set provided location. * * The uniform location being set must be equivalent to the name * provided to identify data specific to this type in the shaders * themselves. */ void setVector3(const std::string& location, math::vec3 value); /** * @brief Sets a uniform location to a 4x4 matrix. * @param location The location being set. * @param value The value to set provided location. * * The uniform location being set must be equivalent to the name * provided to identify data specific to this type in the shaders * themselves. */ void setMatrix(const std::string& location, math::mat4 value); /** * @brief Queries the location set for a specific attribute. * @param attr The layout/attribute name provided in the shader. * @return The set location for the attribute. */ int queryLayoutOfAttribute(const std::string& attr); private: unsigned int m_program; }; } // namespace phx::gfx
33.98913
80
0.713303
[ "render", "vector" ]
64a6c6b185c988a4ae17c58603da8e9f1c76a00c
7,204
cc
C++
GeneratorInterface/Pythia8Interface/src/Py8InterfaceBase.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
GeneratorInterface/Pythia8Interface/src/Py8InterfaceBase.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
GeneratorInterface/Pythia8Interface/src/Py8InterfaceBase.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
#include "GeneratorInterface/Pythia8Interface/interface/Py8InterfaceBase.h" #include "FWCore/Utilities/interface/Exception.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" // EvtGen plugin // //#include "Pythia8Plugins/EvtGen.h" using namespace Pythia8; namespace gen { Py8InterfaceBase::Py8InterfaceBase( edm::ParameterSet const& ps ) : BaseHadronizer(ps), useEvtGen(false), evtgenDecays(0) { fParameters = ps; pythiaPylistVerbosity = ps.getUntrackedParameter<int>("pythiaPylistVerbosity", 0); pythiaHepMCVerbosity = ps.getUntrackedParameter<bool>("pythiaHepMCVerbosity", false); pythiaHepMCVerbosityParticles = ps.getUntrackedParameter<bool>("pythiaHepMCVerbosityParticles", false); maxEventsToPrint = ps.getUntrackedParameter<int>("maxEventsToPrint", 0); if(pythiaHepMCVerbosityParticles) ascii_io = new HepMC::IO_AsciiParticles("cout", std::ios::out); if ( ps.exists("useEvtGenPlugin") ) { useEvtGen = true; string evtgenpath(getenv("EVTGENDATA")); evtgenDecFile = evtgenpath + string("/DECAY_2010.DEC"); evtgenPdlFile = evtgenpath + string("/evt.pdl"); if ( ps.exists( "evtgenDecFile" ) ) evtgenDecFile = ps.getParameter<string>("evtgenDecFile"); if ( ps.exists( "evtgenPdlFile" ) ) evtgenPdlFile = ps.getParameter<string>("evtgenPdlFile"); if ( ps.exists( "evtgenUserFile" ) ) evtgenUserFiles = ps.getParameter< std::vector<std::string> >("evtgenUserFile"); } } bool Py8InterfaceBase::readSettings( int ) { fMasterGen.reset(new Pythia); fDecayer.reset(new Pythia); //add settings for resonance decay filter fMasterGen->settings.addFlag("ResonanceDecayFilter:filter",false); fMasterGen->settings.addFlag("ResonanceDecayFilter:exclusive",false); fMasterGen->settings.addFlag("ResonanceDecayFilter:eMuAsEquivalent",false); fMasterGen->settings.addFlag("ResonanceDecayFilter:eMuTauAsEquivalent",false); fMasterGen->settings.addFlag("ResonanceDecayFilter:allNuAsEquivalent",false); fMasterGen->settings.addFlag("ResonanceDecayFilter:udscAsEquivalent",false); fMasterGen->settings.addFlag("ResonanceDecayFilter:udscbAsEquivalent",false); fMasterGen->settings.addMVec("ResonanceDecayFilter:mothers",std::vector<int>(),false,false,0,0); fMasterGen->settings.addMVec("ResonanceDecayFilter:daughters",std::vector<int>(),false,false,0,0); //add settings for PT filter fMasterGen->settings.addFlag("PTFilter:filter",false); fMasterGen->settings.addMode("PTFilter:quarkToFilter", 5 ,true,true,3, 6); fMasterGen->settings.addParm("PTFilter:scaleToFilter", 0.4,true,true,0.0, 10.); fMasterGen->settings.addParm("PTFilter:quarkRapidity",10.0,true,true,0.0, 10.); fMasterGen->settings.addParm("PTFilter:quarkPt", -.1,true,true,-.1,100.); //add settings for powheg resonance scale calculation fMasterGen->settings.addFlag("POWHEGres:calcScales",false); fMasterGen->settings.addFlag("POWHEG:bb4l",false); fMasterGen->settings.addFlag("POWHEG:bb4l:onlyDistance1",false); fMasterGen->settings.addFlag("POWHEG:bb4l:useScaleResonanceInstead",false); fMasterGen->setRndmEnginePtr( &p8RndmEngine_ ); fDecayer->setRndmEnginePtr( &p8RndmEngine_ ); fMasterGen->readString("Next:numberShowEvent = 0"); fDecayer->readString("Next:numberShowEvent = 0"); edm::ParameterSet currentParameters; if (randomIndex()>=0) { std::vector<edm::ParameterSet> randomizedParameters = fParameters.getParameter<std::vector<edm::ParameterSet> >("RandomizedParameters"); currentParameters = randomizedParameters[randomIndex()]; } else { currentParameters = fParameters; } ParameterCollector pCollector = currentParameters.getParameter<edm::ParameterSet>("PythiaParameters"); for ( ParameterCollector::const_iterator line = pCollector.begin(); line != pCollector.end(); ++line ) { if (line->find("Random:") != std::string::npos) throw cms::Exception("PythiaError") << "Attempted to set random number " "using Pythia commands. Please use " "the RandomNumberGeneratorService." << std::endl; if (!fMasterGen->readString(*line)) throw cms::Exception("PythiaError") << "Pythia 8 did not accept \"" << *line << "\"." << std::endl; if (line->find("ParticleDecays:") != std::string::npos) { if (!fDecayer->readString(*line)) throw cms::Exception("PythiaError") << "Pythia 8 Decayer did not accept \"" << *line << "\"." << std::endl; } } slhafile_.clear(); if( currentParameters.exists( "SLHAFileForPythia8" ) ) { std::string slhafilenameshort = currentParameters.getParameter<std::string>("SLHAFileForPythia8"); edm::FileInPath f1( slhafilenameshort ); fMasterGen->settings.mode("SLHA:readFrom", 2); fMasterGen->settings.word("SLHA:file", f1.fullPath()); } else if( currentParameters.exists( "SLHATableForPythia8" ) ) { std::string slhatable = currentParameters.getParameter<std::string>("SLHATableForPythia8"); char tempslhaname[] = "pythia8SLHAtableXXXXXX"; int fd = mkstemp(tempslhaname); write(fd,slhatable.c_str(),slhatable.size()); close(fd); slhafile_ = tempslhaname; fMasterGen->settings.mode("SLHA:readFrom", 2); fMasterGen->settings.word("SLHA:file", slhafile_); } return true; } bool Py8InterfaceBase::declareStableParticles( const std::vector<int>& pdgIds ) { for ( size_t i=0; i<pdgIds.size(); i++ ) { // FIXME: need to double check if PID's are the same in Py6 & Py8, // because the HepPDT translation tool is actually for **Py6** // // well, actually it looks like Py8 operates in PDT id's rather than Py6's // // int PyID = HepPID::translatePDTtoPythia( pdgIds[i] ); int PyID = pdgIds[i]; std::ostringstream pyCard ; pyCard << PyID <<":mayDecay=false"; if ( fMasterGen->particleData.isParticle( PyID ) ) { fMasterGen->readString( pyCard.str() ); } else { edm::LogWarning("DataNotUnderstood") << "Pythia8 does not " << "recognize particle id = " << PyID << std::endl; } // alternative: // set the 2nd input argument warn=false // - this way Py8 will NOT print warnings about unknown particle code(s) // fMasterPtr->readString( pyCard.str(), false ) } return true; } bool Py8InterfaceBase:: declareSpecialSettings( const std::vector<std::string>& settings ){ for ( unsigned int iss=0; iss<settings.size(); iss++ ){ if ( settings[iss].find("QED-brem-off") != std::string::npos ){ fMasterGen->readString( "TimeShower:QEDshowerByL=off" ); } else{ size_t fnd1 = settings[iss].find("Pythia8:"); if ( fnd1 != std::string::npos ){ std::string value = settings[iss].substr (fnd1+8); fDecayer->readString(value); } } } return true; } void Py8InterfaceBase::statistics() { fMasterGen->stat(); return; } }
35.487685
141
0.66935
[ "vector" ]
64a7ea843aa0a7764a7c183e29b49cda66d9e32d
1,331
cpp
C++
aws-cpp-sdk-storagegateway/source/model/DescribeNFSFileSharesResult.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-05T18:20:03.000Z
2022-01-05T18:20:03.000Z
aws-cpp-sdk-storagegateway/source/model/DescribeNFSFileSharesResult.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-storagegateway/source/model/DescribeNFSFileSharesResult.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/storagegateway/model/DescribeNFSFileSharesResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::StorageGateway::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; DescribeNFSFileSharesResult::DescribeNFSFileSharesResult() { } DescribeNFSFileSharesResult::DescribeNFSFileSharesResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } DescribeNFSFileSharesResult& DescribeNFSFileSharesResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("NFSFileShareInfoList")) { Array<JsonView> nFSFileShareInfoListJsonList = jsonValue.GetArray("NFSFileShareInfoList"); for(unsigned nFSFileShareInfoListIndex = 0; nFSFileShareInfoListIndex < nFSFileShareInfoListJsonList.GetLength(); ++nFSFileShareInfoListIndex) { m_nFSFileShareInfoList.push_back(nFSFileShareInfoListJsonList[nFSFileShareInfoListIndex].AsObject()); } } return *this; }
30.25
146
0.788881
[ "model" ]
64b5a836a819b87d109ea75d17aa70e6d2e18168
18,292
cpp
C++
libakumuli/queryprocessor.cpp
vladon/Akumuli
c45672a23b929ccb3a5743cc5e9aae980c160eb0
[ "Apache-2.0" ]
null
null
null
libakumuli/queryprocessor.cpp
vladon/Akumuli
c45672a23b929ccb3a5743cc5e9aae980c160eb0
[ "Apache-2.0" ]
null
null
null
libakumuli/queryprocessor.cpp
vladon/Akumuli
c45672a23b929ccb3a5743cc5e9aae980c160eb0
[ "Apache-2.0" ]
1
2021-09-22T07:11:13.000Z
2021-09-22T07:11:13.000Z
/** * Copyright (c) 2015 Eugene Lazin <4lazin@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "queryprocessor.h" #include "util.h" #include "datetime.h" #include "anomalydetector.h" #include "saxencoder.h" #include <random> #include <algorithm> #include <unordered_set> #include <set> #include <boost/lexical_cast.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/exception/diagnostic_information.hpp> // Include query processors #include "query_processing/anomaly.h" #include "query_processing/filterbyid.h" #include "query_processing/paa.h" #include "query_processing/randomsamplingnode.h" #include "query_processing/sax.h" #include "query_processing/spacesaver.h" namespace Akumuli { namespace QP { // // // Factory methods // // // static std::shared_ptr<Node> make_sampler(boost::property_tree::ptree const& ptree, std::shared_ptr<Node> next, aku_logger_cb_t logger) { try { std::string name; name = ptree.get<std::string>("name"); return QP::create_node(name, ptree, next); } catch (const boost::property_tree::ptree_error&) { QueryParserError except("invalid sampler description"); BOOST_THROW_EXCEPTION(except); } } static std::shared_ptr<Node> make_filter_by_id_list(std::vector<aku_ParamId> ids, std::shared_ptr<Node> next, aku_logger_cb_t logger) { struct Matcher { std::unordered_set<aku_ParamId> idset; bool operator () (aku_ParamId id) { return idset.count(id) > 0; } }; typedef FilterByIdNode<Matcher> NodeT; std::unordered_set<aku_ParamId> idset(ids.begin(), ids.end()); Matcher fn = { idset }; std::stringstream logfmt; logfmt << "Creating id-list filter node (" << ids.size() << " ids in a list)"; (*logger)(AKU_LOG_TRACE, logfmt.str().c_str()); return std::make_shared<NodeT>(fn, next); } static std::shared_ptr<Node> make_filter_out_by_id_list(std::vector<aku_ParamId> ids, std::shared_ptr<Node> next, aku_logger_cb_t logger) { struct Matcher { std::unordered_set<aku_ParamId> idset; bool operator () (aku_ParamId id) { return idset.count(id) == 0; } }; typedef FilterByIdNode<Matcher> NodeT; std::unordered_set<aku_ParamId> idset(ids.begin(), ids.end()); Matcher fn = { idset }; std::stringstream logfmt; logfmt << "Creating id-list filter out node (" << ids.size() << " ids in a list)"; (*logger)(AKU_LOG_TRACE, logfmt.str().c_str()); return std::make_shared<NodeT>(fn, next); } GroupByStatement::GroupByStatement() : step_(0) , first_hit_(true) , lowerbound_(AKU_MIN_TIMESTAMP) , upperbound_(AKU_MIN_TIMESTAMP) { } GroupByStatement::GroupByStatement(aku_Timestamp step) : step_(step) , first_hit_(true) , lowerbound_(AKU_MIN_TIMESTAMP) , upperbound_(AKU_MIN_TIMESTAMP) { } GroupByStatement::GroupByStatement(const GroupByStatement& other) : step_(other.step_) , first_hit_(other.first_hit_) , lowerbound_(other.lowerbound_) , upperbound_(other.upperbound_) { } GroupByStatement& GroupByStatement::operator = (const GroupByStatement& other) { step_ = other.step_; first_hit_ = other.first_hit_; lowerbound_ = other.lowerbound_; upperbound_ = other.upperbound_; return *this; } bool GroupByStatement::put(aku_Sample const& sample, Node& next) { if (step_) { aku_Timestamp ts = sample.timestamp; if (AKU_UNLIKELY(first_hit_ == true)) { first_hit_ = false; aku_Timestamp aligned = ts / step_ * step_; lowerbound_ = aligned; upperbound_ = aligned + step_; } if (ts >= upperbound_) { // Forward direction aku_Sample empty = EMPTY_SAMPLE; empty.timestamp = upperbound_; if (!next.put(empty)) { return false; } lowerbound_ += step_; upperbound_ += step_; } else if (ts < lowerbound_) { // Backward direction aku_Sample empty = EMPTY_SAMPLE; empty.timestamp = upperbound_; if (!next.put(empty)) { return false; } lowerbound_ -= step_; upperbound_ -= step_; } } return next.put(sample); } bool GroupByStatement::empty() const { return step_ == 0; } ScanQueryProcessor::ScanQueryProcessor(std::vector<std::shared_ptr<Node>> nodes, std::vector<std::string> metrics, aku_Timestamp begin, aku_Timestamp end, GroupByStatement groupby) : lowerbound_(std::min(begin, end)) , upperbound_(std::max(begin, end)) , direction_(begin > end ? AKU_CURSOR_DIR_BACKWARD : AKU_CURSOR_DIR_FORWARD) , metrics_(metrics) , namesofinterest_(StringTools::create_table(0x1000)) , groupby_(groupby) { if (nodes.empty()) { AKU_PANIC("`nodes` shouldn't be empty") } root_node_ = nodes.at(0); // validate query processor data if (groupby_.empty()) { for (auto ptr: nodes) { if ((ptr->get_requirements() & Node::GROUP_BY_REQUIRED) != 0) { NodeException err("`group_by` required"); // TODO: more detailed error message BOOST_THROW_EXCEPTION(err); } } } int nnormal = 0; for (auto it = nodes.rbegin(); it != nodes.rend(); it++) { if (((*it)->get_requirements() & Node::TERMINAL) != 0) { if (nnormal != 0) { NodeException err("invalid sampling order"); // TODO: more detailed error message BOOST_THROW_EXCEPTION(err); } } else { nnormal++; } } } bool ScanQueryProcessor::start() { return true; } bool ScanQueryProcessor::put(const aku_Sample &sample) { return groupby_.put(sample, *root_node_); } void ScanQueryProcessor::stop() { root_node_->complete(); } void ScanQueryProcessor::set_error(aku_Status error) { std::cerr << "ScanQueryProcessor->error" << std::endl; root_node_->set_error(error); } aku_Timestamp ScanQueryProcessor::lowerbound() const { return lowerbound_; } aku_Timestamp ScanQueryProcessor::upperbound() const { return upperbound_; } int ScanQueryProcessor::direction() const { return direction_; } MetadataQueryProcessor::MetadataQueryProcessor(std::vector<aku_ParamId> ids, std::shared_ptr<Node> node) : ids_(ids) , root_(node) { } aku_Timestamp MetadataQueryProcessor::lowerbound() const { return AKU_MAX_TIMESTAMP; } aku_Timestamp MetadataQueryProcessor::upperbound() const { return AKU_MAX_TIMESTAMP; } int MetadataQueryProcessor::direction() const { return AKU_CURSOR_DIR_FORWARD; } bool MetadataQueryProcessor::start() { for (aku_ParamId id: ids_) { aku_Sample s; s.paramid = id; s.timestamp = 0; s.payload.type = aku_PData::PARAMID_BIT; s.payload.size = sizeof(aku_Sample); if (!root_->put(s)) { return false; } } return true; } bool MetadataQueryProcessor::put(const aku_Sample &sample) { // no-op return false; } void MetadataQueryProcessor::stop() { root_->complete(); } void MetadataQueryProcessor::set_error(aku_Status error) { root_->set_error(error); } // // // // // Build query processor // // // // // static boost::optional<std::string> parse_select_stmt(boost::property_tree::ptree const& ptree, aku_logger_cb_t logger) { auto select = ptree.get_child_optional("select"); if (select && select->empty()) { // simple select query auto str = select->get_value<std::string>(""); if (str == "names") { // the only supported select query for now return str; } (*logger)(AKU_LOG_ERROR, "Invalid `select` query"); auto rte = std::runtime_error("Invalid `select` query"); BOOST_THROW_EXCEPTION(rte); } return boost::optional<std::string>(); } static QP::GroupByStatement parse_groupby(boost::property_tree::ptree const& ptree, aku_logger_cb_t logger) { aku_Timestamp duration = 0u; auto groupby = ptree.get_child_optional("group-by"); if (groupby) { for(auto child: *groupby) { if (child.first == "time") { std::string str = child.second.get_value<std::string>(); duration = DateTimeUtil::parse_duration(str.c_str(), str.size()); } } } return QP::GroupByStatement(duration); } static std::vector<std::string> parse_metric(boost::property_tree::ptree const& ptree, aku_logger_cb_t logger) { std::vector<std::string> metrics; auto metric = ptree.get_child_optional("metric"); if (metric) { auto single = metric->get_value<std::string>(); if (single.empty()) { for(auto child: *metric) { auto metric_name = child.second.get_value<std::string>(); metrics.push_back(metric_name); } } else { metrics.push_back(single); } } return metrics; } static aku_Timestamp parse_range_timestamp(boost::property_tree::ptree const& ptree, std::string const& name, aku_logger_cb_t logger) { auto range = ptree.get_child("range"); for(auto child: range) { if (child.first == name) { auto iso_string = child.second.get_value<std::string>(); auto ts = DateTimeUtil::from_iso_string(iso_string.c_str()); return ts; } } std::stringstream fmt; fmt << "can't find `" << name << "` tag inside the query"; QueryParserError error(fmt.str().c_str()); BOOST_THROW_EXCEPTION(error); } static aku_ParamId extract_id_from_pool(StringPool::StringT res) { // Series name in string pool should be followed by \0 character and 64-bit series id. auto p = res.first + res.second; assert(p[0] == '\0'); p += 1; // zero terminator + sizeof(uint64_t) return *reinterpret_cast<uint64_t const*>(p); } static std::vector<aku_ParamId> parse_where_clause(boost::property_tree::ptree const& ptree, std::string metric, std::string pred, StringPool const& pool, aku_logger_cb_t logger) { std::vector<aku_ParamId> ids; bool not_set = false; auto where = ptree.get_child_optional("where"); if (where) { for (auto child: *where) { auto predicate = child.second; auto items = predicate.get_child_optional(pred); if (items) { for (auto item: *items) { std::string tag = item.first; auto idslist = item.second; // Read idlist for (auto idnode: idslist) { std::string value = idnode.second.get_value<std::string>(); std::stringstream series_regexp; series_regexp << "(" << metric << R"((?:\s\w+=\w+)*\s)" << tag << "=" << value << R"((?:\s\w+=\w+)*))"; std::string regex = series_regexp.str(); auto results = pool.regex_match(regex.c_str()); for(auto res: results) { aku_ParamId id = extract_id_from_pool(res); ids.push_back(id); } } } } else { not_set = true; } } } else { not_set = true; } if (not_set) { if (pred == "in") { // there is no "in" predicate so we need to include all // series from this metric std::stringstream series_regexp; series_regexp << "" << metric << R"((\s\w+=\w+)*)"; std::string regex = series_regexp.str(); auto results = pool.regex_match(regex.c_str()); for(auto res: results) { aku_ParamId id = extract_id_from_pool(res); ids.push_back(id); } } } return ids; } static std::string to_json(boost::property_tree::ptree const& ptree, bool pretty_print = true) { std::stringstream ss; boost::property_tree::write_json(ss, ptree, pretty_print); return ss.str(); } std::shared_ptr<QP::IQueryProcessor> Builder::build_query_processor(const char* query, std::shared_ptr<QP::Node> terminal, const SeriesMatcher &matcher, aku_logger_cb_t logger) { namespace pt = boost::property_tree; using namespace QP; const auto NOSAMPLE = std::make_pair<std::string, size_t>("", 0u); //! C-string to streambuf adapter struct MemStreambuf : std::streambuf { MemStreambuf(const char* buf) { char* p = const_cast<char*>(buf); setg(p, p, p+strlen(p)); } }; boost::property_tree::ptree ptree; MemStreambuf strbuf(query); std::istream stream(&strbuf); try { pt::json_parser::read_json(stream, ptree); } catch (pt::json_parser_error& e) { // Error, bad query (*logger)(AKU_LOG_ERROR, e.what()); throw QueryParserError(e.what()); } logger(AKU_LOG_INFO, "Parsing query:"); logger(AKU_LOG_INFO, to_json(ptree, true).c_str()); try { // Read groupby statement auto groupby = parse_groupby(ptree, logger); // Read metric(s) name auto metrics = parse_metric(ptree, logger); // Read select statment auto select = parse_select_stmt(ptree, logger); // Read sampling method auto sampling_params = ptree.get_child_optional("sample"); // Read where clause std::vector<aku_ParamId> ids_included; std::vector<aku_ParamId> ids_excluded; for(auto metric: metrics) { auto in = parse_where_clause(ptree, metric, "in", matcher.pool, logger); std::copy(in.begin(), in.end(), std::back_inserter(ids_included)); auto notin = parse_where_clause(ptree, metric, "not_in", matcher.pool, logger); std::copy(notin.begin(), notin.end(), std::back_inserter(ids_excluded)); } if (sampling_params && select) { (*logger)(AKU_LOG_ERROR, "Can't combine select and sample statements together"); auto rte = std::runtime_error("`sample` and `select` can't be used together"); BOOST_THROW_EXCEPTION(rte); } // Build topology std::shared_ptr<Node> next = terminal; std::vector<std::shared_ptr<Node>> allnodes = { next }; if (!select) { // Read timestamps auto ts_begin = parse_range_timestamp(ptree, "from", logger); auto ts_end = parse_range_timestamp(ptree, "to", logger); if (sampling_params) { for (auto i = sampling_params->rbegin(); i != sampling_params->rend(); i++) { next = make_sampler(i->second, next, logger); allnodes.push_back(next); } } if (!ids_included.empty()) { next = make_filter_by_id_list(ids_included, next, logger); allnodes.push_back(next); } if (!ids_excluded.empty()) { next = make_filter_out_by_id_list(ids_excluded, next, logger); allnodes.push_back(next); } std::reverse(allnodes.begin(), allnodes.end()); // Build query processor return std::make_shared<ScanQueryProcessor>(allnodes, metrics, ts_begin, ts_end, groupby); } if (ids_included.empty() && metrics.empty()) { // list all for (auto val: matcher.table) { auto id = val.second; ids_included.push_back(id); } } if (!ids_excluded.empty()) { std::sort(ids_included.begin(), ids_included.end()); std::sort(ids_excluded.begin(), ids_excluded.end()); std::vector<aku_ParamId> tmp; std::set_difference(ids_included.begin(), ids_included.end(), ids_excluded.begin(), ids_excluded.end(), std::back_inserter(tmp)); std::swap(tmp, ids_included); } return std::make_shared<MetadataQueryProcessor>(ids_included, next); } catch(std::exception const& e) { (*logger)(AKU_LOG_ERROR, e.what()); throw QueryParserError(e.what()); } } }} // namespace
33.501832
121
0.564892
[ "vector" ]
64b66c735e98f244a1a9de2ba97ff2b149dfff41
3,550
hpp
C++
include/net/seda/stage.hpp
izenecloud/izenelib
9d5958100e2ce763fc75f27217adf982d7c9d902
[ "Apache-2.0" ]
31
2015-03-03T19:13:42.000Z
2020-09-03T08:11:56.000Z
include/net/seda/stage.hpp
izenecloud/izenelib
9d5958100e2ce763fc75f27217adf982d7c9d902
[ "Apache-2.0" ]
1
2016-12-24T00:12:11.000Z
2016-12-24T00:12:11.000Z
include/net/seda/stage.hpp
izenecloud/izenelib
9d5958100e2ce763fc75f27217adf982d7c9d902
[ "Apache-2.0" ]
8
2015-09-06T01:55:21.000Z
2021-12-20T02:16:13.000Z
/* * ===================================================================================== * * Filename: stage.hpp * * Description: * * Version: 1.0 * Created: 12/28/2012 05:09:07 PM * Revision: none * Compiler: gcc * * Author: Kevin Hu (), kevin.hu@b5m.com * Company: iZeneSoft.com * * ===================================================================================== */ #ifndef _IZENELIB_SEDA_STAGE_HPP_ #define _IZENELIB_SEDA_STAGE_HPP_ #include "types.h" #include <vector> #include <assert.h> #include <cerrno> #include <iostream> #include <cstdio> #include <cstdlib> #include <ostream> #include <sstream> #include "util/kthread/thread.hpp" #include "util/kthread/mutex.h" #include "net/seda/queue.hpp" namespace izenelib { class StageLog { Mutex _mutx; public: void logging(uint64_t eid, std::ostringstream& ss) { if (ss.tellp()) { ScopedLock mu(&_mutx); std::cout<<"["<<eid<<"]\t"<<ss.str()<<std::endl; } } }; template< class PROC_TYPE, class INPUT_Q_TYPE, class OUTPUT_Q_TYPE, class LOG_TYPE = StageLog > class Stage { typedef Stage<PROC_TYPE, INPUT_Q_TYPE, OUTPUT_Q_TYPE> SelfT; PROC_TYPE* _proc; INPUT_Q_TYPE* _inq; OUTPUT_Q_TYPE* _outq; std::vector<Thread<SelfT>* > _thrds; volatile bool _stop; Mutex _mut4stop; LOG_TYPE _log; public: Stage(PROC_TYPE* proc=NULL,INPUT_Q_TYPE* inq=NULL, OUTPUT_Q_TYPE* outq=NULL, uint32_t thr_num=2) : _proc(proc),_inq(inq),_outq(outq),_stop(false) { for ( uint32_t i=0; i<thr_num; ++i) _thrds.push_back(NULL); } void set_input_queue(INPUT_Q_TYPE* inq) { _inq = inq; _inq.add_ref(); } void set_output_queue( OUTPUT_Q_TYPE* outq) { _outq = outq; } bool stoped() { ScopedLock mu(&_mut4stop); return _stop; } void reset_stop(bool f=false) { ScopedLock mu(&_mut4stop); _stop = f; } void *operator()(void *data) { if (_inq)_inq->reset_stop(); while(1) { if (stoped() && (!_inq || _inq->empty())) { std::cout<<"Get Stop command!\n"; break; } typename INPUT_Q_TYPE::event_t e; uint64_t eid = 0; if (_inq) if(!_inq->pop(e, eid))continue; typename OUTPUT_Q_TYPE::event_t oe; std::ostringstream ss; if(!_proc->doit(e, oe, ss)) { _log.logging(eid, ss); continue; } if (eid == 0) { /* srand(time(NULL));*/ eid = rand(); eid=eid<<32; eid += rand()+(uint64_t)(&eid); } _log.logging(eid, ss); if (_outq)_outq->push(oe, eid); } return NULL; } void start() { if (!_proc) throw std::runtime_error("Uninitialized stage."); reset_stop(); for ( uint32_t i=0; i<_thrds.size(); ++i) _thrds[i] = new Thread<SelfT>(this); } void stop() { //if (_inq)_inq->reset_stop(true); reset_stop(true); for ( uint32_t i=0; i<_thrds.size(); ++i)if(_thrds[i]) { _thrds[i]->join(); delete _thrds[i]; _thrds[i] = NULL; } } } ; } #endif
21.257485
88
0.48169
[ "vector" ]
64b9b821d2cc113dbddf906403e55fedd7db7c5a
2,997
hpp
C++
src/Enzo/enzo_EnzoEOSIdeal.hpp
aoife-flood/enzo-e
ab8ebc4716fff22bed9f692daf0472ae6ffffe73
[ "BSD-3-Clause" ]
26
2019-02-12T19:39:13.000Z
2022-03-31T01:52:29.000Z
src/Enzo/enzo_EnzoEOSIdeal.hpp
aoife-flood/enzo-e
ab8ebc4716fff22bed9f692daf0472ae6ffffe73
[ "BSD-3-Clause" ]
128
2019-02-13T20:22:30.000Z
2022-03-29T20:21:00.000Z
src/Enzo/enzo_EnzoEOSIdeal.hpp
aoife-flood/enzo-e
ab8ebc4716fff22bed9f692daf0472ae6ffffe73
[ "BSD-3-Clause" ]
29
2019-02-12T19:37:51.000Z
2022-03-14T14:02:45.000Z
// See LICENSE_CELLO file for license and copyright information /// @file enzo_EnzoEOSIdeal.hpp /// @author Matthew Abruzzo (matthewabruzzo@gmail.com) /// @date Thurs May 2 2019 /// @brief [\ref Enzo] Implementation of the equation of state for an ideal /// adiabatic gas #ifndef ENZO_ENZO_EOS_IDEAL_HPP #define ENZO_ENZO_EOS_IDEAL_HPP class EnzoEOSIdeal : public EnzoEquationOfState { /// @class EnzoEOSIdeal /// @ingroup Enzo /// @brief [\ref Enzo] Encapsulates equation of state for ideal gas public: // interface /// Create a new EnzoEOSIdeal object EnzoEOSIdeal(double gamma, double density_floor, double pressure_floor, bool dual_energy_formalism, double dual_energy_formalism_eta) throw() : EnzoEquationOfState(), gamma_(gamma), density_floor_(density_floor), pressure_floor_(pressure_floor), dual_energy_formalism_(dual_energy_formalism), dual_energy_formalism_eta_(dual_energy_formalism_eta) { } /// Delete EnzoEOSIdeal object ~EnzoEOSIdeal() { } /// CHARM++ PUP::able declaration PUPable_decl(EnzoEOSIdeal); /// CHARM++ migration constructor for PUP::able EnzoEOSIdeal (CkMigrateMessage *m) : EnzoEquationOfState(m), gamma_(0.), density_floor_(0.), pressure_floor_(0.), dual_energy_formalism_(false), dual_energy_formalism_eta_(0.) { } /// CHARM++ Pack / Unpack function void pup (PUP::er &p); void reconstructable_from_integrable (EnzoEFltArrayMap &integrable, EnzoEFltArrayMap &reconstructable, EnzoEFltArrayMap &conserved_passive_map, int stale_depth, const str_vec_t &passive_list) const; void integrable_from_reconstructable (EnzoEFltArrayMap &reconstructable, EnzoEFltArrayMap &integrable, int stale_depth, const str_vec_t &passive_list) const; void pressure_from_integrable (EnzoEFltArrayMap &integrable_map, const EFlt3DArray &pressure, EnzoEFltArrayMap &conserved_passive_map, int stale_depth) const; void pressure_from_reconstructable(EnzoEFltArrayMap &reconstructable, EFlt3DArray &pressure, int stale_depth) const; inline enzo_float get_density_floor() const { return density_floor_; } enzo_float get_pressure_floor() const { return pressure_floor_; } void apply_floor_to_energy_and_sync(EnzoEFltArrayMap &integrable_map, int stale_depth) const; bool is_barotropic() const { return false; } enzo_float get_gamma() const { return gamma_;} enzo_float get_isothermal_sound_speed() const { return 0;} // In the future, this won't be hardcoded to false bool uses_dual_energy_formalism() const { return dual_energy_formalism_; }; protected: // attributes enzo_float gamma_; // adiabatic index enzo_float density_floor_; enzo_float pressure_floor_; bool dual_energy_formalism_; double dual_energy_formalism_eta_; }; #endif /* ENZO_ENZO_EOS_IDEAL_HPP */
31.547368
78
0.724057
[ "object" ]
64bbafe5d6161c0bda1b0e01f08c33188de87d27
1,592
cpp
C++
c++/leetcode/1473-Paint_House_III-H.cpp
levendlee/leetcode
35e274cb4046f6ec7112cd56babd8fb7d437b844
[ "Apache-2.0" ]
1
2020-03-02T10:56:22.000Z
2020-03-02T10:56:22.000Z
c++/leetcode/1473-Paint_House_III-H.cpp
levendlee/leetcode
35e274cb4046f6ec7112cd56babd8fb7d437b844
[ "Apache-2.0" ]
null
null
null
c++/leetcode/1473-Paint_House_III-H.cpp
levendlee/leetcode
35e274cb4046f6ec7112cd56babd8fb7d437b844
[ "Apache-2.0" ]
null
null
null
class Solution { public: int minCost(vector<int>& houses, vector<vector<int>>& cost, int m, int n, int target) { vector<int> data(m * n * target, INT_MAX); auto dp = [&](int i, int j, int k) ->int&{ return data[i * n * target + k * n + j]; }; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { for (int k = 0; k < target; ++k) { int prev; if (i == 0) { prev = 0; if (k != 0) continue; } else { // same color prev = dp(i - 1, j, k); // different color if (k != 0) { for (int t = 0; t < n; ++t) { if (t != j) { prev = min(prev, dp(i - 1, t, k - 1)); } } } } if (houses[i] == 0) { dp(i, j, k) = prev == INT_MAX ? INT_MAX : prev + cost[i][j]; } else if (houses[i] - 1 == j) { dp(i, j, k) = prev == INT_MAX ? INT_MAX : prev; } else { dp(i, j, k) = INT_MAX; } } } } auto res = *min_element(&dp(m - 1, 0, target-1), &dp(m - 1, n, target-1)); return res == INT_MAX ? -1 : res; } };
37.023256
91
0.284548
[ "vector" ]
64c727674cd7c5d03372e038bfb5139d7fedf136
1,968
cpp
C++
uri/1148.cpp
bryanoliveira/programming-marathon
071e3e6898f9b10cabbf4ed0d8ba1c5fbbf3fac4
[ "MIT" ]
null
null
null
uri/1148.cpp
bryanoliveira/programming-marathon
071e3e6898f9b10cabbf4ed0d8ba1c5fbbf3fac4
[ "MIT" ]
null
null
null
uri/1148.cpp
bryanoliveira/programming-marathon
071e3e6898f9b10cabbf4ed0d8ba1c5fbbf3fac4
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define N 510 using namespace std; bool adj[N][N]; int main() { long n, e; cin >> n >> e; while(n != 0 || e != 0) { map<long, vector<pair<long, long> > > graph; // i -> adjascentes (no, hora) for(long i = 0; i <= n; i++) { for(long j = 0; j <= n; j++) { adj[i][j] = false; } } while(e--) { long x, y, h; cin >> x >> y >> h; graph[x].push_back({y, h}); adj[x][y] = true; } long k; cin >> k; while(k--) { long o, d; cin >> o >> d; vector<int> dist; vector<bool> vis; dist.resize(n+1, 1e9); vis.resize(n+1, false); priority_queue<pair<long, long>, vector<pair<long, long> >, greater<pair<long, long> > > que; dist[o] = 0; que.push({0, o}); while(!que.empty()) { long atual = que.top().second; que.pop(); if(vis[atual]) continue; for(long i = 0; i < graph[atual].size(); i++) { long vizinho = graph[atual].at(i).first; long custo = graph[atual].at(i).second; if(adj[vizinho][atual]){ custo = 0; } if(!vis[vizinho] && dist[vizinho] > dist[atual] + custo) { dist[vizinho] = dist[atual] + custo; que.push({dist[vizinho], vizinho}); } } vis[atual] = true; } if(dist[d] < 1e9) { cout << dist[d] << endl; } else { cout << "Nao e possivel entregar a carta" << endl; } } cout << endl; cin >> n >> e; } return 0; }
25.230769
105
0.362297
[ "vector" ]
64d0e77f1b74cea32b90e061c3eb010d87ed49ac
669
cpp
C++
238 Product of Array Except Self.cpp
akash2099/LeetCode-Problems
74c346146ca5ba2336d1e8d6dc26e3cd8920cb25
[ "MIT" ]
1
2021-11-14T01:06:38.000Z
2021-11-14T01:06:38.000Z
238 Product of Array Except Self.cpp
akash2099/LeetCode-Problems
74c346146ca5ba2336d1e8d6dc26e3cd8920cb25
[ "MIT" ]
null
null
null
238 Product of Array Except Self.cpp
akash2099/LeetCode-Problems
74c346146ca5ba2336d1e8d6dc26e3cd8920cb25
[ "MIT" ]
null
null
null
static int fastio=[](){ std::ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); return 0; }(); class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { // Time: O(n), Space: O(1) int n=nums.size(); vector<int>res(n,1); // initialize all by one int start=1; int end=1; for(int i=0;i<n;++i){ // from start multiply all res[i]*=start; start*=nums[i]; // from end mltiply all res[n-1-i]*=end; end*=nums[n-1-i]; } // can also be done in two separate loops return res; } };
24.777778
54
0.487294
[ "vector" ]
64d40736f4cd93a86cc38f96ad6aef0b71cb06e3
3,910
cpp
C++
src/bounce/cloth/contacts/cloth_particle_triangle_contact.cpp
demiurgestudios/bounce
9f8dcae52a074ba76088da9c94471366f6e4ca8f
[ "Zlib" ]
26
2020-02-10T19:28:00.000Z
2021-09-23T22:36:37.000Z
src/bounce/cloth/contacts/cloth_particle_triangle_contact.cpp
demiurgestudios/bounce
9f8dcae52a074ba76088da9c94471366f6e4ca8f
[ "Zlib" ]
null
null
null
src/bounce/cloth/contacts/cloth_particle_triangle_contact.cpp
demiurgestudios/bounce
9f8dcae52a074ba76088da9c94471366f6e4ca8f
[ "Zlib" ]
7
2020-01-22T20:42:33.000Z
2021-02-25T02:34:54.000Z
/* * Copyright (c) 2016-2019 Irlan Robson https://irlanrobson.github.io * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include <bounce/cloth/contacts/cloth_particle_triangle_contact.h> #include <bounce/cloth/cloth_mesh.h> #include <bounce/cloth/particle.h> #include <bounce/cloth/cloth_triangle.h> #include <bounce/common/geometry.h> // Solve constrained Barycentric coordinates for point Q static void b3Solve3(float32 out[3], const b3Vec3& A, const b3Vec3& B, const b3Vec3& C, const b3Vec3& Q) { // Test vertex regions float32 wAB[3], wBC[3], wCA[3]; b3BarycentricCoordinates(wAB, A, B, Q); b3BarycentricCoordinates(wBC, B, C, Q); b3BarycentricCoordinates(wCA, C, A, Q); // R A if (wAB[1] <= 0.0f && wCA[0] <= 0.0f) { out[0] = 1.0f; out[1] = 0.0f; out[2] = 0.0f; return; } // R B if (wAB[0] <= 0.0f && wBC[1] <= 0.0f) { out[0] = 0.0f; out[1] = 1.0f; out[2] = 0.0f; return; } // R C if (wBC[0] <= 0.0f && wCA[1] <= 0.0f) { out[0] = 0.0f; out[1] = 0.0f; out[2] = 1.0f; return; } // Test edge regions float32 wABC[4]; b3BarycentricCoordinates(wABC, A, B, C, Q); // R AB if (wAB[0] > 0.0f && wAB[1] > 0.0f && wABC[3] * wABC[2] <= 0.0f) { float32 divisor = wAB[2]; B3_ASSERT(divisor > 0.0f); float32 s = 1.0f / divisor; out[0] = s * wAB[0]; out[1] = s * wAB[1]; out[2] = 0.0f; return; } // R BC if (wBC[0] > 0.0f && wBC[1] > 0.0f && wABC[3] * wABC[0] <= 0.0f) { float32 divisor = wBC[2]; B3_ASSERT(divisor > 0.0f); float32 s = 1.0f / divisor; out[0] = 0.0f; out[1] = s * wBC[0]; out[2] = s * wBC[1]; return; } // R CA if (wCA[0] > 0.0f && wCA[1] > 0.0f && wABC[3] * wABC[1] <= 0.0f) { float32 divisor = wCA[2]; B3_ASSERT(divisor > 0.0f); float32 s = 1.0f / divisor; out[0] = s * wCA[1]; out[1] = 0.0f; out[2] = s * wCA[0]; return; } // R ABC/ACB float32 divisor = wABC[3]; if (divisor == 0.0f) { float32 s = 1.0f / 3.0f; out[0] = s; out[1] = s; out[2] = s; return; } B3_ASSERT(divisor > 0.0f); float32 s = 1.0f / divisor; out[0] = s * wABC[0]; out[1] = s * wABC[1]; out[2] = s * wABC[2]; } void b3ParticleTriangleContact::Update() { b3Vec3 A = m_p2->m_position; b3Vec3 B = m_p3->m_position; b3Vec3 C = m_p4->m_position; b3Vec3 N = b3Cross(B - A, C - A); float32 len = N.Normalize(); // Is ABC degenerate? if (len == 0.0f) { m_active = false; return; } float32 r1 = m_p1->m_radius; float32 r2 = m_t2->m_radius; float32 totalRadius = r1 + r2; b3Vec3 P1 = m_p1->m_position; float32 distance = b3Dot(N, P1 - A); // Is P1 below the plane? if (distance < -totalRadius) { m_active = false; return; } // Is P1 above the plane? if (distance > totalRadius) { m_active = false; return; } // Closest point on ABC to P1 float32 wABC[3]; b3Solve3(wABC, A, B, C, P1); b3Vec3 P2 = wABC[0] * A + wABC[1] * B + wABC[2] * C; if (b3DistanceSquared(P1, P2) > totalRadius * totalRadius) { m_active = false; return; } // Activate the contact m_active = true; // Store Barycentric coordinates for P1 m_w2 = wABC[0]; m_w3 = wABC[1]; m_w4 = wABC[2]; }
21.843575
76
0.626343
[ "geometry" ]
64db50fb6f2db1d2eda9be523d8376ac6ea11c73
12,500
cpp
C++
src/RcsGui/MatNdWidget.cpp
smanschi/Rcs
a54980a44c7fb0e925b091cd3c29297e940af39c
[ "BSD-4-Clause" ]
null
null
null
src/RcsGui/MatNdWidget.cpp
smanschi/Rcs
a54980a44c7fb0e925b091cd3c29297e940af39c
[ "BSD-4-Clause" ]
null
null
null
src/RcsGui/MatNdWidget.cpp
smanschi/Rcs
a54980a44c7fb0e925b091cd3c29297e940af39c
[ "BSD-4-Clause" ]
null
null
null
/******************************************************************************* Copyright (c) 2017, Honda Research Institute Europe GmbH. 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. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by the Honda Research Institute Europe GmbH. 4. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ #include "MatNdWidget.h" #include "Rcs_guiFactory.h" #include <Rcs_macros.h> #include <QTimer> #include <QLayout> namespace Rcs { /******************************************************************************* * ******************************************************************************/ typedef struct { void* ptr[10]; } VoidPointerList; static void* matndGui(void* arg) { VoidPointerList* p = (VoidPointerList*) arg; RCHECK(arg); MatNd* mat = (MatNd*) p->ptr[0]; const char* title = (const char*) p->ptr[1]; pthread_mutex_t* mutex = (pthread_mutex_t*) p->ptr[2]; double* lb = (double*) p->ptr[3]; double* ub = (double*) p->ptr[4]; const MatNd* dispMat = (const MatNd*) p->ptr[5]; double lowerBound = (lb != NULL) ? *lb : -1.0; double upperBound = (ub != NULL) ? *ub : 1.0; MatNdWidget* w = new MatNdWidget(mat, dispMat, lowerBound, upperBound, title, mutex); w->show(); if (lb != NULL) { delete lb; } if (ub != NULL) { delete ub; } delete p; return w; } /******************************************************************************* * ******************************************************************************/ MatNdWidget* MatNdWidget::create(MatNd* mat, const char* title, pthread_mutex_t* mutex) { VoidPointerList* p = new VoidPointerList; p->ptr[0] = (void*) mat; p->ptr[1] = (void*) title; p->ptr[2] = (void*) mutex; p->ptr[3] = (void*) NULL; p->ptr[4] = (void*) NULL; p->ptr[5] = (void*) NULL; int handle = RcsGuiFactory_requestGUI(matndGui, p); return (MatNdWidget*) RcsGuiFactory_getPointer(handle); } /******************************************************************************* * ******************************************************************************/ MatNdWidget* MatNdWidget::create(MatNd* mat, double lower, double upper, const char* title, pthread_mutex_t* mutex) { VoidPointerList* p = new VoidPointerList; p->ptr[0] = (void*) mat; p->ptr[1] = (void*) title; p->ptr[2] = (void*) mutex; double* _lower = new double; *_lower = lower; double* _upper = new double; *_upper = upper; p->ptr[3] = (void*) _lower; p->ptr[4] = (void*) _upper; p->ptr[5] = (void*) NULL; int handle = RcsGuiFactory_requestGUI(matndGui, p); return (MatNdWidget*) RcsGuiFactory_getPointer(handle); } /******************************************************************************* * ******************************************************************************/ MatNdWidget* MatNdWidget::create(MatNd* mat, const MatNd* dispMat, double lower, double upper, const char* title, pthread_mutex_t* mutex) { VoidPointerList* p = new VoidPointerList; p->ptr[0] = (void*) mat; p->ptr[1] = (void*) title; p->ptr[2] = (void*) mutex; double* _lower = new double; *_lower = lower; double* _upper = new double; *_upper = upper; p->ptr[3] = (void*) _lower; p->ptr[4] = (void*) _upper; p->ptr[5] = (void*) dispMat; int handle = RcsGuiFactory_requestGUI(matndGui, p); return (MatNdWidget*) RcsGuiFactory_getPointer(handle); } /******************************************************************************* * ******************************************************************************/ MatNdWidget::MatNdWidget(MatNd* mat_, const MatNd* dispMat_, double lower, double upper, const char* title, pthread_mutex_t* mutex_) : QScrollArea(), mat(mat_), mutex(mutex_), updateEnabled(true) { init(mat_, dispMat_, lower, upper, title); } /******************************************************************************* * ******************************************************************************/ MatNdWidget::~MatNdWidget() { RLOG(5, "Destroying MatNdWidget"); } /******************************************************************************* * ******************************************************************************/ void MatNdWidget::setLowerBound(const MatNd* limit) { if (limit->m != this->slider.size()) { RLOG(1, "The number of bounds does not match the number of sliders: " "%u != %zu", limit->m, this->slider.size()); return; } lock(); for (size_t i = 0; i < slider.size(); ++i) { slider[i]->setLowerBound(MatNd_get(limit, i, 0)); } unlock(); } /******************************************************************************* * ******************************************************************************/ void MatNdWidget::setUpperBound(const MatNd* limit) { if (limit->m != this->slider.size()) { RLOG(1, "The number of bounds does not match the number of sliders: " "%u != %zu", limit->m, this->slider.size()); return; } lock(); for (size_t i = 0; i < slider.size(); ++i) { slider[i]->setUpperBound(MatNd_get(limit, i, 0)); } unlock(); } /******************************************************************************* * ******************************************************************************/ void MatNdWidget::setLowerBound(double value) { MatNd* bound = MatNd_create(slider.size(), 1); MatNd_setElementsTo(bound, value); setLowerBound(bound); MatNd_destroy(bound); } /******************************************************************************* * ******************************************************************************/ void MatNdWidget::setUpperBound(double value) { MatNd* bound = MatNd_create(slider.size(), 1); MatNd_setElementsTo(bound, value); setUpperBound(bound); MatNd_destroy(bound); } /******************************************************************************* * ******************************************************************************/ void MatNdWidget::setLabels(std::vector<std::string>& labels) { if (labels.size() != this->slider.size()) { RLOG(1, "The number of labels does not match the number of vector " "elements: %zu != %zu", labels.size(), this->slider.size()); return; } this->labels = labels; for (unsigned int i= 0; i< this->slider.size(); i++) { this->slider[i]->setLabel(labels[i].c_str()); } } /******************************************************************************* * ******************************************************************************/ void MatNdWidget::setMutex(pthread_mutex_t* mutex) { this->mutex = mutex; } /******************************************************************************* * ******************************************************************************/ void MatNdWidget::setUpdateEnabled(bool enabled) { lock(); updateEnabled = enabled; unlock(); } /******************************************************************************* * ******************************************************************************/ void MatNdWidget::init(MatNd* mat_, const MatNd* dispMat_, double lower, double upper, const char* title) { RCHECK(this->mat); this->dispMat = dispMat_ ? dispMat_ : this->mat; char windowTitle[256]; sprintf(windowTitle, "%d x %d matrix", this->mat->m, this->mat->n); setWindowTitle(title ? title : windowTitle); // The layout for the overall task widget QGridLayout* matLayout = new QGridLayout(); // Add a slider instance for each array element for (unsigned int i = 0; i < this->mat->m; i++) { for (unsigned int j = 0; j < this->mat->n; j++) { char indexStr[32]; sprintf(indexStr, "%u", i); LcdSlider* sl = new LcdSlider(lower, this->mat->ele[i*this->mat->n+j], upper, 1.0, 0.0001, indexStr); sl->updateLcd1FromSlider(); matLayout->addWidget(sl, i, j, Qt::AlignLeft); this->slider.push_back(sl); connect(sl, SIGNAL(valueChanged(double)), SLOT(setCommand())); } } QWidget* scrollWidget = new QWidget(this); scrollWidget->setLayout(matLayout); this->setWidget(scrollWidget); this->setWidgetResizable(true); QTimer* timer = new QTimer(this); connect(timer, SIGNAL(timeout()), SLOT(displayAct())); setCommand(); timer->start(40); } /******************************************************************************* * ******************************************************************************/ void MatNdWidget::displayAct() { if (this->dispMat == NULL) { return; } lock(); for (size_t i=0; i< this->slider.size(); i++) { slider[i]->setValueLcd2(this->dispMat->ele[i]); } unlock(); } /******************************************************************************* * ******************************************************************************/ void MatNdWidget::setCommand() { lock(); if (updateEnabled) { unsigned int i = 0; std::vector<LcdSlider*>::iterator it; for (it = this->slider.begin(); it != this->slider.end(); ++it) { this->mat->ele[i] = (*it)->getSliderValue(); i++; } } unlock(); } /******************************************************************************* * ******************************************************************************/ void MatNdWidget::lock() { if (this->mutex != NULL) { pthread_mutex_lock(this->mutex); } } /******************************************************************************* * ******************************************************************************/ void MatNdWidget::unlock() { if (this->mutex != NULL) { pthread_mutex_unlock(this->mutex); } } /******************************************************************************* * ******************************************************************************/ bool MatNdWidget::isUpdateEnabled() { lock(); bool isUpdated = updateEnabled; unlock(); return isUpdated; } /******************************************************************************* * ******************************************************************************/ void MatNdWidget::reset(const MatNd* values) { if ((this->mat->m!=values->m) || (this->mat->n!=values->n)) { RLOG(1, "Mismatch in reset: mat is %u x %u, desired matrix is %u x %u", mat->m, mat->n, values->m, values->n); return; } MatNd_copy(this->mat, values); for (unsigned int i=0; i<values->m; ++i) { slider[i]->setSliderValue(values->ele[i]); } } } // namespace Rcs
29.069767
80
0.4596
[ "vector" ]
64ef4896330a102eedea22c9dc09936bfadc80a7
4,881
cpp
C++
Almost Hero/Motor2D/j1Particles.cpp
RedPillStudios/AlmostHeroes
edf05b6561dfd6028c07d513d589c309f5cd0c54
[ "MIT" ]
1
2019-01-21T10:54:49.000Z
2019-01-21T10:54:49.000Z
Almost Hero/Motor2D/j1Particles.cpp
RedPillStudios/AlmostHeroes
edf05b6561dfd6028c07d513d589c309f5cd0c54
[ "MIT" ]
1
2019-01-04T13:06:38.000Z
2019-01-04T13:08:36.000Z
Almost Hero/Motor2D/j1Particles.cpp
RedPillStudios/AlmostHeroes
edf05b6561dfd6028c07d513d589c309f5cd0c54
[ "MIT" ]
1
2018-12-31T16:15:57.000Z
2018-12-31T16:15:57.000Z
#include "j1App.h" #include "j1Textures.h" #include "j1Render.h" #include "j1Particles.h" #include "j1Scene.h" #include "SDL/include/SDL_timer.h" j1Particles::j1Particles() { name.create("Particles"); for (uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i) active[i] = nullptr; } j1Particles::~j1Particles() {} bool j1Particles::Start() { pugi::xml_parse_result result = ParticleDocument.load_file("Particle_Settings.xml"); if (result == NULL) LOG("The xml file containing the player tileset fails. Pugi error: %s", result.description()); Particle_1 = App->tex->Load("textures/Particles.png"); Animation_node = ParticleDocument.child("config").child("Particle_Pushbacks").child("Note_Press_Succes"); LoadPushbacks(Animation_node, Note_press_Succes.Anim); Note_press_Succes.Sprites = Particle_1; //Animation_node = ParticleDocument.child("config").child("Particle_Pushbacks").child("Player_Shoot"); //App->scene->Player->LoadPushbacks(Animation_node, Player_Shoot.Anim); //Animation_node = ParticleDocument.child("config").child("Particle_Pushbacks").child("Enemy_Shoot"); //App->scene->Player->LoadPushbacks(Animation_node, Enemy_Shoot.Anim); //Animation_node = ParticleDocument.child("config").child("Particle_Pushbacks").child("Player_Shot_Beam"); //App->scene->Player->LoadPushbacks(Animation_node, Player_Shoot_Beam.Anim); //Animation_node = ParticleDocument.child("config").child("Particle_Pushbacks").child("Plasma_explosion"); //App->scene->Player->LoadPushbacks(Animation_node, Plasma_Explosion.Anim); //Particle_1 = App->tex->Load("maps/Particles.png"); ////LOG("Loading Particles"); ////particle0 = App->textures->Load("Images/Player/Ship&Ball_Sprite.png"); //Player_Shoot.Sprites = Blood.Sprites = Enemy_Shoot.Sprites = Plasma_Explosion.Sprites = Player_Shoot_Beam.Sprites = Particle_1; //Enemy_Shoot.Life = 600; //Player_Shoot.Life = 1200; //Player_Shoot.collider = App->collisions->AddCollider({ 0,0,80,10 }, COLLIDER_PLAYER_BULLET, this); return true; } void j1Particles::LoadPushbacks(pugi::xml_node node, Animation &animation) { animation.loop = node.attribute("loop").as_bool(); animation.speed = node.attribute("speed").as_float(); SDL_Rect rect; for (node = node.child("Pushback"); node; node = node.next_sibling("Pushback")) { rect.x = node.attribute("x").as_int(); rect.y = node.attribute("y").as_int(); rect.w = node.attribute("w").as_int(); rect.h = node.attribute("h").as_int(); animation.PushBack({ rect }); } } bool j1Particles::CleanUp() { LOG("Unloading Particles"); for (uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i) { if (active[i] != nullptr) { App->tex->UnLoad(active[i]->Sprites); delete active[i]; active[i] = nullptr; } } return true; } bool j1Particles::Update(float dt) { bool ret = true; for (uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i) { Particle *p = active[i]; if (p == nullptr) continue; if (p->Update() == false) { delete p; active[i] = nullptr; } else if (SDL_GetTicks() >= p->Born) { App->render->Blit(p->Sprites, p->Position.x, p->Position.y, &(p->Anim.GetCurrentFrame()), p->scale, 1, 0, 0, 0,p->Flip,true); if (!p->fx_played) p->fx_played = true; } } return ret; } void j1Particles::AddParticle(const Particle& particle, int x, int y, COLLIDER_TYPE collider_type, fPoint speed, float scale, SDL_RendererFlip Flip, Uint32 delay) { int a = rand() % 2; if (a == 0) Flip = SDL_FLIP_NONE; else if (a == 1) Flip = SDL_FLIP_HORIZONTAL; for (uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i) { if (active[i] == nullptr) { Particle* p = new Particle(particle); p->Born = SDL_GetTicks() + delay; p->Position.x = x; p->Position.y = y; p->Sprites = particle.Sprites; p->Speed.x = speed.x; p->Speed.y = speed.y; p->Flip = Flip; p->scale = scale; active[i] = p; break; } } } void j1Particles::OnCollision(Collider* c1, Collider* c2) { for (uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i) { if (active[i] != nullptr && active[i]->collider == c1) { if (c2->type == COLLIDER_STATIC /*|| c2->type == COLLIDER_WALL*/) { delete active[i]; active[i] = nullptr; break; } } } } Particle::Particle() { Position.SetToZero(); Speed.SetToZero(); } Particle::Particle(const Particle &p) : Anim(p.Anim), Position(p.Position), Speed(p.Speed), fx(p.fx), Born(p.Born), Life(p.Life) {} Particle::~Particle() { if (collider != nullptr) collider->to_delete = true; } bool Particle::Update() { bool ret = true; if (Life > 0) { if (((int)SDL_GetTicks() - (int)Born) > (int)Life) return false; } else if (Anim.Finished()) ret = false; if (collider != nullptr) ret = true; if (SDL_GetTicks() >= Born) { Position.x += Speed.x; Position.y += Speed.y; if (collider != nullptr) collider->SetPos(Position.x, Position.y); } return ret; }
23.809756
164
0.669125
[ "render" ]
64f4bd8444b73f532ab0905a71808825856ad59f
352
cpp
C++
C++ Programs/flatten tree.cpp
Anshhdeep/Hacktoberfest2020-Expert
8745380deb626d1a06faf5a60ca37081aaeab426
[ "MIT" ]
77
2020-10-01T10:06:59.000Z
2021-11-08T08:57:18.000Z
C++ Programs/flatten tree.cpp
Anshhdeep/Hacktoberfest2020-Expert
8745380deb626d1a06faf5a60ca37081aaeab426
[ "MIT" ]
46
2020-09-27T04:55:36.000Z
2021-05-14T18:49:06.000Z
C++ Programs/flatten tree.cpp
Anshhdeep/Hacktoberfest2020-Expert
8745380deb626d1a06faf5a60ca37081aaeab426
[ "MIT" ]
327
2020-09-26T17:06:03.000Z
2021-10-09T06:04:39.000Z
int timer = 0; void dfs(int v, int par){ entr[v] = timer++; for(auto u: adj[v]) { if (u == par) continue; dfs(u, v); } ext[v] = timer++; } vector<long long> flattenedTree(2*n); for(int u = 0; u < n; u++) { flattenedTree[entr[u]] = s[u]; flattenedTree[ext[u]] = -s[u]; }
20.705882
42
0.440341
[ "vector" ]
64f8b4013ad2c0731c2af4739b83b241d8dfb4fc
7,559
cpp
C++
SpaceshIT!/SpaceshIT!/Player.cpp
ColdSpotYZ/SpaceshIT
8fe2dcdd202536b5127e14a140c5f833720b1eeb
[ "MIT" ]
null
null
null
SpaceshIT!/SpaceshIT!/Player.cpp
ColdSpotYZ/SpaceshIT
8fe2dcdd202536b5127e14a140c5f833720b1eeb
[ "MIT" ]
null
null
null
SpaceshIT!/SpaceshIT!/Player.cpp
ColdSpotYZ/SpaceshIT
8fe2dcdd202536b5127e14a140c5f833720b1eeb
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Player.h" void Player::initVariables() { this->health = this->max_health; this->speed = this->max_speed; this->attackCoolDownMax = 10.f; this->attackCoolDown = this->attackCoolDownMax; this->ammo = this->max_ammo; } Player::Player() { this->initVariables(); } Player::Player(char* filename, sf::Vector2f pos) : Actor(filename, pos) { if (filename == "player1") this->playerNum = 1; else this->playerNum = 2; this->initVariables(); this->initSprite(pos, sf::Vector2f(0.4f, 0.4f)); if (this->playerNum == 1) this->sprite->setRotation(90); else this->sprite->setRotation(270); /*this->initGUI();*/ } Player::~Player() { // Delete Textures for (auto* i : this->bullets) { delete i; } } const int Player::getHp() const { return this->health; } const int Player::getHpMax() const { return this->max_health; } const int Player::getPlayerNum() const { return this->playerNum; } const int Player::getPoints() const { return (this->points < 0) ? 0 : this->points; } void Player::move(const float dt, const float x, const float y) { this->sprite->move(this->speed * x * dt, this->speed * y * dt); } void Player::takeDamage() { this->health -= 20; this->points += this->healthLostPoints; if (this->health < 0) { this->health = 0; } } void Player::shoot() { this->ammo -= 1; this->points += this->bulletUsedPoints; if (this->ammo < 0) { this->ammo = 0; } } void Player::heal() { this->health += 60; if (this->health > this->max_health) { this->health = this->max_health; } } void Player::restockammo() { this->ammo += 20; if (this->ammo > this->max_ammo) { this->ammo = this->max_ammo; } } void Player::updateBullets() { for (unsigned counter = 0; counter < this->bullets.getsize(); counter++) { bullets.at(counter)->update(); // Bulleting culling if (bullets.at(counter)->getBounds().top + bullets.at(counter)->getBounds().height < 0.f || bullets.at(counter)->getBounds().top + bullets.at(counter)->getBounds().height > 900.f || bullets.at(counter)->getBounds().width + bullets.at(counter)->getBounds().left > 1600.f || bullets.at(counter)->getBounds().width + bullets.at(counter)->getBounds().left < 0.f) { //Delete bullet // std::cout << "culling of bullets" << endl; delete this->bullets.at(counter); this->bullets.erase(counter); } } } const bool Player::canAttack() { if (this->attackCoolDown >= this->attackCoolDownMax) { this->attackCoolDown = 0.f; return true; } return false; } void Player::Combat(Player* player, Player* player2) { for (unsigned i = 0; i < player->bullets.getsize(); i++) { if (player->bullets[i]->getBounds().intersects(player2->getBounds())) { player->bullets.erase(i); player2->takeDamage(); } } } void Player::updateAttack() { if (this->attackCoolDown < this->attackCoolDownMax) this->attackCoolDown += 0.5f; } void Player::update(const float dt) { } void Player::update(const float dt, Map<std::string, int> keybinds) { this->queuePlayerLocation(); bool isPress = false; if (this->playerNum == 1) { if (sf::Keyboard::isKeyPressed((sf::Keyboard::Key)keybinds.at("p1_left"))) { isPress = true; this->rotateAmount1 = -0.03f; } if (sf::Keyboard::isKeyPressed((sf::Keyboard::Key)keybinds.at("p1_right"))) { isPress = true; this->rotateAmount1 = 0.03f; } if (sf::Keyboard::isKeyPressed((sf::Keyboard::Key)keybinds.at("p1_front"))) { this->p1Velocity.y = -1; this->p1Velocity.x = 1; } /* if (sf::Keyboard::isKeyPressed((sf::Keyboard::Key)keybinds.at("p1_back"))) { this->p1Velocity.y = 1; this->p1Velocity.x = -1; } */ if (sf::Keyboard::isKeyPressed((sf::Keyboard::Key)keybinds.at("p1_shoot")) && canAttack() && ammo > 0) { Bullet* tempBullet = new Bullet(this->getPos().x - 5.f + (5.f * sin(this->sprite->getRotation() * ((2 * acos(0.0)) / 180.0))), this->getPos().y - this->sprite->getLocalBounds().height / 50.f + (-0.f * sin(this->sprite->getRotation() * ((2 * acos(0.0)) / 180.0))), 1 * sin(this->sprite->getRotation() * ((2 * acos(0.0)) / 180.0)), (-1 * cos(this->sprite->getRotation() * ((2 * acos(0.0)) / 180.0))), 7.f); this->bullets.push_back(tempBullet); this->shoot(); } if (!isPress) this->rotation1 = 0; if (this->rotation1 < 0 && this->rotateAmount1 > 0) this->rotation1 = 0; else if (this->rotation1 > 0 && this->rotateAmount1 < 0) this->rotation1 = 0; this->rotation1 += this->rotateAmount1; this->sprite->rotate(this->rotation1); this->move(dt, this->p1Velocity.x * sin(this->sprite->getRotation() * ((2 * acos(0.0)) / 180.0)), this->p1Velocity.y * cos(this->sprite->getRotation() * ((2 * acos(0.0)) / 180.0))); this->p1Velocity.x = 0; this->p1Velocity.y = 0; this->rotateAmount1 = 0; } else { if (sf::Keyboard::isKeyPressed((sf::Keyboard::Key)keybinds.at("p2_left"))) { isPress = true; this->rotateAmount2 = -0.02f; } if (sf::Keyboard::isKeyPressed((sf::Keyboard::Key)keybinds.at("p2_right"))) { isPress = true; this->rotateAmount2 = 0.02f; } if (sf::Keyboard::isKeyPressed((sf::Keyboard::Key)keybinds.at("p2_front"))) { this->p2Velocity.y = -1; this->p2Velocity.x = 1; } /* if (sf::Keyboard::isKeyPressed((sf::Keyboard::Key)keybinds.at("p2_back"))) { this->p2Velocity.y = 1; this->p2Velocity.x = -1; } */ if (sf::Keyboard::isKeyPressed((sf::Keyboard::Key)keybinds.at("p2_shoot")) && canAttack() && ammo > 0) { Bullet* tempBullet = new Bullet(this->getPos().x - 5.f + (5.f * sin(this->sprite->getRotation() * ((2 * acos(0.0)) / 180.0))), this->getPos().y - this->sprite->getLocalBounds().height / 50.f + (-0.f * sin(this->sprite->getRotation() * ((2 * acos(0.0)) / 180.0))), 1 * sin(this->sprite->getRotation() * ((2 * acos(0.0)) / 180.0)), (-1 * cos(this->sprite->getRotation() * ((2 * acos(0.0)) / 180.0))), 7.f); this->bullets.push_back(tempBullet); this->shoot(); } if (!isPress) this->rotation2 = 0; if (this->rotation2 < 0 && this->rotateAmount2 > 0) this->rotation2 = 0; else if (this->rotation2 > 0 && this->rotateAmount2 < 0) this->rotation2 = 0; this->rotation2 += this->rotateAmount2; this->sprite->rotate(this->rotation2); this->move(dt, this->p2Velocity.x * sin(this->sprite->getRotation() * ((2 * acos(0.0)) / 180.0)), this->p2Velocity.y * cos(this->sprite->getRotation() * ((2 * acos(0.0)) / 180.0))); this->p2Velocity.x = 0; this->p2Velocity.y = 0; this->rotateAmount2 = 0; } this->updateAttack(); this->points += this->tickPoints; } void Player::queuePlayerLocation() { bool validmovement = true; sf::Vector2f CurrentLocation = this->sprite->getPosition(); sf::Vector2f location = CurrentLocation; std::string hash; if (!this->PlayerLocations.isEmpty()) this->PlayerLocations.getBack(location, hash); this->PlayerLocations.enqueue_back(CurrentLocation); if (this->PlayerLocations.getNoOfElements() > 1) { if (xhash((std::to_string(location.x) + std::to_string(location.y))) == hash) { if (!((CurrentLocation.x - location.x) < 8) && ((CurrentLocation.x - location.x) > -8) && ((CurrentLocation.y - location.y) < 8) && ((CurrentLocation.y - location.y) > -8)) validmovement = false; } else validmovement = false; } if (!validmovement) { // Server Implementation (Ban the user) std::cout << "Cheating have been detected" << endl; } } void Player::render(sf::RenderTarget* target) { target->draw(*this->sprite); for (auto* i : this->bullets) { i->render(target); } }
25.029801
183
0.631168
[ "render" ]
64fa739a393853a6c60034a84ced61b91bcb81c4
6,341
cpp
C++
test/advisor_test.cpp
NigoroJr/erlang-b-model
f282a1b88729008f29804d26b5bf7065f83a5845
[ "MIT" ]
null
null
null
test/advisor_test.cpp
NigoroJr/erlang-b-model
f282a1b88729008f29804d26b5bf7065f83a5845
[ "MIT" ]
null
null
null
test/advisor_test.cpp
NigoroJr/erlang-b-model
f282a1b88729008f29804d26b5bf7065f83a5845
[ "MIT" ]
null
null
null
#define BOOST_TEST_MODULE AdvisorTest #include <boost/test/unit_test.hpp> #include "Advisor.h" #include "Event.h" #include "Link.h" #include <boost/graph/adjacency_list.hpp> #include <boost/graph/breadth_first_search.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/graph/visitors.hpp> #include <vector> using Graph = Advisor::Graph; using vertex_t = Advisor::vertex_t; using edge_t = Advisor::edge_t; /* 0 * | * 1 -- 2 -- 3 * | * 4 */ Graph make_crossing_graph(const unsigned num_links) { Graph g; boost::add_edge(0, 2, Link(num_links), g); boost::add_edge(1, 2, Link(num_links), g); boost::add_edge(2, 3, Link(num_links), g); boost::add_edge(2, 4, Link(num_links), g); return g; } /* With diagonal edges * * - 0 - * / | \ * / | \ * 1 -- 2 -- 3 * \ | / * \ | / * - 4 - */ Graph make_diamond_graph(const unsigned num_links) { auto g = make_crossing_graph(num_links); boost::add_edge(0, 1, Link(num_links), g); boost::add_edge(0, 3, Link(num_links), g); boost::add_edge(1, 4, Link(num_links), g); boost::add_edge(3, 4, Link(num_links), g); return g; } Graph make_graph(const unsigned num_links) { Graph g; std::vector<std::pair<int, int>> connections = { {0, 1}, {0, 3}, {0, 8}, {0, 9}, {1, 8}, {1, 9}, {2, 6}, {3, 2}, {3, 6}, {3, 7}, {4, 0}, {4, 1}, {4, 2}, {4, 6}, {4, 7}, {6, 1}, {6, 5}, {6, 8}, {7, 2}, {9, 5}, }; for (auto&& p : connections) { boost::add_edge(p.first, p.second, Link(num_links), g); } return g; } BOOST_AUTO_TEST_CASE(advisor_path_between_test) { auto nodes = make_graph(5); const Event::event_t lambda = 5; const Event::event_t duration_mean = 1; Advisor advisor{nodes, lambda, duration_mean}; // Adjacent // 0 -- 8 // Only one edge auto path = advisor.path_between(0, 8).first; BOOST_CHECK_EQUAL(path.size(), 1); // Multiple hops // 0 -- 9 -- 5 // Two edges path = advisor.path_between(0, 5).first; BOOST_CHECK_EQUAL(path.size(), 2); auto g = make_crossing_graph(1); Advisor a2{g, lambda, duration_mean}; Link::wavelength_t wl; std::tie(path, wl) = a2.path_between(0, 4); // 0 -- 2 -- 4 // Two edges BOOST_REQUIRE_EQUAL(path.size(), 2); // Lock the path a2.make_connection(0, 4); std::tie(path, wl) = a2.path_between(1, 3); BOOST_CHECK_NE(wl, Link::NONE); auto g2 = make_diamond_graph(1); a2 = Advisor{g2, lambda, duration_mean}; /* This type of connection * * 0 - * \ * \ * 1 -- 2 -- 3 * \ * \ * - 4 */ a2.make_connection(0, 1); a2.make_connection(0, 2); a2.make_connection(2, 4); a2.make_connection(3, 4); std::tie(path, std::ignore) = a2.path_between(0, 4); BOOST_CHECK_EQUAL(path.size(), 4); } BOOST_AUTO_TEST_CASE(advisor_has_path_between_test) { auto nodes = make_graph(5); const Event::event_t lambda = 5; const Event::event_t duration_mean = 1; Advisor advisor{nodes, lambda, duration_mean}; // Adjacent BOOST_CHECK(advisor.has_path_between(0, 8)); BOOST_CHECK(advisor.has_path_between(8, 0)); // Multiple hops BOOST_CHECK(advisor.has_path_between(0, 5)); BOOST_CHECK(advisor.has_path_between(5, 0)); // With multiple paths and links advisor = Advisor{make_diamond_graph(2), lambda, duration_mean}; advisor.make_connection(0, 4); advisor.make_connection(0, 4); BOOST_CHECK(advisor.has_path_between(0, 4)); advisor.make_connection(0, 4); advisor.make_connection(0, 4); BOOST_CHECK(advisor.has_path_between(4, 0)); advisor.make_connection(0, 4); advisor.make_connection(0, 4); // Now there should be no more path BOOST_CHECK(!advisor.has_path_between(4, 0)); } BOOST_AUTO_TEST_CASE(advisor_make_connection_test) { auto nodes = make_crossing_graph(1); const Event::event_t lambda = 5; const Event::event_t duration_mean = 1; Advisor advisor{nodes, lambda, duration_mean}; BOOST_REQUIRE(advisor.has_path_between(0, 4)); advisor.make_connection(0, 4); BOOST_CHECK(!advisor.has_path_between(0, 3)); BOOST_CHECK(!advisor.has_path_between(0, 4)); // 1 -- 2 -- 3 // Links are not used BOOST_CHECK(advisor.has_path_between(1, 3)); // Blocking with a detour nodes = make_diamond_graph(1); advisor = Advisor{nodes, lambda, duration_mean}; advisor.make_connection(2, 4); std::vector<edge_t> path; std::tie(path, std::ignore) = advisor.make_connection(1, 3); // 1 -- 0 -- 3 BOOST_CHECK_EQUAL(path.size(), 2); // Only two nodes with two links each nodes = Graph(); boost::add_edge(0, 1, Link(2), nodes); advisor = Advisor{nodes, lambda, duration_mean}; BOOST_CHECK(advisor.has_path_between(0, 1)); advisor.make_connection(0, 1); BOOST_CHECK(advisor.has_path_between(0, 1)); advisor.make_connection(0, 1); BOOST_CHECK(!advisor.has_path_between(0, 1)); } BOOST_AUTO_TEST_CASE(advisor_remove_connection_test) { auto nodes = make_crossing_graph(1); const Event::event_t lambda = 5; const Event::event_t duration_mean = 1; Advisor advisor{nodes, lambda, duration_mean}; std::vector<edge_t> path; Link::wavelength_t wl; // Normal blocking std::tie(path, wl) = advisor.make_connection(0, 4); BOOST_REQUIRE(!advisor.has_path_between(0, 4)); advisor.remove_connection(path, wl); BOOST_CHECK(advisor.has_path_between(0, 4)); std::tie(path, wl) = advisor.make_connection(0, 4); BOOST_REQUIRE(!advisor.has_path_between(0, 4)); advisor.remove_connection(path, wl); BOOST_CHECK(advisor.has_path_between(0, 4)); // Only two nodes with two links each nodes = Graph(); boost::add_edge(0, 1, Link(2), nodes); advisor = Advisor{nodes, lambda, duration_mean}; advisor.make_connection(0, 1); std::tie(path, wl) = advisor.make_connection(0, 1); BOOST_REQUIRE(!advisor.has_path_between(0, 1)); // Removing advisor.remove_connection(path, wl); BOOST_CHECK(advisor.has_path_between(0, 1)); }
26.09465
68
0.620091
[ "vector" ]
64fdd966578d07bf1292fe9ab03d2e86a1b8405a
1,151
hpp
C++
include/lib/Engine/Rendering/Particles.hpp
edisonlee0212/UniEngine
62278ae811235179e6a1c24eb35acf73e400fe28
[ "BSD-3-Clause" ]
22
2020-05-18T02:37:09.000Z
2022-03-13T18:44:30.000Z
include/lib/Engine/Rendering/Particles.hpp
edisonlee0212/UniEngine
62278ae811235179e6a1c24eb35acf73e400fe28
[ "BSD-3-Clause" ]
null
null
null
include/lib/Engine/Rendering/Particles.hpp
edisonlee0212/UniEngine
62278ae811235179e6a1c24eb35acf73e400fe28
[ "BSD-3-Clause" ]
3
2020-12-21T01:21:03.000Z
2021-09-06T08:07:41.000Z
#pragma once #include <Material.hpp> #include <Mesh.hpp> #include <Scene.hpp> namespace UniEngine { class UNIENGINE_API ParticleMatrices : ISerializable{ std::shared_ptr<OpenGLUtils::GLVBO> m_buffer; bool m_bufferReady = false; friend class Mesh; friend class SkinnedMesh; public: ParticleMatrices(); std::vector<glm::mat4> m_value; void Serialize(YAML::Emitter &out) override; void Deserialize(const YAML::Node &in) override; void Update(); }; class UNIENGINE_API Particles : public IPrivateComponent { public: void OnCreate() override; Bound m_boundingBox; bool m_forwardRendering = false; bool m_castShadow = true; bool m_receiveShadow = true; std::shared_ptr<ParticleMatrices> m_matrices; AssetRef m_mesh; AssetRef m_material; void RecalculateBoundingBox(); void OnInspect() override; void Serialize(YAML::Emitter &out) override; void Deserialize(const YAML::Node &in) override; void PostCloneAction(const std::shared_ptr<IPrivateComponent>& target) override; void CollectAssetRef(std::vector<AssetRef> &list) override; }; } // namespace UniEngine
28.073171
84
0.725456
[ "mesh", "vector" ]
8f015d78082610bbb775caab949749a1634df613
1,017
cpp
C++
src/mm/fmm/ubodt_gen_app.cpp
jczaplew/fmm
e325196f355b6c7674d1846401fb14b0d9203301
[ "Apache-2.0" ]
null
null
null
src/mm/fmm/ubodt_gen_app.cpp
jczaplew/fmm
e325196f355b6c7674d1846401fb14b0d9203301
[ "Apache-2.0" ]
null
null
null
src/mm/fmm/ubodt_gen_app.cpp
jczaplew/fmm
e325196f355b6c7674d1846401fb14b0d9203301
[ "Apache-2.0" ]
null
null
null
// // Created by Can Yang on 2020/4/1. // #include "mm/fmm/ubodt_gen_app.hpp" #include "mm/fmm/ubodt_gen_algorithm.hpp" #include "network/network.hpp" #include "network/network_graph.hpp" #include <boost/archive/binary_oarchive.hpp> #include "util/debug.hpp" #include <omp.h> using namespace FMM; using namespace FMM::CORE; using namespace FMM::NETWORK; using namespace FMM::MM; void UBODTGenApp::run() const { std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now(); SPDLOG_INFO("Write UBODT to file {}", config_.result_file); UBODTGenAlgorithm model(network_,ng_); bool binary = config_.is_binary_output(); std::string status = model.generate_ubodt(config_.result_file, config_.delta, binary, config_.use_omp); std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now(); double time_spent = std::chrono::duration_cast<std::chrono::milliseconds> (end - begin).count() / 1000.; SPDLOG_INFO("Time takes {}", time_spent); };
30.818182
79
0.717797
[ "model" ]
5582c8925789b604485aa54bba6148ffd8a8d3be
1,254
cpp
C++
UVA/10226 - Hardwood Species.cpp
knroy/Competitive-Programming
5c03b1f4d15bdd1d4ba30a39464b42a7ded59e29
[ "Apache-2.0" ]
null
null
null
UVA/10226 - Hardwood Species.cpp
knroy/Competitive-Programming
5c03b1f4d15bdd1d4ba30a39464b42a7ded59e29
[ "Apache-2.0" ]
null
null
null
UVA/10226 - Hardwood Species.cpp
knroy/Competitive-Programming
5c03b1f4d15bdd1d4ba30a39464b42a7ded59e29
[ "Apache-2.0" ]
1
2019-08-07T15:26:19.000Z
2019-08-07T15:26:19.000Z
#include <vector> #include <list> #include <map> #include <set> #include <deque> #include <queue> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <cstring> #include <cctype> #define In freopen("In.txt", "r", stdin); #define Out freopen("out.txt", "w", stdout); using namespace std; map <string,double> data; set <string> s; int main() { long int t,i,j; string mystring; char str[35]; scanf("%ld\n\n",&t); for(j=0; j<t; j++) { if(j>0) cout << endl; i = 0; while(gets(str)) { if(str[0]=='\0') break; mystring = str; data[mystring]++; s.insert(mystring); i++; } set <string > :: iterator it; for(it=s.begin(); it!=s.end(); it++) { double sum = (data[*it] * 100.0 )/(double)i; cout << *it << " "; printf("%.4lf\n",sum); } data.clear(); s.clear(); } }
20.9
57
0.485646
[ "vector" ]
5582e7de52940b4b912054fa10538f385a2ea79f
4,099
cpp
C++
src/data/RtElementAccess.cpp
satra/murfi2
95d954a8735c107caae2ab4eec2926fafe420402
[ "Apache-2.0" ]
7
2015-02-10T17:00:49.000Z
2021-07-27T22:09:43.000Z
src/data/RtElementAccess.cpp
satra/murfi2
95d954a8735c107caae2ab4eec2926fafe420402
[ "Apache-2.0" ]
11
2015-02-22T19:15:53.000Z
2021-08-04T17:26:18.000Z
src/data/RtElementAccess.cpp
satra/murfi2
95d954a8735c107caae2ab4eec2926fafe420402
[ "Apache-2.0" ]
8
2015-07-06T22:31:51.000Z
2019-04-22T21:22:07.000Z
/*========================================================================= * RtElementAccess.cpp defines a class that can retreive and set elements in * RtDataImages of double or short template type * * Copyright 2007-2013, the MURFI dev team. * * 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.txt * * 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"RtElementAccess.h" // setup to access elements of this image RtElementAccess::RtElementAccess(RtData *_data) : data(_data), mask(NULL) { if(data == NULL || data->getElementType() == RT_UNKNOWN_TYPE) { // cant return; } // build the indices switch(data->getElementType()) { case RT_DOUBLE_TYPE: buildElementIndices<double>(); break; case RT_SHORT_TYPE: buildElementIndices<short>(); break; default: return; } } // setup to access elements of this image RtElementAccess::RtElementAccess(RtData *_data, RtMaskImage *_mask = NULL) : data(_data), mask(_mask) { } // destructor RtElementAccess::~RtElementAccess() { } // get an element (double) double RtElementAccess::getDoubleElement(unsigned int index) { // get based on type switch(data->getElementType()) { case RT_DOUBLE_TYPE: return static_cast<RtDataImage<double>*>(data)->getElement(index); break; case RT_SHORT_TYPE: return static_cast<RtDataImage<short>*>(data)->getElement(index); break; default: return numeric_limits<double>::quiet_NaN(); } } // get an element (short) short RtElementAccess::getShortElement(unsigned int index) { // get based on type switch(data->getElementType()) { case RT_DOUBLE_TYPE: return static_cast<short>( rint(static_cast<RtDataImage<double>*>(data)->getElement(index))); break; case RT_SHORT_TYPE: return static_cast<RtDataImage<short>*>(data)->getElement(index); break; default: return numeric_limits<short>::quiet_NaN(); } } // set anelement (double) void RtElementAccess::setElement(unsigned int index, double val) { // set based on type switch(data->getElementType()) { case RT_DOUBLE_TYPE: return static_cast<RtDataImage<double>*>(data)->setElement(index, val); break; case RT_SHORT_TYPE: return static_cast<RtDataImage<short>*>(data)->setElement( index, static_cast<short>(rint(val))); break; default: break; } } // set an element (short) void RtElementAccess::setElement(unsigned int index, short val) { // set based on type switch(data->getElementType()) { case RT_DOUBLE_TYPE: return static_cast<RtDataImage<double>*>(data)->setElement(index, val); break; case RT_SHORT_TYPE: return static_cast<RtDataImage<short>*>(data)->setElement(index, val); break; default: break; } } // get the element indices (from mask if there is one) vector<unsigned int> RtElementAccess::getElementIndices() { if(mask == NULL) { return elementIndices; } return mask->getOnVoxelIndices(); } // build the element indices for a particular datatype by finding // non-NaN and non-infinity entries template<class T> void RtElementAccess::buildElementIndices() { // cast the data to the appropriate type RtDataImage<T> *img = static_cast<RtDataImage<T>*>(data); elementIndices.reserve(img->getNumEl()); // go through pixels looking for non-nan entries for(unsigned int i = 0; i < img->getNumEl(); i++) { if(!std::isnan(img->getElement(i))) { elementIndices.push_back(i); } } }
27.326667
77
0.659917
[ "vector" ]
5589f614f3c6a533be13d17a7e118d86df1c15e8
7,810
cpp
C++
source/code/providers/Container_Process_Class_Provider.cpp
DalavanCloud/Docker-Provider
cd7db76c87100205338fe6710425d905e3d9b8d5
[ "MIT" ]
1
2018-09-30T04:46:51.000Z
2018-09-30T04:46:51.000Z
source/code/providers/Container_Process_Class_Provider.cpp
DalavanCloud/Docker-Provider
cd7db76c87100205338fe6710425d905e3d9b8d5
[ "MIT" ]
null
null
null
source/code/providers/Container_Process_Class_Provider.cpp
DalavanCloud/Docker-Provider
cd7db76c87100205338fe6710425d905e3d9b8d5
[ "MIT" ]
null
null
null
/* @migen@ */ #include <MI.h> #include "Container_Process_Class_Provider.h" #include <vector> #include <string> #include <cstdlib> #include <syslog.h> #include <sstream> #include "../cjson/cJSON.h" #include "../dockerapi/DockerRemoteApi.h" #include "../dockerapi/DockerRestHelper.h" using namespace std; MI_BEGIN_NAMESPACE class ContainerProcessQuery { public: /// /// \returns vector of strings parsed based on delimiter /// static vector<string> delimiterParse(const string strToParse, const char delimiterChar) { vector<string> parsedList; stringstream strStream(strToParse); string delmitedStr; while(getline(strStream,delmitedStr,delimiterChar)) { parsedList.push_back(delmitedStr); } return parsedList; } /// /// \returns Object representing process info for each container /// static vector<Container_Process_Class> GetProcessInfoPerContainer() { vector<Container_Process_Class> runningProcessListInstance; // Get computer name string hostname = getDockerHostName(); try { // Request containers vector<string> dockerPsRequest(1, DockerRestHelper::restDockerPsRunning()); vector<cJSON*> dockerPsResponse = getResponse(dockerPsRequest); if (!dockerPsResponse.empty() && dockerPsResponse[0]) { for (int i = 0; i < cJSON_GetArraySize(dockerPsResponse[0]); i++) { cJSON* containerEntry = cJSON_GetArrayItem(dockerPsResponse[0], i); if (containerEntry) { cJSON* objItem = cJSON_GetObjectItem(containerEntry, "Id"); if (objItem != NULL) { if (objItem->valuestring != NULL) { string containerId = string(objItem->valuestring); string containerName; string containerPod; string containerNamespace; // Get container name cJSON* names = cJSON_GetObjectItem(containerEntry, "Names"); if (cJSON_GetArraySize(names)) { containerName = string(cJSON_GetArrayItem(names, 0)->valuestring + 1); vector <string> containerMetaInformation = delimiterParse(containerName, '_'); //only k8 now if (containerMetaInformation[0].find("k8s") != string::npos) { //add namespace pod info containerPod = containerMetaInformation[2]; containerNamespace = containerMetaInformation[3]; } else { containerPod = "None"; containerNamespace = "None"; } } // Request container process info vector<string> dockerTopRequest(1, DockerRestHelper::restDockerTop(containerId)); vector<cJSON*> dockerTopResponse = getResponse(dockerTopRequest); if (!dockerTopResponse.empty() && dockerTopResponse[0]) { //Get process entry cJSON* processArr = cJSON_GetObjectItem(dockerTopResponse[0], "Processes"); if (processArr != NULL) { for (int j = 0; j < cJSON_GetArraySize(processArr); j++) { Container_Process_Class processInstance; cJSON* processEntry = cJSON_GetArrayItem(processArr, j); //process scpecific values if ((processEntry != NULL) && (cJSON_GetArraySize(processEntry) >= 8)) { processInstance.InstanceID_value(containerId.c_str()); cJSON* arrItem = cJSON_GetArrayItem(processEntry, 0); if (arrItem != NULL) { processInstance.Uid_value(arrItem->valuestring); } arrItem = cJSON_GetArrayItem(processEntry, 1); if (arrItem != NULL) { processInstance.PID_value(arrItem->valuestring); } arrItem = cJSON_GetArrayItem(processEntry, 2); if (arrItem != NULL) { processInstance.PPID_value(arrItem->valuestring); } arrItem = cJSON_GetArrayItem(processEntry, 3); if (arrItem != NULL) { processInstance.C_value(arrItem->valuestring); } arrItem = cJSON_GetArrayItem(processEntry, 4); if (arrItem != NULL) { processInstance.STIME_value(arrItem->valuestring); } arrItem = cJSON_GetArrayItem(processEntry, 5); if (arrItem != NULL) { processInstance.Tty_value(arrItem->valuestring); } arrItem = cJSON_GetArrayItem(processEntry, 6); if (arrItem != NULL) { processInstance.TIME_value(arrItem->valuestring); } arrItem = cJSON_GetArrayItem(processEntry, 7); if (arrItem != NULL) { processInstance.Cmd_value(arrItem->valuestring); } //container specific values processInstance.Id_value(containerId.c_str()); processInstance.Name_value(containerName.c_str()); processInstance.Pod_value(containerPod.c_str()); processInstance.Namespace_value(containerNamespace.c_str()); processInstance.Computer_value(hostname.c_str()); } runningProcessListInstance.push_back(processInstance); } } } cJSON_Delete(dockerTopResponse[0]); } } } } } cJSON_Delete(dockerPsResponse[0]); } catch (std::exception &e) { syslog(LOG_ERR, "Container_ContainerProcess - GetProcessInfoPerContainer %s", e.what()); } catch (...) { syslog(LOG_ERR, "Container_ContainerProcess - GetProcessInfoPerContainer - Unknown exception"); } return runningProcessListInstance; } }; Container_Process_Class_Provider::Container_Process_Class_Provider( Module* module) : m_Module(module) { } Container_Process_Class_Provider::~Container_Process_Class_Provider() { } void Container_Process_Class_Provider::Load( Context& context) { context.Post(MI_RESULT_OK); } void Container_Process_Class_Provider::Unload( Context& context) { context.Post(MI_RESULT_OK); } void Container_Process_Class_Provider::EnumerateInstances( Context& context, const String& nameSpace, const PropertySet& propertySet, bool keysOnly, const MI_Filter* filter) { try { vector<Container_Process_Class> queryResult = ContainerProcessQuery::GetProcessInfoPerContainer(); for (unsigned i = 0; i < queryResult.size(); i++) { context.Post(queryResult[i]); } context.Post(MI_RESULT_OK); } catch (std::exception &e) { syslog(LOG_ERR, "Container_Process %s", e.what()); context.Post(MI_RESULT_FAILED); } catch (...) { syslog(LOG_ERR, "Container_Process Unknown exception"); context.Post(MI_RESULT_FAILED); } } void Container_Process_Class_Provider::GetInstance( Context& context, const String& nameSpace, const Container_Process_Class& instanceName, const PropertySet& propertySet) { context.Post(MI_RESULT_NOT_SUPPORTED); } void Container_Process_Class_Provider::CreateInstance( Context& context, const String& nameSpace, const Container_Process_Class& newInstance) { context.Post(MI_RESULT_NOT_SUPPORTED); } void Container_Process_Class_Provider::ModifyInstance( Context& context, const String& nameSpace, const Container_Process_Class& modifiedInstance, const PropertySet& propertySet) { context.Post(MI_RESULT_NOT_SUPPORTED); } void Container_Process_Class_Provider::DeleteInstance( Context& context, const String& nameSpace, const Container_Process_Class& instanceName) { context.Post(MI_RESULT_NOT_SUPPORTED); } MI_END_NAMESPACE
29.360902
106
0.635595
[ "object", "vector" ]
558b5d7ada8f47b02fa990e4db4685e451b219b4
8,472
cpp
C++
src/projects/compute_shader/src/main.cpp
computersarecool/opengl_examples
658196529420dcdded5436ef4a118cb4a3bc9b2c
[ "MIT" ]
8
2020-01-09T13:19:12.000Z
2022-02-10T02:44:21.000Z
src/projects/compute_shader/src/main.cpp
computersarecool/opengl_examples
658196529420dcdded5436ef4a118cb4a3bc9b2c
[ "MIT" ]
null
null
null
src/projects/compute_shader/src/main.cpp
computersarecool/opengl_examples
658196529420dcdded5436ef4a118cb4a3bc9b2c
[ "MIT" ]
1
2021-03-16T03:54:39.000Z
2021-03-16T03:54:39.000Z
// This renders a cube to an FBO then uses a compute shader to invert that image // It uses Image load/store to write the image #include <memory> #include <vector> #include "glm/glm/gtc/matrix_transform.hpp" #include "base_app.h" #include "glsl_program.h" #include "camera.h" // Cube vertices static const GLfloat cube_vertices[]{ // Positions // Normals -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f }; class ComputeShaderExample : public Application { private: GLuint m_cube_vao{ 0 }; GLuint m_full_screen_quad_vao{ 0 }; GLuint m_cube_vbo{ 0 }; GLuint m_src_fbo{ 0 }; GLuint m_color_texture{ 0 }; GLuint m_depth_texture{ 0 }; GLuint m_second_color_texture{ 0 }; Camera m_camera{ glm::vec3{ 0, 0, 5 } }; const GLuint m_vertices_per_cube{ sizeof(cube_vertices) / sizeof(*cube_vertices) }; const int m_number_cubes{ 9 }; const glm::vec3 m_world_up{ glm::vec3{ 0, 1, 0 } }; const std::vector<GLfloat> m_clear_color{ 0.2f, 0.0f, 0.2f, 1.0f }; const GLfloat m_depth_reset_val{ 1.0f }; std::unique_ptr<GlslProgram> m_cube_shader; std::unique_ptr<GlslProgram> m_full_screen_quad_shader; std::unique_ptr<GlslProgram> m_compute_shader; const int m_workgroup_divisor { 32 }; void set_info() override { Application::set_info(); m_info.title = "Compute shader example"; } void load_shaders() { m_cube_shader = std::make_unique<GlslProgram>(GlslProgram::Format().vertex("../assets/shaders/cube.vert").fragment("../assets/shaders/cube.frag")); m_full_screen_quad_shader = std::make_unique<GlslProgram>(GlslProgram::Format().vertex("../assets/shaders/full_screen_quad.vert").fragment("../assets/shaders/full_screen_quad.frag")); m_compute_shader = std::make_unique<GlslProgram>(GlslProgram::Format().compute("../assets/shaders/shader.comp")); } void setup_cube() { // Vertex attribute parameters const GLuint elements_per_face{ 6 }; // Positions const GLuint position_index{ 0 }; const GLenum position_type{ GL_FLOAT }; const GLuint position_size{ 3 }; const GLboolean position_normalize{ GL_FALSE }; const GLuint position_offset_in_buffer{ 0 }; // Normals const GLuint normal_index{ 1 }; const GLuint normal_size{ 3 }; const GLenum normal_type{ GL_FLOAT }; const GLboolean normal_normalize{ GL_FALSE }; const GLuint normal_offset_in_buffer{ sizeof(GLfloat) * position_size }; // Vertex buffer attributes const GLuint binding_index{ 0 }; const GLuint offset{ 0 }; const GLuint element_stride{ sizeof(GLfloat) * elements_per_face }; // Set up VBO and its data store const GLuint flags{ 0 }; glCreateBuffers(1, &m_cube_vbo); glNamedBufferStorage(m_cube_vbo, sizeof(cube_vertices), cube_vertices, flags); // Set up cube VAO glCreateVertexArrays(1, &m_cube_vao); glEnableVertexArrayAttrib(m_cube_vao, position_index); glVertexArrayAttribFormat(m_cube_vao, position_index, position_size, position_type, position_normalize, position_offset_in_buffer); glVertexArrayAttribBinding(m_cube_vao, position_index, binding_index); glEnableVertexArrayAttrib(m_cube_vao, normal_index); glVertexArrayAttribFormat(m_cube_vao, normal_index, normal_size, normal_type, normal_normalize, normal_offset_in_buffer); glVertexArrayAttribBinding(m_cube_vao, normal_index, binding_index); glVertexArrayVertexBuffer(m_cube_vao, binding_index, m_cube_vbo, offset, element_stride); } void setup_textures_and_buffers() { // Create a framebuffer const std::vector<GLenum> draw_buffers{ GL_COLOR_ATTACHMENT0 }; glCreateFramebuffers(1, &m_src_fbo); glNamedFramebufferDrawBuffers(m_src_fbo, 1, draw_buffers.data()); // Create depth texture glCreateTextures(GL_TEXTURE_2D, 1, &m_depth_texture); glTextureStorage2D(m_depth_texture, 1, GL_DEPTH_COMPONENT32F, m_info.window_width, m_info.window_height); glTextureParameteri(m_depth_texture, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTextureParameteri(m_depth_texture, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Create the color texture glCreateTextures(GL_TEXTURE_2D, 1, &m_color_texture); glTextureStorage2D(m_color_texture, 1, GL_RGBA32F, m_info.window_width, m_info.window_height); glTextureParameteri(m_color_texture, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTextureParameteri(m_color_texture, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Create the second color texture glCreateTextures(GL_TEXTURE_2D, 1, &m_second_color_texture); glTextureStorage2D(m_second_color_texture, 1, GL_RGBA32F, m_info.window_width, m_info.window_height); glTextureParameteri(m_second_color_texture, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTextureParameteri(m_second_color_texture, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Attach textures glNamedFramebufferTexture(m_src_fbo, GL_DEPTH_ATTACHMENT, m_depth_texture, 0); glNamedFramebufferTexture(m_src_fbo, GL_COLOR_ATTACHMENT0, m_color_texture, 0); // Set up full screen quad VAO glCreateVertexArrays(1, &m_full_screen_quad_vao); } void setup() override { load_shaders(); setup_cube(); setup_textures_and_buffers(); } void render(double current_time) override { // Draw scene into the src FBO m_cube_shader->use(); glBindVertexArray(m_cube_vao); glBindFramebuffer(GL_FRAMEBUFFER, m_src_fbo); glViewport(0, 0, m_info.window_width, m_info.window_height); glClearBufferfv(GL_COLOR, 0, m_clear_color.data()); glClearBufferfv(GL_DEPTH, 0, &m_depth_reset_val); glEnable(GL_DEPTH_TEST); for (int index{ 0 }; index != m_number_cubes; ++index) { glm::mat4 model_matrix{ glm::mat4{ 1.0 } }; // Numbers here are just to offset each cube model_matrix = glm::translate(model_matrix, glm::vec3{ -1.5, 0, 0 }); model_matrix = glm::translate(model_matrix, glm::vec3{index, static_cast<float>(index) / 5, index * -2 }); model_matrix = glm::rotate(model_matrix, static_cast<GLfloat>(current_time), m_world_up); m_cube_shader->uniform("u_model_view_matrix", m_camera.get_view_matrix() * model_matrix); m_cube_shader->uniform("u_projection_matrix", m_camera.get_proj_matrix()); glDrawArrays(GL_TRIANGLES, 0, m_vertices_per_cube); } // Compute shader m_compute_shader->use(); glBindImageTexture(0, m_color_texture, 0, GL_FALSE, 0, GL_READ_ONLY, GL_RGBA32F); glBindImageTexture(1, m_second_color_texture, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA32F); glDispatchCompute(static_cast<GLuint>(m_info.window_width / m_workgroup_divisor), static_cast<GLuint>(m_info.window_height / m_workgroup_divisor), 1); // Draw full screen quad m_full_screen_quad_shader->use(); glBindVertexArray(m_full_screen_quad_vao); glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0, 0, m_info.window_width, m_info.window_height); glBindTextureUnit(0, m_second_color_texture); glDisable(GL_DEPTH_TEST); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); }; }; int main(int argc, char* argv[]) { std::unique_ptr<Application> app{ new ComputeShaderExample }; app->run(); }
38.334842
185
0.697002
[ "render", "vector" ]
558c511cfc0a80a42ba8d62a342116da7303d499
4,788
hpp
C++
include/CL/sycl/kernel/detail/opencl_kernel.hpp
infinitesnow/InceptionCL
e3d3a6218e551d42dfcead4f121cec294d50d85c
[ "Unlicense" ]
2
2017-10-05T13:13:41.000Z
2019-05-15T19:20:49.000Z
include/CL/sycl/kernel/detail/opencl_kernel.hpp
infinitesnow/InceptionCL
e3d3a6218e551d42dfcead4f121cec294d50d85c
[ "Unlicense" ]
null
null
null
include/CL/sycl/kernel/detail/opencl_kernel.hpp
infinitesnow/InceptionCL
e3d3a6218e551d42dfcead4f121cec294d50d85c
[ "Unlicense" ]
null
null
null
#ifndef TRISYCL_SYCL_KERNEL_DETAIL_OPENCL_KERNEL_HPP #define TRISYCL_SYCL_KERNEL_DETAIL_OPENCL_KERNEL_HPP /** \file The OpenCL SYCL kernel Ronan at Keryell point FR This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details. */ #ifdef TRISYCL_OPENCL #include <boost/compute.hpp> #endif #include "CL/sycl/detail/cache.hpp" #include "CL/sycl/detail/debug.hpp" #include "CL/sycl/detail/unimplemented.hpp" //#include "CL/sycl/info/kernel.hpp" #include "CL/sycl/kernel/detail/kernel.hpp" #include "CL/sycl/queue/detail/queue.hpp" namespace cl { namespace sycl { namespace detail { /// An abstraction of the OpenCL kernel class opencl_kernel : public detail::kernel, detail::debug<opencl_kernel> { /// Use the Boost Compute abstraction of the OpenCL kernel boost::compute::kernel k; /** A cache to always return the same alive kernel for a given OpenCL kernel C++11 guaranties the static construction is thread-safe */ static detail::cache<cl_kernel, detail::opencl_kernel> cache; opencl_kernel(const boost::compute::kernel &k) : k { k } {} public: ///// Get a singleton instance of the opencl_device static std::shared_ptr<opencl_kernel> instance(const boost::compute::kernel &k) { return cache.get_or_register(k.get(), [&] { return new opencl_kernel { k }; }); } /** Return the underlying OpenCL object \todo Improve the spec to deprecate C OpenCL host API and move to C++ instead to avoid this ugly ownership management */ cl_kernel get() const override { /// \todo Test error and throw. Externalize this feature in Boost.Compute? clRetainKernel(k); return k.get(); } /** Return the Boost.Compute OpenCL kernel object for this kernel This is an extension. */ boost::compute::kernel get_boost_compute() const override { return k; } //context get_context() const override //program get_program() const override #if 0 template <info::kernel param> typename info::param_traits<info::kernel, param>::type get_info() const { detail::unimplemented(); } #endif /** Launch a single task of the OpenCL kernel \todo Remove either task or q */ void single_task(std::shared_ptr<detail::task> task, std::shared_ptr<detail::queue> q) override { q->get_boost_compute().enqueue_task(k); /* For now use a crude synchronization mechanism to map directly a host task to an accelerator task */ q->get_boost_compute().finish(); } /** Launch an OpenCL kernel with a range<> Do not use a template since it does not work with virtual functions \todo Think to a cleaner solution \todo Remove either task or q */ #define TRISYCL_ParallelForKernel_RANGE(N) \ void parallel_for(std::shared_ptr<detail::task> task, \ std::shared_ptr<detail::queue> q, \ const range<N> &num_work_items) override { \ static_assert(sizeof(range<N>::value_type) == sizeof(size_t), \ "num_work_items::value_type compatible with " \ "Boost.Compute"); \ q->get_boost_compute().enqueue_nd_range_kernel \ (k, \ static_cast<size_t>(N), \ NULL, \ static_cast<const size_t *>(num_work_items.data()), \ NULL); \ /* For now use a crude synchronization mechanism to map directly a \ host task to an accelerator task */ \ q->get_boost_compute().finish(); \ }; TRISYCL_ParallelForKernel_RANGE(1) TRISYCL_ParallelForKernel_RANGE(2) TRISYCL_ParallelForKernel_RANGE(3) #undef TRISYCL_ParallelForKernel_RANGE /// Unregister from the cache on destruction ~opencl_kernel() override { cache.remove(k.get()); } }; /* Allocate the cache here but since this is a pure-header library, use a weak symbol so that only one remains when SYCL headers are used in different compilation units of a program */ TRISYCL_WEAK_ATTRIB_PREFIX detail::cache<cl_kernel, detail::opencl_kernel> opencl_kernel::cache TRISYCL_WEAK_ATTRIB_SUFFIX; } } } /* # Some Emacs stuff: ### Local Variables: ### ispell-local-dictionary: "american" ### eval: (flyspell-prog-mode) ### End: */ #endif // TRISYCL_SYCL_KERNEL_DETAIL_OPENCL_KERNEL_HPP
29.925
78
0.620301
[ "object" ]
558f46c9871e1d744461a98f8ce0b66f2d6b8c19
3,231
hpp
C++
src/metaspades/src/common/toolchain/subgraph_utils.hpp
STRIDES-Codes/Exploring-the-Microbiome-
bd29c8c74d8f40a58b63db28815acb4081f20d6b
[ "MIT" ]
null
null
null
src/metaspades/src/common/toolchain/subgraph_utils.hpp
STRIDES-Codes/Exploring-the-Microbiome-
bd29c8c74d8f40a58b63db28815acb4081f20d6b
[ "MIT" ]
null
null
null
src/metaspades/src/common/toolchain/subgraph_utils.hpp
STRIDES-Codes/Exploring-the-Microbiome-
bd29c8c74d8f40a58b63db28815acb4081f20d6b
[ "MIT" ]
2
2021-06-05T07:40:20.000Z
2021-06-05T08:02:58.000Z
//*************************************************************************** //* Copyright (c) 2018 Saint Petersburg State University //* Copyright (c) 2019 University of Warwick //* All Rights Reserved //* See file LICENSE for details. //*************************************************************************** #pragma once #include "assembly_graph/core/graph.hpp" #include "assembly_graph/components/graph_component.hpp" #include "io/graph/gfa_writer.hpp" #include <fstream> namespace toolchain { class ComponentExpander { const debruijn_graph::Graph &g_; bool IsInnerVertex(debruijn_graph::VertexId v, const std::set<debruijn_graph::EdgeId> &edges) const { auto in_f = [&edges](debruijn_graph::EdgeId e) { return edges.count(e); }; return std::any_of(g_.in_begin(v), g_.in_end(v), in_f) && std::any_of(g_.out_begin(v), g_.out_end(v), in_f); } public: explicit ComponentExpander(const debruijn_graph::Graph &g) : g_(g) {} omnigraph::GraphComponent<debruijn_graph::Graph> Expand(const omnigraph::GraphComponent<debruijn_graph::Graph> &component) const { INFO("Expanding component to include incident edges of all 'inner' vertices"); std::set<debruijn_graph::EdgeId> expanded_edges(component.edges()); for (debruijn_graph::VertexId v : component.vertices()) { if (IsInnerVertex(v, component.edges())) { utils::insert_all(expanded_edges, g_.IncidentEdges(v)); } } return omnigraph::GraphComponent<debruijn_graph::Graph>::FromEdges(g_, expanded_edges.begin(), expanded_edges.end()); } private: DECL_LOGGER("ComponentExpander"); }; static bool IsDeadEnd(const debruijn_graph::Graph &g, debruijn_graph::VertexId v) { return g.IncomingEdgeCount(v) * g.OutgoingEdgeCount(v) == 0; } static std::vector<debruijn_graph::EdgeId> CollectDeadEnds(const omnigraph::GraphComponent<debruijn_graph::Graph> &gc, bool canonical_only = true) { const auto &g = gc.g(); std::vector<debruijn_graph::EdgeId> answer; for (debruijn_graph::EdgeId e : gc.edges()) { VERIFY(gc.edges().count(g.conjugate(e))); if (canonical_only && g.conjugate(e) < e) continue; if (IsDeadEnd(g, g.EdgeStart(e)) || IsDeadEnd(g, g.EdgeEnd(e))) { answer.push_back(e); } } return answer; } static void WriteComponentWithDeadends(const omnigraph::GraphComponent<debruijn_graph::Graph> &component, const std::string &prefix, const io::EdgeNamingF<debruijn_graph::Graph> &naming_f) { INFO("Writing GFA to " << prefix << ".gfa") std::ofstream os(prefix + ".gfa"); const auto &g = component.g(); gfa::GFAWriter writer(g, os, naming_f); writer.WriteSegmentsAndLinks(component); INFO("Writing dead-ends to " << prefix << ".deadends") std::ofstream deadends_os(prefix + ".deadends"); for (debruijn_graph::EdgeId e : CollectDeadEnds(component)) { deadends_os << naming_f(g, e) << "\n"; } } }
38.464286
148
0.597957
[ "vector" ]