hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
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
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
a790c61c43f1fa8b82035b8605f11a51d41f37b1
9,253
cpp
C++
ContentTools/PrimitiveMesh.cpp
ZackShrout/HavanaEngine
b8869acfff27e41bd37079716d152c2df9674fe2
[ "Apache-2.0" ]
null
null
null
ContentTools/PrimitiveMesh.cpp
ZackShrout/HavanaEngine
b8869acfff27e41bd37079716d152c2df9674fe2
[ "Apache-2.0" ]
null
null
null
ContentTools/PrimitiveMesh.cpp
ZackShrout/HavanaEngine
b8869acfff27e41bd37079716d152c2df9674fe2
[ "Apache-2.0" ]
null
null
null
#include "PrimitiveMesh.h" #include "Geometry.h" namespace Havana::Tools { namespace { using namespace Math; using namespace DirectX; using primitive_mesh_creator = void(*)(Scene&, const PrimitiveInitInfo& info); void CreatePlane(Scene& scene, const PrimitiveInitInfo& info); void CreateCube(Scene& scene, const PrimitiveInitInfo& info); void CreateUVSphere(Scene& scene, const PrimitiveInitInfo& info); void CreateICOSphere(Scene& scene, const PrimitiveInitInfo& info); void CreateCylinder(Scene& scene, const PrimitiveInitInfo& info); void CreateCapsule(Scene& scene, const PrimitiveInitInfo& info); primitive_mesh_creator creators[] { CreatePlane, CreateCube, CreateUVSphere, CreateICOSphere, CreateCylinder, CreateCapsule }; static_assert(_countof(creators) == PrimitiveMeshType::Count); struct Axis { enum: u32 { x = 0, y = 1, z = 2 }; }; Mesh CreatePlane(const PrimitiveInitInfo& info, u32 horizontalIndex = Axis::x, u32 verticalIndex = Axis::z, bool flipWinding = false, Vec3 offset = { -0.5f, 0.0f, -0.5f }, Vec2 uRange = { 0.0f, 1.0f }, Vec2 vRange = { 0.0f, 1.0f }) { assert(horizontalIndex < 3 && verticalIndex < 3); assert(horizontalIndex != verticalIndex); const u32 horizontalCount{ clamp(info.segments[horizontalIndex], 1u, 10u) }; const u32 verticalCount{ clamp(info.segments[verticalIndex], 1u, 10u) }; const f32 horizontalStep{ 1.0f / horizontalCount }; const f32 verticalStep{ 1.0f / verticalCount }; const f32 uStep{ (uRange.y - uRange.x) / horizontalCount }; const f32 vStep{ (vRange.y - vRange.x) / verticalCount }; Mesh m{}; Utils::vector<Vec2> uvs; for (u32 j{ 0 }; j <= verticalCount; j++) { for (u32 i{ 0 }; i <= horizontalCount; i++) { Vec3 position{ offset }; f32* const as_array{ &position.x }; as_array[horizontalIndex] += i * horizontalStep; as_array[verticalIndex] += j * verticalStep; m.positions.emplace_back(position.x * info.size.x, position.y * info.size.y, position.z * info.size.z); Vec2 uv{ uRange.x, 1.0f - vRange.x }; uv.x += i * uStep; uv.y -= j * vStep; uvs.emplace_back(uv); } } assert(m.positions.size() == (((u64)horizontalCount + 1)*((u64)verticalCount + 1))); const u32 rowLength{ horizontalCount + 1 }; // number of vertices in a row for (u32 j{ 0 }; j < verticalCount; j++) { u32 k{ 0 }; for (u32 i{ k }; i < horizontalCount; i++) { const u32 index[4] { i + j * rowLength, i + (j + 1) * rowLength, (i + 1) + j * rowLength, (i + 1) + (j + 1) * rowLength, }; // Triangle 1 m.rawIndices.emplace_back(index[0]); m.rawIndices.emplace_back(index[flipWinding ? 2 : 1]); m.rawIndices.emplace_back(index[flipWinding ? 1 : 2]); // Triangle 2 m.rawIndices.emplace_back(index[2]); m.rawIndices.emplace_back(index[flipWinding ? 3 : 1]); m.rawIndices.emplace_back(index[flipWinding ? 1 : 3]); } ++k; } const u32 numIndices{ 3 * 2 * horizontalCount * verticalCount }; assert(m.rawIndices.size() == numIndices); m.uvSets.resize(1); for (u32 i{ 0 }; i < numIndices; i++) { m.uvSets[0].emplace_back(uvs[m.rawIndices[i]]); } return m; } Mesh CreateUVSphere(const PrimitiveInitInfo& info) { const u32 phiCount{ clamp(info.segments[Axis::x], 3u, 64u) }; const u32 thetaCount{ clamp(info.segments[Axis::y], 2u, 64u) }; const f32 thetaStep{ pi / thetaCount }; const f32 phiStep{ twoPi / phiCount }; const u32 numVertices{ 2 + phiCount * (thetaCount - 1) }; const u32 numIndices{ 2 * 3 * phiCount + 2 * 3 * phiCount * (thetaCount - 2) }; Mesh m{}; m.name = "uvSphere"; m.positions.resize(numVertices); // Add top vertex u32 c{ 0 }; m.positions[c++] = { 0.0f, info.size.y, 0.0f }; // Add the body of the vertices for (u32 j{ 1 }; j < thetaCount; j++) { const f32 theta{ j * thetaStep }; for (u32 i{ 0 }; i < phiCount; i++) { const f32 phi{ i * phiStep }; m.positions[c++] = { info.size.x * XMScalarSin(theta) * XMScalarCos(phi), info.size.y * XMScalarCos(theta), -info.size.z * XMScalarSin(theta) * XMScalarSin(phi) }; } } // Add bottom vertex m.positions[c++] = { 0.0f, -info.size.y, 0.0f }; assert(numVertices == c); c = 0; m.rawIndices.resize(numIndices); Utils::vector<Vec2> uvs(numIndices); const f32 inverseThetaCount{ 1.0f / thetaCount }; const f32 inversePhiCount{ 1.0f / phiCount }; // Indices for top cap, connecting the north pole to the first ring // UV Coords at the same time for (u32 i{ 0 }; i < (phiCount - 1); i++) { uvs[c] = { (2 * i + 1) * 0.5f * inversePhiCount, 1.0f }; m.rawIndices[c++] = 0; uvs[c] = { i * inversePhiCount, 1.0f - inverseThetaCount }; m.rawIndices[c++] = i + 1; uvs[c] = { (i + 1) * inversePhiCount, 1.0f - inverseThetaCount }; m.rawIndices[c++] = i + 2; } uvs[c] = { 1.0f - 0.5f * inversePhiCount, 1.0f }; m.rawIndices[c++] = 0; uvs[c] = { 1.0f - inversePhiCount, 1.0f - inverseThetaCount }; m.rawIndices[c++] = phiCount; uvs[c] = { 1.0f, 1.0f - inverseThetaCount }; m.rawIndices[c++] = 1; // Indices for the section between the top and bottom rings // UV Coords at the same time for (u32 j{ 0 }; j < (thetaCount - 2); j++) { for (u32 i{ 0 }; i < (phiCount - 1); i++) { const u32 index[4] { 1 + i + j * phiCount, 1 + i + (j + 1) * phiCount, 1 + (i + 1) + (j + 1) * phiCount, 1 + (i + 1) + j * phiCount }; // Triangle 1 uvs[c] = { i * inversePhiCount, 1.0f - (j + 1) * inverseThetaCount }; m.rawIndices[c++] = index[0]; uvs[c] = { i * inversePhiCount, 1.0f - (j + 2) * inverseThetaCount }; m.rawIndices[c++] = index[1]; uvs[c] = { (i + 1) * inversePhiCount, 1.0f - (j + 2) * inverseThetaCount }; m.rawIndices[c++] = index[2]; // Triangle 2 uvs[c] = { i * inversePhiCount, 1.0f - (j + 1) * inverseThetaCount }; m.rawIndices[c++] = index[0]; uvs[c] = { (i + 1) * inversePhiCount, 1.0f - (j + 2) * inverseThetaCount }; m.rawIndices[c++] = index[2]; uvs[c] = { (i + 1) * inversePhiCount, 1.0f - (j + 1) * inverseThetaCount }; m.rawIndices[c++] = index[3]; } const u32 index[4] { phiCount + j * phiCount, phiCount + (j + 1) * phiCount, 1 + (j + 1) * phiCount, 1 + j * phiCount }; // Triangle 1 uvs[c] = { 1.0f - inversePhiCount, 1.0f - (j + 1) * inverseThetaCount }; m.rawIndices[c++] = index[0]; uvs[c] = { 1.0f - inversePhiCount, 1.0f - (j + 2) * inverseThetaCount }; m.rawIndices[c++] = index[1]; uvs[c] = { 1.0f, 1.0f - (j + 2) * inverseThetaCount }; m.rawIndices[c++] = index[2]; // Triangle 2 uvs[c] = { 1.0f - inversePhiCount, 1.0f - (j + 1) * inverseThetaCount }; m.rawIndices[c++] = index[0]; uvs[c] = { 1.0f, 1.0f - (j + 2) * inverseThetaCount }; m.rawIndices[c++] = index[2]; uvs[c] = { 1.0f, 1.0f - (j + 1) * inverseThetaCount }; m.rawIndices[c++] = index[3]; } // Indices for bottom cap, connecting the south pole to the last ring // UV Coords at the same time const u32 southPoleIndex{ (u32)m.positions.size() - 1 }; for (u32 i{ 0 }; i < (phiCount - 1); i++) { uvs[c] = { (2 * i + 1) * 0.5f * inversePhiCount, 0.0f }; m.rawIndices[c++] = southPoleIndex; uvs[c] = { (i + 1) * inversePhiCount, inverseThetaCount }; m.rawIndices[c++] = southPoleIndex - phiCount + i + 1; uvs[c] = { i * inversePhiCount, inverseThetaCount }; m.rawIndices[c++] = southPoleIndex - phiCount + i; } uvs[c] = { 1.0f - 0.5f * inversePhiCount, 0.0f }; m.rawIndices[c++] = southPoleIndex; uvs[c] = { 1.0f, inverseThetaCount }; m.rawIndices[c++] = southPoleIndex - phiCount; uvs[c] = { 1.0f - inversePhiCount, inverseThetaCount }; m.rawIndices[c++] = southPoleIndex - 1; assert(c == numIndices); m.uvSets.emplace_back(uvs); return m; } void CreatePlane(Scene& scene, const PrimitiveInitInfo& info) { LoDGroup lod{}; lod.name = "plane"; lod.meshes.emplace_back(CreatePlane(info)); scene.lodGroups.emplace_back(lod); } void CreateCube(Scene& scene, const PrimitiveInitInfo& info) {} void CreateUVSphere(Scene& scene, const PrimitiveInitInfo& info) { LoDGroup lod{}; lod.name = "uvSphere"; lod.meshes.emplace_back(CreateUVSphere(info)); scene.lodGroups.emplace_back(lod); } void CreateICOSphere(Scene& scene, const PrimitiveInitInfo& info) {} void CreateCylinder(Scene& scene, const PrimitiveInitInfo& info) {} void CreateCapsule(Scene& scene, const PrimitiveInitInfo& info) {} } // anonymous namespace EDITOR_INTERFACE void CreatePrimitiveMesh(SceneData* data, PrimitiveInitInfo* info) { assert(data && info); assert(info->type < PrimitiveMeshType::Count); Scene scene{}; creators[info->type](scene, *info); // TODO: process scene and pack to be sent to the Editor data->settings.calculateNormals = 1; ProcessScene(scene, data->settings); PackData(scene, *data); } }
30.238562
108
0.602832
ZackShrout
0427bd33aa17e82efd3c0f572e58865a8f46b5c5
16,935
cpp
C++
sdl1/cannonball/src/main/frontend/config.cpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
sdl1/cannonball/src/main/frontend/config.cpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
sdl1/cannonball/src/main/frontend/config.cpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
/*************************************************************************** XML Configuration File Handling. Load Settings. Load & Save Hi-Scores. Copyright Chris White. See license.txt for more details. ***************************************************************************/ // see: http://www.boost.org/doc/libs/1_52_0/doc/html/boost_propertytree/tutorial.html #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include <iostream> #include "main.hpp" #include "config.hpp" #include "globals.hpp" #include "setup.hpp" #include "../utils.hpp" #include "engine/ohiscore.hpp" #include "engine/audio/osoundint.hpp" // api change in boost 1.56 #include <boost/version.hpp> #if (BOOST_VERSION >= 105600) typedef boost::property_tree::xml_writer_settings<std::string> xml_writer_settings; #else typedef boost::property_tree::xml_writer_settings<char> xml_writer_settings; #endif Config config; Config::Config(void) { } Config::~Config(void) { } void Config::init() { } using boost::property_tree::ptree; ptree pt_config; void Config::load(const std::string &filename) { // Load XML file and put its contents in property tree. // No namespace qualification is needed, because of Koenig // lookup on the second argument. If reading fails, exception // is thrown. try { read_xml(filename, pt_config, boost::property_tree::xml_parser::trim_whitespace); } catch (std::exception &e) { std::cout << "Error: " << e.what() << "\n"; } // ------------------------------------------------------------------------ // Menu Settings // ------------------------------------------------------------------------ menu.enabled = pt_config.get("menu.enabled", 1); menu.road_scroll_speed = pt_config.get("menu.roadspeed", 50); // ------------------------------------------------------------------------ // Video Settings // ------------------------------------------------------------------------ video.mode = pt_config.get("video.mode", 0); // Video Mode: Default is Windowed video.scale = pt_config.get("video.window.scale", 2); // Video Scale: Default is 2x video.scanlines = pt_config.get("video.scanlines", 0); // Scanlines video.fps = pt_config.get("video.fps", 2); // Default is 60 fps video.fps_count = pt_config.get("video.fps_counter", 0); // FPS Counter video.widescreen = pt_config.get("video.widescreen", 1); // Enable Widescreen Mode video.hires = pt_config.get("video.hires", 0); // Hi-Resolution Mode video.filtering = pt_config.get("video.filtering", 0); // Open GL Filtering Mode set_fps(video.fps); // ------------------------------------------------------------------------ // Sound Settings // ------------------------------------------------------------------------ sound.enabled = pt_config.get("sound.enable", 1); sound.advertise = pt_config.get("sound.advertise", 1); sound.preview = pt_config.get("sound.preview", 1); sound.fix_samples = pt_config.get("sound.fix_samples", 1); // Custom Music for (int i = 0; i < 4; i++) { std::string xmltag = "sound.custom_music.track"; xmltag += Utils::to_string(i+1); sound.custom_music[i].enabled = pt_config.get(xmltag + ".<xmlattr>.enabled", 0); sound.custom_music[i].title = pt_config.get(xmltag + ".title", "TRACK " +Utils::to_string(i+1)); sound.custom_music[i].filename= pt_config.get(xmltag + ".filename", "track"+Utils::to_string(i+1)+".wav"); } // ------------------------------------------------------------------------ // CannonBoard Settings // ------------------------------------------------------------------------ cannonboard.enabled = pt_config.get("cannonboard.<xmlattr>.enabled", 0); cannonboard.port = pt_config.get("cannonboard.port", "COM6"); cannonboard.baud = pt_config.get("cannonboard.baud", 57600); cannonboard.debug = pt_config.get("cannonboard.debug", 0); cannonboard.cabinet = pt_config.get("cannonboard.cabinet", 0); // ------------------------------------------------------------------------ // Controls // ------------------------------------------------------------------------ controls.gear = pt_config.get("controls.gear", 0); controls.steer_speed = pt_config.get("controls.steerspeed", 3); controls.pedal_speed = pt_config.get("controls.pedalspeed", 4); controls.keyconfig[0] = pt_config.get("controls.keyconfig.up", 273); controls.keyconfig[1] = pt_config.get("controls.keyconfig.down", 274); controls.keyconfig[2] = pt_config.get("controls.keyconfig.left", 276); controls.keyconfig[3] = pt_config.get("controls.keyconfig.right", 275); controls.keyconfig[4] = pt_config.get("controls.keyconfig.acc", 122); controls.keyconfig[5] = pt_config.get("controls.keyconfig.brake", 120); controls.keyconfig[6] = pt_config.get("controls.keyconfig.gear1", 32); controls.keyconfig[7] = pt_config.get("controls.keyconfig.gear2", 32); controls.keyconfig[8] = pt_config.get("controls.keyconfig.start", 49); controls.keyconfig[9] = pt_config.get("controls.keyconfig.coin", 53); controls.keyconfig[10] = pt_config.get("controls.keyconfig.menu", 286); controls.keyconfig[11] = pt_config.get("controls.keyconfig.view", 304); controls.padconfig[0] = pt_config.get("controls.padconfig.acc", 0); controls.padconfig[1] = pt_config.get("controls.padconfig.brake", 1); controls.padconfig[2] = pt_config.get("controls.padconfig.gear1", 2); controls.padconfig[3] = pt_config.get("controls.padconfig.gear2", 2); controls.padconfig[4] = pt_config.get("controls.padconfig.start", 3); controls.padconfig[5] = pt_config.get("controls.padconfig.coin", 4); controls.padconfig[6] = pt_config.get("controls.padconfig.menu", 5); controls.padconfig[7] = pt_config.get("controls.padconfig.view", 6); controls.analog = pt_config.get("controls.analog.<xmlattr>.enabled", 0); controls.pad_id = pt_config.get("controls.pad_id", 0); controls.axis[0] = pt_config.get("controls.analog.axis.wheel", 0); controls.axis[1] = pt_config.get("controls.analog.axis.accel", 2); controls.axis[2] = pt_config.get("controls.analog.axis.brake", 3); controls.asettings[0] = pt_config.get("controls.analog.wheel.zone", 75); controls.asettings[1] = pt_config.get("controls.analog.wheel.dead", 0); controls.asettings[2] = pt_config.get("controls.analog.pedals.dead", 0); controls.haptic = pt_config.get("controls.analog.haptic.<xmlattr>.enabled", 0); controls.max_force = pt_config.get("controls.analog.haptic.max_force", 9000); controls.min_force = pt_config.get("controls.analog.haptic.min_force", 8500); controls.force_duration= pt_config.get("controls.analog.haptic.force_duration", 20); // ------------------------------------------------------------------------ // Engine Settings // ------------------------------------------------------------------------ engine.dip_time = pt_config.get("engine.time", 0); engine.dip_traffic = pt_config.get("engine.traffic", 1); engine.freeze_timer = engine.dip_time == 4; engine.disable_traffic = engine.dip_traffic == 4; engine.dip_time &= 3; engine.dip_traffic &= 3; engine.freeplay = pt_config.get("engine.freeplay", 0) != 0; engine.jap = pt_config.get("engine.japanese_tracks", 0); engine.prototype = pt_config.get("engine.prototype", 0); // Additional Level Objects engine.level_objects = pt_config.get("engine.levelobjects", 1); engine.randomgen = pt_config.get("engine.randomgen", 1); engine.fix_bugs_backup = engine.fix_bugs = pt_config.get("engine.fix_bugs", 1) != 0; engine.fix_timer = pt_config.get("engine.fix_timer", 0) != 0; engine.layout_debug = pt_config.get("engine.layout_debug", 0) != 0; engine.new_attract = pt_config.get("engine.new_attract", 1) != 0; // ------------------------------------------------------------------------ // Time Trial Mode // ------------------------------------------------------------------------ ttrial.laps = pt_config.get("time_trial.laps", 5); ttrial.traffic = pt_config.get("time_trial.traffic", 3); cont_traffic = pt_config.get("continuous.traffic", 3); } bool Config::save(const std::string &filename) { // Save stuff pt_config.put("video.mode", video.mode); pt_config.put("video.window.scale", video.scale); pt_config.put("video.scanlines", video.scanlines); pt_config.put("video.fps", video.fps); pt_config.put("video.widescreen", video.widescreen); pt_config.put("video.hires", video.hires); pt_config.put("sound.enable", sound.enabled); pt_config.put("sound.advertise", sound.advertise); pt_config.put("sound.preview", sound.preview); pt_config.put("sound.fix_samples", sound.fix_samples); pt_config.put("controls.gear", controls.gear); pt_config.put("controls.steerspeed", controls.steer_speed); pt_config.put("controls.pedalspeed", controls.pedal_speed); pt_config.put("controls.keyconfig.up", controls.keyconfig[0]); pt_config.put("controls.keyconfig.down", controls.keyconfig[1]); pt_config.put("controls.keyconfig.left", controls.keyconfig[2]); pt_config.put("controls.keyconfig.right", controls.keyconfig[3]); pt_config.put("controls.keyconfig.acc", controls.keyconfig[4]); pt_config.put("controls.keyconfig.brake", controls.keyconfig[5]); pt_config.put("controls.keyconfig.gear1", controls.keyconfig[6]); pt_config.put("controls.keyconfig.gear2", controls.keyconfig[7]); pt_config.put("controls.keyconfig.start", controls.keyconfig[8]); pt_config.put("controls.keyconfig.coin", controls.keyconfig[9]); pt_config.put("controls.keyconfig.menu", controls.keyconfig[10]); pt_config.put("controls.keyconfig.view", controls.keyconfig[11]); pt_config.put("controls.padconfig.acc", controls.padconfig[0]); pt_config.put("controls.padconfig.brake", controls.padconfig[1]); pt_config.put("controls.padconfig.gear1", controls.padconfig[2]); pt_config.put("controls.padconfig.gear2", controls.padconfig[3]); pt_config.put("controls.padconfig.start", controls.padconfig[4]); pt_config.put("controls.padconfig.coin", controls.padconfig[5]); pt_config.put("controls.padconfig.menu", controls.padconfig[6]); pt_config.put("controls.padconfig.view", controls.padconfig[7]); pt_config.put("controls.analog.<xmlattr>.enabled", controls.analog); pt_config.put("engine.time", engine.freeze_timer ? 4 : engine.dip_time); pt_config.put("engine.traffic", engine.disable_traffic ? 4 : engine.dip_traffic); pt_config.put("engine.japanese_tracks", engine.jap); pt_config.put("engine.prototype", engine.prototype); pt_config.put("engine.levelobjects", engine.level_objects); pt_config.put("engine.new_attract", engine.new_attract); pt_config.put("time_trial.laps", ttrial.laps); pt_config.put("time_trial.traffic", ttrial.traffic); pt_config.put("continuous.traffic", cont_traffic), ttrial.laps = pt_config.get("time_trial.laps", 5); ttrial.traffic = pt_config.get("time_trial.traffic", 3); cont_traffic = pt_config.get("continuous.traffic", 3); try { write_xml(filename, pt_config, std::locale(), xml_writer_settings('\t', 1)); // Tab space 1 } catch (std::exception &e) { std::cout << "Error saving config: " << e.what() << "\n"; return false; } return true; } void Config::load_scores(const std::string &filename) { // Create empty property tree object ptree pt; try { read_xml(engine.jap ? filename + "_jap.xml" : filename + ".xml" , pt, boost::property_tree::xml_parser::trim_whitespace); } catch (std::exception &e) { e.what(); return; } // Game Scores for (int i = 0; i < ohiscore.NO_SCORES; i++) { score_entry* e = &ohiscore.scores[i]; std::string xmltag = "score"; xmltag += Utils::to_string(i); e->score = Utils::from_hex_string(pt.get<std::string>(xmltag + ".score", "0")); e->initial1 = pt.get(xmltag + ".initial1", ".")[0]; e->initial2 = pt.get(xmltag + ".initial2", ".")[0]; e->initial3 = pt.get(xmltag + ".initial3", ".")[0]; e->maptiles = Utils::from_hex_string(pt.get<std::string>(xmltag + ".maptiles", "20202020")); e->time = Utils::from_hex_string(pt.get<std::string>(xmltag + ".time" , "0")); if (e->initial1 == '.') e->initial1 = 0x20; if (e->initial2 == '.') e->initial2 = 0x20; if (e->initial3 == '.') e->initial3 = 0x20; } } void Config::save_scores(const std::string &filename) { // Create empty property tree object ptree pt; for (int i = 0; i < ohiscore.NO_SCORES; i++) { score_entry* e = &ohiscore.scores[i]; std::string xmltag = "score"; xmltag += Utils::to_string(i); pt.put(xmltag + ".score", Utils::to_hex_string(e->score)); pt.put(xmltag + ".initial1", e->initial1 == 0x20 ? "." : Utils::to_string((char) e->initial1)); // use . to represent space pt.put(xmltag + ".initial2", e->initial2 == 0x20 ? "." : Utils::to_string((char) e->initial2)); pt.put(xmltag + ".initial3", e->initial3 == 0x20 ? "." : Utils::to_string((char) e->initial3)); pt.put(xmltag + ".maptiles", Utils::to_hex_string(e->maptiles)); pt.put(xmltag + ".time", Utils::to_hex_string(e->time)); } try { write_xml(engine.jap ? filename + "_jap.xml" : filename + ".xml", pt, std::locale(), xml_writer_settings('\t', 1)); // Tab space 1 } catch (std::exception &e) { std::cout << "Error saving hiscores: " << e.what() << "\n"; } } void Config::load_tiletrial_scores() { const std::string filename = FILENAME_TTRIAL; // Counter value that represents 1m 15s 0ms static const uint16_t COUNTER_1M_15 = 0x11D0; // Create empty property tree object ptree pt; try { read_xml(engine.jap ? filename + "_jap.xml" : filename + ".xml" , pt, boost::property_tree::xml_parser::trim_whitespace); } catch (std::exception &e) { for (int i = 0; i < 15; i++) ttrial.best_times[i] = COUNTER_1M_15; e.what(); return; } // Time Trial Scores for (int i = 0; i < 15; i++) { ttrial.best_times[i] = pt.get("time_trial.score" + Utils::to_string(i), COUNTER_1M_15); } } void Config::save_tiletrial_scores() { const std::string filename = FILENAME_TTRIAL; // Create empty property tree object ptree pt; // Time Trial Scores for (int i = 0; i < 15; i++) { pt.put("time_trial.score" + Utils::to_string(i), ttrial.best_times[i]); } try { write_xml(engine.jap ? filename + "_jap.xml" : filename + ".xml", pt, std::locale(), xml_writer_settings('\t', 1)); // Tab space 1 } catch (std::exception &e) { std::cout << "Error saving hiscores: " << e.what() << "\n"; } } bool Config::clear_scores() { // Init Default Hiscores ohiscore.init_def_scores(); int clear = 0; // Remove XML files if they exist clear += remove(std::string(FILENAME_SCORES).append(".xml").c_str()); clear += remove(std::string(FILENAME_SCORES).append("_jap.xml").c_str()); clear += remove(std::string(FILENAME_TTRIAL).append(".xml").c_str()); clear += remove(std::string(FILENAME_TTRIAL).append("_jap.xml").c_str()); clear += remove(std::string(FILENAME_CONT).append(".xml").c_str()); clear += remove(std::string(FILENAME_CONT).append("_jap.xml").c_str()); // remove returns 0 on success return clear == 6; } void Config::set_fps(int fps) { video.fps = fps; // Set core FPS to 30fps or 60fps this->fps = video.fps == 0 ? 30 : 60; // Original game ticks sprites at 30fps but background scroll at 60fps tick_fps = video.fps < 2 ? 30 : 60; cannonball::frame_ms = 1000.0 / this->fps; #ifdef COMPILE_SOUND_CODE if (config.sound.enabled) cannonball::audio.stop_audio(); osoundint.init(); if (config.sound.enabled) cannonball::audio.start_audio(); #endif }
40.611511
138
0.58943
pdpdds
042848ffe5b2e29b9dc50d6529d6a156b34354cd
5,428
cc
C++
chrome/browser/ui/tabs/tab_strip_model_stats_recorder.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/browser/ui/tabs/tab_strip_model_stats_recorder.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
chrome/browser/ui/tabs/tab_strip_model_stats_recorder.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/tabs/tab_strip_model_stats_recorder.h" #include <algorithm> #include <utility> #include "base/check.h" #include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "base/notreached.h" #include "base/supports_user_data.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" TabStripModelStatsRecorder::TabStripModelStatsRecorder() : browser_tab_strip_tracker_(this, nullptr) { browser_tab_strip_tracker_.Init(); } TabStripModelStatsRecorder::~TabStripModelStatsRecorder() { } class TabStripModelStatsRecorder::TabInfo : public base::SupportsUserData::Data { public: ~TabInfo() override; void UpdateState(TabState new_state); TabState state() const { return current_state_; } static TabInfo* Get(content::WebContents* contents) { TabInfo* info = static_cast<TabStripModelStatsRecorder::TabInfo*>( contents->GetUserData(kKey)); if (!info) { info = new TabInfo(); contents->SetUserData(kKey, base::WrapUnique(info)); } return info; } private: TabState current_state_ = TabState::INITIAL; static const char kKey[]; }; const char TabStripModelStatsRecorder::TabInfo::kKey[] = "WebContents TabInfo"; TabStripModelStatsRecorder::TabInfo::~TabInfo() {} void TabStripModelStatsRecorder::TabInfo::UpdateState(TabState new_state) { if (new_state == current_state_) return; // Avoid state transition from CLOSED. // When tab is closed, we receive TabStripModelObserver::TabClosingAt and then // TabStripModelStatsRecorder::ActiveTabChanged. // Here we ignore CLOSED -> INACTIVE state transition from last // ActiveTabChanged. if (current_state_ == TabState::CLOSED) return; switch (current_state_) { case TabState::INITIAL: break; case TabState::ACTIVE: UMA_HISTOGRAM_ENUMERATION("Tabs.StateTransfer.Target_Active", static_cast<int>(new_state), static_cast<int>(TabState::MAX)); break; case TabState::INACTIVE: UMA_HISTOGRAM_ENUMERATION("Tabs.StateTransfer.Target_Inactive", static_cast<int>(new_state), static_cast<int>(TabState::MAX)); break; case TabState::CLOSED: case TabState::MAX: NOTREACHED(); break; } current_state_ = new_state; } void TabStripModelStatsRecorder::OnTabClosing(content::WebContents* contents) { TabInfo::Get(contents)->UpdateState(TabState::CLOSED); // Avoid having stale pointer in active_tab_history_ std::replace(active_tab_history_.begin(), active_tab_history_.end(), contents, static_cast<content::WebContents*>(nullptr)); } void TabStripModelStatsRecorder::OnActiveTabChanged( content::WebContents* old_contents, content::WebContents* new_contents, int reason) { if (reason & TabStripModelObserver::CHANGE_REASON_REPLACED) { // We already handled tab clobber at TabReplacedAt notification. return; } if (old_contents) TabInfo::Get(old_contents)->UpdateState(TabState::INACTIVE); DCHECK(new_contents); TabInfo* tab_info = TabInfo::Get(new_contents); bool was_inactive = tab_info->state() == TabState::INACTIVE; tab_info->UpdateState(TabState::ACTIVE); // A UMA Histogram must be bounded by some number. // We chose 64 as our bound as 99.5% of the users open <64 tabs. const int kMaxTabHistory = 64; auto it = std::find(active_tab_history_.cbegin(), active_tab_history_.cend(), new_contents); int age = (it != active_tab_history_.cend()) ? (it - active_tab_history_.cbegin()) : (kMaxTabHistory - 1); if (was_inactive) { UMA_HISTOGRAM_ENUMERATION( "Tabs.StateTransfer.NumberOfOtherTabsActivatedBeforeMadeActive", std::min(age, kMaxTabHistory - 1), kMaxTabHistory); } active_tab_history_.insert(active_tab_history_.begin(), new_contents); if (active_tab_history_.size() > kMaxTabHistory) active_tab_history_.resize(kMaxTabHistory); } void TabStripModelStatsRecorder::OnTabReplaced( content::WebContents* old_contents, content::WebContents* new_contents) { DCHECK(old_contents != new_contents); *TabInfo::Get(new_contents) = *TabInfo::Get(old_contents); std::replace(active_tab_history_.begin(), active_tab_history_.end(), old_contents, new_contents); } void TabStripModelStatsRecorder::OnTabStripModelChanged( TabStripModel* tab_strip_model, const TabStripModelChange& change, const TabStripSelectionChange& selection) { if (change.type() == TabStripModelChange::kRemoved) { for (const auto& contents : change.GetRemove()->contents) { if (contents.remove_reason == TabStripModelChange::RemoveReason::kDeleted) OnTabClosing(contents.contents); } } else if (change.type() == TabStripModelChange::kReplaced) { auto* replace = change.GetReplace(); OnTabReplaced(replace->old_contents, replace->new_contents); } if (!selection.active_tab_changed() || tab_strip_model->empty()) return; OnActiveTabChanged(selection.old_contents, selection.new_contents, selection.reason); }
33.300613
80
0.713707
zealoussnow
042c8582ce7be8f2c9d239da2727d8384847d5b2
22,847
cpp
C++
src/protocol/Connection.cpp
garrettr/ricochet
a22c729b3e912794a8af65879ed1b38573385657
[ "OpenSSL" ]
3,461
2015-01-01T09:44:50.000Z
2022-03-26T06:24:41.000Z
src/protocol/Connection.cpp
infocoms/Ricochet-DarkMode
0d3513965aac61f0af10369d05fc3a8cfa6f6d1c
[ "BSD-3-Clause" ]
498
2015-01-02T07:32:06.000Z
2022-01-22T16:44:07.000Z
src/protocol/Connection.cpp
infocoms/Ricochet-DarkMode
0d3513965aac61f0af10369d05fc3a8cfa6f6d1c
[ "BSD-3-Clause" ]
447
2015-01-08T01:19:39.000Z
2022-01-27T19:07:39.000Z
/* Ricochet - https://ricochet.im/ * Copyright (C) 2014, John Brooks <john.brooks@dereferenced.net> * * 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 names of the copyright owners 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. */ #include "Connection_p.h" #include "ControlChannel.h" #include "utils/Useful.h" #include <QTcpSocket> #include <QTimer> #include <QtEndian> #include <QDebug> using namespace Protocol; Connection::Connection(QTcpSocket *socket, Direction direction) : QObject() , d(new ConnectionPrivate(this)) { d->setSocket(socket, direction); } ConnectionPrivate::ConnectionPrivate(Connection *qq) : QObject(qq) , q(qq) , socket(0) , direction(Connection::ClientSide) , purpose(Connection::Purpose::Unknown) , wasClosed(false) , handshakeDone(false) , nextOutboundChannelId(-1) { ageTimer.start(); QTimer *timeout = new QTimer(this); timeout->setSingleShot(true); timeout->setInterval(UnknownPurposeTimeout * 1000); connect(timeout, &QTimer::timeout, this, [this,timeout]() { if (purpose == Connection::Purpose::Unknown) { qDebug() << "Closing connection" << q << "with unknown purpose after timeout"; q->close(); } timeout->deleteLater(); } ); timeout->start(); } Connection::~Connection() { qDebug() << this << "Destroying connection"; // When we call closeImmediately, the list of channels will be cleared. // In the normal case, they will all use deleteLater to be freed at the // next event loop. Since the connection is being destructed immediately, // and we want to be certain that channels don't outlive it, copy the // list before it's cleared and delete them immediately afterwards. auto channels = d->channels; d->closeImmediately(); // These would be deleted by QObject ownership as well, but we want to // give them a chance to destruct before the connection d pointer is reset. foreach (Channel *c, channels) delete c; // Reset d pointer, so we'll crash nicely if anything tries to call // into Connection after this. d = 0; } ConnectionPrivate::~ConnectionPrivate() { // Reset q pointer, for the same reason as above q = 0; } Connection::Direction Connection::direction() const { return d->direction; } bool Connection::isConnected() const { bool re = d->socket && d->socket->state() == QAbstractSocket::ConnectedState; if (d->wasClosed) { Q_ASSERT(!re); } return re; } QString Connection::serverHostname() const { QString hostname; if (direction() == ClientSide) hostname = d->socket->peerName(); else if (direction() == ServerSide) hostname = d->socket->property("localHostname").toString(); if (!hostname.endsWith(QStringLiteral(".onion"))) { BUG() << "Connection does not have a valid server hostname:" << hostname; return QString(); } return hostname; } int Connection::age() const { return qRound(d->ageTimer.elapsed() / 1000.0); } void ConnectionPrivate::setSocket(QTcpSocket *s, Connection::Direction d) { if (socket) { BUG() << "Connection already has a socket"; return; } socket = s; direction = d; connect(socket, &QAbstractSocket::disconnected, this, &ConnectionPrivate::socketDisconnected); connect(socket, &QIODevice::readyRead, this, &ConnectionPrivate::socketReadable); socket->setParent(q); if (socket->state() != QAbstractSocket::ConnectedState) { BUG() << "Connection created with socket in a non-connected state" << socket->state(); } Channel *control = new ControlChannel(direction == Connection::ClientSide ? Channel::Outbound : Channel::Inbound, q); // Closing the control channel must also close the connection connect(control, &Channel::invalidated, q, &Connection::close); insertChannel(control); if (!control->isOpened() || control->identifier() != 0 || q->channel(0) != control) { BUG() << "Control channel on new connection is not set up properly"; q->close(); return; } if (direction == Connection::ClientSide) { // The server side is implicitly authenticated (by the transport) as the correct service, so grant that QString serverName = q->serverHostname(); if (serverName.isEmpty()) { BUG() << "Server side of connection doesn't have an authenticated name, aborting"; q->close(); return; } q->grantAuthentication(Connection::HiddenServiceAuth, serverName); // Send the introduction version handshake message char intro[] = { 0x49, 0x4D, 0x02, ProtocolVersion, 0 }; if (socket->write(intro, sizeof(intro)) < (int)sizeof(intro)) { qDebug() << "Failed writing introduction message to socket"; q->close(); return; } } } void Connection::close() { if (isConnected()) { Q_ASSERT(!d->wasClosed); qDebug() << "Disconnecting socket for connection" << this; d->socket->disconnectFromHost(); // If not fully closed in 5 seconds, abort QTimer *timeout = new QTimer(this); timeout->setSingleShot(true); connect(timeout, &QTimer::timeout, d, &ConnectionPrivate::closeImmediately); timeout->start(5000); } } void ConnectionPrivate::closeImmediately() { if (socket) socket->abort(); if (!wasClosed) { BUG() << "Socket was forcefully closed but never emitted closed signal"; wasClosed = true; emit q->closed(); } if (!channels.isEmpty()) { foreach (Channel *c, channels) qDebug() << "Open channel:" << c << c->type() << c->connection(); BUG() << "Channels remain open after forcefully closing connection socket"; } } void ConnectionPrivate::socketDisconnected() { qDebug() << "Connection" << this << "disconnected"; closeAllChannels(); if (!wasClosed) { wasClosed = true; emit q->closed(); } } void ConnectionPrivate::socketReadable() { if (!handshakeDone) { qint64 available = socket->bytesAvailable(); if (direction == Connection::ClientSide && available >= 1) { // Expecting a single byte in response with the chosen version uchar version = ProtocolVersionFailed; if (socket->read(reinterpret_cast<char*>(&version), 1) < 1) { qDebug() << "Connection socket error" << socket->error() << "during read:" << socket->errorString(); socket->abort(); return; } handshakeDone = true; if (version == 0) { qDebug() << "Server in outbound connection is using the version 1.0 protocol"; emit q->oldVersionNegotiated(socket); q->close(); return; } else if (version != ProtocolVersion) { qDebug() << "Version negotiation failed on outbound connection"; emit q->versionNegotiationFailed(); socket->abort(); return; } else emit q->ready(); } else if (direction == Connection::ServerSide && available >= 3) { // Expecting at least 3 bytes uchar intro[3] = { 0 }; qint64 re = socket->peek(reinterpret_cast<char*>(intro), sizeof(intro)); if (re < (int)sizeof(intro)) { qDebug() << "Connection socket error" << socket->error() << "during read:" << socket->errorString(); socket->abort(); return; } quint8 nVersions = intro[2]; if (intro[0] != 0x49 || intro[1] != 0x4D || nVersions == 0) { qDebug() << "Invalid introduction sequence on inbound connection"; socket->abort(); return; } if (available < (qint64)sizeof(intro) + nVersions) return; // Discard intro header re = socket->read(reinterpret_cast<char*>(intro), sizeof(intro)); QByteArray versions(nVersions, 0); re = socket->read(versions.data(), versions.size()); if (re != versions.size()) { qDebug() << "Connection socket error" << socket->error() << "during read:" << socket->errorString(); socket->abort(); return; } quint8 selectedVersion = ProtocolVersionFailed; foreach (quint8 v, versions) { if (v == ProtocolVersion) { selectedVersion = v; break; } } re = socket->write(reinterpret_cast<char*>(&selectedVersion), 1); if (re != 1) { qDebug() << "Connection socket error" << socket->error() << "during write:" << socket->errorString(); socket->abort(); return; } handshakeDone = true; if (selectedVersion != ProtocolVersion) { qDebug() << "Version negotiation failed on inbound connection"; emit q->versionNegotiationFailed(); // Close gracefully to allow the response to write q->close(); return; } else emit q->ready(); } else { return; } } qint64 available; while ((available = socket->bytesAvailable()) >= PacketHeaderSize) { uchar header[PacketHeaderSize]; // Peek at the header first, to read the size of the packet and make sure // the entire thing is available within the buffer. qint64 re = socket->peek(reinterpret_cast<char*>(header), PacketHeaderSize); if (re < 0) { qDebug() << "Connection socket error" << socket->error() << "during read:" << socket->errorString(); socket->abort(); return; } else if (re < PacketHeaderSize) { BUG() << "Socket had" << available << "bytes available but peek only returned" << re; return; } Q_STATIC_ASSERT(PacketHeaderSize == 4); quint16 packetSize = qFromBigEndian<quint16>(header); quint16 channelId = qFromBigEndian<quint16>(&header[2]); if (packetSize < PacketHeaderSize) { qWarning() << "Corrupted data from connection (packet size is too small); disconnecting"; socket->abort(); return; } if (packetSize > available) break; // Read header out of the buffer and discard re = socket->read(reinterpret_cast<char*>(header), PacketHeaderSize); if (re != PacketHeaderSize) { if (re < 0) { qDebug() << "Connection socket error" << socket->error() << "during read:" << socket->errorString(); } else { // Because of QTcpSocket buffering, we can expect that up to 'available' bytes // will read. Treat anything less as an error condition. BUG() << "Socket read was unexpectedly small;" << available << "bytes should've been available but we read" << re; } socket->abort(); return; } // Read data QByteArray data(packetSize - PacketHeaderSize, 0); re = (data.size() == 0) ? 0 : socket->read(data.data(), data.size()); if (re != data.size()) { if (re < 0) { qDebug() << "Connection socket error" << socket->error() << "during read:" << socket->errorString(); } else { // As above BUG() << "Socket read was unexpectedly small;" << available << "bytes should've been available but we read" << re; } socket->abort(); return; } Channel *channel = q->channel(channelId); if (!channel) { // XXX We should sanity-check and rate limit these responses better if (data.isEmpty()) { qDebug() << "Ignoring channel close message for non-existent channel" << channelId; } else { qDebug() << "Ignoring" << data.size() << "byte packet for non-existent channel" << channelId; // Send channel close message writePacket(channelId, QByteArray()); } continue; } if (channel->connection() != q) { // If this fails, something is extremely broken. It may be dangerous to continue // processing any data at all. Crash gracefully. BUG() << "Channel" << channelId << "found on connection" << this << "but its connection is" << channel->connection(); qFatal("Connection mismatch while handling packet"); return; } if (data.isEmpty()) { channel->closeChannel(); } else { channel->receivePacket(data); } } } bool ConnectionPrivate::writePacket(Channel *channel, const QByteArray &data) { if (channel->connection() != q) { // As above, dangerously broken, crash the process to avoid damage BUG() << "Writing packet for channel" << channel->identifier() << "on connection" << this << "but its connection is" << channel->connection(); qFatal("Connection mismatch while writing packet"); return false; } return writePacket(channel->identifier(), data); } bool ConnectionPrivate::writePacket(int channelId, const QByteArray &data) { if (channelId < 0 || channelId > UINT16_MAX) { BUG() << "Cannot write packet for channel with invalid identifier" << channelId; return false; } if (data.size() > PacketMaxDataSize) { BUG() << "Cannot write oversized packet of" << data.size() << "bytes to channel" << channelId; return false; } if (!q->isConnected()) { qDebug() << "Cannot write packet to closed connection"; return false; } Q_STATIC_ASSERT(PacketHeaderSize + PacketMaxDataSize <= UINT16_MAX); Q_STATIC_ASSERT(PacketHeaderSize == 4); uchar header[PacketHeaderSize] = { 0 }; qToBigEndian(static_cast<quint16>(PacketHeaderSize + data.size()), header); qToBigEndian(static_cast<quint16>(channelId), &header[2]); qint64 re = socket->write(reinterpret_cast<char*>(header), PacketHeaderSize); if (re != PacketHeaderSize) { qDebug() << "Connection socket error" << socket->error() << "during write:" << socket->errorString(); socket->abort(); return false; } re = socket->write(data); if (re != data.size()) { qDebug() << "Connection socket error" << socket->error() << "during write:" << socket->errorString(); socket->abort(); return false; } return true; } int ConnectionPrivate::availableOutboundChannelId() { // Server opens even-nubmered channels, client opens odd-numbered bool evenNumbered = (direction == Connection::ServerSide); const int minId = evenNumbered ? 2 : 1; const int maxId = evenNumbered ? (UINT16_MAX-1) : UINT16_MAX; if (nextOutboundChannelId < minId || nextOutboundChannelId > maxId) nextOutboundChannelId = minId; // Find an unused id, trying a maximum of 100 times, using a random step to avoid collision for (int i = 0; i < 100 && channels.contains(nextOutboundChannelId); i++) { nextOutboundChannelId += 1 + (qrand() % 200); if (evenNumbered) nextOutboundChannelId += nextOutboundChannelId % 2; if (nextOutboundChannelId > maxId) nextOutboundChannelId = minId; } if (channels.contains(nextOutboundChannelId)) { // Abort the connection if we still couldn't find an id, because it's probably a nasty bug BUG() << "Can't find an available outbound channel ID for connection; aborting connection"; socket->abort(); return -1; } if (nextOutboundChannelId < minId || nextOutboundChannelId > maxId) { BUG() << "Selected a channel id that isn't within range"; return -1; } if (evenNumbered == bool(nextOutboundChannelId % 2)) { BUG() << "Selected a channel id that isn't valid for this side of the connection"; return -1; } int re = nextOutboundChannelId; nextOutboundChannelId += 2; return re; } bool ConnectionPrivate::isValidAvailableChannelId(int id, Connection::Direction side) { if (id < 1 || id > UINT16_MAX) return false; bool evenNumbered = bool(id % 2); if (evenNumbered == (side == Connection::ServerSide)) return false; if (channels.contains(id)) return false; return true; } bool ConnectionPrivate::insertChannel(Channel *channel) { if (channel->connection() != q) { BUG() << "Connection tried to insert a channel assigned to a different connection"; return false; } if (channel->identifier() < 0) { BUG() << "Connection tried to insert a channel without a valid identifier"; return false; } if (channels.contains(channel->identifier())) { BUG() << "Connection tried to insert a channel with a duplicate id" << channel->identifier() << "- we have" << channels.value(channel->identifier()) << "and inserted" << channel; return false; } if (channel->parent() != q) { BUG() << "Connection inserted a channel without expected parent object. Fixing."; channel->setParent(q); } channels.insert(channel->identifier(), channel); return true; } void ConnectionPrivate::removeChannel(Channel *channel) { if (channel->connection() != q) { BUG() << "Connection tried to remove a channel assigned to a different connection"; return; } // Out of caution, find the channel by pointer instead of identifier. This will make sure // it's always removed from the list, even if the identifier was somehow reset or lost. for (auto it = channels.begin(); it != channels.end(); ) { if (*it == channel) it = channels.erase(it); else it++; } } void ConnectionPrivate::closeAllChannels() { // Takes a copy, won't be broken by removeChannel calls foreach (Channel *channel, channels) channel->closeChannel(); if (!channels.isEmpty()) BUG() << "Channels remain open on connection after calling closeAllChannels"; } QHash<int,Channel*> Connection::channels() { return d->channels; } Channel *Connection::channel(int identifier) { return d->channels.value(identifier); } Connection::Purpose Connection::purpose() const { return d->purpose; } bool Connection::setPurpose(Purpose value) { if (d->purpose == value) return true; switch (value) { case Purpose::Unknown: BUG() << "A connection can't reset to unknown purpose"; return false; case Purpose::KnownContact: if (!hasAuthenticated(HiddenServiceAuth)) { BUG() << "Connection purpose cannot be KnownContact without authenticating a service"; return false; } break; case Purpose::OutboundRequest: if (d->direction != ClientSide) { BUG() << "Connection purpose cannot be OutboundRequest on an inbound connection"; return false; } else if (d->purpose != Purpose::Unknown) { BUG() << "Connection purpose cannot change from" << int(d->purpose) << "to OutboundRequest"; return false; } break; case Purpose::InboundRequest: if (d->direction != ServerSide) { BUG() << "Connection purpose cannot be InboundRequest on an outbound connection"; return false; } else if (d->purpose != Purpose::Unknown) { BUG() << "Connection purpose cannot change from" << int(d->purpose) << "to InboundRequest"; return false; } break; default: BUG() << "Purpose type" << int(value) << "is not defined"; return false; } Purpose old = d->purpose; d->purpose = value; emit purposeChanged(d->purpose, old); return true; } bool Connection::hasAuthenticated(AuthenticationType type) const { return d->authentication.contains(type); } bool Connection::hasAuthenticatedAs(AuthenticationType type, const QString &identity) const { auto it = d->authentication.find(type); if (!identity.isEmpty() && it != d->authentication.end()) return *it == identity; return false; } QString Connection::authenticatedIdentity(AuthenticationType type) const { return d->authentication.value(type); } void Connection::grantAuthentication(AuthenticationType type, const QString &identity) { if (hasAuthenticated(type)) { BUG() << "Tried to redundantly grant" << type << "authentication to connection"; return; } qDebug() << "Granting" << type << "authentication as" << identity << "to connection"; d->authentication.insert(type, identity); emit authenticated(type, identity); }
34.616667
130
0.600823
garrettr
042c9dc2cd0d2405799a6e5b0ca994ce53a07029
1,136
hpp
C++
src/ui/Font.hpp
PegasusEpsilon/Barony
6311f7e5da4835eaea65a95b5cc258409bb0dfa4
[ "FTL", "Zlib", "MIT" ]
null
null
null
src/ui/Font.hpp
PegasusEpsilon/Barony
6311f7e5da4835eaea65a95b5cc258409bb0dfa4
[ "FTL", "Zlib", "MIT" ]
null
null
null
src/ui/Font.hpp
PegasusEpsilon/Barony
6311f7e5da4835eaea65a95b5cc258409bb0dfa4
[ "FTL", "Zlib", "MIT" ]
null
null
null
//! @file Font.hpp #pragma once #include "../main.hpp" class Font { private: Font() = default; Font(const char* _name); Font(const Font&) = delete; Font(Font&&) = delete; virtual ~Font(); Font& operator=(const Font&) = delete; Font& operator=(Font&&) = delete; public: //! built-in font static const char* defaultFont; const char* getName() const { return name.c_str(); } TTF_Font* getTTF() { return font; } //! get the size of the given text string in pixels //! @param str the utf-8 string to get the size of //! @param out_w the integer to hold the width //! @param out_h the integer to hold the height //! @return 0 on success, non-zero on error int sizeText(const char* str, int* out_w, int* out_h) const; //! get the height of the font //! @return the font height in pixels int height() const; //! get a Font object from the engine //! @param name The Font name //! @return the Font or nullptr if it could not be retrieved static Font* get(const char* name); //! dump engine's font cache static void dumpCache(); private: std::string name; TTF_Font* font = nullptr; int pointSize = 16; };
23.666667
61
0.672535
PegasusEpsilon
042cf49955f381c33af736b13f3712813964bf1c
876
cc
C++
apps/solve.cc
CS126SP20/sudoku-hecht3
a7f6a453eb7be8782167418c8c64dc293d1e3a8c
[ "MIT" ]
null
null
null
apps/solve.cc
CS126SP20/sudoku-hecht3
a7f6a453eb7be8782167418c8c64dc293d1e3a8c
[ "MIT" ]
null
null
null
apps/solve.cc
CS126SP20/sudoku-hecht3
a7f6a453eb7be8782167418c8c64dc293d1e3a8c
[ "MIT" ]
null
null
null
// Copyright (c) 2020 [Your Name]. All rights reserved. #include <sudoku/sudoku_parser.h> #include <iostream> #include <fstream> void HandleFile(std::string puzzle); int main(int argc, char** argv) { // There is always at least 1 argument -- the name of the program which we // don't care about if (argc == 1) { std::cout << "Please input a file " << std::endl; std::string file; std::cin >> file; HandleFile(file); } else { for (int i = 1; i < argc; i++) { HandleFile(argv[i]); } } } void HandleFile(std::string puzzle) { std::ifstream puzzle_stream(puzzle); if (puzzle_stream.fail()) { std::cout << "\nInvalid file" << std::endl; } else { sudoku_parser parser; std::istream& input_stream = puzzle_stream; std::ostream& output_stream = std::cout; input_stream >> parser; output_stream << parser; } }
25.028571
76
0.627854
CS126SP20
042f62b522d5c4e94a3a91d40ff19f6170803aee
329
cpp
C++
1-6-11z.cpp
Kaermor/stepik-course363-cpp
7df3381ee5460565754745b6d48ed3f1324e73ef
[ "Apache-2.0" ]
null
null
null
1-6-11z.cpp
Kaermor/stepik-course363-cpp
7df3381ee5460565754745b6d48ed3f1324e73ef
[ "Apache-2.0" ]
null
null
null
1-6-11z.cpp
Kaermor/stepik-course363-cpp
7df3381ee5460565754745b6d48ed3f1324e73ef
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <cmath> #include <iomanip> using namespace std; int foo_1_6_11z() { double a, b, c, d, e, f, x, y; cin >> a; cin >> b; cin >> c; cin >> d; cin >> e; cin >> f; x = (e*d - b*f) / (d*a - b*c); y = (a*f - e*c) / (d*a - b*c); cout << x << " " << y << endl; }
14.954545
34
0.419453
Kaermor
042f890043cf1be0dcd3612270f70377536110a1
53,038
cpp
C++
src/renderer/editor/terrain_editor.cpp
santaclose/LumixEngine
f163e673d7ebc451c134db8d2fbb55ac38962137
[ "MIT" ]
null
null
null
src/renderer/editor/terrain_editor.cpp
santaclose/LumixEngine
f163e673d7ebc451c134db8d2fbb55ac38962137
[ "MIT" ]
null
null
null
src/renderer/editor/terrain_editor.cpp
santaclose/LumixEngine
f163e673d7ebc451c134db8d2fbb55ac38962137
[ "MIT" ]
null
null
null
#include <imgui/imgui.h> #include "terrain_editor.h" #include "editor/asset_browser.h" #include "editor/asset_compiler.h" #include "editor/entity_folders.h" #include "editor/prefab_system.h" #include "editor/studio_app.h" #include "editor/utils.h" #include "engine/crc32.h" #include "engine/crt.h" #include "engine/engine.h" #include "engine/geometry.h" #include "engine/log.h" #include "engine/os.h" #include "engine/path.h" #include "engine/prefab.h" #include "engine/profiler.h" #include "engine/resource_manager.h" #include "engine/universe.h" #include "physics/physics_scene.h" #include "renderer/culling_system.h" #include "renderer/editor/composite_texture.h" #include "renderer/material.h" #include "renderer/model.h" #include "renderer/render_scene.h" #include "renderer/renderer.h" #include "renderer/terrain.h" #include "renderer/texture.h" #include "stb/stb_image.h" namespace Lumix { static const ComponentType MODEL_INSTANCE_TYPE = reflection::getComponentType("model_instance"); static const ComponentType TERRAIN_TYPE = reflection::getComponentType("terrain"); static const ComponentType HEIGHTFIELD_TYPE = reflection::getComponentType("physical_heightfield"); static const char* HEIGHTMAP_SLOT_NAME = "Heightmap"; static const char* SPLATMAP_SLOT_NAME = "Splatmap"; static const char* DETAIL_ALBEDO_SLOT_NAME = "Detail albedo"; static const char* DETAIL_NORMAL_SLOT_NAME = "Detail normal"; static const float MIN_BRUSH_SIZE = 0.5f; struct PaintTerrainCommand final : IEditorCommand { struct Rectangle { int from_x; int from_y; int to_x; int to_y; }; PaintTerrainCommand(WorldEditor& editor, TerrainEditor::ActionType action_type, u16 grass_mask, u64 textures_mask, const DVec3& hit_pos, const Array<bool>& mask, float radius, float rel_amount, u16 flat_height, Vec3 color, EntityRef terrain, u32 layers_mask, Vec2 fixed_value, bool can_be_merged) : m_world_editor(editor) , m_terrain(terrain) , m_can_be_merged(can_be_merged) , m_new_data(editor.getAllocator()) , m_old_data(editor.getAllocator()) , m_items(editor.getAllocator()) , m_action_type(action_type) , m_textures_mask(textures_mask) , m_grass_mask(grass_mask) , m_mask(editor.getAllocator()) , m_flat_height(flat_height) , m_layers_masks(layers_mask) , m_fixed_value(fixed_value) { m_mask.resize(mask.size()); for (int i = 0; i < mask.size(); ++i) { m_mask[i] = mask[i]; } m_width = m_height = m_x = m_y = -1; Universe& universe = *editor.getUniverse(); const Transform entity_transform = universe.getTransform(terrain).inverted(); RenderScene* scene = (RenderScene*)universe.getScene(TERRAIN_TYPE); DVec3 local_pos = entity_transform.transform(hit_pos); float terrain_size = scene->getTerrainSize(terrain).x; local_pos = local_pos / terrain_size; local_pos.y = -1; Item& item = m_items.emplace(); item.m_local_pos = Vec3(local_pos); item.m_radius = radius / terrain_size; item.m_amount = rel_amount; item.m_color = color; } bool execute() override { if (m_new_data.empty()) { saveOldData(); generateNewData(); } applyData(m_new_data); return true; } void undo() override { applyData(m_old_data); } const char* getType() override { return "paint_terrain"; } bool merge(IEditorCommand& command) override { if (!m_can_be_merged) { return false; } PaintTerrainCommand& my_command = static_cast<PaintTerrainCommand&>(command); if (m_terrain == my_command.m_terrain && m_action_type == my_command.m_action_type && m_textures_mask == my_command.m_textures_mask && m_layers_masks == my_command.m_layers_masks) { my_command.m_items.push(m_items.back()); my_command.resizeData(); my_command.rasterItem(getDestinationTexture(), my_command.m_new_data, m_items.back()); return true; } return false; } private: struct Item { Rectangle getBoundingRectangle(int texture_size) const { Rectangle r; r.from_x = maximum(0, int(texture_size * (m_local_pos.x - m_radius) - 0.5f)); r.from_y = maximum(0, int(texture_size * (m_local_pos.z - m_radius) - 0.5f)); r.to_x = minimum(texture_size, int(texture_size * (m_local_pos.x + m_radius) + 0.5f)); r.to_y = minimum(texture_size, int(texture_size * (m_local_pos.z + m_radius) + 0.5f)); return r; } float m_radius; float m_amount; Vec3 m_local_pos; Vec3 m_color; }; private: Texture* getDestinationTexture() { const char* uniform_name; switch (m_action_type) { case TerrainEditor::REMOVE_GRASS: case TerrainEditor::LAYER: uniform_name = SPLATMAP_SLOT_NAME; break; default: uniform_name = HEIGHTMAP_SLOT_NAME; break; } RenderScene* scene = (RenderScene*)m_world_editor.getUniverse()->getScene(TERRAIN_TYPE); return scene->getTerrainMaterial(m_terrain)->getTextureByName(uniform_name); } u16 computeAverage16(const Texture* texture, int from_x, int to_x, int from_y, int to_y) { ASSERT(texture->format == gpu::TextureFormat::R16); u32 sum = 0; int texture_width = texture->width; for (int i = from_x, end = to_x; i < end; ++i) { for (int j = from_y, end2 = to_y; j < end2; ++j) { sum += ((u16*)texture->getData())[(i + j * texture_width)]; } } return u16(sum / (to_x - from_x) / (to_y - from_y)); } float getAttenuation(Item& item, int i, int j, int texture_size) const { float dist = ((texture_size * item.m_local_pos.x - 0.5f - i) * (texture_size * item.m_local_pos.x - 0.5f - i) + (texture_size * item.m_local_pos.z - 0.5f - j) * (texture_size * item.m_local_pos.z - 0.5f - j)); dist = powf(dist, 4); float max_dist = powf(texture_size * item.m_radius, 8); return 1.0f - minimum(dist / max_dist, 1.0f); } bool isMasked(float x, float y) { if (m_mask.size() == 0) return true; int s = int(sqrtf((float)m_mask.size())); int ix = int(x * s); int iy = int(y * s); return m_mask[int(ix + x * iy)]; } void rasterLayerItem(Texture* texture, Array<u8>& data, Item& item) { int texture_size = texture->width; Rectangle r = item.getBoundingRectangle(texture_size); if (texture->format != gpu::TextureFormat::RGBA8) { ASSERT(false); return; } float fx = 0; float fstepx = 1.0f / (r.to_x - r.from_x); float fstepy = 1.0f / (r.to_y - r.from_y); u8 tex[64]; u32 tex_count = 0; for (u8 i = 0; i < 64; ++i) { if (m_textures_mask & ((u64)1 << i)) { tex[tex_count] = i; ++tex_count; } } if (tex_count == 0) return; for (int i = r.from_x, end = r.to_x; i < end; ++i, fx += fstepx) { float fy = 0; for (int j = r.from_y, end2 = r.to_y; j < end2; ++j, fy += fstepy) { if (!isMasked(fx, fy)) continue; const int offset = 4 * (i - m_x + (j - m_y) * m_width); for (u32 layer = 0; layer < 2; ++layer) { if ((m_layers_masks & (1 << layer)) == 0) continue; const float attenuation = getAttenuation(item, i, j, texture_size); int add = int(attenuation * item.m_amount * 255); if (add <= 0) continue; if (((u64)1 << data[offset]) & m_textures_mask) { if (layer == 1) { if (m_fixed_value.x >= 0) { data[offset + 1] = (u8)clamp(randFloat(m_fixed_value.x, m_fixed_value.y) * 255.f, 0.f, 255.f); } else { data[offset + 1] += minimum(255 - data[offset + 1], add); } } } else { if (layer == 1) { if (m_fixed_value.x >= 0) { data[offset + 1] = (u8)clamp(randFloat(m_fixed_value.x, m_fixed_value.y) * 255.f, 0.f, 255.f); } else { data[offset + 1] = add; } } data[offset] = tex[rand() % tex_count]; } } } } } void rasterGrassItem(Texture* texture, Array<u8>& data, Item& item, bool remove) { int texture_size = texture->width; Rectangle r = item.getBoundingRectangle(texture_size); if (texture->format != gpu::TextureFormat::RGBA8) { ASSERT(false); return; } float fx = 0; float fstepx = 1.0f / (r.to_x - r.from_x); float fstepy = 1.0f / (r.to_y - r.from_y); for (int i = r.from_x, end = r.to_x; i < end; ++i, fx += fstepx) { float fy = 0; for (int j = r.from_y, end2 = r.to_y; j < end2; ++j, fy += fstepy) { if (isMasked(fx, fy)) { int offset = 4 * (i - m_x + (j - m_y) * m_width) + 2; float attenuation = getAttenuation(item, i, j, texture_size); int add = int(attenuation * item.m_amount * 255); if (add > 0) { u16* tmp = ((u16*)&data[offset]); if (remove) { *tmp &= ~m_grass_mask; } else { *tmp |= m_grass_mask; } } } } } } void rasterSmoothHeightItem(Texture* texture, Array<u8>& data, Item& item) { ASSERT(texture->format == gpu::TextureFormat::R16); int texture_size = texture->width; Rectangle rect = item.getBoundingRectangle(texture_size); float avg = computeAverage16(texture, rect.from_x, rect.to_x, rect.from_y, rect.to_y); for (int i = rect.from_x, end = rect.to_x; i < end; ++i) { for (int j = rect.from_y, end2 = rect.to_y; j < end2; ++j) { float attenuation = getAttenuation(item, i, j, texture_size); int offset = i - m_x + (j - m_y) * m_width; u16 x = ((u16*)texture->getData())[(i + j * texture_size)]; x += u16((avg - x) * item.m_amount * attenuation); ((u16*)&data[0])[offset] = x; } } } void rasterFlatHeightItem(Texture* texture, Array<u8>& data, Item& item) { ASSERT(texture->format == gpu::TextureFormat::R16); int texture_size = texture->width; Rectangle rect = item.getBoundingRectangle(texture_size); for (int i = rect.from_x, end = rect.to_x; i < end; ++i) { for (int j = rect.from_y, end2 = rect.to_y; j < end2; ++j) { int offset = i - m_x + (j - m_y) * m_width; float dist = sqrtf( (texture_size * item.m_local_pos.x - 0.5f - i) * (texture_size * item.m_local_pos.x - 0.5f - i) + (texture_size * item.m_local_pos.z - 0.5f - j) * (texture_size * item.m_local_pos.z - 0.5f - j)); float t = (dist - texture_size * item.m_radius * item.m_amount) / (texture_size * item.m_radius * (1 - item.m_amount)); t = clamp(1 - t, 0.0f, 1.0f); u16 old_value = ((u16*)&data[0])[offset]; ((u16*)&data[0])[offset] = (u16)(m_flat_height * t + old_value * (1-t)); } } } void rasterItem(Texture* texture, Array<u8>& data, Item& item) { if (m_action_type == TerrainEditor::LAYER || m_action_type == TerrainEditor::REMOVE_GRASS) { if (m_textures_mask) { rasterLayerItem(texture, data, item); } if (m_grass_mask) { rasterGrassItem(texture, data, item, m_action_type == TerrainEditor::REMOVE_GRASS); } return; } else if (m_action_type == TerrainEditor::SMOOTH_HEIGHT) { rasterSmoothHeightItem(texture, data, item); return; } else if (m_action_type == TerrainEditor::FLAT_HEIGHT) { rasterFlatHeightItem(texture, data, item); return; } ASSERT(texture->format == gpu::TextureFormat::R16); int texture_size = texture->width; Rectangle rect = item.getBoundingRectangle(texture_size); const float STRENGTH_MULTIPLICATOR = 256.0f; float amount = maximum(item.m_amount * item.m_amount * STRENGTH_MULTIPLICATOR, 1.0f); for (int i = rect.from_x, end = rect.to_x; i < end; ++i) { for (int j = rect.from_y, end2 = rect.to_y; j < end2; ++j) { float attenuation = getAttenuation(item, i, j, texture_size); int offset = i - m_x + (j - m_y) * m_width; int add = int(attenuation * amount); u16 x = ((u16*)texture->getData())[(i + j * texture_size)]; x += m_action_type == TerrainEditor::RAISE_HEIGHT ? minimum(add, 0xFFFF - x) : maximum(-add, -x); ((u16*)&data[0])[offset] = x; } } } void generateNewData() { auto texture = getDestinationTexture(); const u32 bpp = gpu::getBytesPerPixel(texture->format); Rectangle rect; getBoundingRectangle(texture, rect); m_new_data.resize(bpp * maximum(1, (rect.to_x - rect.from_x) * (rect.to_y - rect.from_y))); if(m_old_data.size() > 0) { memcpy(&m_new_data[0], &m_old_data[0], m_new_data.size()); } for (int item_index = 0; item_index < m_items.size(); ++item_index) { Item& item = m_items[item_index]; rasterItem(texture, m_new_data, item); } } void saveOldData() { auto texture = getDestinationTexture(); const u32 bpp = gpu::getBytesPerPixel(texture->format); Rectangle rect; getBoundingRectangle(texture, rect); m_x = rect.from_x; m_y = rect.from_y; m_width = rect.to_x - rect.from_x; m_height = rect.to_y - rect.from_y; m_old_data.resize(bpp * (rect.to_x - rect.from_x) * (rect.to_y - rect.from_y)); int index = 0; for (int j = rect.from_y, end2 = rect.to_y; j < end2; ++j) { for (int i = rect.from_x, end = rect.to_x; i < end; ++i) { for (u32 k = 0; k < bpp; ++k) { m_old_data[index] = texture->getData()[(i + j * texture->width) * bpp + k]; ++index; } } } } void applyData(Array<u8>& data) { auto texture = getDestinationTexture(); const u32 bpp = gpu::getBytesPerPixel(texture->format); for (int j = m_y; j < m_y + m_height; ++j) { for (int i = m_x; i < m_x + m_width; ++i) { int index = bpp * (i + j * texture->width); for (u32 k = 0; k < bpp; ++k) { texture->getData()[index + k] = data[bpp * (i - m_x + (j - m_y) * m_width) + k]; } } } texture->onDataUpdated(m_x, m_y, m_width, m_height); if (m_action_type != TerrainEditor::LAYER && m_action_type != TerrainEditor::REMOVE_GRASS) { IScene* scene = m_world_editor.getUniverse()->getScene(crc32("physics")); if (!scene) return; auto* phy_scene = static_cast<PhysicsScene*>(scene); if (!scene->getUniverse().hasComponent(m_terrain, HEIGHTFIELD_TYPE)) return; phy_scene->updateHeighfieldData(m_terrain, m_x, m_y, m_width, m_height, &data[0], bpp); } } void resizeData() { Array<u8> new_data(m_world_editor.getAllocator()); Array<u8> old_data(m_world_editor.getAllocator()); auto texture = getDestinationTexture(); Rectangle rect; getBoundingRectangle(texture, rect); int new_w = rect.to_x - rect.from_x; const u32 bpp = gpu::getBytesPerPixel(texture->format); new_data.resize(bpp * new_w * (rect.to_y - rect.from_y)); old_data.resize(bpp * new_w * (rect.to_y - rect.from_y)); // original for (int row = rect.from_y; row < rect.to_y; ++row) { memcpy(&new_data[(row - rect.from_y) * new_w * bpp], &texture->getData()[row * bpp * texture->width + rect.from_x * bpp], bpp * new_w); memcpy(&old_data[(row - rect.from_y) * new_w * bpp], &texture->getData()[row * bpp * texture->width + rect.from_x * bpp], bpp * new_w); } // new for (int row = 0; row < m_height; ++row) { memcpy(&new_data[((row + m_y - rect.from_y) * new_w + m_x - rect.from_x) * bpp], &m_new_data[row * bpp * m_width], bpp * m_width); memcpy(&old_data[((row + m_y - rect.from_y) * new_w + m_x - rect.from_x) * bpp], &m_old_data[row * bpp * m_width], bpp * m_width); } m_x = rect.from_x; m_y = rect.from_y; m_height = rect.to_y - rect.from_y; m_width = rect.to_x - rect.from_x; m_new_data.swap(new_data); m_old_data.swap(old_data); } void getBoundingRectangle(Texture* texture, Rectangle& rect) { int s = texture->width; Item& item = m_items[0]; rect.from_x = maximum(int(s * (item.m_local_pos.x - item.m_radius) - 0.5f), 0); rect.from_y = maximum(int(s * (item.m_local_pos.z - item.m_radius) - 0.5f), 0); rect.to_x = minimum(1 + int(s * (item.m_local_pos.x + item.m_radius) + 0.5f), texture->width); rect.to_y = minimum(1 + int(s * (item.m_local_pos.z + item.m_radius) + 0.5f), texture->height); for (int i = 1; i < m_items.size(); ++i) { Item& item = m_items[i]; rect.from_x = minimum(int(s * (item.m_local_pos.x - item.m_radius) - 0.5f), rect.from_x); rect.to_x = maximum(1 + int(s * (item.m_local_pos.x + item.m_radius) + 0.5f), rect.to_x); rect.from_y = minimum(int(s * (item.m_local_pos.z - item.m_radius) - 0.5f), rect.from_y); rect.to_y = maximum(1 + int(s * (item.m_local_pos.z + item.m_radius) + 0.5f), rect.to_y); } rect.from_x = maximum(rect.from_x, 0); rect.to_x = minimum(rect.to_x, texture->width); rect.from_y = maximum(rect.from_y, 0); rect.to_y = minimum(rect.to_y, texture->height); } private: WorldEditor& m_world_editor; Array<u8> m_new_data; Array<u8> m_old_data; u64 m_textures_mask; u16 m_grass_mask; int m_width; int m_height; int m_x; int m_y; TerrainEditor::ActionType m_action_type; Array<Item> m_items; EntityRef m_terrain; Array<bool> m_mask; u16 m_flat_height; u32 m_layers_masks; Vec2 m_fixed_value; bool m_can_be_merged; }; TerrainEditor::~TerrainEditor() { m_app.removeAction(&m_smooth_terrain_action); m_app.removeAction(&m_lower_terrain_action); m_app.removeAction(&m_remove_grass_action); m_app.removeAction(&m_remove_entity_action); if (m_brush_texture) { m_brush_texture->destroy(); LUMIX_DELETE(m_app.getAllocator(), m_brush_texture); } m_app.removePlugin(*this); } TerrainEditor::TerrainEditor(StudioApp& app) : m_app(app) , m_color(1, 1, 1) , m_current_brush(0) , m_selected_prefabs(app.getAllocator()) , m_brush_mask(app.getAllocator()) , m_brush_texture(nullptr) , m_flat_height(0) , m_is_enabled(false) , m_size_spread(1, 1) , m_y_spread(0, 0) , m_albedo_composite(app.getAllocator()) { m_smooth_terrain_action.init("Smooth terrain", "Terrain editor - smooth", "smoothTerrain", "", false); m_lower_terrain_action.init("Lower terrain", "Terrain editor - lower", "lowerTerrain", "", false); m_remove_grass_action.init("Remove grass from terrain", "Terrain editor - remove grass", "removeGrassFromTerrain", "", false); m_remove_entity_action.init("Remove entities from terrain", "Terrain editor - remove entities", "removeEntitiesFromTerrain", "", false); app.addAction(&m_smooth_terrain_action); app.addAction(&m_lower_terrain_action); app.addAction(&m_remove_grass_action); app.addAction(&m_remove_entity_action); app.addPlugin(*this); m_terrain_brush_size = 10; m_terrain_brush_strength = 0.1f; m_textures_mask = 0b1; m_layers_mask = 0b1; m_grass_mask = 1; m_is_align_with_normal = false; m_is_rotate_x = false; m_is_rotate_y = false; m_is_rotate_z = false; m_rotate_x_spread = m_rotate_y_spread = m_rotate_z_spread = Vec2(0, PI * 2); } void TerrainEditor::increaseBrushSize() { if (m_terrain_brush_size < 10) { ++m_terrain_brush_size; return; } m_terrain_brush_size = minimum(100.0f, m_terrain_brush_size + 10); } void TerrainEditor::decreaseBrushSize() { if (m_terrain_brush_size < 10) { m_terrain_brush_size = maximum(MIN_BRUSH_SIZE, m_terrain_brush_size - 1.0f); return; } m_terrain_brush_size = maximum(MIN_BRUSH_SIZE, m_terrain_brush_size - 10.0f); } void TerrainEditor::drawCursor(RenderScene& scene, EntityRef entity, const DVec3& center) const { PROFILE_FUNCTION(); Terrain* terrain = scene.getTerrain(entity); constexpr int SLICE_COUNT = 30; constexpr float angle_step = PI * 2 / SLICE_COUNT; if (m_mode == Mode::HEIGHT && m_is_flat_height && ImGui::GetIO().KeyCtrl) { scene.addDebugCross(center, 1.0f, 0xff0000ff); return; } float brush_size = m_terrain_brush_size; const Vec3 local_center = Vec3(getRelativePosition(center, entity, scene.getUniverse())); const Transform terrain_transform = scene.getUniverse().getTransform(entity); for (int i = 0; i < SLICE_COUNT + 1; ++i) { const float angle = i * angle_step; const float next_angle = i * angle_step + angle_step; Vec3 local_from = local_center + Vec3(cosf(angle), 0, sinf(angle)) * brush_size; local_from.y = terrain->getHeight(local_from.x, local_from.z); local_from.y += 0.25f; Vec3 local_to = local_center + Vec3(cosf(next_angle), 0, sinf(next_angle)) * brush_size; local_to.y = terrain->getHeight(local_to.x, local_to.z); local_to.y += 0.25f; const DVec3 from = terrain_transform.transform(local_from); const DVec3 to = terrain_transform.transform(local_to); scene.addDebugLine(from, to, 0xffff0000); } const Vec3 rel_pos = Vec3(terrain_transform.inverted().transform(center)); const i32 w = terrain->getWidth(); const i32 h = terrain->getHeight(); const float scale = terrain->getXZScale(); const IVec3 p = IVec3(rel_pos / scale); const i32 half_extents = i32(1 + brush_size / scale); for (i32 j = p.z - half_extents; j <= p.z + half_extents; ++j) { for (i32 i = p.x - half_extents; i <= p.x + half_extents; ++i) { DVec3 p00(i * scale, 0, j * scale); DVec3 p10((i + 1) * scale, 0, j * scale); DVec3 p11((i + 1) * scale, 0, (j + 1) * scale); DVec3 p01(i * scale, 0, (j + 1) * scale); p00.y = terrain->getHeight(i, j); p10.y = terrain->getHeight(i + 1, j); p11.y = terrain->getHeight(i + 1, j + 1); p01.y = terrain->getHeight(i, j + 1); p00 = terrain_transform.transform(p00); p10 = terrain_transform.transform(p10); p01 = terrain_transform.transform(p01); p11 = terrain_transform.transform(p11); scene.addDebugLine(p10, p01, 0xff800000); scene.addDebugLine(p10, p11, 0xff800000); scene.addDebugLine(p00, p10, 0xff800000); scene.addDebugLine(p01, p11, 0xff800000); scene.addDebugLine(p00, p01, 0xff800000); } } } DVec3 TerrainEditor::getRelativePosition(const DVec3& world_pos, EntityRef terrain, Universe& universe) const { const Transform transform = universe.getTransform(terrain); const Transform inv_transform = transform.inverted(); return inv_transform.transform(world_pos); } u16 TerrainEditor::getHeight(const DVec3& world_pos, RenderScene* scene, EntityRef terrain) const { const DVec3 rel_pos = getRelativePosition(world_pos, terrain, scene->getUniverse()); ComponentUID cmp; cmp.entity = terrain; cmp.scene = scene; cmp.type = TERRAIN_TYPE; Texture* heightmap = getMaterial(cmp)->getTextureByName(HEIGHTMAP_SLOT_NAME); if (!heightmap) return 0; u16* data = (u16*)heightmap->getData(); float scale = scene->getTerrainXZScale(terrain); return data[int(rel_pos.x / scale) + int(rel_pos.z / scale) * heightmap->width]; } bool TerrainEditor::onMouseDown(UniverseView& view, int x, int y) { if (!m_is_enabled) return false; WorldEditor& editor = view.getEditor(); const Array<EntityRef>& selected_entities = editor.getSelectedEntities(); if (selected_entities.size() != 1) return false; Universe& universe = *editor.getUniverse(); bool is_terrain = universe.hasComponent(selected_entities[0], TERRAIN_TYPE); if (!is_terrain) return false; RenderScene* scene = (RenderScene*)universe.getScene(TERRAIN_TYPE); DVec3 origin; Vec3 dir; view.getViewport().getRay({(float)x, (float)y}, origin, dir); const RayCastModelHit hit = scene->castRayTerrain(selected_entities[0], origin, dir); if (!hit.is_hit) return false; const DVec3 hit_pos = hit.origin + hit.dir * hit.t; switch(m_mode) { case Mode::ENTITY: if (m_remove_entity_action.isActive()) { removeEntities(hit_pos, editor); } else { paintEntities(hit_pos, editor, selected_entities[0]); } break; case Mode::HEIGHT: if (m_is_flat_height) { if (ImGui::GetIO().KeyCtrl) { m_flat_height = getHeight(hit_pos, scene, selected_entities[0]); } else { paint(hit_pos, TerrainEditor::FLAT_HEIGHT, false, selected_entities[0], editor); } } else { TerrainEditor::ActionType action = TerrainEditor::RAISE_HEIGHT; if (m_lower_terrain_action.isActive()) { action = TerrainEditor::LOWER_HEIGHT; } else if (m_smooth_terrain_action.isActive()) { action = TerrainEditor::SMOOTH_HEIGHT; } paint(hit_pos, action, false, selected_entities[0], editor); break; } break; case Mode::LAYER: TerrainEditor::ActionType action = TerrainEditor::LAYER; if (m_remove_grass_action.isActive()) { action = TerrainEditor::REMOVE_GRASS; } paint(hit_pos, action, false, selected_entities[0], editor); break; } return true; } static void getProjections(const Vec3& axis, const Vec3 vertices[8], float& min, float& max) { max = dot(vertices[0], axis); min = max; for(int i = 1; i < 8; ++i) { float d = dot(vertices[i], axis); min = minimum(d, min); max = maximum(d, max); } } static bool overlaps(float min1, float max1, float min2, float max2) { return (min1 <= min2 && min2 <= max1) || (min2 <= min1 && min1 <= max2); } static bool testOBBCollision(const AABB& a, const Matrix& mtx_b, const AABB& b) { Vec3 box_a_points[8]; Vec3 box_b_points[8]; a.getCorners(Matrix::IDENTITY, box_a_points); b.getCorners(mtx_b, box_b_points); const Vec3 normals[] = {Vec3(1, 0, 0), Vec3(0, 1, 0), Vec3(0, 0, 1)}; for(int i = 0; i < 3; i++) { float box_a_min, box_a_max, box_b_min, box_b_max; getProjections(normals[i], box_a_points, box_a_min, box_a_max); getProjections(normals[i], box_b_points, box_b_min, box_b_max); if(!overlaps(box_a_min, box_a_max, box_b_min, box_b_max)) { return false; } } Vec3 normals_b[] = { normalize(mtx_b.getXVector()), normalize(mtx_b.getYVector()), normalize(mtx_b.getZVector())}; for(int i = 0; i < 3; i++) { float box_a_min, box_a_max, box_b_min, box_b_max; getProjections(normals_b[i], box_a_points, box_a_min, box_a_max); getProjections(normals_b[i], box_b_points, box_b_min, box_b_max); if(!overlaps(box_a_min, box_a_max, box_b_min, box_b_max)) { return false; } } return true; } void TerrainEditor::removeEntities(const DVec3& hit_pos, WorldEditor& editor) const { if (m_selected_prefabs.empty()) return; PrefabSystem& prefab_system = editor.getPrefabSystem(); PROFILE_FUNCTION(); Universe& universe = *editor.getUniverse(); RenderScene* scene = static_cast<RenderScene*>(universe.getScene(TERRAIN_TYPE)); ShiftedFrustum frustum; frustum.computeOrtho(hit_pos, Vec3(0, 0, 1), Vec3(0, 1, 0), m_terrain_brush_size, m_terrain_brush_size, -m_terrain_brush_size, m_terrain_brush_size); const AABB brush_aabb(Vec3(-m_terrain_brush_size), Vec3(m_terrain_brush_size)); CullResult* meshes = scene->getRenderables(frustum, RenderableTypes::MESH); if(meshes) { meshes->merge(scene->getRenderables(frustum, RenderableTypes::MESH_GROUP)); } else { meshes = scene->getRenderables(frustum, RenderableTypes::MESH_GROUP); } if(meshes) { meshes->merge(scene->getRenderables(frustum, RenderableTypes::MESH_MATERIAL_OVERRIDE)); } else { meshes = scene->getRenderables(frustum, RenderableTypes::MESH_MATERIAL_OVERRIDE); } if(!meshes) return; editor.beginCommandGroup("remove_entities"); if (m_selected_prefabs.empty()) { meshes->forEach([&](EntityRef entity){ if (prefab_system.getPrefab(entity) == 0) return; const Model* model = scene->getModelInstanceModel(entity); const AABB entity_aabb = model ? model->getAABB() : AABB(Vec3::ZERO, Vec3::ZERO); const bool collide = testOBBCollision(brush_aabb, universe.getRelativeMatrix(entity, hit_pos), entity_aabb); if (collide) editor.destroyEntities(&entity, 1); }); } else { meshes->forEach([&](EntityRef entity){ for (auto* res : m_selected_prefabs) { if ((prefab_system.getPrefab(entity) & 0xffffFFFF) == res->getPath().getHash()) { const Model* model = scene->getModelInstanceModel(entity); const AABB entity_aabb = model ? model->getAABB() : AABB(Vec3::ZERO, Vec3::ZERO); const bool collide = testOBBCollision(brush_aabb, universe.getRelativeMatrix(entity, hit_pos), entity_aabb); if (collide) editor.destroyEntities(&entity, 1); } } }); } editor.endCommandGroup(); meshes->free(scene->getEngine().getPageAllocator()); } static bool isOBBCollision(RenderScene& scene, const CullResult* meshes, const Transform& model_tr, Model* model, bool ignore_not_in_folder, const EntityFolders& folders, EntityFolders::FolderID folder) { float radius_a_squared = model->getOriginBoundingRadius() * model_tr.scale; radius_a_squared = radius_a_squared * radius_a_squared; Universe& universe = scene.getUniverse(); Span<const ModelInstance> model_instances = scene.getModelInstances(); const Transform* transforms = universe.getTransforms(); while(meshes) { const EntityRef* entities = meshes->entities; for (u32 i = 0, c = meshes->header.count; i < c; ++i) { const EntityRef mesh = entities[i]; // we resolve collisions when painting by removing recently added mesh, but we do not refresh `meshes` // so it can contain invalid entities if (!universe.hasEntity(mesh)) continue; const ModelInstance& model_instance = model_instances[mesh.index]; const Transform& tr_b = transforms[mesh.index]; const float radius_b = model_instance.model->getOriginBoundingRadius() * tr_b.scale; const float radius_squared = radius_a_squared + radius_b * radius_b; if (squaredLength(model_tr.pos - tr_b.pos) < radius_squared) { const Transform rel_tr = model_tr.inverted() * tr_b; Matrix mtx = rel_tr.rot.toMatrix(); mtx.multiply3x3(rel_tr.scale); mtx.setTranslation(Vec3(rel_tr.pos)); if (testOBBCollision(model->getAABB(), mtx, model_instance.model->getAABB())) { if (ignore_not_in_folder && folders.getFolder(EntityRef{mesh.index}) != folder) { continue; } return true; } } } meshes = meshes->header.next; } return false; } static bool areAllReady(Span<PrefabResource*> prefabs) { for (PrefabResource* p : prefabs) if (!p->isReady()) return false; return true; } void TerrainEditor::paintEntities(const DVec3& hit_pos, WorldEditor& editor, EntityRef terrain) const { PROFILE_FUNCTION(); if (m_selected_prefabs.empty()) return; if (!areAllReady(m_selected_prefabs)) return; auto& prefab_system = editor.getPrefabSystem(); editor.beginCommandGroup("paint_entities"); { Universe& universe = *editor.getUniverse(); RenderScene* scene = static_cast<RenderScene*>(universe.getScene(TERRAIN_TYPE)); const Transform terrain_tr = universe.getTransform(terrain); const Transform inv_terrain_tr = terrain_tr.inverted(); ShiftedFrustum frustum; frustum.computeOrtho(hit_pos, Vec3(0, 0, 1), Vec3(0, 1, 0), m_terrain_brush_size, m_terrain_brush_size, -m_terrain_brush_size, m_terrain_brush_size); CullResult* meshes = scene->getRenderables(frustum, RenderableTypes::MESH); if (meshes) meshes->merge(scene->getRenderables(frustum, RenderableTypes::MESH_GROUP)); else meshes = scene->getRenderables(frustum, RenderableTypes::MESH_GROUP); if (meshes) meshes->merge(scene->getRenderables(frustum, RenderableTypes::MESH_MATERIAL_OVERRIDE)); else meshes = scene->getRenderables(frustum, RenderableTypes::MESH_MATERIAL_OVERRIDE); const EntityFolders& folders = editor.getEntityFolders(); const EntityFolders::FolderID folder = folders.getSelectedFolder(); Vec2 size = scene->getTerrainSize(terrain); float scale = 1.0f - maximum(0.01f, m_terrain_brush_strength); for (int i = 0; i <= m_terrain_brush_size * m_terrain_brush_size / 100.0f * m_terrain_brush_strength; ++i) { const float angle = randFloat(0, PI * 2); const float dist = randFloat(0, 1.0f) * m_terrain_brush_size; const float y = randFloat(m_y_spread.x, m_y_spread.y); DVec3 pos(hit_pos.x + cosf(angle) * dist, 0, hit_pos.z + sinf(angle) * dist); const Vec3 terrain_pos = Vec3(inv_terrain_tr.transform(pos)); if (terrain_pos.x >= 0 && terrain_pos.z >= 0 && terrain_pos.x <= size.x && terrain_pos.z <= size.y) { pos.y = scene->getTerrainHeightAt(terrain, terrain_pos.x, terrain_pos.z) + y; pos.y += terrain_tr.pos.y; Quat rot(0, 0, 0, 1); if(m_is_align_with_normal) { Vec3 normal = scene->getTerrainNormalAt(terrain, terrain_pos.x, terrain_pos.z); Vec3 dir = normalize(cross(normal, Vec3(1, 0, 0))); Matrix mtx = Matrix::IDENTITY; mtx.setXVector(cross(normal, dir)); mtx.setYVector(normal); mtx.setXVector(dir); rot = mtx.getRotation(); } else { if (m_is_rotate_x) { float angle = randFloat(m_rotate_x_spread.x, m_rotate_x_spread.y); Quat q(Vec3(1, 0, 0), angle); rot = q * rot; } if (m_is_rotate_y) { float angle = randFloat(m_rotate_y_spread.x, m_rotate_y_spread.y); Quat q(Vec3(0, 1, 0), angle); rot = q * rot; } if (m_is_rotate_z) { float angle = randFloat(m_rotate_z_spread.x, m_rotate_z_spread.y); Quat q(rot.rotate(Vec3(0, 0, 1)), angle); rot = q * rot; } } float size = randFloat(m_size_spread.x, m_size_spread.y); int random_idx = rand(0, m_selected_prefabs.size() - 1); if (!m_selected_prefabs[random_idx]) continue; const EntityPtr entity = prefab_system.instantiatePrefab(*m_selected_prefabs[random_idx], pos, rot, size); if (entity.isValid()) { if (universe.hasComponent((EntityRef)entity, MODEL_INSTANCE_TYPE)) { Model* model = scene->getModelInstanceModel((EntityRef)entity); const Transform tr = { pos, rot, size * scale }; if (isOBBCollision(*scene, meshes, tr, model, m_ignore_entities_not_in_folder, folders, folder)) { editor.undo(); } } } } } meshes->free(m_app.getEngine().getPageAllocator()); } editor.endCommandGroup(); } void TerrainEditor::onMouseMove(UniverseView& view, int x, int y, int, int) { if (!m_is_enabled) return; WorldEditor& editor = view.getEditor(); const Array<EntityRef>& selected_entities = editor.getSelectedEntities(); if (selected_entities.size() != 1) return; const EntityRef entity = selected_entities[0]; Universe& universe = *editor.getUniverse(); if (!universe.hasComponent(entity, TERRAIN_TYPE)) return; RenderScene* scene = (RenderScene*)universe.getScene(TERRAIN_TYPE); DVec3 origin; Vec3 dir; view.getViewport().getRay({(float)x, (float)y}, origin, dir); const RayCastModelHit hit = scene->castRayTerrain(entity, origin, dir); if (!hit.is_hit) return; if (hit.entity != entity) return; const DVec3 hit_pos = hit.origin + hit.dir * hit.t; switch(m_mode) { case Mode::ENTITY: if (m_remove_entity_action.isActive()) { removeEntities(hit_pos, editor); } else { paintEntities(hit_pos, editor, entity); } break; case Mode::HEIGHT: if (m_is_flat_height) { if (ImGui::GetIO().KeyCtrl) { m_flat_height = getHeight(hit_pos, scene, entity); } else { paint(hit_pos, TerrainEditor::FLAT_HEIGHT, true, selected_entities[0], editor); } } else { TerrainEditor::ActionType action = TerrainEditor::RAISE_HEIGHT; if (m_lower_terrain_action.isActive()) { action = TerrainEditor::LOWER_HEIGHT; } else if (m_smooth_terrain_action.isActive()) { action = TerrainEditor::SMOOTH_HEIGHT; } paint(hit_pos, action, true, selected_entities[0], editor); break; } break; case Mode::LAYER: TerrainEditor::ActionType action = TerrainEditor::LAYER; if (m_remove_grass_action.isActive()) { action = TerrainEditor::REMOVE_GRASS; } paint(hit_pos, action, true, selected_entities[0], editor); break; } } Material* TerrainEditor::getMaterial(ComponentUID cmp) const { if (!cmp.isValid()) return nullptr; auto* scene = static_cast<RenderScene*>(cmp.scene); return scene->getTerrainMaterial((EntityRef)cmp.entity); } static Array<u8> getFileContent(const char* path, IAllocator& allocator) { Array<u8> res(allocator); os::InputFile file; if (!file.open(path)) return res; res.resize((u32)file.size()); if (!file.read(res.begin(), res.byte_size())) res.clear(); file.close(); return res; } void TerrainEditor::layerGUI(ComponentUID cmp) { m_mode = Mode::LAYER; RenderScene* scene = static_cast<RenderScene*>(cmp.scene); Material* material = scene->getTerrainMaterial((EntityRef)cmp.entity); if (!material) return; if (material->getTextureByName(SPLATMAP_SLOT_NAME) && ImGuiEx::ToolbarButton(m_app.getBigIconFont(), ICON_FA_SAVE, ImGui::GetStyle().Colors[ImGuiCol_Text], "Save")) { material->getTextureByName(SPLATMAP_SLOT_NAME)->save(); } if (m_brush_texture) { ImGui::Image(m_brush_texture->handle, ImVec2(100, 100)); if (ImGuiEx::ToolbarButton(m_app.getBigIconFont(), ICON_FA_TIMES, ImGui::GetStyle().Colors[ImGuiCol_Text], "Clear brush mask")) { m_brush_texture->destroy(); LUMIX_DELETE(m_app.getAllocator(), m_brush_texture); m_brush_mask.clear(); m_brush_texture = nullptr; } ImGui::SameLine(); } ImGui::SameLine(); if (ImGuiEx::ToolbarButton(m_app.getBigIconFont(), ICON_FA_MASK, ImGui::GetStyle().Colors[ImGuiCol_Text], "Select brush mask")) { char filename[LUMIX_MAX_PATH]; if (os::getOpenFilename(Span(filename), "All\0*.*\0", nullptr)) { int image_width; int image_height; int image_comp; Array<u8> tmp = getFileContent(filename, m_app.getAllocator()); auto* data = stbi_load_from_memory(tmp.begin(), tmp.byte_size(), &image_width, &image_height, &image_comp, 4); if (data) { m_brush_mask.resize(image_width * image_height); for (int j = 0; j < image_width; ++j) { for (int i = 0; i < image_width; ++i) { m_brush_mask[i + j * image_width] = data[image_comp * (i + j * image_width)] > 128; } } Engine& engine = m_app.getEngine(); ResourceManagerHub& rm = engine.getResourceManager(); if (m_brush_texture) { m_brush_texture->destroy(); LUMIX_DELETE(m_app.getAllocator(), m_brush_texture); } Lumix::IPlugin* plugin = engine.getPluginManager().getPlugin("renderer"); Renderer& renderer = *static_cast<Renderer*>(plugin); m_brush_texture = LUMIX_NEW(m_app.getAllocator(), Texture)( Path("brush_texture"), *rm.get(Texture::TYPE), renderer, m_app.getAllocator()); m_brush_texture->create(image_width, image_height, gpu::TextureFormat::RGBA8, data, image_width * image_height * 4); stbi_image_free(data); } } } char grass_mode_shortcut[64]; if (m_remove_entity_action.shortcutText(Span(grass_mode_shortcut))) { ImGuiEx::Label(StaticString<64>("Grass mode (", grass_mode_shortcut, ")")); ImGui::TextUnformatted(m_remove_entity_action.isActive() ? "Remove" : "Add"); } int type_count = scene->getGrassCount((EntityRef)cmp.entity); for (int i = 0; i < type_count; ++i) { ImGui::SameLine(); if (i == 0 || ImGui::GetContentRegionAvail().x < 50) ImGui::NewLine(); bool b = (m_grass_mask & (1 << i)) != 0; m_app.getAssetBrowser().tile(scene->getGrassPath((EntityRef)cmp.entity, i), b); if (ImGui::IsItemClicked()) { if (!ImGui::GetIO().KeyCtrl) m_grass_mask = 0; if (b) { m_grass_mask &= ~(1 << i); } else { m_grass_mask |= 1 << i; } } } Texture* albedo = material->getTextureByName(DETAIL_ALBEDO_SLOT_NAME); Texture* normal = material->getTextureByName(DETAIL_NORMAL_SLOT_NAME); if (!albedo) { ImGui::Text("No detail albedo in material %s", material->getPath().c_str()); return; } if (albedo->isFailure()) { ImGui::Text("%s failed to load", albedo->getPath().c_str()); return; } if (!albedo->isReady()) { ImGui::Text("Loading %s...", albedo->getPath().c_str()); return; } if (!normal) { ImGui::Text("No detail normal in material %s", material->getPath().c_str()); return; } if (normal->isFailure()) { ImGui::Text("%s failed to load", normal->getPath().c_str()); return; } if (!normal->isReady()) { ImGui::Text("Loading %s...", normal->getPath().c_str()); return; } if (albedo->depth != normal->depth) { ImGui::TextWrapped(ICON_FA_EXCLAMATION_TRIANGLE " albedo texture %s has different number of layers than normal texture %s" , albedo->getPath().c_str() , normal->getPath().c_str()); } bool primary = m_layers_mask & 0b1; bool secondary = m_layers_mask & 0b10; // TODO shader does not handle secondary surfaces now, so pretend they don't exist // uncomment once shader is ready m_layers_mask = 0xb11; /*ImGuiEx::Label("Primary surface"); ImGui::Checkbox("##prim", &primary); ImGuiEx::Label("Secondary surface"); ImGui::Checkbox("##sec", &secondary); if (secondary) { bool use = m_fixed_value.x >= 0; ImGuiEx::Label("Use fixed value"); if (ImGui::Checkbox("##fxd", &use)) { m_fixed_value.x = use ? 0.f : -1.f; } if (m_fixed_value.x >= 0) { ImGuiEx::Label("Min/max"); ImGui::DragFloatRange2("##minmax", &m_fixed_value.x, &m_fixed_value.y, 0.01f, 0, 1); } }*/ FileSystem& fs = m_app.getEngine().getFileSystem(); if (albedo->getPath() != m_albedo_composite_path) { m_albedo_composite.loadSync(fs, albedo->getPath()); m_albedo_composite_path = albedo->getPath(); } m_layers_mask = (primary ? 1 : 0) | (secondary ? 0b10 : 0); for (i32 i = 0; i < m_albedo_composite.layers.size(); ++i) { ImGui::SameLine(); if (i == 0 || ImGui::GetContentRegionAvail().x < 50) ImGui::NewLine(); bool b = m_textures_mask & ((u64)1 << i); m_app.getAssetBrowser().tile(m_albedo_composite.layers[i].red.path, b); if (ImGui::IsItemClicked()) { if (!ImGui::GetIO().KeyCtrl) m_textures_mask = 0; if (b) m_textures_mask &= ~((u64)1 << i); else m_textures_mask |= (u64)1 << i; } if (ImGui::IsItemClicked(ImGuiMouseButton_Right)) { ImGui::OpenPopup(StaticString<8>("ctx", i)); } if (ImGui::BeginPopup(StaticString<8>("ctx", i))) { if (ImGui::Selectable("Remove surface")) { compositeTextureRemoveLayer(albedo->getPath(), i); compositeTextureRemoveLayer(normal->getPath(), i); m_albedo_composite_path = ""; } ImGui::EndPopup(); } } if (albedo->depth < 255) { if (ImGui::Button(ICON_FA_PLUS "Add surface")) ImGui::OpenPopup("Add surface"); } ImGui::SetNextWindowSizeConstraints(ImVec2(200, 100), ImVec2(FLT_MAX, FLT_MAX)); if (ImGui::BeginPopupModal("Add surface")) { ImGuiEx::Label("Albedo"); m_app.getAssetBrowser().resourceInput("albedo", Span(m_add_layer_popup.albedo), Texture::TYPE); ImGuiEx::Label("Normal"); m_app.getAssetBrowser().resourceInput("normal", Span(m_add_layer_popup.normal), Texture::TYPE); if (ImGui::Button(ICON_FA_PLUS "Add")) { saveCompositeTexture(albedo->getPath(), m_add_layer_popup.albedo); saveCompositeTexture(normal->getPath(), m_add_layer_popup.normal); m_albedo_composite_path = ""; } ImGui::SameLine(); if (ImGui::Button(ICON_FA_TIMES "Cancel")) { ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } } void TerrainEditor::compositeTextureRemoveLayer(const Path& path, i32 layer) const { CompositeTexture texture(m_app.getAllocator()); FileSystem& fs = m_app.getEngine().getFileSystem(); if (!texture.loadSync(fs, path)) { logError("Failed to load ", path); } else { texture.layers.erase(layer); if (!texture.save(fs, path)) { logError("Failed to save ", path); } } } void TerrainEditor::saveCompositeTexture(const Path& path, const char* channel) const { CompositeTexture texture(m_app.getAllocator()); FileSystem& fs = m_app.getEngine().getFileSystem(); if (!texture.loadSync(fs, path)) { logError("Failed to load ", path); } else { CompositeTexture::Layer new_layer; new_layer.red.path = channel; new_layer.red.src_channel = 0; new_layer.green.path = channel; new_layer.green.src_channel = 1; new_layer.blue.path = channel; new_layer.blue.src_channel = 2; new_layer.alpha.path = channel; new_layer.alpha.src_channel = 3; texture.layers.push(new_layer); if (!texture.save(fs, path)) { logError("Failed to save ", path); } } } void TerrainEditor::entityGUI() { m_mode = Mode::ENTITY; ImGuiEx::Label("Ignore other folders (?)"); if (ImGui::IsItemHovered()) { ImGui::SetTooltip("When placing entities, ignore collisions with " "entities in other folders than the currently selected folder " "in hierarchy view"); } ImGui::Checkbox("##ignore_filter", &m_ignore_entities_not_in_folder); static char filter[100] = {0}; const float w = ImGui::CalcTextSize(ICON_FA_TIMES).x + ImGui::GetStyle().ItemSpacing.x * 2; ImGui::SetNextItemWidth(-w); ImGui::InputTextWithHint("##filter", "Filter", filter, sizeof(filter)); ImGui::SameLine(); if (ImGuiEx::IconButton(ICON_FA_TIMES, "Clear filter")) { filter[0] = '\0'; } static ImVec2 size(-1, 200); if (ImGui::ListBoxHeader("##prefabs", size)) { auto& resources = m_app.getAssetCompiler().lockResources(); u32 count = 0; for (const AssetCompiler::ResourceItem& res : resources) { if (res.type != PrefabResource::TYPE) continue; ++count; if (filter[0] != 0 && stristr(res.path.c_str(), filter) == nullptr) continue; int selected_idx = m_selected_prefabs.find([&](PrefabResource* r) -> bool { return r && r->getPath() == res.path; }); bool selected = selected_idx >= 0; const char* loading_str = selected_idx >= 0 && m_selected_prefabs[selected_idx]->isEmpty() ? " - loading..." : ""; StaticString<LUMIX_MAX_PATH + 15> label(res.path.c_str(), loading_str); if (ImGui::Selectable(label, &selected)) { if (selected) { ResourceManagerHub& manager = m_app.getEngine().getResourceManager(); PrefabResource* prefab = manager.load<PrefabResource>(res.path); if (!ImGui::GetIO().KeyShift) { for (PrefabResource* res : m_selected_prefabs) res->decRefCount(); m_selected_prefabs.clear(); } m_selected_prefabs.push(prefab); } else { PrefabResource* prefab = m_selected_prefabs[selected_idx]; if (!ImGui::GetIO().KeyShift) { for (PrefabResource* res : m_selected_prefabs) res->decRefCount(); m_selected_prefabs.clear(); } else { m_selected_prefabs.swapAndPop(selected_idx); prefab->decRefCount(); } } } } if (count == 0) ImGui::TextUnformatted("No prefabs"); m_app.getAssetCompiler().unlockResources(); ImGui::ListBoxFooter(); } ImGuiEx::HSplitter("after_prefab", &size); if(ImGui::Checkbox("Align with normal", &m_is_align_with_normal)) { if(m_is_align_with_normal) m_is_rotate_x = m_is_rotate_y = m_is_rotate_z = false; } if (ImGui::Checkbox("Rotate around X", &m_is_rotate_x)) { if (m_is_rotate_x) m_is_align_with_normal = false; } if (m_is_rotate_x) { Vec2 tmp = m_rotate_x_spread; tmp.x = radiansToDegrees(tmp.x); tmp.y = radiansToDegrees(tmp.y); if (ImGui::DragFloatRange2("Rotate X spread", &tmp.x, &tmp.y)) { m_rotate_x_spread.x = degreesToRadians(tmp.x); m_rotate_x_spread.y = degreesToRadians(tmp.y); } } if (ImGui::Checkbox("Rotate around Y", &m_is_rotate_y)) { if (m_is_rotate_y) m_is_align_with_normal = false; } if (m_is_rotate_y) { Vec2 tmp = m_rotate_y_spread; tmp.x = radiansToDegrees(tmp.x); tmp.y = radiansToDegrees(tmp.y); if (ImGui::DragFloatRange2("Rotate Y spread", &tmp.x, &tmp.y)) { m_rotate_y_spread.x = degreesToRadians(tmp.x); m_rotate_y_spread.y = degreesToRadians(tmp.y); } } if(ImGui::Checkbox("Rotate around Z", &m_is_rotate_z)) { if(m_is_rotate_z) m_is_align_with_normal = false; } if (m_is_rotate_z) { Vec2 tmp = m_rotate_z_spread; tmp.x = radiansToDegrees(tmp.x); tmp.y = radiansToDegrees(tmp.y); if (ImGui::DragFloatRange2("Rotate Z spread", &tmp.x, &tmp.y)) { m_rotate_z_spread.x = degreesToRadians(tmp.x); m_rotate_z_spread.y = degreesToRadians(tmp.y); } } ImGui::DragFloatRange2("Size spread", &m_size_spread.x, &m_size_spread.y, 0.01f); m_size_spread.x = minimum(m_size_spread.x, m_size_spread.y); ImGui::DragFloatRange2("Y spread", &m_y_spread.x, &m_y_spread.y, 0.01f); m_y_spread.x = minimum(m_y_spread.x, m_y_spread.y); } void TerrainEditor::exportToOBJ(ComponentUID cmp) const { char filename[LUMIX_MAX_PATH]; if (!os::getSaveFilename(Span(filename), "Wavefront obj\0*.obj", "obj")) return; os::OutputFile file; if (!file.open(filename)) { logError("Failed to open ", filename); return; } char basename[LUMIX_MAX_PATH]; copyString(Span(basename), Path::getBasename(filename)); auto* scene = static_cast<RenderScene*>(cmp.scene); const EntityRef e = (EntityRef)cmp.entity; const Texture* hm = getMaterial(cmp)->getTextureByName(HEIGHTMAP_SLOT_NAME); OutputMemoryStream blob(m_app.getAllocator()); blob.reserve(8 * 1024 * 1024); blob << "mtllib " << basename << ".mtl\n"; blob << "o Terrain\n"; const float xz_scale = scene->getTerrainXZScale(e); const float y_scale = scene->getTerrainYScale(e); ASSERT(hm->format == gpu::TextureFormat::R16); const u16* hm_data = (const u16*)hm->getData(); for (u32 j = 0; j < hm->height; ++j) { for (u32 i = 0; i < hm->width; ++i) { const float height = hm_data[i + j * hm->width] / float(0xffff) * y_scale; blob << "v " << i * xz_scale << " " << height << " " << j * xz_scale << "\n"; } } for (u32 j = 0; j < hm->height; ++j) { for (u32 i = 0; i < hm->width; ++i) { blob << "vt " << i / float(hm->width - 1) << " " << j / float(hm->height - 1) << "\n"; } } blob << "usemtl Material\n"; auto write_face_vertex = [&](u32 idx){ blob << idx << "/" << idx; }; for (u32 j = 0; j < hm->height - 1; ++j) { for (u32 i = 0; i < hm->width - 1; ++i) { const u32 idx = i + j * hm->width + 1; blob << "f "; write_face_vertex(idx); blob << " "; write_face_vertex(idx + 1); blob << " "; write_face_vertex(idx + 1 + hm->width); blob << "\n"; blob << "f "; write_face_vertex(idx); blob << " "; write_face_vertex(idx + 1 + hm->width); blob << " "; write_face_vertex(idx + hm->width); blob << "\n"; } } if (!file.write(blob.data(), blob.size())) { logError("Failed to write ", filename); } file.close(); char dir[LUMIX_MAX_PATH]; copyString(Span(dir), Path::getDir(filename)); StaticString<LUMIX_MAX_PATH> mtl_filename(dir, basename, ".mtl"); if (!file.open(mtl_filename)) { logError("Failed to open ", mtl_filename); return; } blob.clear(); blob << "newmtl Material"; if (!file.write(blob.data(), blob.size())) { logError("Failed to write ", mtl_filename); } file.close(); } void TerrainEditor::onGUI(ComponentUID cmp, WorldEditor& editor) { ASSERT(cmp.type == TERRAIN_TYPE); auto* scene = static_cast<RenderScene*>(cmp.scene); ImGui::Unindent(); if (!ImGui::CollapsingHeader("Terrain editor")) { ImGui::Indent(); return; } ImGui::Indent(); ImGuiEx::Label("Enable"); ImGui::Checkbox("##ed_enabled", &m_is_enabled); if (!m_is_enabled) return; Material* material = getMaterial(cmp); if (!material) { ImGui::Text("No material"); return; } if (!material->getTextureByName(HEIGHTMAP_SLOT_NAME)) { ImGui::Text("No heightmap"); return; } if (ImGui::Button(ICON_FA_FILE_EXPORT)) exportToOBJ(cmp); ImGuiEx::Label("Brush size"); ImGui::DragFloat("##br_size", &m_terrain_brush_size, 1, MIN_BRUSH_SIZE, FLT_MAX); ImGuiEx::Label("Brush strength"); ImGui::SliderFloat("##br_str", &m_terrain_brush_strength, 0, 1.0f); if (ImGui::BeginTabBar("brush_type")) { if (ImGui::BeginTabItem("Height")) { m_mode = Mode::HEIGHT; if (ImGuiEx::ToolbarButton(m_app.getBigIconFont(), ICON_FA_SAVE, ImGui::GetStyle().Colors[ImGuiCol_Text], "Save")) { material->getTextureByName(HEIGHTMAP_SLOT_NAME)->save(); } ImGuiEx::Label("Mode"); if (m_is_flat_height) { ImGui::TextUnformatted("flat"); } else if (m_smooth_terrain_action.isActive()) { char shortcut[64]; if (m_smooth_terrain_action.shortcutText(Span(shortcut))) { ImGui::Text("smooth (%s)", shortcut); } else { ImGui::TextUnformatted("smooth"); } } else if (m_lower_terrain_action.isActive()) { char shortcut[64]; if (m_lower_terrain_action.shortcutText(Span(shortcut))) { ImGui::Text("lower (%s)", shortcut); } else { ImGui::TextUnformatted("lower"); } } else { ImGui::TextUnformatted("raise"); } ImGui::Checkbox("Flat", &m_is_flat_height); if (m_is_flat_height) { ImGui::SameLine(); ImGui::Text("- Press Ctrl to pick height"); } ImGui::EndTabItem(); } if (ImGui::BeginTabItem("Surface and grass")) { layerGUI(cmp); ImGui::EndTabItem(); } if (ImGui::BeginTabItem("Entity")) { entityGUI(); ImGui::EndTabItem(); } ImGui::EndTabBar(); } if (!cmp.isValid() || !m_is_enabled) { return; } const Vec2 mp = editor.getView().getMousePos(); Universe& universe = *editor.getUniverse(); for(auto entity : editor.getSelectedEntities()) { if (!universe.hasComponent(entity, TERRAIN_TYPE)) continue; RenderScene* scene = static_cast<RenderScene*>(universe.getScene(TERRAIN_TYPE)); DVec3 origin; Vec3 dir; editor.getView().getViewport().getRay(mp, origin, dir); const RayCastModelHit hit = scene->castRayTerrain(entity, origin, dir); if(hit.is_hit) { DVec3 center = hit.origin + hit.dir * hit.t; drawCursor(*scene, entity, center); return; } } } void TerrainEditor::paint(const DVec3& hit_pos, ActionType action_type, bool old_stroke, EntityRef terrain, WorldEditor& editor) const { UniquePtr<PaintTerrainCommand> command = UniquePtr<PaintTerrainCommand>::create(editor.getAllocator(), editor, action_type, m_grass_mask, (u64)m_textures_mask, hit_pos, m_brush_mask, m_terrain_brush_size, m_terrain_brush_strength, m_flat_height, m_color, terrain, m_layers_mask, m_fixed_value, old_stroke); editor.executeCommand(command.move()); } } // namespace Lumix
30.359473
165
0.678419
santaclose
04326480283816f6e982b697093aab4f31b36529
21,971
hpp
C++
include/UnityEngine/Networking/UnityWebRequest_UnityWebRequestError.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/UnityEngine/Networking/UnityWebRequest_UnityWebRequestError.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/UnityEngine/Networking/UnityWebRequest_UnityWebRequestError.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: UnityEngine.Networking.UnityWebRequest #include "UnityEngine/Networking/UnityWebRequest.hpp" // Including type: System.Enum #include "System/Enum.hpp" // Completed includes // Type namespace: UnityEngine.Networking namespace UnityEngine::Networking { // Size: 0x4 #pragma pack(push, 1) // Autogenerated type: UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError // [TokenAttribute] Offset: FFFFFFFF struct UnityWebRequest::UnityWebRequestError/*, public System::Enum*/ { public: // public System.Int32 value__ // Size: 0x4 // Offset: 0x0 int value; // Field size check static_assert(sizeof(int) == 0x4); // Creating value type constructor for type: UnityWebRequestError constexpr UnityWebRequestError(int value_ = {}) noexcept : value{value_} {} // Creating interface conversion operator: operator System::Enum operator System::Enum() noexcept { return *reinterpret_cast<System::Enum*>(this); } // Creating conversion operator: operator int constexpr operator int() const noexcept { return value; } // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError OK static constexpr const int OK = 0; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError OK static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_OK(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError OK static void _set_OK(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError Unknown static constexpr const int Unknown = 1; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError Unknown static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_Unknown(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError Unknown static void _set_Unknown(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SDKError static constexpr const int SDKError = 2; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SDKError static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_SDKError(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SDKError static void _set_SDKError(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError UnsupportedProtocol static constexpr const int UnsupportedProtocol = 3; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError UnsupportedProtocol static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_UnsupportedProtocol(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError UnsupportedProtocol static void _set_UnsupportedProtocol(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError MalformattedUrl static constexpr const int MalformattedUrl = 4; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError MalformattedUrl static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_MalformattedUrl(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError MalformattedUrl static void _set_MalformattedUrl(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError CannotResolveProxy static constexpr const int CannotResolveProxy = 5; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError CannotResolveProxy static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_CannotResolveProxy(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError CannotResolveProxy static void _set_CannotResolveProxy(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError CannotResolveHost static constexpr const int CannotResolveHost = 6; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError CannotResolveHost static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_CannotResolveHost(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError CannotResolveHost static void _set_CannotResolveHost(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError CannotConnectToHost static constexpr const int CannotConnectToHost = 7; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError CannotConnectToHost static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_CannotConnectToHost(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError CannotConnectToHost static void _set_CannotConnectToHost(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError AccessDenied static constexpr const int AccessDenied = 8; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError AccessDenied static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_AccessDenied(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError AccessDenied static void _set_AccessDenied(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError GenericHttpError static constexpr const int GenericHttpError = 9; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError GenericHttpError static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_GenericHttpError(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError GenericHttpError static void _set_GenericHttpError(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError WriteError static constexpr const int WriteError = 10; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError WriteError static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_WriteError(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError WriteError static void _set_WriteError(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError ReadError static constexpr const int ReadError = 11; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError ReadError static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_ReadError(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError ReadError static void _set_ReadError(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError OutOfMemory static constexpr const int OutOfMemory = 12; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError OutOfMemory static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_OutOfMemory(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError OutOfMemory static void _set_OutOfMemory(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError Timeout static constexpr const int Timeout = 13; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError Timeout static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_Timeout(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError Timeout static void _set_Timeout(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError HTTPPostError static constexpr const int HTTPPostError = 14; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError HTTPPostError static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_HTTPPostError(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError HTTPPostError static void _set_HTTPPostError(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCannotConnect static constexpr const int SSLCannotConnect = 15; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCannotConnect static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_SSLCannotConnect(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCannotConnect static void _set_SSLCannotConnect(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError Aborted static constexpr const int Aborted = 16; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError Aborted static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_Aborted(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError Aborted static void _set_Aborted(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError TooManyRedirects static constexpr const int TooManyRedirects = 17; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError TooManyRedirects static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_TooManyRedirects(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError TooManyRedirects static void _set_TooManyRedirects(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError ReceivedNoData static constexpr const int ReceivedNoData = 18; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError ReceivedNoData static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_ReceivedNoData(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError ReceivedNoData static void _set_ReceivedNoData(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLNotSupported static constexpr const int SSLNotSupported = 19; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLNotSupported static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_SSLNotSupported(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLNotSupported static void _set_SSLNotSupported(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError FailedToSendData static constexpr const int FailedToSendData = 20; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError FailedToSendData static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_FailedToSendData(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError FailedToSendData static void _set_FailedToSendData(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError FailedToReceiveData static constexpr const int FailedToReceiveData = 21; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError FailedToReceiveData static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_FailedToReceiveData(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError FailedToReceiveData static void _set_FailedToReceiveData(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCertificateError static constexpr const int SSLCertificateError = 22; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCertificateError static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_SSLCertificateError(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCertificateError static void _set_SSLCertificateError(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCipherNotAvailable static constexpr const int SSLCipherNotAvailable = 23; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCipherNotAvailable static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_SSLCipherNotAvailable(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCipherNotAvailable static void _set_SSLCipherNotAvailable(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCACertError static constexpr const int SSLCACertError = 24; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCACertError static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_SSLCACertError(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLCACertError static void _set_SSLCACertError(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError UnrecognizedContentEncoding static constexpr const int UnrecognizedContentEncoding = 25; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError UnrecognizedContentEncoding static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_UnrecognizedContentEncoding(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError UnrecognizedContentEncoding static void _set_UnrecognizedContentEncoding(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError LoginFailed static constexpr const int LoginFailed = 26; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError LoginFailed static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_LoginFailed(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError LoginFailed static void _set_LoginFailed(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLShutdownFailed static constexpr const int SSLShutdownFailed = 27; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLShutdownFailed static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_SSLShutdownFailed(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError SSLShutdownFailed static void _set_SSLShutdownFailed(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // static field const value: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError NoInternetConnection static constexpr const int NoInternetConnection = 28; // Get static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError NoInternetConnection static UnityEngine::Networking::UnityWebRequest::UnityWebRequestError _get_NoInternetConnection(); // Set static field: static public UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError NoInternetConnection static void _set_NoInternetConnection(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError value); // Get instance field reference: public System.Int32 value__ int& dyn_value__(); }; // UnityEngine.Networking.UnityWebRequest/UnityEngine.Networking.UnityWebRequestError #pragma pack(pop) static check_size<sizeof(UnityWebRequest::UnityWebRequestError), 0 + sizeof(int)> __UnityEngine_Networking_UnityWebRequest_UnityWebRequestErrorSizeCheck; static_assert(sizeof(UnityWebRequest::UnityWebRequestError) == 0x4); } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(UnityEngine::Networking::UnityWebRequest::UnityWebRequestError, "UnityEngine.Networking", "UnityWebRequest/UnityWebRequestError"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
99.41629
158
0.823449
Fernthedev
0436636dbe6171fdda0d241fd15f9b284699395f
24
cpp
C++
util/draft/estimators.cpp
SitdikovRustam/CatBoost
39fb9dfddb24e977ed87efc71063b03cd4bc8f16
[ "Apache-2.0" ]
33
2016-12-15T21:47:13.000Z
2020-10-27T23:53:59.000Z
util/draft/estimators.cpp
dsferz/machinelearning_yandex
8fde8314c5c70299ece8b8f00075ddfcd5e07ddf
[ "Apache-2.0" ]
null
null
null
util/draft/estimators.cpp
dsferz/machinelearning_yandex
8fde8314c5c70299ece8b8f00075ddfcd5e07ddf
[ "Apache-2.0" ]
14
2016-12-28T17:00:33.000Z
2022-01-16T20:15:27.000Z
#include "estimators.h"
12
23
0.75
SitdikovRustam
04375a304f2cd29a9b0c5eb3ce8b357124ad381c
11,956
hh
C++
src/lib/MeshFEM/EnergyDensities/TensionFieldTheory.hh
MeshFEM/MeshFEM
9b3619fa450d83722879bfd0f5a3fe69d927bd63
[ "MIT" ]
19
2020-10-21T10:05:17.000Z
2022-03-20T13:41:50.000Z
src/lib/MeshFEM/EnergyDensities/TensionFieldTheory.hh
MeshFEM/MeshFEM
9b3619fa450d83722879bfd0f5a3fe69d927bd63
[ "MIT" ]
4
2021-01-01T15:58:15.000Z
2021-09-19T03:31:09.000Z
src/lib/MeshFEM/EnergyDensities/TensionFieldTheory.hh
MeshFEM/MeshFEM
9b3619fa450d83722879bfd0f5a3fe69d927bd63
[ "MIT" ]
4
2020-10-05T09:01:50.000Z
2022-01-11T03:02:39.000Z
//////////////////////////////////////////////////////////////////////////////// // TensionFieldTheory.hh //////////////////////////////////////////////////////////////////////////////// /*! @file // Implements a field theory relaxed energy density for a fully generic, // potentially anisotropic, 2D "C-based" energy density. Here "C-based" means // the energy density is expressed in terms of the Cauchy-Green deformation // tensor. // Our implementation is based on the applied math paper // [Pipkin1994:"Relaxed energy densities for large deformations of membranes"] // whose optimality criterion for the wrinkling strain we use to obtain a // slightly less expensive optimization formulation. // // We implement the second derivatives needed for a Newton-based equilibrium // solver; these are nontrivial since they must account for the dependence of // the wrinkling strain on C. */ // Author: Julian Panetta (jpanetta), julian.panetta@gmail.com // Created: 06/28/2020 19:01:21 //////////////////////////////////////////////////////////////////////////////// #ifndef TENSIONFIELDTHEORY_HH #define TENSIONFIELDTHEORY_HH #include <Eigen/Dense> #include <MeshFEM/Types.hh> #include <stdexcept> #include <iostream> #include <MeshFEM/newton_optimizer/dense_newton.hh> template<class _Psi> struct IsotropicWrinkleStrainProblem { using Psi = _Psi; using Real = typename Psi::Real; using VarType = Eigen::Matrix<Real, 1, 1>; using HessType = Eigen::Matrix<Real, 1, 1>; using M2d = Mat2_T<Real>; IsotropicWrinkleStrainProblem(Psi &psi, const M2d &C, const Vec2_T<Real> &n) : m_psi(psi), m_C(C), m_nn(n * n.transpose()) { } void setC(const M2d &C) { m_C = C; } const M2d &getC() const { return m_C; } size_t numVars() const { return 1; } void setVars(const VarType &vars) { m_a = vars; m_psi.setC(m_C + m_a[0] * m_nn); } const VarType &getVars() const { return m_a; } Real energy() const { return m_psi.energy(); } VarType gradient() const { return VarType(0.5 * doubleContract(m_nn, m_psi.PK2Stress()) ); } HessType hessian() const { return HessType(0.5 * doubleContract(m_psi.delta_PK2Stress(m_nn), m_nn)); } void solve() { dense_newton(*this, /* maxIter = */ 100, /*gradTol = */1e-14, /* verbose = */ false); } EIGEN_MAKE_ALIGNED_OPERATOR_NEW private: VarType m_a = VarType::Zero(); Psi &m_psi; M2d m_C, m_nn; }; template<class _Psi> struct AnisotropicWrinkleStrainProblem { using Psi = _Psi; using Real = typename Psi::Real; using VarType = Vec2_T<Real>; using HessType = Mat2_T<Real>; using M2d = Mat2_T<Real>; AnisotropicWrinkleStrainProblem(Psi &psi, const M2d &C, const VarType &n) : m_psi(psi), m_C(C), m_ntilde(n) { } void setC(const M2d &C) { m_C = C; } const M2d &getC() const { return m_C; } size_t numVars() const { return 2; } void setVars(const VarType &vars) { m_ntilde = vars; m_psi.setC(m_C + m_ntilde * m_ntilde.transpose()); } const VarType &getVars() const { return m_ntilde; } Real energy() const { return m_psi.energy(); } // S : (0.5 * (n delta_n^T + delta_n n^T)) // = S : n delta_n^T = (S n) . delta_n VarType gradient() const { return m_psi.PK2Stress() * m_ntilde; } // psi(n * n^T) // dpsi = n^T psi'(n * n^T) . dn // d2psi = dn_a^T psi'(n * n^T) . dn_b + n^T (psi'' : (n * dn_a^T)) . dn_b // = psi' : (dn_a dn_b^T) + ... HessType hessian() const { HessType h = m_psi.PK2Stress(); // psi' : (dn_a dn_b^T) M2d dnn(M2d::Zero()); dnn.col(0) = m_ntilde; h.row(0) += m_ntilde.transpose() * m_psi.delta_PK2Stress(symmetrized_x2(dnn)); dnn.col(0).setZero(); dnn.col(1) = m_ntilde; h.row(1) += m_ntilde.transpose() * m_psi.delta_PK2Stress(symmetrized_x2(dnn)); if (h.array().isNaN().any()) throw std::runtime_error("NaN Hessian"); if (std::abs(h(0, 1) - h(1, 0)) > 1e-10 * std::abs(h(1, 0)) + 1e-10) throw std::runtime_error("Asymmetric Hessian"); return h; } void solve() { dense_newton(*this, /* maxIter = */ 100, /*gradTol = */1e-14, /* verbose = */ false); } EIGEN_MAKE_ALIGNED_OPERATOR_NEW private: Psi &m_psi; M2d m_C; VarType m_ntilde = VarType::Zero(); }; // Define a relaxed 2D C-based energy based on a given 2D C-based energy `Psi_C` template<class Psi_C> struct RelaxedEnergyDensity { static_assert(Psi_C::EDType == EDensityType::CBased, "Tension field theory only works on C-based energy densities"); static constexpr size_t N = Psi_C::N; static constexpr size_t Dimension = N; static constexpr EDensityType EDType = EDensityType::CBased; using Matrix = typename Psi_C::Matrix; using Real = typename Psi_C::Real; using ES = Eigen::SelfAdjointEigenSolver<Matrix>; using V2d = Vec2_T<Real>; static_assert(N == 2, "Tension field theory relaxation only defined for 2D energies"); static std::string name() { return std::string("Relaxed") + Psi_C::name(); } // Forward all constructor arguments to m_psi template<class... Args> RelaxedEnergyDensity(Args&&... args) : m_psi(std::forward<Args>(args)...), m_anisoProb(m_psi, Matrix::Identity(), V2d::Zero()) { } // We need a custom copy constructor since m_anisoProb contains a // reference to this->m_psi RelaxedEnergyDensity(const RelaxedEnergyDensity &b) : m_psi(b.m_psi), m_anisoProb(m_psi, Matrix::Identity(), V2d::Zero()) { setC(b.m_C); } // Note: UninitializedDeformationTag argument must be a rvalue reference so it exactly // matches the type passed by the constructor call // RelaxedEnergyDensity(b, UninitializedDeformationTag()); otherwise the // perfect forwarding constructor above will be preferred for this call, // incorrectly forwarding b to Psi's constructor. RelaxedEnergyDensity(const RelaxedEnergyDensity &b, UninitializedDeformationTag &&) : m_psi(b.m_psi, UninitializedDeformationTag()), m_anisoProb(m_psi, Matrix::Identity(), V2d::Zero()) { setC(b.m_C); } void setC(const Matrix &C) { m_C = C; if (!relaxationEnabled()) { m_psi.setC(C); return; } // Note: Eigen guarantees eigenvalues are sorted in ascending order. ES C_eigs(C); // std::cout << "C eigenvalues: " << C_eigs.eigenvalues().transpose() << std::endl; // Detect full compression if (C_eigs.eigenvalues()[1] < 1) { m_tensionState = 0; m_wrinkleStrain = -C; return; } m_psi.setC(C); ES S_eigs(m_psi.PK2Stress()); // Detect full tension // std::cout << "S eigenvalues: " << S_eigs.eigenvalues().transpose() << std::endl; if (S_eigs.eigenvalues()[0] >= -1e-12) { m_tensionState = 2; m_wrinkleStrain.setZero(); return; } // Handle partial tension m_tensionState = 1; // In the isotropic case, principal stress and strain directions // coincide, and the wrinkling strain must be in the form // a n n^T, where n is the eigenvector corresponding to the smallest // stress eigenvalue and a > 0 is an unknown. // This simplifies the determination of wrinkling strain to a convex // 1D optimization problem that we solve with Newton's method. V2d n = S_eigs.eigenvectors().col(0); using IWSP = IsotropicWrinkleStrainProblem<Psi_C>; IWSP isoProb(m_psi, C, n); // std::cout << "Solving isotropic wrinkle strain problem" << std::endl; isoProb.setVars(typename IWSP::VarType{0.0}); isoProb.solve(); Real a = isoProb.getVars()[0]; if (a < 0) throw std::runtime_error("Invalid wrinkle strain"); // We use this isotropic assumption to obtain initial guess for the // anisotropic case, where the wrinkling strain is in the form // n_tilde n_tilde^T // with a 2D vector n_tilde as the unknown. m_anisoProb.setC(C); // std::cout << "Solving anisotropic wrinkle strain problem" << std::endl; m_anisoProb.setVars(std::sqrt(a) * n); m_anisoProb.solve(); auto ntilde = m_anisoProb.getVars(); m_wrinkleStrain = -ntilde * ntilde.transpose(); // { // ES S_eigs_new(m_psi.PK2Stress()); // std::cout << "new S eigenvalues: " << S_eigs_new.eigenvalues().transpose() << std::endl; // } } Real energy() const { if (relaxationEnabled() && fullCompression()) return 0.0; return m_psi.energy(); } Matrix PK2Stress() const { if (relaxationEnabled() && fullCompression()) return Matrix::Zero(); // By envelope theorem, the wrinkling strain's perturbation can be // neglected, and the stress is simply the stress of the underlying // material model evaluated on the "elastic strain". return m_psi.PK2Stress(); } template<class Mat_> Matrix delta_PK2Stress(const Mat_ &dC) const { if (!relaxationEnabled() || fullTension()) return m_psi.delta_PK2Stress(dC); if (fullCompression()) return Matrix::Zero(); // n solves m_anisoProb: // (psi') n = 0 // delta_n solves: // (psi'' : dC + n delta n) n + (psi') delta_n = 0 // (psi'' : n delta_n) n + (psi') delta_n = -(psi'' : dC) n // H delta_n = -(psi'' : dC) n auto ntilde = m_anisoProb.getVars(); V2d delta_n = -m_anisoProb.hessian().inverse() * (m_psi.delta_PK2Stress(dC.matrix()) * ntilde); // In the partial tension case, we need to account for the wrinkling // strain perturbation. return m_psi.delta_PK2Stress(dC.matrix() + ntilde * delta_n.transpose() + delta_n * ntilde.transpose()); } template<class Mat_, class Mat2_> Matrix delta2_PK2Stress(const Mat_ &/* dF_a */, const Mat2_ &/* dF_b */) const { throw std::runtime_error("Unimplemented"); } V2d principalBiotStrains() const { ES es(m_C); return es.eigenvalues().array().sqrt() - 1.0; } const Matrix &wrinkleStrain() const { return m_wrinkleStrain; } bool fullCompression() const { return m_tensionState == 0; } bool partialTension() const { return m_tensionState == 1; } bool fullTension() const { return m_tensionState == 2; } int tensionState() const { return m_tensionState; } // Copying is super dangerous since we m_anisoProb uses a reference to m_psi... RelaxedEnergyDensity &operator=(const RelaxedEnergyDensity &) = delete; // Direct access to the energy density for debugging or // to change the material properties Psi_C &psi() { return m_psi; } const Psi_C &psi() const { return m_psi; } // Turn on or off the tension field theory approximation void setRelaxationEnabled(bool enable) { m_relaxationEnabled = enable; setC(m_C); } bool relaxationEnabled() const { return m_relaxationEnabled; } void copyMaterialProperties(const RelaxedEnergyDensity &other) { psi().copyMaterialProperties(other.psi()); } EIGEN_MAKE_ALIGNED_OPERATOR_NEW private: // Tension state: // 0: compression in all directions // 1: partial tension // 2: tension in all directions int m_tensionState = 2; Psi_C m_psi; Matrix m_wrinkleStrain = Matrix::Zero(), m_C = Matrix::Identity(); // full Cauchy-Green deformation tensor. AnisotropicWrinkleStrainProblem<Psi_C> m_anisoProb; bool m_relaxationEnabled = true; }; #endif /* end of include guard: TENSIONFIELDTHEORY_HH */
39.328947
113
0.613499
MeshFEM
0437f79bb5ade9e9b582a4fc33393bd9e0301583
8,119
cpp
C++
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/shp/XBaseParser.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
3
2018-08-20T12:12:43.000Z
2021-06-06T09:43:27.000Z
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/shp/XBaseParser.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
null
null
null
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/shp/XBaseParser.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
1
2022-03-31T03:12:23.000Z
2022-03-31T03:12:23.000Z
#include "XBaseParser.h" #include <vector> #include <string> #include <memory.h> #include <stdio.h> #include <stdlib.h> #if defined(_MSC_VER) || defined(__MINGW32__) #include <io.h> #else #include <unistd.h> #endif #include <fcntl.h> #include <osg/Notify> namespace ESRIShape { void XBaseHeader::print() { osg::notify(osg::INFO) << "VersionNumber = " << (int) _versionNumber << std::endl << "LastUpdate = " << 1900 + (int) _lastUpdate[0] << "/" << (int) _lastUpdate[1] << "/" << (int) _lastUpdate[2] << std::endl << "NumRecord = " << _numRecord << std::endl << "HeaderLength = " << _headerLength << std::endl << "RecordLength = " << _recordLength << std::endl; } bool XBaseHeader::read(int fd) { int nbytes = 0; if ((nbytes = ::read( fd, &_versionNumber, sizeof(_versionNumber))) <= 0) return false; if ((nbytes = ::read( fd, &_lastUpdate, sizeof(_lastUpdate))) <= 0) return false; if ((nbytes = ::read( fd, &_numRecord, sizeof(_numRecord))) <= 0) return false; if ((nbytes = ::read( fd, &_headerLength, sizeof(_headerLength))) <= 0) return false; if ((nbytes = ::read( fd, &_recordLength, sizeof(_recordLength))) <= 0) return false; if ((nbytes = ::read( fd, &_reserved, sizeof(_reserved))) <= 0) return false; if ((nbytes = ::read( fd, &_incompleteTransaction, sizeof(_incompleteTransaction))) <= 0) return false; if ((nbytes = ::read( fd, &_encryptionFlag, sizeof(_encryptionFlag))) <= 0) return false; if ((nbytes = ::read( fd, &_freeRecordThread, sizeof(_freeRecordThread))) <= 0) return false; if ((nbytes = ::read( fd, &_reservedMultiUser, sizeof(_reservedMultiUser))) <= 0) return false; if ((nbytes = ::read( fd, &_mdxflag, sizeof(_mdxflag))) <= 0) return false; if ((nbytes = ::read( fd, &_languageDriver, sizeof(_languageDriver))) <= 0) return false; if ((nbytes = ::read( fd, &_reserved2, sizeof(_reserved2))) <= 0) return false; return true; } void XBaseFieldDescriptor::print() { osg::notify(osg::INFO) << "name = " << _name << std::endl << "type = " << _fieldType << std::endl << "length = " << (int) _fieldLength << std::endl << "decimalCount = " << (int) _decimalCount << std::endl << "workAreaID = " << (int) _workAreaID << std::endl << "setFieldFlag = " << (int) _setFieldFlag << std::endl << "indexFieldFlag = " << (int) _indexFieldFlag << std::endl; } bool XBaseFieldDescriptor::read(int fd) { int nbytes = 0; if ((nbytes = ::read( fd, &_name, sizeof(_name))) <= 0) return false; if ((nbytes = ::read( fd, &_fieldType, sizeof(_fieldType))) <= 0) return false; if ((nbytes = ::read( fd, &_fieldDataAddress, sizeof(_fieldDataAddress))) <= 0) return false; if ((nbytes = ::read( fd, &_fieldLength, sizeof(_fieldLength))) <= 0) return false; if ((nbytes = ::read( fd, &_decimalCount, sizeof(_decimalCount))) <= 0) return false; if ((nbytes = ::read( fd, &_reservedMultiUser, sizeof(_reservedMultiUser))) <= 0) return false; if ((nbytes = ::read( fd, &_workAreaID, sizeof(_workAreaID))) <= 0) return false; if ((nbytes = ::read( fd, &_reservedMultiUser2, sizeof(_reservedMultiUser2))) <= 0) return false; if ((nbytes = ::read( fd, &_setFieldFlag, sizeof(_setFieldFlag))) <= 0) return false; if ((nbytes = ::read( fd, &_reserved, sizeof(_reserved))) <= 0) return false; if ((nbytes = ::read( fd, &_indexFieldFlag, sizeof(_indexFieldFlag))) <= 0) return false; return true; } XBaseParser::XBaseParser(const std::string fileName): _valid(false) { int fd = 0; if (fileName.empty() == false) { #ifdef WIN32 if( (fd = open( fileName.c_str(), O_RDONLY | O_BINARY )) <= 0 ) #else if( (fd = ::open( fileName.c_str(), O_RDONLY )) <= 0 ) #endif { perror( fileName.c_str() ); return ; } } _valid = parse(fd); } bool XBaseParser::parse(int fd) { int nbytes; XBaseHeader _xBaseHeader; std::vector<XBaseFieldDescriptor> _xBaseFieldDescriptorList; XBaseFieldDescriptor _xBaseFieldDescriptorTmp; // ** read the header if (_xBaseHeader.read(fd) == false) return false; // _xBaseHeader.print(); // ** read field descriptor bool fieldDescriptorDone = false; Byte nullTerminator; while (fieldDescriptorDone == false) { // ** store the field descriptor if (_xBaseFieldDescriptorTmp.read(fd) == false) return false; _xBaseFieldDescriptorList.push_back(_xBaseFieldDescriptorTmp); // _xBaseFieldDescriptorTmp.print(); // ** check the terminator if ((nbytes = ::read( fd, &nullTerminator, sizeof(nullTerminator))) <= 0) return false; if (nullTerminator == 0x0D) fieldDescriptorDone = true; else ::lseek( fd, -1, SEEK_CUR); } // ** move to the end of the Header ::lseek( fd, _xBaseHeader._headerLength + 1, SEEK_SET); // ** reserve AttributeListList _shapeAttributeListList.reserve(_xBaseHeader._numRecord); // ** read each record and store them in the ShapeAttributeListList char* record = new char[_xBaseHeader._recordLength]; std::vector<XBaseFieldDescriptor>::iterator it, end = _xBaseFieldDescriptorList.end(); for (Integer i = 0; i < _xBaseHeader._numRecord; ++i) { if ((nbytes = ::read( fd, record, _xBaseHeader._recordLength)) <= 0) return false; char * recordPtr = record; osgSim::ShapeAttributeList * shapeAttributeList = new osgSim::ShapeAttributeList; shapeAttributeList->reserve(_xBaseFieldDescriptorList.size()); for (it = _xBaseFieldDescriptorList.begin(); it != end; ++it) { switch (it->_fieldType) { case 'C': { char* str = new char[it->_fieldLength + 1]; memcpy(str, recordPtr, it->_fieldLength); str[it->_fieldLength] = 0; shapeAttributeList->push_back(osgSim::ShapeAttribute((const char *) it->_name, (char*) str)); delete [] str; break; } case 'N': { char* number = new char[it->_fieldLength + 1]; memcpy(number, recordPtr, it->_fieldLength); number[it->_fieldLength] = 0; shapeAttributeList->push_back(osgSim::ShapeAttribute((const char *) it->_name, (int) atoi(number))); delete [] number; break; } case 'I': { int number; memcpy(&number, record, it->_fieldLength); shapeAttributeList->push_back(osgSim::ShapeAttribute((const char *) it->_name, (int) number)); break; } case 'O': { double number; memcpy(&number, record, it->_fieldLength); shapeAttributeList->push_back(osgSim::ShapeAttribute((const char *) it->_name, (double) number)); break; } default: { osg::notify(osg::WARN) << "ESRIShape::XBaseParser : record type " << it->_fieldType << "not supported, skipped" << std::endl; shapeAttributeList->push_back(osgSim::ShapeAttribute((const char *) it->_name, (double) 0)); break; } } recordPtr += it->_fieldLength; } _shapeAttributeListList.push_back(shapeAttributeList); } delete [] record; close (fd); return true; } }
36.904545
154
0.55093
UM-ARM-Lab
04380da30516f9931c814f7e57999f699f2103d4
7,764
cpp
C++
Blizzlike/Trinity/Scripts/Dungeons/Stratholme/boss_dathrohan_balnazzar.cpp
499453466/Lua-Other
43fd2b72405faf3f2074fd2a2706ef115d16faa6
[ "Unlicense" ]
2
2015-06-23T16:26:32.000Z
2019-06-27T07:45:59.000Z
Blizzlike/Trinity/Scripts/Dungeons/Stratholme/boss_dathrohan_balnazzar.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
null
null
null
Blizzlike/Trinity/Scripts/Dungeons/Stratholme/boss_dathrohan_balnazzar.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
3
2015-01-10T18:22:59.000Z
2021-04-27T21:28:28.000Z
/* * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Boss_Dathrohan_Balnazzar SD%Complete: 95 SDComment: Possibly need to fix/improve summons after death SDCategory: Stratholme EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" enum eEnums { //Dathrohan spells SPELL_CRUSADERSHAMMER = 17286, //AOE stun SPELL_CRUSADERSTRIKE = 17281, SPELL_HOLYSTRIKE = 17284, //weapon dmg +3 //Transform SPELL_BALNAZZARTRANSFORM = 17288, //restore full HP/mana, trigger spell Balnazzar Transform Stun //Balnazzar spells SPELL_SHADOWSHOCK = 17399, SPELL_MINDBLAST = 17287, SPELL_PSYCHICSCREAM = 13704, SPELL_SLEEP = 12098, SPELL_MINDCONTROL = 15690, NPC_DATHROHAN = 10812, NPC_BALNAZZAR = 10813, NPC_ZOMBIE = 10698 //probably incorrect }; struct SummonDef { float m_fX, m_fY, m_fZ, m_fOrient; }; SummonDef m_aSummonPoint[]= { {3444.156f, -3090.626f, 135.002f, 2.240f}, //G1 front, left {3449.123f, -3087.009f, 135.002f, 2.240f}, //G1 front, right {3446.246f, -3093.466f, 135.002f, 2.240f}, //G1 back left {3451.160f, -3089.904f, 135.002f, 2.240f}, //G1 back, right {3457.995f, -3080.916f, 135.002f, 3.784f}, //G2 front, left {3454.302f, -3076.330f, 135.002f, 3.784f}, //G2 front, right {3460.975f, -3078.901f, 135.002f, 3.784f}, //G2 back left {3457.338f, -3073.979f, 135.002f, 3.784f} //G2 back, right }; class boss_dathrohan_balnazzar : public CreatureScript { public: boss_dathrohan_balnazzar() : CreatureScript("boss_dathrohan_balnazzar") { } CreatureAI* GetAI(Creature* creature) const { return new boss_dathrohan_balnazzarAI (creature); } struct boss_dathrohan_balnazzarAI : public ScriptedAI { boss_dathrohan_balnazzarAI(Creature* creature) : ScriptedAI(creature) {} uint32 m_uiCrusadersHammer_Timer; uint32 m_uiCrusaderStrike_Timer; uint32 m_uiMindBlast_Timer; uint32 m_uiHolyStrike_Timer; uint32 m_uiShadowShock_Timer; uint32 m_uiPsychicScream_Timer; uint32 m_uiDeepSleep_Timer; uint32 m_uiMindControl_Timer; bool m_bTransformed; void Reset() { m_uiCrusadersHammer_Timer = 8000; m_uiCrusaderStrike_Timer = 12000; m_uiMindBlast_Timer = 6000; m_uiHolyStrike_Timer = 18000; m_uiShadowShock_Timer = 4000; m_uiPsychicScream_Timer = 16000; m_uiDeepSleep_Timer = 20000; m_uiMindControl_Timer = 10000; m_bTransformed = false; if (me->GetEntry() == NPC_BALNAZZAR) me->UpdateEntry(NPC_DATHROHAN); } void JustDied(Unit* /*killer*/) { static uint32 uiCount = sizeof(m_aSummonPoint)/sizeof(SummonDef); for (uint8 i=0; i<uiCount; ++i) me->SummonCreature(NPC_ZOMBIE, m_aSummonPoint[i].m_fX, m_aSummonPoint[i].m_fY, m_aSummonPoint[i].m_fZ, m_aSummonPoint[i].m_fOrient, TEMPSUMMON_TIMED_DESPAWN, HOUR*IN_MILLISECONDS); } void EnterCombat(Unit* /*who*/) { } void UpdateAI(const uint32 uiDiff) { if (!UpdateVictim()) return; //START NOT TRANSFORMED if (!m_bTransformed) { //MindBlast if (m_uiMindBlast_Timer <= uiDiff) { DoCast(me->getVictim(), SPELL_MINDBLAST); m_uiMindBlast_Timer = urand(15000, 20000); } else m_uiMindBlast_Timer -= uiDiff; //CrusadersHammer if (m_uiCrusadersHammer_Timer <= uiDiff) { DoCast(me->getVictim(), SPELL_CRUSADERSHAMMER); m_uiCrusadersHammer_Timer = 12000; } else m_uiCrusadersHammer_Timer -= uiDiff; //CrusaderStrike if (m_uiCrusaderStrike_Timer <= uiDiff) { DoCast(me->getVictim(), SPELL_CRUSADERSTRIKE); m_uiCrusaderStrike_Timer = 15000; } else m_uiCrusaderStrike_Timer -= uiDiff; //HolyStrike if (m_uiHolyStrike_Timer <= uiDiff) { DoCast(me->getVictim(), SPELL_HOLYSTRIKE); m_uiHolyStrike_Timer = 15000; } else m_uiHolyStrike_Timer -= uiDiff; //BalnazzarTransform if (HealthBelowPct(40)) { if (me->IsNonMeleeSpellCasted(false)) me->InterruptNonMeleeSpells(false); //restore hp, mana and stun DoCast(me, SPELL_BALNAZZARTRANSFORM); me->UpdateEntry(NPC_BALNAZZAR); m_bTransformed = true; } } else { //MindBlast if (m_uiMindBlast_Timer <= uiDiff) { DoCast(me->getVictim(), SPELL_MINDBLAST); m_uiMindBlast_Timer = urand(15000, 20000); } else m_uiMindBlast_Timer -= uiDiff; //ShadowShock if (m_uiShadowShock_Timer <= uiDiff) { DoCast(me->getVictim(), SPELL_SHADOWSHOCK); m_uiShadowShock_Timer = 11000; } else m_uiShadowShock_Timer -= uiDiff; //PsychicScream if (m_uiPsychicScream_Timer <= uiDiff) { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) DoCast(target, SPELL_PSYCHICSCREAM); m_uiPsychicScream_Timer = 20000; } else m_uiPsychicScream_Timer -= uiDiff; //DeepSleep if (m_uiDeepSleep_Timer <= uiDiff) { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) DoCast(target, SPELL_SLEEP); m_uiDeepSleep_Timer = 15000; } else m_uiDeepSleep_Timer -= uiDiff; //MindControl if (m_uiMindControl_Timer <= uiDiff) { DoCast(me->getVictim(), SPELL_MINDCONTROL); m_uiMindControl_Timer = 15000; } else m_uiMindControl_Timer -= uiDiff; } DoMeleeAttackIfReady(); } }; }; void AddSC_boss_dathrohan_balnazzar() { new boss_dathrohan_balnazzar(); }
34.816143
122
0.551391
499453466
0438c5e47926dbfe5ee9f60971e30e206204d7fa
3,624
cpp
C++
league_skin_changer/game_classes.cpp
slowptr/LeagueSkinChanger
c37d505c4062b1acc1a7012650d6a33d5d8a3bce
[ "MIT" ]
1
2020-11-24T14:51:20.000Z
2020-11-24T14:51:20.000Z
league_skin_changer/game_classes.cpp
devzhai/LeagueSkinChanger
aaad169c8b74756c0ceb668fa003577aedc62965
[ "MIT" ]
null
null
null
league_skin_changer/game_classes.cpp
devzhai/LeagueSkinChanger
aaad169c8b74756c0ceb668fa003577aedc62965
[ "MIT" ]
null
null
null
/* This file is part of LeagueSkinChanger by b3akers, licensed under the MIT license: * * MIT License * * Copyright (c) b3akers 2020 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "game_classes.hpp" #include "encryption.hpp" #include "fnv_hash.hpp" #include <Windows.h> void character_data_stack::push( const char* model, int32_t skin ) { static const auto Push = reinterpret_cast<int( __thiscall* )( void*, const char* model, int32_t skinid, int32_t, bool update_spells, bool dont_update_hud, bool, bool change_particle, bool, char, const char*, int32_t, const char*, int32_t )>( std::uintptr_t( GetModuleHandle( nullptr ) ) + offsets::functions::CharacterDataStack__Push ); Push( this, model, skin, 0, false, false, false, true, false, -1, "\x00", 0, "\x00", 0 ); } void character_data_stack::update( bool change ) { static const auto Update = reinterpret_cast<void( __thiscall* )( void*, bool )>( std::uintptr_t( GetModuleHandle( nullptr ) ) + offsets::functions::CharacterDataStack__Update ); Update( this, change ); } void obj_ai_base::change_skin( const char* model, int32_t skin ) { //Update skinid in object class to appear name in scoreboard and fix for some things // reinterpret_cast<xor_value<int32_t>*>( std::uintptr_t( this ) + offsets::ai_base::SkinId )->encrypt( skin ); this->get_character_data_stack( )->base_skin.skin = skin; //Lux has same skinid but diff model we have to handle it, game receives packets and calls Push function to change skin we do same but don't pushing new class but modify existing // if ( fnv::hash_runtime( this->get_character_data_stack( )->base_skin.model.str ) == FNV( "Lux" ) ) { if ( skin == 7 ) { if ( this->get_character_data_stack( )->stack.empty( ) ) { this->get_character_data_stack( )->push( model, skin ); return; } auto& last = this->get_character_data_stack( )->stack.back( ); last.skin = skin; last.model.str = model; last.model.length = strlen( model ); last.model.capacity = last.model.length + 1; } else { //Make sure that stack for lux is cleared // this->get_character_data_stack( )->stack.clear( ); } } this->get_character_data_stack( )->update( true ); } obj_ai_base* obj_ai_minion::get_owner( ) { static const auto GetOwnerObject = reinterpret_cast<obj_ai_base * ( __thiscall* )( void* )>( std::uintptr_t( GetModuleHandle( nullptr ) ) + offsets::functions::GetOwnerObject ); return GetOwnerObject( this ); } bool obj_ai_minion::is_lane_minion( ) { return reinterpret_cast<xor_value<bool>*>( std::uintptr_t( this ) + offsets::ai_minion::IsLaneMinion )->decrypt( ); }
45.873418
337
0.73234
slowptr
0438e9cbaa51f7f0861a54a1a739e896e8cdb011
6,573
cc
C++
src/vnsw/agent/ovs_tor_agent/ovsdb_client/test/test_ovs_base.cc
casek14/contrail-controller
18e2572635370b3cb6da2731af049cbeb934f2bb
[ "Apache-2.0" ]
1
2019-01-11T06:16:10.000Z
2019-01-11T06:16:10.000Z
src/vnsw/agent/ovs_tor_agent/ovsdb_client/test/test_ovs_base.cc
chnyda/contrail-controller
398f13bb5bad831550389be6ac3eb3e259642664
[ "Apache-2.0" ]
null
null
null
src/vnsw/agent/ovs_tor_agent/ovsdb_client/test/test_ovs_base.cc
chnyda/contrail-controller
398f13bb5bad831550389be6ac3eb3e259642664
[ "Apache-2.0" ]
1
2020-06-08T11:50:36.000Z
2020-06-08T11:50:36.000Z
/* * Copyright (c) 2015 Juniper Networks, Inc. All rights reserved. */ #include "base/os.h" #include "testing/gunit.h" #include <base/logging.h> #include <io/event_manager.h> #include <io/test/event_manager_test.h> #include <tbb/task.h> #include <base/task.h> #include <cmn/agent_cmn.h> #include "cfg/cfg_init.h" #include "cfg/cfg_interface.h" #include "pkt/pkt_init.h" #include "services/services_init.h" #include "vrouter/ksync/ksync_init.h" #include "oper/interface_common.h" #include "oper/nexthop.h" #include "oper/tunnel_nh.h" #include "route/route.h" #include "oper/vrf.h" #include "oper/mpls.h" #include "oper/vm.h" #include "oper/vn.h" #include "filter/acl.h" #include "test_cmn_util.h" #include "vr_types.h" #include "xmpp/xmpp_init.h" #include "xmpp/test/xmpp_test_util.h" #include "vr_types.h" #include "control_node_mock.h" #include "xml/xml_pugi.h" #include "controller/controller_peer.h" #include "controller/controller_export.h" #include "controller/controller_vrf_export.h" #include "ovs_tor_agent/ovsdb_client/ovsdb_route_peer.h" #include "ovs_tor_agent/ovsdb_client/physical_switch_ovsdb.h" #include "ovs_tor_agent/ovsdb_client/logical_switch_ovsdb.h" #include "ovs_tor_agent/ovsdb_client/physical_port_ovsdb.h" #include "ovs_tor_agent/ovsdb_client/vrf_ovsdb.h" #include "ovs_tor_agent/ovsdb_client/vlan_port_binding_ovsdb.h" #include "ovs_tor_agent/ovsdb_client/unicast_mac_local_ovsdb.h" #include "test_ovs_agent_init.h" #include <ovsdb_types.h> using namespace pugi; using namespace OVSDB; EventManager evm1; ServerThread *thread1; test::ControlNodeMock *bgp_peer1; EventManager evm2; ServerThread *thread2; test::ControlNodeMock *bgp_peer2; void RouterIdDepInit(Agent *agent) { Agent::GetInstance()->controller()->Connect(); } class OvsBaseTest : public ::testing::Test { protected: OvsBaseTest() { } virtual void SetUp() { agent_ = Agent::GetInstance(); init_ = static_cast<TestOvsAgentInit *>(client->agent_init()); peer_manager_ = init_->ovs_peer_manager(); WAIT_FOR(100, 10000, (tcp_session_ = static_cast<OvsdbClientTcpSession *> (init_->ovsdb_client()->NextSession(NULL))) != NULL); WAIT_FOR(100, 10000, (tcp_session_->client_idl() != NULL)); WAIT_FOR(100, 10000, (tcp_session_->status() == string("Established"))); client->WaitForIdle(); WAIT_FOR(100, 10000, (!tcp_session_->client_idl()->IsMonitorInProcess())); client->WaitForIdle(); } virtual void TearDown() { } Agent *agent_; TestOvsAgentInit *init_; OvsPeerManager *peer_manager_; OvsdbClientTcpSession *tcp_session_; }; TEST_F(OvsBaseTest, connection) { WAIT_FOR(100, 10000, (tcp_session_->status() == string("Established"))); OvsdbClientReq *req = new OvsdbClientReq(); req->HandleRequest(); client->WaitForIdle(); req->Release(); } TEST_F(OvsBaseTest, physical_router) { PhysicalSwitchTable *table = tcp_session_->client_idl()->physical_switch_table(); PhysicalSwitchEntry key(table, "test-router"); WAIT_FOR(100, 10000, (table->FindActiveEntry(&key) != NULL)); OvsdbPhysicalSwitchReq *req = new OvsdbPhysicalSwitchReq(); req->HandleRequest(); client->WaitForIdle(); req->Release(); } TEST_F(OvsBaseTest, physical_port) { PhysicalPortTable *table = tcp_session_->client_idl()->physical_port_table(); PhysicalPortEntry key(table, "test-router", "ge-0/0/0"); WAIT_FOR(100, 10000, (table->FindActiveEntry(&key) != NULL)); PhysicalPortEntry key1(table, "test-router", "ge-0/0/1"); WAIT_FOR(100, 10000, (table->FindActiveEntry(&key1) != NULL)); PhysicalPortEntry key2(table, "test-router", "ge-0/0/2"); WAIT_FOR(100, 10000, (table->FindActiveEntry(&key2) != NULL)); PhysicalPortEntry key3(table, "test-router", "ge-0/0/3"); WAIT_FOR(100, 10000, (table->FindActiveEntry(&key3) != NULL)); PhysicalPortEntry key4(table, "test-router", "ge-0/0/4"); WAIT_FOR(100, 10000, (table->FindActiveEntry(&key4) != NULL)); PhysicalPortEntry key5(table, "test-router", "ge-0/0/47"); WAIT_FOR(100, 10000, (table->FindActiveEntry(&key5) != NULL)); OvsdbPhysicalPortReq *req = new OvsdbPhysicalPortReq(); req->HandleRequest(); client->WaitForIdle(); req->Release(); } TEST_F(OvsBaseTest, VrfAuditRead) { VrfOvsdbObject *table = tcp_session_->client_idl()->vrf_ovsdb(); VrfOvsdbEntry vrf_key(table, UuidToString(MakeUuid(1))); WAIT_FOR(1000, 10000, (table->Find(&vrf_key) != NULL)); OvsdbLogicalSwitchReq *req = new OvsdbLogicalSwitchReq(); req->HandleRequest(); client->WaitForIdle(); req->Release(); OvsdbMulticastMacLocalReq *mcast_req = new OvsdbMulticastMacLocalReq(); mcast_req->HandleRequest(); client->WaitForIdle(); mcast_req->Release(); OvsdbUnicastMacRemoteReq *mac_req = new OvsdbUnicastMacRemoteReq(); mac_req->HandleRequest(); client->WaitForIdle(); mac_req->Release(); } TEST_F(OvsBaseTest, VlanPortBindingAuditRead) { VlanPortBindingTable *table = tcp_session_->client_idl()->vlan_port_table(); VlanPortBindingEntry key(table, "test-router", "ge-0/0/0", 100, ""); WAIT_FOR(1000, 10000, (table->Find(&key) != NULL)); OvsdbVlanPortBindingReq *req = new OvsdbVlanPortBindingReq(); req->HandleRequest(); client->WaitForIdle(); req->Release(); } TEST_F(OvsBaseTest, connection_close) { // Take reference to idl so that session object itself is not deleted. OvsdbClientIdlPtr tcp_idl = tcp_session_->client_idl(); tcp_session_->TriggerClose(); client->WaitForIdle(); // Validate that keepalive timer has stopped, for the idl WAIT_FOR(100, 10000, (tcp_idl->IsKeepAliveTimerActive() == false)); UnicastMacLocalOvsdb *ucast_local_table = tcp_idl->unicast_mac_local_ovsdb(); // Validate that vrf re-eval queue of unicast mac local // table has stopped WAIT_FOR(100, 10000, (ucast_local_table->IsVrfReEvalQueueActive() == false)); // release idl reference tcp_idl = NULL; WAIT_FOR(100, 10000, (tcp_session_ = static_cast<OvsdbClientTcpSession *> (init_->ovsdb_client()->NextSession(NULL))) != NULL); } int main(int argc, char *argv[]) { GETUSERARGS(); // override with true to initialize ovsdb server and client ksync_init = true; client = OvsTestInit(init_file, ksync_init); int ret = RUN_ALL_TESTS(); TestShutdown(); return ret; }
30.859155
82
0.694964
casek14
043ac0b5c34ad8ecec530d8db83cb7eba171b072
2,298
cpp
C++
lib/spdk/BdevStats.cpp
janlt/daqdb
04ff602fe0a6c199a782b877203b8b8b9d3fec66
[ "Apache-2.0" ]
22
2019-02-08T17:23:12.000Z
2021-10-12T06:35:37.000Z
lib/spdk/BdevStats.cpp
janlt/daqdb
04ff602fe0a6c199a782b877203b8b8b9d3fec66
[ "Apache-2.0" ]
8
2019-02-11T06:30:47.000Z
2020-04-22T09:49:44.000Z
lib/spdk/BdevStats.cpp
daq-db/daqdb
e30afe8a9a4727e60d0c1122d28679a4ce326844
[ "Apache-2.0" ]
10
2019-02-11T10:26:52.000Z
2019-09-16T20:49:25.000Z
/** * Copyright (c) 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <time.h> #include <iostream> #include <sstream> #include <string> #include "BdevStats.h" namespace DaqDB { /* * BdevStats */ std::ostringstream &BdevStats::formatWriteBuf(std::ostringstream &buf, const char *bdev_addr) { buf << "bdev_addr[" << bdev_addr << "] write_compl_cnt[" << write_compl_cnt << "] write_err_cnt[" << write_err_cnt << "] outs_io_cnt[" << outstanding_io_cnt << "]"; return buf; } std::ostringstream &BdevStats::formatReadBuf(std::ostringstream &buf, const char *bdev_addr) { buf << "bdev_addr[" << bdev_addr << "] read_compl_cnt[" << read_compl_cnt << "] read_err_cnt[" << read_err_cnt << "] outs_io_cnt[" << outstanding_io_cnt << "]"; return buf; } void BdevStats::printWritePer(std::ostream &os, const char *bdev_addr) { if (!(write_compl_cnt % quant_per)) { std::ostringstream buf; char time_buf[128]; time_t now = time(0); strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S.000", localtime(&now)); os << formatWriteBuf(buf, bdev_addr).str() << " " << time_buf << std::endl; } } void BdevStats::printReadPer(std::ostream &os, const char *bdev_addr) { if (!(read_compl_cnt % quant_per)) { std::ostringstream buf; char time_buf[128]; time_t now = time(0); strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S.000", localtime(&now)); os << formatReadBuf(buf, bdev_addr).str() << " " << time_buf << std::endl; } } } // namespace DaqDB
31.916667
79
0.60705
janlt
043c2ada10f75b08679083126bd169f4cc59f250
601
cpp
C++
UVa 10508 - Word Morphing/sample/10508 - Word Morphing.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2020-11-24T03:17:21.000Z
2020-11-24T03:17:21.000Z
UVa 10508 - Word Morphing/sample/10508 - Word Morphing.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
null
null
null
UVa 10508 - Word Morphing/sample/10508 - Word Morphing.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2021-04-11T16:22:31.000Z
2021-04-11T16:22:31.000Z
#include <stdio.h> char word[1005][1005]; int main() { int n, m, i, j; int idx[1005]; while(scanf("%d %d", &n, &m) == 2) { while(getchar() != '\n'); gets(word[0]); idx[0] = 0; for(i = 1; i < n; i++) { int cnt = 0; gets(word[i]); for(j = 0; j < m; j++) if(word[i][j] != word[0][j]) cnt++; idx[cnt] = i; } for(i = 0; i < n; i++) puts(word[idx[i]]); } return 0; } /* 6 5 remar pitos remas remos retos ritos 5 4 pato lisa pata pita pisa */
15.410256
44
0.386023
tadvi
043cb4f04d9e8e2afacf1f781cc1f86786d7a247
551
hpp
C++
include/lol/def/LolLootPlayerLootMap.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
1
2020-07-22T11:14:55.000Z
2020-07-22T11:14:55.000Z
include/lol/def/LolLootPlayerLootMap.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
null
null
null
include/lol/def/LolLootPlayerLootMap.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
4
2018-12-01T22:48:21.000Z
2020-07-22T11:14:56.000Z
#pragma once #include "../base_def.hpp" #include "LolLootPlayerLoot.hpp" namespace lol { struct LolLootPlayerLootMap { int64_t version; std::map<std::string, LolLootPlayerLoot> playerLoot; }; inline void to_json(json& j, const LolLootPlayerLootMap& v) { j["version"] = v.version; j["playerLoot"] = v.playerLoot; } inline void from_json(const json& j, LolLootPlayerLootMap& v) { v.version = j.at("version").get<int64_t>(); v.playerLoot = j.at("playerLoot").get<std::map<std::string, LolLootPlayerLoot>>(); } }
32.411765
87
0.675136
Maufeat
043e9e1e97af908abcd322c0a6ce04f7d2d4ca3d
629
cpp
C++
lib/air/tool/cli/Main.cpp
mjlee34/poseidonos
8eff75c5ba7af8090d3ff4ac51d7507b37571f9b
[ "BSD-3-Clause" ]
null
null
null
lib/air/tool/cli/Main.cpp
mjlee34/poseidonos
8eff75c5ba7af8090d3ff4ac51d7507b37571f9b
[ "BSD-3-Clause" ]
null
null
null
lib/air/tool/cli/Main.cpp
mjlee34/poseidonos
8eff75c5ba7af8090d3ff4ac51d7507b37571f9b
[ "BSD-3-Clause" ]
null
null
null
#include <stdio.h> #include <unistd.h> #include "tool/cli/CliRecv.h" #include "tool/cli/CliSend.h" int main(int argc, char* argv[]) { int pid = getpid(); air::CliResult* cli_result = new air::CliResult{}; air::CliSend* cli_send = new air::CliSend{cli_result, pid}; air::CliRecv* cli_recv = new air::CliRecv{cli_result, pid}; int num_cmd{0}; int target_pid{-1}; num_cmd = cli_send->Send(argc, argv, target_pid); if (0 < num_cmd) { cli_recv->Receive(num_cmd, target_pid); } cli_result->PrintCliResult(); delete cli_send; delete cli_recv; delete cli_result; }
19.65625
63
0.63911
mjlee34
0440b22e726607f0bc25c07f77966ae5042e7172
2,488
cc
C++
google_apis/gaia/core_account_id.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
google_apis/gaia/core_account_id.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
google_apis/gaia/core_account_id.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2019 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 "google_apis/gaia/core_account_id.h" #include "base/check.h" namespace { // Returns whether the string looks like an email (the test is // crude an only checks whether it includes an '@'). bool IsEmailString(const std::string& string) { return string.find('@') != std::string::npos; } } // anonymous namespace CoreAccountId::CoreAccountId() = default; CoreAccountId::CoreAccountId(const CoreAccountId&) = default; CoreAccountId::CoreAccountId(CoreAccountId&&) noexcept = default; CoreAccountId::~CoreAccountId() = default; CoreAccountId& CoreAccountId::operator=(const CoreAccountId&) = default; CoreAccountId& CoreAccountId::operator=(CoreAccountId&&) noexcept = default; // static CoreAccountId CoreAccountId::FromGaiaId(const std::string& gaia_id) { if (gaia_id.empty()) return CoreAccountId(); DCHECK(!IsEmailString(gaia_id)) << "Expected a Gaia ID and got an email [actual = " << gaia_id << "]"; return CoreAccountId::FromString(gaia_id); } // static CoreAccountId CoreAccountId::FromEmail(const std::string& email) { if (email.empty()) return CoreAccountId(); DCHECK(IsEmailString(email)) << "Expected an email [actual = " << email << "]"; return CoreAccountId::FromString(email); } // static CoreAccountId CoreAccountId::FromString(const std::string value) { CoreAccountId account_id; account_id.id_ = value; return account_id; } bool CoreAccountId::empty() const { return id_.empty(); } bool CoreAccountId::IsEmail() const { return IsEmailString(id_); } const std::string& CoreAccountId::ToString() const { return id_; } bool operator<(const CoreAccountId& lhs, const CoreAccountId& rhs) { return lhs.ToString() < rhs.ToString(); } bool operator==(const CoreAccountId& lhs, const CoreAccountId& rhs) { return lhs.ToString() == rhs.ToString(); } bool operator!=(const CoreAccountId& lhs, const CoreAccountId& rhs) { return lhs.ToString() != rhs.ToString(); } std::ostream& operator<<(std::ostream& out, const CoreAccountId& a) { return out << a.ToString(); } std::vector<std::string> ToStringList( const std::vector<CoreAccountId>& account_ids) { std::vector<std::string> account_ids_string; for (const auto& account_id : account_ids) account_ids_string.push_back(account_id.ToString()); return account_ids_string; }
27.644444
76
0.724277
zealoussnow
04429fd235d6659428bd0141cf64515cf9d012af
3,328
hpp
C++
source/external/mongo-cxx-driver/include/mongocxx/v_noabi/mongocxx/options/insert.hpp
VincentPT/vschk
f8f40a7666d80224a9a24c097a4d52f5507d03de
[ "MIT" ]
null
null
null
source/external/mongo-cxx-driver/include/mongocxx/v_noabi/mongocxx/options/insert.hpp
VincentPT/vschk
f8f40a7666d80224a9a24c097a4d52f5507d03de
[ "MIT" ]
null
null
null
source/external/mongo-cxx-driver/include/mongocxx/v_noabi/mongocxx/options/insert.hpp
VincentPT/vschk
f8f40a7666d80224a9a24c097a4d52f5507d03de
[ "MIT" ]
1
2021-06-18T05:00:10.000Z
2021-06-18T05:00:10.000Z
// Copyright 2014 MongoDB 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. #pragma once #include <bsoncxx/document/view.hpp> #include <bsoncxx/stdx/optional.hpp> #include <mongocxx/stdx.hpp> #include <mongocxx/write_concern.hpp> #include <mongocxx/config/prelude.hpp> namespace mongocxx { MONGOCXX_INLINE_NAMESPACE_BEGIN namespace options { /// /// Class representing the optional arguments to a MongoDB insert operation /// class MONGOCXX_API insert { public: /// /// Sets the bypass_document_validation option. /// If true, allows the write to opt-out of document level validation. /// /// @note /// On servers >= 3.2, the server applies validation by default. On servers < 3.2, this option /// is ignored. /// /// @param bypass_document_validation /// Whether or not to bypass document validation /// insert& bypass_document_validation(bool bypass_document_validation); /// /// Gets the current value of the bypass_document_validation option. /// /// @return The optional value of the bypass_document_validation option. /// const stdx::optional<bool>& bypass_document_validation() const; /// /// Sets the write_concern for this operation. /// /// @param wc /// The new write_concern. /// /// @see https://docs.mongodb.com/master/core/write-concern/ /// insert& write_concern(class write_concern wc); /// /// The current write_concern for this operation. /// /// @return The current write_concern. /// /// @see https://docs.mongodb.com/master/core/write-concern/ /// const stdx::optional<class write_concern>& write_concern() const; /// /// @note: This applies only to insert_many and is ignored for insert_one. /// /// If true, when an insert fails, return without performing the remaining /// writes. If false, when a write fails, continue with the remaining /// writes, if any. Inserts can be performed in any order if this is false. /// Defaults to true. /// /// @param ordered /// Whether or not the insert_many will be ordered. /// /// @see https://docs.mongodb.com/master/reference/method/db.collection.insert/ /// insert& ordered(bool ordered); /// /// The current ordered value for this operation. /// /// @return The current ordered value. /// /// @see https://docs.mongodb.com/master/reference/method/db.collection.insert/ /// const stdx::optional<bool>& ordered() const; private: stdx::optional<class write_concern> _write_concern; stdx::optional<bool> _ordered; stdx::optional<bool> _bypass_document_validation; }; } // namespace options MONGOCXX_INLINE_NAMESPACE_END } // namespace mongocxx #include <mongocxx/config/postlude.hpp>
31.102804
100
0.682091
VincentPT
04458d4bd362c54a9a27195322e1ad616d5d4a14
2,320
cpp
C++
test/test_tree/test_splits.cpp
guillempalou/eigenml
3991ddbfd01032cbbe698f6ec35eecbfe127e9b4
[ "Apache-2.0" ]
null
null
null
test/test_tree/test_splits.cpp
guillempalou/eigenml
3991ddbfd01032cbbe698f6ec35eecbfe127e9b4
[ "Apache-2.0" ]
null
null
null
test/test_tree/test_splits.cpp
guillempalou/eigenml
3991ddbfd01032cbbe698f6ec35eecbfe127e9b4
[ "Apache-2.0" ]
null
null
null
#include <gtest/gtest.h> #include <eigenml/decision_tree/decision_tree_traits.hpp> #include <eigenml/decision_tree/splitting/find_thresholds.hpp> #include <eigenml/decision_tree/splitting/criteria.hpp> using namespace eigenml; using namespace eigenml::decision_tree; typedef tree_traits<ModelType::kSupervisedClassifier, Matrix, Matrix> classification_tree_traits; TEST(ThresholdFinding, Entropy) { classification_tree_traits::DistributionType hist; hist.add_sample(0, 10); hist.add_sample(1, 10); ValueAndWeight v = entropy(hist); ASSERT_DOUBLE_EQ(v.first, 1); ASSERT_DOUBLE_EQ(v.second, 20); } TEST(ThresholdFinding, Gini) { classification_tree_traits::DistributionType hist; hist.add_sample(0, 10); hist.add_sample(1, 10); ValueAndWeight v = gini(hist); ASSERT_DOUBLE_EQ(v.first, 0.5); ASSERT_DOUBLE_EQ(v.second, 20); } TEST(ThresholdFinding, SimplethresholdEntropy) { size_t N = 2; Matrix X(N, 1); Vector Y(N); X << 1, 2; Y << 0, 1; IdxVector idx{0, 1}; IdxVector sorted{0, 1}; typedef classification_tree_traits::DistributionType DistributionType; typedef classification_tree_traits::CriterionType CriterionType; auto criterion = CriterionType(entropy<DistributionType>); ThresholdFinder<DistributionType, CriterionType, Matrix, Vector> splitter; ThresholdSplit split = splitter.find_threshold(X, Y, 0, idx, sorted, criterion); ASSERT_DOUBLE_EQ(1, split.threshold); ASSERT_DOUBLE_EQ(2, split.gain); ASSERT_EQ(0, split.feature_index); ASSERT_EQ(0, split.threshold_index); } TEST(ThresholdFinding, SimplethresholdGini) { size_t N = 2; Matrix X(N, 1); Vector Y(N); X << 1, 2; Y << 0, 1; IdxVector idx{0, 1}; IdxVector sorted{0, 1}; typedef classification_tree_traits::DistributionType DistributionType; typedef classification_tree_traits::CriterionType CriterionType; auto criterion = CriterionType(gini<DistributionType>); ThresholdFinder<DistributionType, CriterionType, Matrix, Vector> splitter; ThresholdSplit split = splitter.find_threshold(X, Y, 0, idx, sorted, criterion); ASSERT_DOUBLE_EQ(1, split.threshold); ASSERT_DOUBLE_EQ(1, split.gain); ASSERT_EQ(0, split.feature_index); ASSERT_EQ(0, split.threshold_index); }
30.12987
97
0.731466
guillempalou
044640c9f5523e8f3ad733ea5e4d0e19963a13cc
5,021
cc
C++
pw_log_rpc/log_filter.cc
Tiggerlaboratoriet/pigweed
7d7e7ad6223433f45af680f43ab4d75e23ad3257
[ "Apache-2.0" ]
null
null
null
pw_log_rpc/log_filter.cc
Tiggerlaboratoriet/pigweed
7d7e7ad6223433f45af680f43ab4d75e23ad3257
[ "Apache-2.0" ]
null
null
null
pw_log_rpc/log_filter.cc
Tiggerlaboratoriet/pigweed
7d7e7ad6223433f45af680f43ab4d75e23ad3257
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 The Pigweed Authors // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. #include "pw_log_rpc/log_filter.h" #include "pw_log/levels.h" #include "pw_protobuf/decoder.h" #include "pw_status/try.h" namespace pw::log_rpc { namespace { // Returns true if the provided log parameters match the given filter rule. bool IsRuleMet(const Filter::Rule& rule, uint32_t level, ConstByteSpan module, uint32_t flags, ConstByteSpan thread) { if (level < static_cast<uint32_t>(rule.level_greater_than_or_equal)) { return false; } if ((rule.any_flags_set != 0) && ((flags & rule.any_flags_set) == 0)) { return false; } if (!rule.module_equals.empty() && !std::equal(module.begin(), module.end(), rule.module_equals.begin(), rule.module_equals.end())) { return false; } if (!rule.thread_equals.empty() && !std::equal(thread.begin(), thread.end(), rule.thread_equals.begin(), rule.thread_equals.end())) { return false; } return true; } } // namespace Status Filter::UpdateRulesFromProto(ConstByteSpan buffer) { if (rules_.empty()) { return Status::FailedPrecondition(); } // Reset rules. for (auto& rule : rules_) { rule = {}; } protobuf::Decoder decoder(buffer); Status status; for (size_t i = 0; (i < rules_.size()) && (status = decoder.Next()).ok(); ++i) { ConstByteSpan rule_buffer; PW_TRY(decoder.ReadBytes(&rule_buffer)); protobuf::Decoder rule_decoder(rule_buffer); while ((status = rule_decoder.Next()).ok()) { switch ( static_cast<log::FilterRule::Fields>(rule_decoder.FieldNumber())) { case log::FilterRule::Fields::LEVEL_GREATER_THAN_OR_EQUAL: PW_TRY(rule_decoder.ReadUint32(reinterpret_cast<uint32_t*>( &rules_[i].level_greater_than_or_equal))); break; case log::FilterRule::Fields::MODULE_EQUALS: { ConstByteSpan module; PW_TRY(rule_decoder.ReadBytes(&module)); if (module.size() > rules_[i].module_equals.max_size()) { return Status::InvalidArgument(); } rules_[i].module_equals.assign(module.begin(), module.end()); } break; case log::FilterRule::Fields::ANY_FLAGS_SET: PW_TRY(rule_decoder.ReadUint32(&rules_[i].any_flags_set)); break; case log::FilterRule::Fields::ACTION: PW_TRY(rule_decoder.ReadUint32( reinterpret_cast<uint32_t*>(&rules_[i].action))); break; case log::FilterRule::Fields::THREAD_EQUALS: { ConstByteSpan thread; PW_TRY(rule_decoder.ReadBytes(&thread)); if (thread.size() > rules_[i].thread_equals.max_size()) { return Status::InvalidArgument(); } rules_[i].thread_equals.assign(thread.begin(), thread.end()); } break; } } } return status.IsOutOfRange() ? OkStatus() : status; } bool Filter::ShouldDropLog(ConstByteSpan entry) const { if (rules_.empty()) { return false; } uint32_t log_level = 0; ConstByteSpan log_module; ConstByteSpan log_thread; uint32_t log_flags = 0; protobuf::Decoder decoder(entry); while (decoder.Next().ok()) { switch (static_cast<log::LogEntry::Fields>(decoder.FieldNumber())) { case log::LogEntry::Fields::LINE_LEVEL: if (decoder.ReadUint32(&log_level).ok()) { log_level &= PW_LOG_LEVEL_BITMASK; } break; case log::LogEntry::Fields::MODULE: decoder.ReadBytes(&log_module).IgnoreError(); break; case log::LogEntry::Fields::FLAGS: decoder.ReadUint32(&log_flags).IgnoreError(); break; case log::LogEntry::Fields::THREAD: decoder.ReadBytes(&log_thread).IgnoreError(); break; default: break; } } // Follow the action of the first rule whose condition is met. for (const auto& rule : rules_) { if (rule.action == Filter::Rule::Action::kInactive) { continue; } if (IsRuleMet(rule, log_level, log_module, log_flags, log_thread)) { return rule.action == Filter::Rule::Action::kDrop; } } return false; } } // namespace pw::log_rpc
33.251656
80
0.605457
Tiggerlaboratoriet
04483907ef40fb6a91d8701926c809d4c9be6bf6
7,348
cc
C++
ash/system/unified/unified_system_tray_view.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
ash/system/unified/unified_system_tray_view.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
ash/system/unified/unified_system_tray_view.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2018 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 "ash/system/unified/unified_system_tray_view.h" #include "ash/public/cpp/app_list/app_list_features.h" #include "ash/system/tray/interacted_by_tap_recorder.h" #include "ash/system/tray/tray_constants.h" #include "ash/system/unified/feature_pod_button.h" #include "ash/system/unified/feature_pods_container_view.h" #include "ash/system/unified/top_shortcuts_view.h" #include "ash/system/unified/unified_message_center_view.h" #include "ash/system/unified/unified_system_info_view.h" #include "ash/system/unified/unified_system_tray_controller.h" #include "ash/system/unified/unified_system_tray_model.h" #include "ui/message_center/message_center.h" #include "ui/views/background.h" #include "ui/views/layout/box_layout.h" #include "ui/views/painter.h" namespace ash { namespace { std::unique_ptr<views::Background> CreateUnifiedBackground() { return views::CreateBackgroundFromPainter( views::Painter::CreateSolidRoundRectPainter( app_list::features::IsBackgroundBlurEnabled() ? kUnifiedMenuBackgroundColorWithBlur : kUnifiedMenuBackgroundColor, kUnifiedTrayCornerRadius)); } class DetailedViewContainer : public views::View { public: DetailedViewContainer() = default; ~DetailedViewContainer() override = default; void Layout() override { for (int i = 0; i < child_count(); ++i) child_at(i)->SetBoundsRect(GetContentsBounds()); views::View::Layout(); } private: DISALLOW_COPY_AND_ASSIGN(DetailedViewContainer); }; } // namespace UnifiedSlidersContainerView::UnifiedSlidersContainerView( bool initially_expanded) : expanded_amount_(initially_expanded ? 1.0 : 0.0) { SetVisible(initially_expanded); } UnifiedSlidersContainerView::~UnifiedSlidersContainerView() = default; void UnifiedSlidersContainerView::SetExpandedAmount(double expanded_amount) { DCHECK(0.0 <= expanded_amount && expanded_amount <= 1.0); SetVisible(expanded_amount > 0.0); expanded_amount_ = expanded_amount; PreferredSizeChanged(); UpdateOpacity(); } void UnifiedSlidersContainerView::Layout() { int y = 0; for (int i = 0; i < child_count(); ++i) { views::View* child = child_at(i); int height = child->GetHeightForWidth(kTrayMenuWidth); child->SetBounds(0, y, kTrayMenuWidth, height); y += height; } } gfx::Size UnifiedSlidersContainerView::CalculatePreferredSize() const { int height = 0; for (int i = 0; i < child_count(); ++i) height += child_at(i)->GetHeightForWidth(kTrayMenuWidth); return gfx::Size(kTrayMenuWidth, height * expanded_amount_); } void UnifiedSlidersContainerView::UpdateOpacity() { for (int i = 0; i < child_count(); ++i) { views::View* child = child_at(i); double opacity = 1.0; if (child->y() > height()) opacity = 0.0; else if (child->bounds().bottom() < height()) opacity = 1.0; else opacity = static_cast<double>(height() - child->y()) / child->height(); child->layer()->SetOpacity(opacity); } } UnifiedSystemTrayView::UnifiedSystemTrayView( UnifiedSystemTrayController* controller, bool initially_expanded) : controller_(controller), message_center_view_( new UnifiedMessageCenterView(message_center::MessageCenter::Get())), top_shortcuts_view_(new TopShortcutsView(controller_)), feature_pods_container_(new FeaturePodsContainerView(initially_expanded)), sliders_container_(new UnifiedSlidersContainerView(initially_expanded)), system_info_view_(new UnifiedSystemInfoView()), system_tray_container_(new views::View()), detailed_view_container_(new DetailedViewContainer()), interacted_by_tap_recorder_( std::make_unique<InteractedByTapRecorder>(this)) { DCHECK(controller_); auto* layout = SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::kVertical, gfx::Insets(), kUnifiedNotificationCenterSpacing)); SetBackground(CreateUnifiedBackground()); SetPaintToLayer(); layer()->SetFillsBoundsOpaquely(false); AddChildView(message_center_view_); layout->SetFlexForView(message_center_view_, 1); system_tray_container_->SetLayoutManager( std::make_unique<views::BoxLayout>(views::BoxLayout::kVertical)); system_tray_container_->SetBackground(CreateUnifiedBackground()); AddChildView(system_tray_container_); system_tray_container_->AddChildView(top_shortcuts_view_); system_tray_container_->AddChildView(feature_pods_container_); system_tray_container_->AddChildView(sliders_container_); system_tray_container_->AddChildView(system_info_view_); detailed_view_container_->SetVisible(false); AddChildView(detailed_view_container_); } UnifiedSystemTrayView::~UnifiedSystemTrayView() = default; void UnifiedSystemTrayView::SetMaxHeight(int max_height) { message_center_view_->SetMaxHeight(max_height); } void UnifiedSystemTrayView::AddFeaturePodButton(FeaturePodButton* button) { feature_pods_container_->AddChildView(button); } void UnifiedSystemTrayView::AddSliderView(views::View* slider_view) { slider_view->SetPaintToLayer(); slider_view->layer()->SetFillsBoundsOpaquely(false); sliders_container_->AddChildView(slider_view); } void UnifiedSystemTrayView::SetDetailedView(views::View* detailed_view) { auto system_tray_size = system_tray_container_->GetPreferredSize(); system_tray_container_->SetVisible(false); detailed_view_container_->RemoveAllChildViews(true /* delete_children */); detailed_view_container_->AddChildView(detailed_view); detailed_view_container_->SetPreferredSize(system_tray_size); detailed_view_container_->SetVisible(true); detailed_view->InvalidateLayout(); Layout(); } void UnifiedSystemTrayView::SetExpandedAmount(double expanded_amount) { DCHECK(0.0 <= expanded_amount && expanded_amount <= 1.0); if (expanded_amount == 1.0 || expanded_amount == 0.0) top_shortcuts_view_->SetExpanded(expanded_amount == 1.0); feature_pods_container_->SetExpandedAmount(expanded_amount); sliders_container_->SetExpandedAmount(expanded_amount); PreferredSizeChanged(); // It is possible that the ratio between |message_center_view_| and others // can change while the bubble size remain unchanged. Layout(); } void UnifiedSystemTrayView::OnGestureEvent(ui::GestureEvent* event) { gfx::Point screen_location = event->location(); ConvertPointToScreen(this, &screen_location); switch (event->type()) { case ui::ET_GESTURE_SCROLL_BEGIN: controller_->BeginDrag(screen_location); event->SetHandled(); break; case ui::ET_GESTURE_SCROLL_UPDATE: controller_->UpdateDrag(screen_location); event->SetHandled(); break; case ui::ET_GESTURE_END: controller_->EndDrag(screen_location); event->SetHandled(); break; default: break; } } void UnifiedSystemTrayView::ChildPreferredSizeChanged(views::View* child) { // Size change is always caused by SetExpandedAmount except for // |message_center_view_|. So we only have to call PreferredSizeChanged() // here when the child is |message_center_view_|. if (child == message_center_view_) PreferredSizeChanged(); } } // namespace ash
34.824645
80
0.753674
zipated
0448f440d168700d188da35d1fcba68c95c5ed80
4,150
cpp
C++
IO/src/av/src/export.cpp
tlalexander/stitchEm
cdff821ad2c500703e6cb237ec61139fce7bf11c
[ "MIT" ]
182
2019-04-19T12:38:30.000Z
2022-03-20T16:48:20.000Z
IO/src/av/src/export.cpp
tlalexander/stitchEm
cdff821ad2c500703e6cb237ec61139fce7bf11c
[ "MIT" ]
107
2019-04-23T10:49:35.000Z
2022-03-02T18:12:28.000Z
IO/src/av/src/export.cpp
tlalexander/stitchEm
cdff821ad2c500703e6cb237ec61139fce7bf11c
[ "MIT" ]
59
2019-06-04T11:27:25.000Z
2022-03-17T23:49:49.000Z
// Copyright (c) 2012-2017 VideoStitch SAS // Copyright (c) 2018 stitchEm #include "export.hpp" #include "videoReader.hpp" #include "netStreamReader.hpp" #include "avWriter.hpp" #include "libvideostitch/logging.hpp" #include "libvideostitch/output.hpp" #include "libvideostitch/plugin.hpp" #include "libvideostitch/ptv.hpp" #include "libvideostitch/status.hpp" #include <ostream> /** \name Services for reader plugin. */ //\{ extern "C" VS_PLUGINS_EXPORT VideoStitch::Potential<VideoStitch::Input::Reader>* createReaderFn( VideoStitch::Ptv::Value const* config, VideoStitch::Plugin::VSReaderPlugin::Config runtime) { if (VideoStitch::Input::FFmpegReader::handles(config->asString()) || VideoStitch::Input::netStreamReader::handles(config->asString())) { auto potLibAvReader = VideoStitch::Input::LibavReader::create(config->asString(), runtime); if (potLibAvReader.ok()) { return new VideoStitch::Potential<VideoStitch::Input::Reader>(potLibAvReader.release()); } else { return new VideoStitch::Potential<VideoStitch::Input::Reader>(potLibAvReader.status()); } } return new VideoStitch::Potential<VideoStitch::Input::Reader>{VideoStitch::Origin::Input, VideoStitch::ErrType::InvalidConfiguration, "Reader doesn't handle this configuration"}; } extern "C" VS_PLUGINS_EXPORT bool handleReaderFn(VideoStitch::Ptv::Value const* config) { if (config && config->getType() == VideoStitch::Ptv::Value::STRING) { return (VideoStitch::Input::FFmpegReader::handles(config->asString()) || VideoStitch::Input::netStreamReader::handles(config->asString())); } else { return false; } } extern "C" VS_PLUGINS_EXPORT VideoStitch::Input::ProbeResult probeReaderFn(std::string const& p_filename) { return VideoStitch::Input::LibavReader::probe(p_filename); } //\} /** \name Services for writer plugin. */ //\{ extern "C" VS_PLUGINS_EXPORT VideoStitch::Potential<VideoStitch::Output::Output>* createWriterFn( VideoStitch::Ptv::Value const* config, VideoStitch::Plugin::VSWriterPlugin::Config run_time) { VideoStitch::Output::Output* lReturn = nullptr; VideoStitch::Output::BaseConfig baseConfig; const VideoStitch::Status parseStatus = baseConfig.parse(*config); if (parseStatus.ok()) { lReturn = VideoStitch::Output::LibavWriter::create(*config, run_time.name, baseConfig.baseName, run_time.width, run_time.height, run_time.framerate, run_time.rate, run_time.depth, run_time.layout); if (lReturn) { return new VideoStitch::Potential<VideoStitch::Output::Output>(lReturn); } return new VideoStitch::Potential<VideoStitch::Output::Output>( VideoStitch::Origin::Output, VideoStitch::ErrType::InvalidConfiguration, "Could not create av writer"); } return new VideoStitch::Potential<VideoStitch::Output::Output>( VideoStitch::Origin::Output, VideoStitch::ErrType::InvalidConfiguration, "Could not parse AV Writer configuration", parseStatus); } extern "C" VS_PLUGINS_EXPORT bool handleWriterFn(VideoStitch::Ptv::Value const* config) { bool lReturn(false); VideoStitch::Output::BaseConfig baseConfig; if (baseConfig.parse(*config).ok()) { lReturn = (!strcmp(baseConfig.strFmt, "mp4") || !strcmp(baseConfig.strFmt, "mov")); } else { // TODOLATERSTATUS VideoStitch::Logger::get(VideoStitch::Logger::Verbose) << "avPlugin: cannot parse BaseConfnig" << std::endl; } return lReturn; } //\} #ifdef TestLinking int main() { /** This code is not expected to run: it's just a way to check all required symbols will be in library. */ VideoStitch::Ptv::Value const* config = 0; { VideoStitch::Plugin::VSReaderPlugin::Config runtime; createReaderFn(config, runtime); } handleReaderFn(config); probeReaderFn(std::string()); VideoStitch::Plugin::VSWriterPlugin::Config runtime; createWriterFn(config, runtime); handleWriterFn(config); return 0; } #endif
41.089109
115
0.68747
tlalexander
044d0c1fd78751ffbea415337b6b2fc0c75051ec
29,450
cc
C++
icing/index/main/posting-list-used_test.cc
PixelPlusUI-SnowCone/external_icing
206a7d6b4ab83c6acdb8b14565e2431751c9e4cf
[ "Apache-2.0" ]
null
null
null
icing/index/main/posting-list-used_test.cc
PixelPlusUI-SnowCone/external_icing
206a7d6b4ab83c6acdb8b14565e2431751c9e4cf
[ "Apache-2.0" ]
null
null
null
icing/index/main/posting-list-used_test.cc
PixelPlusUI-SnowCone/external_icing
206a7d6b4ab83c6acdb8b14565e2431751c9e4cf
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 "icing/index/main/posting-list-used.h" #include <fcntl.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <algorithm> #include <cstdint> #include <deque> #include <iterator> #include <memory> #include <random> #include <string> #include <vector> #include "icing/text_classifier/lib3/utils/base/status.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "icing/index/main/posting-list-utils.h" #include "icing/legacy/index/icing-bit-util.h" #include "icing/schema/section.h" #include "icing/store/document-id.h" #include "icing/testing/common-matchers.h" #include "icing/testing/hit-test-utils.h" using std::reverse; using std::vector; using testing::ElementsAre; using testing::ElementsAreArray; using testing::Eq; using testing::IsEmpty; using testing::Le; using testing::Lt; namespace icing { namespace lib { struct HitElt { HitElt() = default; explicit HitElt(const Hit &hit_in) : hit(hit_in) {} static Hit get_hit(const HitElt &hit_elt) { return hit_elt.hit; } Hit hit; }; TEST(PostingListTest, PostingListUsedPrependHitNotFull) { static const int kNumHits = 2551; static const size_t kHitsSize = kNumHits * sizeof(Hit); std::unique_ptr<char[]> hits_buf = std::make_unique<char[]>(kHitsSize); ICING_ASSERT_OK_AND_ASSIGN( PostingListUsed pl_used, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf.get()), kHitsSize)); // Make used. Hit hit0(/*section_id=*/0, 0, /*term_frequency=*/56); pl_used.PrependHit(hit0); // Size = sizeof(uncompressed hit0) int expected_size = sizeof(Hit); EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit0))); Hit hit1(/*section_id=*/0, 1, Hit::kDefaultTermFrequency); pl_used.PrependHit(hit1); // Size = sizeof(uncompressed hit1) // + sizeof(hit0-hit1) + sizeof(hit0::term_frequency) expected_size += 2 + sizeof(Hit::TermFrequency); EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit1, hit0))); Hit hit2(/*section_id=*/0, 2, /*term_frequency=*/56); pl_used.PrependHit(hit2); // Size = sizeof(uncompressed hit2) // + sizeof(hit1-hit2) // + sizeof(hit0-hit1) + sizeof(hit0::term_frequency) expected_size += 2; EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit2, hit1, hit0))); Hit hit3(/*section_id=*/0, 3, Hit::kDefaultTermFrequency); pl_used.PrependHit(hit3); // Size = sizeof(uncompressed hit3) // + sizeof(hit2-hit3) + sizeof(hit2::term_frequency) // + sizeof(hit1-hit2) // + sizeof(hit0-hit1) + sizeof(hit0::term_frequency) expected_size += 2 + sizeof(Hit::TermFrequency); EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit3, hit2, hit1, hit0))); } TEST(PostingListTest, PostingListUsedPrependHitAlmostFull) { constexpr int kHitsSize = 2 * posting_list_utils::min_posting_list_size(); std::unique_ptr<char[]> hits_buf = std::make_unique<char[]>(kHitsSize); ICING_ASSERT_OK_AND_ASSIGN( PostingListUsed pl_used, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf.get()), kHitsSize)); // Fill up the compressed region. // Transitions: // Adding hit0: EMPTY -> NOT_FULL // Adding hit1: NOT_FULL -> NOT_FULL // Adding hit2: NOT_FULL -> NOT_FULL Hit hit0(/*section_id=*/0, 0, Hit::kDefaultTermFrequency); Hit hit1 = CreateHit(hit0, /*desired_byte_length=*/2); Hit hit2 = CreateHit(hit1, /*desired_byte_length=*/2); ICING_EXPECT_OK(pl_used.PrependHit(hit0)); ICING_EXPECT_OK(pl_used.PrependHit(hit1)); ICING_EXPECT_OK(pl_used.PrependHit(hit2)); // Size used will be 2+2+4=8 bytes int expected_size = sizeof(Hit::Value) + 2 + 2; EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit2, hit1, hit0))); // Add one more hit to transition NOT_FULL -> ALMOST_FULL Hit hit3 = CreateHit(hit2, /*desired_byte_length=*/3); ICING_EXPECT_OK(pl_used.PrependHit(hit3)); // Compressed region would be 2+2+3+4=11 bytes, but the compressed region is // only 10 bytes. So instead, the posting list will transition to ALMOST_FULL. // The in-use compressed region will actually shrink from 8 bytes to 7 bytes // because the uncompressed version of hit2 will be overwritten with the // compressed delta of hit2. hit3 will be written to one of the special hits. // Because we're in ALMOST_FULL, the expected size is the size of the pl minus // the one hit used to mark the posting list as ALMOST_FULL. expected_size = kHitsSize - sizeof(Hit); EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit3, hit2, hit1, hit0))); // Add one more hit to transition ALMOST_FULL -> ALMOST_FULL Hit hit4 = CreateHit(hit3, /*desired_byte_length=*/2); ICING_EXPECT_OK(pl_used.PrependHit(hit4)); // There are currently 7 bytes in use in the compressed region. hit3 will have // a 2-byte delta. That delta will fit in the compressed region (which will // now have 9 bytes in use), hit4 will be placed in one of the special hits // and the posting list will remain in ALMOST_FULL. EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit4, hit3, hit2, hit1, hit0))); // Add one more hit to transition ALMOST_FULL -> FULL Hit hit5 = CreateHit(hit4, /*desired_byte_length=*/2); ICING_EXPECT_OK(pl_used.PrependHit(hit5)); // There are currently 9 bytes in use in the compressed region. hit4 will have // a 2-byte delta which will not fit in the compressed region. So hit4 will // remain in one of the special hits and hit5 will occupy the other, making // the posting list FULL. EXPECT_THAT(pl_used.BytesUsed(), Le(kHitsSize)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit5, hit4, hit3, hit2, hit1, hit0))); // The posting list is FULL. Adding another hit should fail. Hit hit6 = CreateHit(hit5, /*desired_byte_length=*/1); EXPECT_THAT(pl_used.PrependHit(hit6), StatusIs(libtextclassifier3::StatusCode::RESOURCE_EXHAUSTED)); } TEST(PostingListTest, PostingListUsedMinSize) { std::unique_ptr<char[]> hits_buf = std::make_unique<char[]>(posting_list_utils::min_posting_list_size()); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf.get()), posting_list_utils::min_posting_list_size())); // PL State: EMPTY EXPECT_THAT(pl_used.BytesUsed(), Eq(0)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(IsEmpty())); // Add a hit, PL should shift to ALMOST_FULL state Hit hit0(/*section_id=*/0, 0, /*term_frequency=*/0, /*is_in_prefix_section=*/false, /*is_prefix_hit=*/true); ICING_EXPECT_OK(pl_used.PrependHit(hit0)); // Size = sizeof(uncompressed hit0) int expected_size = sizeof(Hit); EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit0))); // Add the smallest hit possible - no term_frequency and a delta of 1. PL // should shift to FULL state. Hit hit1(/*section_id=*/0, 0, /*term_frequency=*/0, /*is_in_prefix_section=*/true, /*is_prefix_hit=*/false); ICING_EXPECT_OK(pl_used.PrependHit(hit1)); // Size = sizeof(uncompressed hit1) + sizeof(uncompressed hit0) expected_size += sizeof(Hit); EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit1, hit0))); // Try to add the smallest hit possible. Should fail Hit hit2(/*section_id=*/0, 0, /*term_frequency=*/0, /*is_in_prefix_section=*/false, /*is_prefix_hit=*/false); EXPECT_THAT(pl_used.PrependHit(hit2), StatusIs(libtextclassifier3::StatusCode::RESOURCE_EXHAUSTED)); EXPECT_THAT(pl_used.BytesUsed(), Le(expected_size)); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAre(hit1, hit0))); } TEST(PostingListTest, PostingListPrependHitArrayMinSizePostingList) { constexpr int kFinalSize = 1025; std::unique_ptr<char[]> hits_buf = std::make_unique<char[]>(kFinalSize); // Min Size = 10 int size = posting_list_utils::min_posting_list_size(); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf.get()), size)); std::vector<HitElt> hits_in; hits_in.emplace_back(Hit(1, 0, Hit::kDefaultTermFrequency)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/1)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/1)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/1)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/1)); std::reverse(hits_in.begin(), hits_in.end()); // Add five hits. The PL is in the empty state and an empty min size PL can // only fit two hits. So PrependHitArray should fail. uint32_t num_can_prepend = pl_used.PrependHitArray<HitElt, HitElt::get_hit>( &hits_in[0], hits_in.size(), false); EXPECT_THAT(num_can_prepend, Eq(2)); int can_fit_hits = num_can_prepend; // The PL has room for 2 hits. We should be able to add them without any // problem, transitioning the PL from EMPTY -> ALMOST_FULL -> FULL const HitElt *hits_in_ptr = hits_in.data() + (hits_in.size() - 2); num_can_prepend = pl_used.PrependHitArray<HitElt, HitElt::get_hit>( hits_in_ptr, can_fit_hits, false); EXPECT_THAT(num_can_prepend, Eq(can_fit_hits)); EXPECT_THAT(size, Eq(pl_used.BytesUsed())); std::deque<Hit> hits_pushed; std::transform(hits_in.rbegin(), hits_in.rend() - hits_in.size() + can_fit_hits, std::front_inserter(hits_pushed), HitElt::get_hit); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAreArray(hits_pushed))); } TEST(PostingListTest, PostingListPrependHitArrayPostingList) { // Size = 30 int size = 3 * posting_list_utils::min_posting_list_size(); std::unique_ptr<char[]> hits_buf = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf.get()), size)); std::vector<HitElt> hits_in; hits_in.emplace_back(Hit(1, 0, Hit::kDefaultTermFrequency)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/1)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/1)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/1)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/1)); std::reverse(hits_in.begin(), hits_in.end()); // The last hit is uncompressed and the four before it should only take one // byte. Total use = 8 bytes. // ---------------------- // 29 delta(Hit #1) // 28 delta(Hit #2) // 27 delta(Hit #3) // 26 delta(Hit #4) // 25-22 Hit #5 // 21-10 <unused> // 9-5 kSpecialHit // 4-0 Offset=22 // ---------------------- int byte_size = sizeof(Hit::Value) + hits_in.size() - 1; // Add five hits. The PL is in the empty state and should be able to fit all // five hits without issue, transitioning the PL from EMPTY -> NOT_FULL. uint32_t num_could_fit = pl_used.PrependHitArray<HitElt, HitElt::get_hit>( &hits_in[0], hits_in.size(), false); EXPECT_THAT(num_could_fit, Eq(hits_in.size())); EXPECT_THAT(byte_size, Eq(pl_used.BytesUsed())); std::deque<Hit> hits_pushed; std::transform(hits_in.rbegin(), hits_in.rend(), std::front_inserter(hits_pushed), HitElt::get_hit); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAreArray(hits_pushed))); Hit first_hit = CreateHit(hits_in.begin()->hit, /*desired_byte_length=*/1); hits_in.clear(); hits_in.emplace_back(first_hit); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/2)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/1)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/2)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/3)); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/2)); std::reverse(hits_in.begin(), hits_in.end()); // Size increased by the deltas of these hits (1+2+1+2+3+2) = 11 bytes // ---------------------- // 29 delta(Hit #1) // 28 delta(Hit #2) // 27 delta(Hit #3) // 26 delta(Hit #4) // 25 delta(Hit #5) // 24-23 delta(Hit #6) // 22 delta(Hit #7) // 21-20 delta(Hit #8) // 19-17 delta(Hit #9) // 16-15 delta(Hit #10) // 14-11 Hit #11 // 10 <unused> // 9-5 kSpecialHit // 4-0 Offset=11 // ---------------------- byte_size += 11; // Add these 6 hits. The PL is currently in the NOT_FULL state and should // remain in the NOT_FULL state. num_could_fit = pl_used.PrependHitArray<HitElt, HitElt::get_hit>( &hits_in[0], hits_in.size(), false); EXPECT_THAT(num_could_fit, Eq(hits_in.size())); EXPECT_THAT(byte_size, Eq(pl_used.BytesUsed())); // All hits from hits_in were added. std::transform(hits_in.rbegin(), hits_in.rend(), std::front_inserter(hits_pushed), HitElt::get_hit); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAreArray(hits_pushed))); first_hit = CreateHit(hits_in.begin()->hit, /*desired_byte_length=*/3); hits_in.clear(); hits_in.emplace_back(first_hit); // ---------------------- // 29 delta(Hit #1) // 28 delta(Hit #2) // 27 delta(Hit #3) // 26 delta(Hit #4) // 25 delta(Hit #5) // 24-23 delta(Hit #6) // 22 delta(Hit #7) // 21-20 delta(Hit #8) // 19-17 delta(Hit #9) // 16-15 delta(Hit #10) // 14-12 delta(Hit #11) // 11-10 <unused> // 9-5 Hit #12 // 4-0 kSpecialHit // ---------------------- byte_size = 25; // Add this 1 hit. The PL is currently in the NOT_FULL state and should // transition to the ALMOST_FULL state - even though there is still some // unused space. num_could_fit = pl_used.PrependHitArray<HitElt, HitElt::get_hit>( &hits_in[0], hits_in.size(), false); EXPECT_THAT(num_could_fit, Eq(hits_in.size())); EXPECT_THAT(byte_size, Eq(pl_used.BytesUsed())); // All hits from hits_in were added. std::transform(hits_in.rbegin(), hits_in.rend(), std::front_inserter(hits_pushed), HitElt::get_hit); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAreArray(hits_pushed))); first_hit = CreateHit(hits_in.begin()->hit, /*desired_byte_length=*/1); hits_in.clear(); hits_in.emplace_back(first_hit); hits_in.emplace_back( CreateHit(hits_in.rbegin()->hit, /*desired_byte_length=*/2)); std::reverse(hits_in.begin(), hits_in.end()); // ---------------------- // 29 delta(Hit #1) // 28 delta(Hit #2) // 27 delta(Hit #3) // 26 delta(Hit #4) // 25 delta(Hit #5) // 24-23 delta(Hit #6) // 22 delta(Hit #7) // 21-20 delta(Hit #8) // 19-17 delta(Hit #9) // 16-15 delta(Hit #10) // 14-12 delta(Hit #11) // 11 delta(Hit #12) // 10 <unused> // 9-5 Hit #13 // 4-0 Hit #14 // ---------------------- // Add these 2 hits. The PL is currently in the ALMOST_FULL state. Adding the // first hit should keep the PL in ALMOST_FULL because the delta between Hit // #12 and Hit #13 (1 byte) can fit in the unused area (2 bytes). Adding the // second hit should tranisition to the FULL state because the delta between // Hit #13 and Hit #14 (2 bytes) is larger than the remaining unused area // (1 byte). num_could_fit = pl_used.PrependHitArray<HitElt, HitElt::get_hit>( &hits_in[0], hits_in.size(), false); EXPECT_THAT(num_could_fit, Eq(hits_in.size())); EXPECT_THAT(size, Eq(pl_used.BytesUsed())); // All hits from hits_in were added. std::transform(hits_in.rbegin(), hits_in.rend(), std::front_inserter(hits_pushed), HitElt::get_hit); EXPECT_THAT(pl_used.GetHits(), IsOkAndHolds(ElementsAreArray(hits_pushed))); } TEST(PostingListTest, PostingListPrependHitArrayTooManyHits) { static constexpr int kNumHits = 128; static constexpr int kDeltaSize = 1; static constexpr int kTermFrequencySize = 1; static constexpr size_t kHitsSize = ((kNumHits * (kDeltaSize + kTermFrequencySize)) / 5) * 5; std::unique_ptr<char[]> hits_buf = std::make_unique<char[]>(kHitsSize); // Create an array with one too many hits vector<Hit> hits_in_too_many = CreateHits(kNumHits + 1, /*desired_byte_length=*/1); vector<HitElt> hit_elts_in_too_many; for (const Hit &hit : hits_in_too_many) { hit_elts_in_too_many.emplace_back(hit); } ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf.get()), posting_list_utils::min_posting_list_size())); // PrependHitArray should fail because hit_elts_in_too_many is far too large // for the minimum size pl. uint32_t num_could_fit = pl_used.PrependHitArray<HitElt, HitElt::get_hit>( &hit_elts_in_too_many[0], hit_elts_in_too_many.size(), false); ASSERT_THAT(num_could_fit, Lt(hit_elts_in_too_many.size())); ASSERT_THAT(pl_used.BytesUsed(), Eq(0)); ASSERT_THAT(pl_used.GetHits(), IsOkAndHolds(IsEmpty())); ICING_ASSERT_OK_AND_ASSIGN( pl_used, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf.get()), kHitsSize)); // PrependHitArray should fail because hit_elts_in_too_many is one hit too // large for this pl. num_could_fit = pl_used.PrependHitArray<HitElt, HitElt::get_hit>( &hit_elts_in_too_many[0], hit_elts_in_too_many.size(), false); ASSERT_THAT(num_could_fit, Lt(hit_elts_in_too_many.size())); ASSERT_THAT(pl_used.BytesUsed(), Eq(0)); ASSERT_THAT(pl_used.GetHits(), IsOkAndHolds(IsEmpty())); } TEST(PostingListTest, PostingListStatusJumpFromNotFullToFullAndBack) { const uint32_t pl_size = 3 * sizeof(Hit); char hits_buf[pl_size]; ICING_ASSERT_OK_AND_ASSIGN( PostingListUsed pl, PostingListUsed::CreateFromUnitializedRegion(hits_buf, pl_size)); ICING_ASSERT_OK(pl.PrependHit(Hit(Hit::kInvalidValue - 1, 0))); uint32_t bytes_used = pl.BytesUsed(); // Status not full. ASSERT_THAT(bytes_used, Le(pl_size - posting_list_utils::kSpecialHitsSize)); ICING_ASSERT_OK(pl.PrependHit(Hit(Hit::kInvalidValue >> 2, 0))); // Status should jump to full directly. ASSERT_THAT(pl.BytesUsed(), Eq(pl_size)); pl.PopFrontHits(1); // Status should return to not full as before. ASSERT_THAT(pl.BytesUsed(), Eq(bytes_used)); } TEST(PostingListTest, DeltaOverflow) { char hits_buf[1000]; ICING_ASSERT_OK_AND_ASSIGN( PostingListUsed pl, PostingListUsed::CreateFromUnitializedRegion(hits_buf, 4 * sizeof(Hit))); static const Hit::Value kOverflow[4] = { Hit::kInvalidValue >> 2, (Hit::kInvalidValue >> 2) * 2, (Hit::kInvalidValue >> 2) * 3, Hit::kInvalidValue - 1, }; // Fit at least 4 ordinary values. for (Hit::Value v = 0; v < 4; v++) { ICING_EXPECT_OK(pl.PrependHit(Hit(4 - v))); } // Cannot fit 4 overflow values. ICING_ASSERT_OK_AND_ASSIGN(pl, PostingListUsed::CreateFromUnitializedRegion( hits_buf, 4 * sizeof(Hit))); ICING_EXPECT_OK(pl.PrependHit(Hit(kOverflow[3]))); ICING_EXPECT_OK(pl.PrependHit(Hit(kOverflow[2]))); // Can fit only one more. ICING_EXPECT_OK(pl.PrependHit(Hit(kOverflow[1]))); EXPECT_THAT(pl.PrependHit(Hit(kOverflow[0])), StatusIs(libtextclassifier3::StatusCode::RESOURCE_EXHAUSTED)); } TEST(PostingListTest, MoveFrom) { int size = 3 * posting_list_utils::min_posting_list_size(); std::unique_ptr<char[]> hits_buf1 = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used1, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf1.get()), size)); std::vector<Hit> hits1 = CreateHits(/*num_hits=*/5, /*desired_byte_length=*/1); for (const Hit &hit : hits1) { ICING_ASSERT_OK(pl_used1.PrependHit(hit)); } std::unique_ptr<char[]> hits_buf2 = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used2, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf2.get()), size)); std::vector<Hit> hits2 = CreateHits(/*num_hits=*/5, /*desired_byte_length=*/2); for (const Hit &hit : hits2) { ICING_ASSERT_OK(pl_used2.PrependHit(hit)); } ICING_ASSERT_OK(pl_used2.MoveFrom(&pl_used1)); EXPECT_THAT(pl_used2.GetHits(), IsOkAndHolds(ElementsAreArray(hits1.rbegin(), hits1.rend()))); EXPECT_THAT(pl_used1.GetHits(), IsOkAndHolds(IsEmpty())); } TEST(PostingListTest, MoveFromNullArgumentReturnsInvalidArgument) { int size = 3 * posting_list_utils::min_posting_list_size(); std::unique_ptr<char[]> hits_buf1 = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used1, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf1.get()), size)); std::vector<Hit> hits = CreateHits(/*num_hits=*/5, /*desired_byte_length=*/1); for (const Hit &hit : hits) { ICING_ASSERT_OK(pl_used1.PrependHit(hit)); } EXPECT_THAT(pl_used1.MoveFrom(/*other=*/nullptr), StatusIs(libtextclassifier3::StatusCode::FAILED_PRECONDITION)); EXPECT_THAT(pl_used1.GetHits(), IsOkAndHolds(ElementsAreArray(hits.rbegin(), hits.rend()))); } TEST(PostingListTest, MoveFromInvalidPostingListReturnsInvalidArgument) { int size = 3 * posting_list_utils::min_posting_list_size(); std::unique_ptr<char[]> hits_buf1 = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used1, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf1.get()), size)); std::vector<Hit> hits1 = CreateHits(/*num_hits=*/5, /*desired_byte_length=*/1); for (const Hit &hit : hits1) { ICING_ASSERT_OK(pl_used1.PrependHit(hit)); } std::unique_ptr<char[]> hits_buf2 = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used2, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf2.get()), size)); std::vector<Hit> hits2 = CreateHits(/*num_hits=*/5, /*desired_byte_length=*/2); for (const Hit &hit : hits2) { ICING_ASSERT_OK(pl_used2.PrependHit(hit)); } // Write invalid hits to the beginning of pl_used1 to make it invalid. Hit invalid_hit; Hit *first_hit = reinterpret_cast<Hit *>(hits_buf1.get()); *first_hit = invalid_hit; ++first_hit; *first_hit = invalid_hit; EXPECT_THAT(pl_used2.MoveFrom(&pl_used1), StatusIs(libtextclassifier3::StatusCode::INVALID_ARGUMENT)); EXPECT_THAT(pl_used2.GetHits(), IsOkAndHolds(ElementsAreArray(hits2.rbegin(), hits2.rend()))); } TEST(PostingListTest, MoveToInvalidPostingListReturnsInvalidArgument) { int size = 3 * posting_list_utils::min_posting_list_size(); std::unique_ptr<char[]> hits_buf1 = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used1, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf1.get()), size)); std::vector<Hit> hits1 = CreateHits(/*num_hits=*/5, /*desired_byte_length=*/1); for (const Hit &hit : hits1) { ICING_ASSERT_OK(pl_used1.PrependHit(hit)); } std::unique_ptr<char[]> hits_buf2 = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used2, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf2.get()), size)); std::vector<Hit> hits2 = CreateHits(/*num_hits=*/5, /*desired_byte_length=*/2); for (const Hit &hit : hits2) { ICING_ASSERT_OK(pl_used2.PrependHit(hit)); } // Write invalid hits to the beginning of pl_used2 to make it invalid. Hit invalid_hit; Hit *first_hit = reinterpret_cast<Hit *>(hits_buf2.get()); *first_hit = invalid_hit; ++first_hit; *first_hit = invalid_hit; EXPECT_THAT(pl_used2.MoveFrom(&pl_used1), StatusIs(libtextclassifier3::StatusCode::FAILED_PRECONDITION)); EXPECT_THAT(pl_used1.GetHits(), IsOkAndHolds(ElementsAreArray(hits1.rbegin(), hits1.rend()))); } TEST(PostingListTest, MoveToPostingListTooSmall) { int size = 3 * posting_list_utils::min_posting_list_size(); std::unique_ptr<char[]> hits_buf1 = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used1, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf1.get()), size)); std::vector<Hit> hits1 = CreateHits(/*num_hits=*/5, /*desired_byte_length=*/1); for (const Hit &hit : hits1) { ICING_ASSERT_OK(pl_used1.PrependHit(hit)); } std::unique_ptr<char[]> hits_buf2 = std::make_unique<char[]>(posting_list_utils::min_posting_list_size()); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used2, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf2.get()), posting_list_utils::min_posting_list_size())); std::vector<Hit> hits2 = CreateHits(/*num_hits=*/1, /*desired_byte_length=*/2); for (const Hit &hit : hits2) { ICING_ASSERT_OK(pl_used2.PrependHit(hit)); } EXPECT_THAT(pl_used2.MoveFrom(&pl_used1), StatusIs(libtextclassifier3::StatusCode::INVALID_ARGUMENT)); EXPECT_THAT(pl_used1.GetHits(), IsOkAndHolds(ElementsAreArray(hits1.rbegin(), hits1.rend()))); EXPECT_THAT(pl_used2.GetHits(), IsOkAndHolds(ElementsAreArray(hits2.rbegin(), hits2.rend()))); } TEST(PostingListTest, PopHitsWithScores) { int size = 2 * posting_list_utils::min_posting_list_size(); std::unique_ptr<char[]> hits_buf1 = std::make_unique<char[]>(size); ICING_ASSERT_OK_AND_ASSIGN(PostingListUsed pl_used, PostingListUsed::CreateFromUnitializedRegion( static_cast<void *>(hits_buf1.get()), size)); // This posting list is 20-bytes. Create four hits that will have deltas of // two bytes each and all of whom will have a non-default score. This posting // list will be almost_full. // // ---------------------- // 19 score(Hit #0) // 18-17 delta(Hit #0) // 16 score(Hit #1) // 15-14 delta(Hit #1) // 13 score(Hit #2) // 12-11 delta(Hit #2) // 10 <unused> // 9-5 Hit #3 // 4-0 kInvalidHitVal // ---------------------- Hit hit0(/*section_id=*/0, /*document_id=*/0, /*score=*/5); Hit hit1 = CreateHit(hit0, /*desired_byte_length=*/2); Hit hit2 = CreateHit(hit1, /*desired_byte_length=*/2); Hit hit3 = CreateHit(hit2, /*desired_byte_length=*/2); ICING_ASSERT_OK(pl_used.PrependHit(hit0)); ICING_ASSERT_OK(pl_used.PrependHit(hit1)); ICING_ASSERT_OK(pl_used.PrependHit(hit2)); ICING_ASSERT_OK(pl_used.PrependHit(hit3)); ICING_ASSERT_OK_AND_ASSIGN(std::vector<Hit> hits_out, pl_used.GetHits()); EXPECT_THAT(hits_out, ElementsAre(hit3, hit2, hit1, hit0)); // Now, pop the last hit. The posting list should contain the first three // hits. // // ---------------------- // 19 score(Hit #0) // 18-17 delta(Hit #0) // 16 score(Hit #1) // 15-14 delta(Hit #1) // 13-10 <unused> // 9-5 Hit #2 // 4-0 kInvalidHitVal // ---------------------- ICING_ASSERT_OK(pl_used.PopFrontHits(1)); ICING_ASSERT_OK_AND_ASSIGN(hits_out, pl_used.GetHits()); EXPECT_THAT(hits_out, ElementsAre(hit2, hit1, hit0)); } } // namespace lib } // namespace icing
41.304348
80
0.67399
PixelPlusUI-SnowCone
044d4604f3e34abc3f895b3190868adfbaed3869
21,557
cc
C++
ftr/font/font.cc
louis-tru/Ngui
c1f25d8b6c42e873d5969fb588af22f428c58d4c
[ "BSD-3-Clause-Clear" ]
86
2017-11-21T01:05:30.000Z
2020-05-21T12:30:31.000Z
ftr/font/font.cc
louis-tru/Ngui
c1f25d8b6c42e873d5969fb588af22f428c58d4c
[ "BSD-3-Clause-Clear" ]
14
2020-10-16T11:30:57.000Z
2021-04-16T06:10:06.000Z
ftr/font/font.cc
louis-tru/Ngui
c1f25d8b6c42e873d5969fb588af22f428c58d4c
[ "BSD-3-Clause-Clear" ]
13
2017-11-21T10:18:53.000Z
2019-10-18T09:15:55.000Z
/* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2015, xuewen.chu * 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 xuewen.chu 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 xuewen.chu 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. * * ***** END LICENSE BLOCK ***** */ #include "ftr/sys.h" #include "ftr/util/buffer.h" #include "font-1.h" #include "native-font.h" #include "ftr/bezier.h" #include "ftr/texture.h" #include "ftr/display-port.h" #include "ftr/draw.h" #include "ftr/app.h" #include "ftr/app-1.h" #include "font.cc.levels.inl" #include "font.cc.all.inl" #ifndef FX_SUPPORT_MAX_TEXTURE_FONT_SIZE #define FX_SUPPORT_MAX_TEXTURE_FONT_SIZE 512 #endif FX_NS(ftr) static String THIN_("thin"); static String ULTRALIGHT_("ultralight"); static String BOOK_("book"); static String LIGHT_("light"); static String REGULAR_("regular"); static String NORMAL_("normal"); static String MEDIUM_("medium"); static String DEMI_("demi"); static String SEMIBOLD_("semibold"); static String ROMAN_("roman"); static String BOLD_("bold"); static String CONDENSED_("condensed"); static String HEAVY_("heavy"); static String BLACK_("black"); static String ITALIC_("italic"); static String OBLIQUE_("oblique"); /** * @class FontPool::Inl */ class FontPool::Inl: public FontPool { public: #define _inl_pool(self) static_cast<FontPool::Inl*>(self) /** * @func initialize_default_fonts() */ void initialize_default_fonts(); /** * @fucn m_add_font */ bool register_font( cString& family_name, cString& font_name, TextStyleEnum style, uint num_glyphs, uint face_index, int height, /* text height in 26.6 frac. pixels */ int max_advance, /* max horizontal advance, in 26.6 pixels */ int ascender, /* ascender in 26.6 frac. pixels */ int descender, /* descender in 26.6 frac. pixels */ int underline_position, int underline_thickness, cString& path, FontFromData::Data* data ) { if ( ! path.is_empty() ) { // 文件 if ( ! FileHelper::is_file_sync(path) ) return false; m_paths[path] = family_name; } else if ( !data || !data->value ) { return false; } String font_name_ = font_name; /* FX_DEBUG("family_name:%s, font_name:%s, %s, ------%dkb%s", *family_name, *font_name, *path, uint(FileHelper::stat_sync(path).size() / 1024), m_fonts.has(font_name) ? "+++++++++++": ""); */ for (int i = 1; m_fonts.has(font_name_); i++ ) { // 重复的字体名称 font_name_ = font_name + "_" + i; } FontFamily* family = nullptr; auto i = m_familys.find(family_name); if ( i != m_familys.end() ) { family = i.value(); } else { family = new FontFamily(family_name); m_familys[family_name] = family; m_blend_fonts[family_name] = family; // 替换别名 } Font* font = nullptr; if ( path.is_empty() ) { font = new FontFromData(data); } else { font = new FontFromFile(path); } _inl_font(font)->initialize(this, family, font_name_, style, num_glyphs, face_index, height, max_advance, ascender, descender, underline_position, underline_thickness, (FT_Library)m_ft_lib); m_fonts[font_name_] = font; if ( font_name_ != family_name ) { // 与家族名称相同忽略 m_blend_fonts[font_name_] = font; } _inl_family(family)->add_font(font); return true; } bool register_font(FontFromData::Data* font_data, cString& family_alias) { Handle<FontFromData::Data> _font_data = font_data; const FT_Byte* data = font_data->value; FT_Face face; FT_Error err = FT_New_Memory_Face((FT_Library)m_ft_lib, data, font_data->length, 0, &face); if (err) { FX_ERR("Unable to load font, Freetype2 error code: %d", err); } else if (!face->family_name) { FX_ERR("Unable to load font, not family name"); } else { FT_Long num_faces = face->num_faces; String family_name = face->family_name; int face_index = 0; while (1) { if (face->charmap && face->charmap->encoding == FT_ENCODING_UNICODE && // 必须要有unicode编码表 FT_IS_SCALABLE(face) // 必须为矢量字体 ) { // 以64 pem 为标准 float ratio = face->units_per_EM / 4096.0 /*( 64 * 64 = 4096 )*/; int height = face->height / ratio; int max_advance_width = face->max_advance_width / ratio; int ascender = face->ascender / ratio; int descender = -face->descender / ratio; int underline_position = face->underline_position; int underline_thickness = face->underline_thickness; String name = FT_Get_Postscript_Name(face); if (! register_font(family_name, name, parse_style_flags(name, face->style_name), (uint)face->num_glyphs, face_index, height, max_advance_width, ascender, descender, underline_position, underline_thickness, String(), font_data) ) { return false; } } face_index++; FT_Done_Face(face); if (face_index < num_faces) { err = FT_New_Memory_Face((FT_Library)m_ft_lib, data, font_data->length, face_index, &face); if (err) { FX_ERR("Unable to load font, Freetype2 error code: %d", err); return false; } } else { break; } } // set family_alias set_family_alias(family_name, family_alias); return true; } return false; } /** * @func display_port_change_handle */ void display_port_change_handle(Event<>& evt) { Vec2 scale_value = m_display_port->scale_value(); float scale = FX_MAX(scale_value[0], scale_value[1]); if ( scale != m_display_port_scale ) { if ( m_display_port_scale != 0.0 ) { // 缩放改变影响字型纹理,所有全部清理 clear(true); } m_display_port_scale = scale; m_draw_ctx->host()->render_loop()->post(Cb([this](CbD& e) { m_draw_ctx->refresh_font_pool(this); _inl_app(m_draw_ctx->host())->refresh_display(); })); Vec2 size = m_display_port->size(); uint font_size = sqrtf(size.width() * size.height()) / 10; // 最大纹理字体不能超过上下文支持的大小 if (font_size >= FX_SUPPORT_MAX_TEXTURE_FONT_SIZE) { m_max_glyph_texture_size = FX_SUPPORT_MAX_TEXTURE_FONT_SIZE; } else { m_max_glyph_texture_size = font_glyph_texture_levels_idx[font_size].max_font_size; } } } static bool has_italic_style(cString& style_name) { return style_name.index_of(ITALIC_) != -1 || style_name.index_of(OBLIQUE_) != -1; } /** * @func parse_style_flag() */ static TextStyleEnum parse_style_flags(cString& name, cString& style_name) { String str = style_name.to_lower_case(); if ( str.index_of(THIN_) != -1 ) { return has_italic_style(str) ? TextStyleEnum::THIN_ITALIC : TextStyleEnum::THIN; } if ( str.index_of(ULTRALIGHT_) != -1 || str.index_of(BOOK_) != -1 ) { return has_italic_style(str) ? TextStyleEnum::ULTRALIGHT_ITALIC : TextStyleEnum::ULTRALIGHT; } if ( str.index_of(LIGHT_) != -1 ) { return has_italic_style(str) ? TextStyleEnum::LIGHT_ITALIC : TextStyleEnum::LIGHT; } if ( str.index_of(REGULAR_) != -1 || str.index_of(NORMAL_) != -1 ) { return has_italic_style(str) ? TextStyleEnum::ITALIC : TextStyleEnum::REGULAR; } if ( str.index_of(MEDIUM_) != -1 || str.index_of(DEMI_) != -1 ) { return has_italic_style(str) ? TextStyleEnum::MEDIUM_ITALIC : TextStyleEnum::MEDIUM; } if ( str.index_of(SEMIBOLD_) != -1 || str.index_of(ROMAN_) != -1 ) { return has_italic_style(str) ? TextStyleEnum::SEMIBOLD_ITALIC : TextStyleEnum::SEMIBOLD; } if ( str.index_of(BOLD_) != -1 || str.index_of(CONDENSED_) != -1 ) { return has_italic_style(str) ? TextStyleEnum::BOLD_ITALIC : TextStyleEnum::BOLD; } if ( str.index_of(HEAVY_) != -1 ) { return has_italic_style(str) ? TextStyleEnum::HEAVY_ITALIC : TextStyleEnum::HEAVY; } if ( str.index_of(BLACK_) != -1 ) { return has_italic_style(str) ? TextStyleEnum::BLACK_ITALIC : TextStyleEnum::BLACK; } return TextStyleEnum::OTHER; } /** * @func inl_read_font_file */ static Handle<FontPool::SimpleFontFamily> inl_read_font_file(cString& path, FT_Library lib) { FT_Face face; FT_Error err = FT_New_Face(lib, Path::fallback_c(path), 0, &face); if (err) { FX_WARN("Unable to load font file \"%s\", Freetype2 error code: %d", *path, err); } else if (!face->family_name) { FX_WARN("Unable to load font file \"%s\", not family name", *path); } else { FT_Long num_faces = face->num_faces; Handle<FontPool::SimpleFontFamily> sff = new FontPool::SimpleFontFamily(); sff->path = path; sff->family = face->family_name; int face_index = 0; while (1) { if (face->charmap && face->charmap->encoding == FT_ENCODING_UNICODE && // 必须要有unicode编码表 FT_IS_SCALABLE(face) // 必须为矢量字体 ) { FT_Set_Char_Size(face, 0, 64 * 64, 72, 72); // 以64 pt 为标准 float ratio = face->units_per_EM / 4096.0 /*( 64 * 64 = 4096 )*/; int height = face->height / ratio; int max_advance_width = face->max_advance_width / ratio; int ascender = face->ascender / ratio; int descender = -face->descender / ratio; int underline_position = face->underline_position; int underline_thickness = face->underline_thickness; String name = FT_Get_Postscript_Name(face); DLOG("------------inl_read_font_file, %s, %s", *name, face->style_name); sff->fonts.push({ name, parse_style_flags(name, face->style_name), (uint)face->num_glyphs, height, max_advance_width, ascender, descender, underline_position, underline_thickness }); } face_index++; FT_Done_Face(face); if (face_index < num_faces) { err = FT_New_Face(lib, Path::fallback_c(path), face_index, &face); if (err) { FX_WARN("Unable to load font file \"%s\", Freetype2 error code: %d", *path, err); break; } } else { if (sff->fonts.length()) return sff; else break; } } } return Handle<FontPool::SimpleFontFamily>(); } }; /** * @constructor */ FontPool::FontPool(Draw* ctx) : m_ft_lib(nullptr) , m_draw_ctx(ctx) , m_display_port(nullptr) , m_total_data_size(0) , m_max_glyph_texture_size(0) , m_display_port_scale(0) { ASSERT(m_draw_ctx); FT_Init_FreeType((FT_Library*)&m_ft_lib); { // 载入内置字体 uint count = sizeof(native_fonts_) / sizeof(Native_font_data_); for (uint i = 0 ; i < count; i++) { WeakBuffer data((cchar*)native_fonts_[i].data, native_fonts_[i].count); auto font_data = new FontFromData::Data(data); // LOG("register_font,%d", i); _inl_pool(this)->register_font(font_data, i == 1 ? "icon" : String()); // LOG("register_font ok,%d", i); } if ( m_familys.has("langou") ) { // LOG("m_familys.has langou ok"); // 这个内置字体必须载入成功,否则退出程序 // 把载入的一个内置字体做为默认备用字体,当没有任何字体可用时候,使用这个内置字体 m_spare_family = m_familys["langou"]; } else { FX_FATAL("Unable to initialize ftr font"); } } { // 载入系统字体 const Array<SimpleFontFamily>& arr = system_font_family(); for (auto i = arr.begin(), e = arr.end(); i != e; i++) { const SimpleFontFamily& sffd = i.value(); for (uint i = 0; i < sffd.fonts.length(); i++) { const SimpleFont& sfd = sffd.fonts[i]; _inl_pool(this)->register_font(sffd.family, sfd.name, sfd.style, sfd.num_glyphs, i, sfd.height, sfd.max_advance, sfd.ascender, sfd.descender, sfd.underline_position, sfd.underline_thickness, sffd.path, nullptr); // end for } } } _inl_pool(this)->initialize_default_fonts(); // 设置默认字体列表 } /** * @destructor */ FontPool::~FontPool() { for ( auto& i : m_familys ) { Release(i.value()); // delete } for ( auto& i : m_fonts ) { Release(i.value()); // delete } for ( auto& i : m_tables ) { Release(i.value()); // delete } m_familys.clear(); m_fonts.clear(); m_tables.clear(); m_blend_fonts.clear(); m_default_fonts.clear(); FT_Done_FreeType((FT_Library)m_ft_lib); m_ft_lib = nullptr; if ( m_display_port ) { m_display_port->FX_OFF(change, &Inl::display_port_change_handle, _inl_pool(this)); } } /** * @func set_default_fonts # 尝试设置默认字体 * @arg first {const Array<String>*} # 第一字体列表 * @arg ... {const Array<String>*} # 第2/3/4..字体列表 */ void FontPool::set_default_fonts(const Array<String>* first, ...) { m_default_fonts.clear(); Map<String, bool> has; auto end = m_blend_fonts.end(); for (uint i = 0; i < first->length(); i++) { auto j = m_blend_fonts.find(first->item(i)); if (j != end) { has.set(j.value()->name(), true); m_default_fonts.push(j.value()); break; } } va_list arg; va_start(arg, first); const Array<String>* ls = va_arg(arg, const Array<String>*); while (ls) { for (uint i = 0; i < ls->length(); i++) { auto j = m_blend_fonts.find(ls->item(i)); if (j != end) { if ( ! has.has(j.value()->name()) ) { has.set(j.value()->name(), true); m_default_fonts.push(j.value()); } break; } } ls = va_arg(arg, const Array<String>*); } va_end(arg); if ( !has.has(m_spare_family->name()) ) { m_default_fonts.push(m_spare_family); } } /** * @func set_default_fonts # 在当前字体库找到字体名称,设置才能生效 * @arg fonts {const Array<String>&} # 要设置的默认字体的名称 */ void FontPool::set_default_fonts(const Array<String>& fonts) { m_default_fonts.clear(); Map<String, bool> has; auto end = m_blend_fonts.end(); for (uint i = 0; i < fonts.length(); i++) { auto j = m_blend_fonts.find(fonts[i].trim()); if (j != end) { if ( ! has.has(j.value()->name()) ) { has.set(j.value()->name(), true); m_default_fonts.push(j.value()); } } } if ( !has.has(m_spare_family->name()) ) { m_default_fonts.push(m_spare_family); } } /** * @func default_font_names */ Array<String> FontPool::default_font_names() const { Array<String> rev; for (uint i = 0; i < m_default_fonts.length(); i++) rev.push(m_default_fonts[i]->name()); return rev; } /** * @func font_names() */ Array<String> FontPool::font_names(cString& family_name) const { FontFamily* ff = const_cast<FontPool*>(this)->get_font_family(family_name); return ff ? ff->font_names() : Array<String>(); } /** * @func get_font_family() */ FontFamily* FontPool::get_font_family(cString& family_name) { auto i = m_familys.find(family_name); return i == m_familys.end() ? NULL : i.value(); } /** * @func get_font # 通过名称获得一个字体对像 * @arg name {cString&} # 字体名称或家族名称 * @arg [style = fs_regular] {Font::TextStyle} * @ret {Font*} */ Font* FontPool::get_font(cString& name, TextStyleEnum style) { auto i = m_blend_fonts.find(name); return i == m_blend_fonts.end() ? NULL : i.value()->font(style); } /** * @func get_group # 通过字体名称列表获取字型集合 * @arg id {cFFID} # cFFID * @arg [style = fs_regular] {Font::TextStyle} # 使用的字体家族才生效 */ FontGlyphTable* FontPool::get_table(cFFID ffid, TextStyleEnum style) { ASSERT(ffid); uint code = ffid->code() + (uint)style; auto i = m_tables.find(code); if ( !i.is_null() ) { return i.value(); } FontGlyphTable* table = new FontGlyphTable(); _inl_table(table)->initialize(ffid, style, this); m_tables.set(code, table); return table; } /** * @func get_table # 获取默认字型集合 * @arg [style = fs_regular] {TextStyleEnum} */ FontGlyphTable* FontPool::get_table(TextStyleEnum style) { return get_table(get_font_familys_id(String()), style); } /** * @func register_font # 通过Buffer数据注册字体 * @arg buff {cBuffer} # 字体数据 * @arg [family_alias = String()] {cString&} # 给所属家族添加一个别名 */ bool FontPool::register_font(Buffer buff, cString& family_alias) { DLOG("register_font,%d", buff.length()); return _inl_pool(this)->register_font(new FontFromData::Data(buff), family_alias); } /** * @func register_font_file # 注册本地字体文件 * @arg path {cString&} # 字体文件的本地路径 * @arg [family_alias = String()] {cString&} # 给所属家族添加一个别名 */ bool FontPool::register_font_file(cString& path, cString& family_alias) { if (!m_paths.has(path) ) { // Handle<SimpleFontFamily> sffd = Inl::inl_read_font_file(path, (FT_Library)m_ft_lib); if ( !sffd.is_null() ) { for (uint i = 0; i < sffd->fonts.length(); i++) { SimpleFont& sfd = sffd->fonts[i]; if (! _inl_pool(this)->register_font(sffd->family, sfd.name, sfd.style, sfd.num_glyphs, i, sfd.height, sfd.max_advance, sfd.ascender, sfd.descender, sfd.underline_position, sfd.underline_thickness, sffd->path, nullptr) ) { return false; } } // set family_alias set_family_alias(sffd->family, family_alias); return true; } } return false; } /** * @func set_family_alias */ void FontPool::set_family_alias(cString& family, cString& alias) { if ( ! alias.is_empty() ) { auto i = m_blend_fonts.find(family); if (i != m_blend_fonts.end() && !m_blend_fonts.has(alias)) { m_blend_fonts[alias] = i.value(); // 设置一个别名 } } } /** * @func clear(full) 释放池中不用的字体数据 * @arg [full = false] {bool} # 全面清理资源尽可能最大程度清理 */ void FontPool::clear(bool full) { for ( auto& i : m_tables ) { _inl_table(i.value())->clear_table(); } for ( auto& i : m_fonts ) { _inl_font(i.value())->clear(full); } } /** * @func set_display_port */ void FontPool::set_display_port(DisplayPort* display_port) { ASSERT(!m_display_port); display_port->FX_ON(change, &Inl::display_port_change_handle, _inl_pool(this)); m_display_port = display_port; } /** * @func get_glyph_texture_level 通过字体尺寸获取纹理等级,与纹理大小font_size */ FGTexureLevel FontPool::get_glyph_texture_level(float& font_size_out) { if (font_size_out > m_max_glyph_texture_size) { return FontGlyph::LEVEL_NONE; } uint index = ceilf(font_size_out); FontGlyphTextureLevel leval = font_glyph_texture_levels_idx[index]; font_size_out = leval.max_font_size; return leval.level; } /** * @func get_family_name(path) get current register family name by font file path */ String FontPool::get_family_name(cString& path) const { auto it = m_paths.find(path); if ( it.is_null() ) { return String(); } return it.value(); } /** * @func get_glyph_texture_level # 根据字体尺寸获取纹理等级 */ float FontPool::get_glyph_texture_size(FGTexureLevel leval) { ASSERT( leval < FontGlyph::LEVEL_NONE ); const float glyph_texture_levels_size[13] = { 10, 12, 14, 16, 18, 20, 25, 32, 64, 128, 256, 512, 0 }; return glyph_texture_levels_size[leval]; } /** * @func default_font_familys_id */ static cFFID default_font_familys_id() { static FontFamilysID* id = nullptr; // default group i if ( ! id ) { id = new FontFamilysID(); _inl_ff_id(id)->initialize(Array<String>()); } return id; } /** * @func get_font_familys_id */ cFFID FontPool::get_font_familys_id(const Array<String> fonts) { static Map<uint, FontFamilysID*> ffids; // global groups // TODO: 这里如果是同一个字体的不同别名会导致不相同的`ID` if ( fonts.length() ) { FontFamilysID id; _inl_ff_id(&id)->initialize(fonts); auto it = ffids.find(id.code()); if (it != ffids.end()) { return it.value(); } else { FontFamilysID* id_p = new FontFamilysID(move( id )); ffids.set ( id_p->code(), id_p ); return id_p; } } else { return default_font_familys_id(); } } /** * @func read_font_file */ Handle<FontPool::SimpleFontFamily> FontPool::read_font_file(cString& path) { FT_Library lib; FT_Init_FreeType(&lib); ScopeClear clear([&lib]() { FT_Done_FreeType(lib); }); return Inl::inl_read_font_file(path, lib); } /** * @func get_font_familys_id */ cFFID FontPool::get_font_familys_id(cString fonts) { if ( fonts.is_empty() ) { return default_font_familys_id(); } else { Array<String> ls = fonts.split(','); Array<String> ls2; for (int i = 0, len = ls.length(); i < len; i++) { String name = ls[i].trim(); if ( ! name.is_empty() ) { ls2.push(name); } } return get_font_familys_id(ls2); } } FX_END #include "font.cc.init.inl"
26.879052
96
0.646704
louis-tru
044f93add01f770435b6c1a5fbb095c60706423e
26,817
cpp
C++
cpp-restsdk/model/PinEnergy.cpp
thracesystems/powermeter-api
7bdab034ff916ee49e986de88f157bd044e981c1
[ "Apache-2.0" ]
null
null
null
cpp-restsdk/model/PinEnergy.cpp
thracesystems/powermeter-api
7bdab034ff916ee49e986de88f157bd044e981c1
[ "Apache-2.0" ]
null
null
null
cpp-restsdk/model/PinEnergy.cpp
thracesystems/powermeter-api
7bdab034ff916ee49e986de88f157bd044e981c1
[ "Apache-2.0" ]
null
null
null
/** * PowerMeter API * API * * The version of the OpenAPI document: 2021.4.1 * * NOTE: This class is auto generated by OpenAPI-Generator 4.3.1. * https://openapi-generator.tech * Do not edit the class manually. */ #include "PinEnergy.h" namespace powermeter { namespace model { PinEnergy::PinEnergy() { m_Id = 0; m_IdIsSet = false; m_Pin = 0; m_PinIsSet = false; m_Pin_name = utility::conversions::to_string_t(""); m_Pin_nameIsSet = false; m_Related_pin = 0; m_Related_pinIsSet = false; m_Related_pin_name = utility::conversions::to_string_t(""); m_Related_pin_nameIsSet = false; m_Supply = 0; m_SupplyIsSet = false; m_Supply_name = utility::conversions::to_string_t(""); m_Supply_nameIsSet = false; m_Process = utility::conversions::to_string_t(""); m_ProcessIsSet = false; m_Rc = utility::conversions::to_string_t(""); m_RcIsSet = false; m_Voltage = 0.0; m_VoltageIsSet = false; m_Temperature = 0; m_TemperatureIsSet = false; m_When = utility::conversions::to_string_t(""); m_WhenIsSet = false; m_Index1IsSet = false; m_Variable1 = utility::conversions::to_string_t(""); m_Variable1IsSet = false; m_Index2IsSet = false; m_Variable2 = utility::conversions::to_string_t(""); m_Variable2IsSet = false; m_Rise_energyIsSet = false; m_Fall_energyIsSet = false; m_ModesIsSet = false; } PinEnergy::~PinEnergy() { } void PinEnergy::validate() { // TODO: implement validation } web::json::value PinEnergy::toJson() const { web::json::value val = web::json::value::object(); if(m_IdIsSet) { val[utility::conversions::to_string_t("id")] = ModelBase::toJson(m_Id); } if(m_PinIsSet) { val[utility::conversions::to_string_t("pin")] = ModelBase::toJson(m_Pin); } if(m_Pin_nameIsSet) { val[utility::conversions::to_string_t("pin_name")] = ModelBase::toJson(m_Pin_name); } if(m_Related_pinIsSet) { val[utility::conversions::to_string_t("related_pin")] = ModelBase::toJson(m_Related_pin); } if(m_Related_pin_nameIsSet) { val[utility::conversions::to_string_t("related_pin_name")] = ModelBase::toJson(m_Related_pin_name); } if(m_SupplyIsSet) { val[utility::conversions::to_string_t("supply")] = ModelBase::toJson(m_Supply); } if(m_Supply_nameIsSet) { val[utility::conversions::to_string_t("supply_name")] = ModelBase::toJson(m_Supply_name); } if(m_ProcessIsSet) { val[utility::conversions::to_string_t("process")] = ModelBase::toJson(m_Process); } if(m_RcIsSet) { val[utility::conversions::to_string_t("rc")] = ModelBase::toJson(m_Rc); } if(m_VoltageIsSet) { val[utility::conversions::to_string_t("voltage")] = ModelBase::toJson(m_Voltage); } if(m_TemperatureIsSet) { val[utility::conversions::to_string_t("temperature")] = ModelBase::toJson(m_Temperature); } if(m_WhenIsSet) { val[utility::conversions::to_string_t("when")] = ModelBase::toJson(m_When); } if(m_Index1IsSet) { val[utility::conversions::to_string_t("index1")] = ModelBase::toJson(m_Index1); } if(m_Variable1IsSet) { val[utility::conversions::to_string_t("variable1")] = ModelBase::toJson(m_Variable1); } if(m_Index2IsSet) { val[utility::conversions::to_string_t("index2")] = ModelBase::toJson(m_Index2); } if(m_Variable2IsSet) { val[utility::conversions::to_string_t("variable2")] = ModelBase::toJson(m_Variable2); } if(m_Rise_energyIsSet) { val[utility::conversions::to_string_t("rise_energy")] = ModelBase::toJson(m_Rise_energy); } if(m_Fall_energyIsSet) { val[utility::conversions::to_string_t("fall_energy")] = ModelBase::toJson(m_Fall_energy); } if(m_ModesIsSet) { val[utility::conversions::to_string_t("modes")] = ModelBase::toJson(m_Modes); } return val; } bool PinEnergy::fromJson(const web::json::value& val) { bool ok = true; if(val.has_field(utility::conversions::to_string_t("id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("id")); if(!fieldValue.is_null()) { int32_t refVal_id; ok &= ModelBase::fromJson(fieldValue, refVal_id); setId(refVal_id); } } if(val.has_field(utility::conversions::to_string_t("pin"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("pin")); if(!fieldValue.is_null()) { int32_t refVal_pin; ok &= ModelBase::fromJson(fieldValue, refVal_pin); setPin(refVal_pin); } } if(val.has_field(utility::conversions::to_string_t("pin_name"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("pin_name")); if(!fieldValue.is_null()) { utility::string_t refVal_pin_name; ok &= ModelBase::fromJson(fieldValue, refVal_pin_name); setPinName(refVal_pin_name); } } if(val.has_field(utility::conversions::to_string_t("related_pin"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("related_pin")); if(!fieldValue.is_null()) { int32_t refVal_related_pin; ok &= ModelBase::fromJson(fieldValue, refVal_related_pin); setRelatedPin(refVal_related_pin); } } if(val.has_field(utility::conversions::to_string_t("related_pin_name"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("related_pin_name")); if(!fieldValue.is_null()) { utility::string_t refVal_related_pin_name; ok &= ModelBase::fromJson(fieldValue, refVal_related_pin_name); setRelatedPinName(refVal_related_pin_name); } } if(val.has_field(utility::conversions::to_string_t("supply"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("supply")); if(!fieldValue.is_null()) { int32_t refVal_supply; ok &= ModelBase::fromJson(fieldValue, refVal_supply); setSupply(refVal_supply); } } if(val.has_field(utility::conversions::to_string_t("supply_name"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("supply_name")); if(!fieldValue.is_null()) { utility::string_t refVal_supply_name; ok &= ModelBase::fromJson(fieldValue, refVal_supply_name); setSupplyName(refVal_supply_name); } } if(val.has_field(utility::conversions::to_string_t("process"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("process")); if(!fieldValue.is_null()) { utility::string_t refVal_process; ok &= ModelBase::fromJson(fieldValue, refVal_process); setProcess(refVal_process); } } if(val.has_field(utility::conversions::to_string_t("rc"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("rc")); if(!fieldValue.is_null()) { utility::string_t refVal_rc; ok &= ModelBase::fromJson(fieldValue, refVal_rc); setRc(refVal_rc); } } if(val.has_field(utility::conversions::to_string_t("voltage"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("voltage")); if(!fieldValue.is_null()) { double refVal_voltage; ok &= ModelBase::fromJson(fieldValue, refVal_voltage); setVoltage(refVal_voltage); } } if(val.has_field(utility::conversions::to_string_t("temperature"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("temperature")); if(!fieldValue.is_null()) { int32_t refVal_temperature; ok &= ModelBase::fromJson(fieldValue, refVal_temperature); setTemperature(refVal_temperature); } } if(val.has_field(utility::conversions::to_string_t("when"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("when")); if(!fieldValue.is_null()) { utility::string_t refVal_when; ok &= ModelBase::fromJson(fieldValue, refVal_when); setWhen(refVal_when); } } if(val.has_field(utility::conversions::to_string_t("index1"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("index1")); if(!fieldValue.is_null()) { std::vector<double> refVal_index1; ok &= ModelBase::fromJson(fieldValue, refVal_index1); setIndex1(refVal_index1); } } if(val.has_field(utility::conversions::to_string_t("variable1"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("variable1")); if(!fieldValue.is_null()) { utility::string_t refVal_variable1; ok &= ModelBase::fromJson(fieldValue, refVal_variable1); setVariable1(refVal_variable1); } } if(val.has_field(utility::conversions::to_string_t("index2"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("index2")); if(!fieldValue.is_null()) { std::vector<double> refVal_index2; ok &= ModelBase::fromJson(fieldValue, refVal_index2); setIndex2(refVal_index2); } } if(val.has_field(utility::conversions::to_string_t("variable2"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("variable2")); if(!fieldValue.is_null()) { utility::string_t refVal_variable2; ok &= ModelBase::fromJson(fieldValue, refVal_variable2); setVariable2(refVal_variable2); } } if(val.has_field(utility::conversions::to_string_t("rise_energy"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("rise_energy")); if(!fieldValue.is_null()) { std::vector<double> refVal_rise_energy; ok &= ModelBase::fromJson(fieldValue, refVal_rise_energy); setRiseEnergy(refVal_rise_energy); } } if(val.has_field(utility::conversions::to_string_t("fall_energy"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("fall_energy")); if(!fieldValue.is_null()) { std::vector<double> refVal_fall_energy; ok &= ModelBase::fromJson(fieldValue, refVal_fall_energy); setFallEnergy(refVal_fall_energy); } } if(val.has_field(utility::conversions::to_string_t("modes"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("modes")); if(!fieldValue.is_null()) { std::vector<int32_t> refVal_modes; ok &= ModelBase::fromJson(fieldValue, refVal_modes); setModes(refVal_modes); } } return ok; } void PinEnergy::toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) const { utility::string_t namePrefix = prefix; if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { namePrefix += utility::conversions::to_string_t("."); } if(m_IdIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("id"), m_Id)); } if(m_PinIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("pin"), m_Pin)); } if(m_Pin_nameIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("pin_name"), m_Pin_name)); } if(m_Related_pinIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("related_pin"), m_Related_pin)); } if(m_Related_pin_nameIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("related_pin_name"), m_Related_pin_name)); } if(m_SupplyIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("supply"), m_Supply)); } if(m_Supply_nameIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("supply_name"), m_Supply_name)); } if(m_ProcessIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("process"), m_Process)); } if(m_RcIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("rc"), m_Rc)); } if(m_VoltageIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("voltage"), m_Voltage)); } if(m_TemperatureIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("temperature"), m_Temperature)); } if(m_WhenIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("when"), m_When)); } if(m_Index1IsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("index1"), m_Index1)); } if(m_Variable1IsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("variable1"), m_Variable1)); } if(m_Index2IsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("index2"), m_Index2)); } if(m_Variable2IsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("variable2"), m_Variable2)); } if(m_Rise_energyIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("rise_energy"), m_Rise_energy)); } if(m_Fall_energyIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("fall_energy"), m_Fall_energy)); } if(m_ModesIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("modes"), m_Modes)); } } bool PinEnergy::fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) { bool ok = true; utility::string_t namePrefix = prefix; if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { namePrefix += utility::conversions::to_string_t("."); } if(multipart->hasContent(utility::conversions::to_string_t("id"))) { int32_t refVal_id; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("id")), refVal_id ); setId(refVal_id); } if(multipart->hasContent(utility::conversions::to_string_t("pin"))) { int32_t refVal_pin; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("pin")), refVal_pin ); setPin(refVal_pin); } if(multipart->hasContent(utility::conversions::to_string_t("pin_name"))) { utility::string_t refVal_pin_name; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("pin_name")), refVal_pin_name ); setPinName(refVal_pin_name); } if(multipart->hasContent(utility::conversions::to_string_t("related_pin"))) { int32_t refVal_related_pin; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("related_pin")), refVal_related_pin ); setRelatedPin(refVal_related_pin); } if(multipart->hasContent(utility::conversions::to_string_t("related_pin_name"))) { utility::string_t refVal_related_pin_name; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("related_pin_name")), refVal_related_pin_name ); setRelatedPinName(refVal_related_pin_name); } if(multipart->hasContent(utility::conversions::to_string_t("supply"))) { int32_t refVal_supply; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("supply")), refVal_supply ); setSupply(refVal_supply); } if(multipart->hasContent(utility::conversions::to_string_t("supply_name"))) { utility::string_t refVal_supply_name; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("supply_name")), refVal_supply_name ); setSupplyName(refVal_supply_name); } if(multipart->hasContent(utility::conversions::to_string_t("process"))) { utility::string_t refVal_process; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("process")), refVal_process ); setProcess(refVal_process); } if(multipart->hasContent(utility::conversions::to_string_t("rc"))) { utility::string_t refVal_rc; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("rc")), refVal_rc ); setRc(refVal_rc); } if(multipart->hasContent(utility::conversions::to_string_t("voltage"))) { double refVal_voltage; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("voltage")), refVal_voltage ); setVoltage(refVal_voltage); } if(multipart->hasContent(utility::conversions::to_string_t("temperature"))) { int32_t refVal_temperature; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("temperature")), refVal_temperature ); setTemperature(refVal_temperature); } if(multipart->hasContent(utility::conversions::to_string_t("when"))) { utility::string_t refVal_when; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("when")), refVal_when ); setWhen(refVal_when); } if(multipart->hasContent(utility::conversions::to_string_t("index1"))) { std::vector<double> refVal_index1; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("index1")), refVal_index1 ); setIndex1(refVal_index1); } if(multipart->hasContent(utility::conversions::to_string_t("variable1"))) { utility::string_t refVal_variable1; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("variable1")), refVal_variable1 ); setVariable1(refVal_variable1); } if(multipart->hasContent(utility::conversions::to_string_t("index2"))) { std::vector<double> refVal_index2; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("index2")), refVal_index2 ); setIndex2(refVal_index2); } if(multipart->hasContent(utility::conversions::to_string_t("variable2"))) { utility::string_t refVal_variable2; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("variable2")), refVal_variable2 ); setVariable2(refVal_variable2); } if(multipart->hasContent(utility::conversions::to_string_t("rise_energy"))) { std::vector<double> refVal_rise_energy; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("rise_energy")), refVal_rise_energy ); setRiseEnergy(refVal_rise_energy); } if(multipart->hasContent(utility::conversions::to_string_t("fall_energy"))) { std::vector<double> refVal_fall_energy; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("fall_energy")), refVal_fall_energy ); setFallEnergy(refVal_fall_energy); } if(multipart->hasContent(utility::conversions::to_string_t("modes"))) { std::vector<int32_t> refVal_modes; ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("modes")), refVal_modes ); setModes(refVal_modes); } return ok; } int32_t PinEnergy::getId() const { return m_Id; } void PinEnergy::setId(int32_t value) { m_Id = value; m_IdIsSet = true; } bool PinEnergy::idIsSet() const { return m_IdIsSet; } void PinEnergy::unsetId() { m_IdIsSet = false; } int32_t PinEnergy::getPin() const { return m_Pin; } void PinEnergy::setPin(int32_t value) { m_Pin = value; m_PinIsSet = true; } bool PinEnergy::pinIsSet() const { return m_PinIsSet; } void PinEnergy::unsetPin() { m_PinIsSet = false; } utility::string_t PinEnergy::getPinName() const { return m_Pin_name; } void PinEnergy::setPinName(const utility::string_t& value) { m_Pin_name = value; m_Pin_nameIsSet = true; } bool PinEnergy::pinNameIsSet() const { return m_Pin_nameIsSet; } void PinEnergy::unsetPin_name() { m_Pin_nameIsSet = false; } int32_t PinEnergy::getRelatedPin() const { return m_Related_pin; } void PinEnergy::setRelatedPin(int32_t value) { m_Related_pin = value; m_Related_pinIsSet = true; } bool PinEnergy::relatedPinIsSet() const { return m_Related_pinIsSet; } void PinEnergy::unsetRelated_pin() { m_Related_pinIsSet = false; } utility::string_t PinEnergy::getRelatedPinName() const { return m_Related_pin_name; } void PinEnergy::setRelatedPinName(const utility::string_t& value) { m_Related_pin_name = value; m_Related_pin_nameIsSet = true; } bool PinEnergy::relatedPinNameIsSet() const { return m_Related_pin_nameIsSet; } void PinEnergy::unsetRelated_pin_name() { m_Related_pin_nameIsSet = false; } int32_t PinEnergy::getSupply() const { return m_Supply; } void PinEnergy::setSupply(int32_t value) { m_Supply = value; m_SupplyIsSet = true; } bool PinEnergy::supplyIsSet() const { return m_SupplyIsSet; } void PinEnergy::unsetSupply() { m_SupplyIsSet = false; } utility::string_t PinEnergy::getSupplyName() const { return m_Supply_name; } void PinEnergy::setSupplyName(const utility::string_t& value) { m_Supply_name = value; m_Supply_nameIsSet = true; } bool PinEnergy::supplyNameIsSet() const { return m_Supply_nameIsSet; } void PinEnergy::unsetSupply_name() { m_Supply_nameIsSet = false; } utility::string_t PinEnergy::getProcess() const { return m_Process; } void PinEnergy::setProcess(const utility::string_t& value) { m_Process = value; m_ProcessIsSet = true; } bool PinEnergy::processIsSet() const { return m_ProcessIsSet; } void PinEnergy::unsetProcess() { m_ProcessIsSet = false; } utility::string_t PinEnergy::getRc() const { return m_Rc; } void PinEnergy::setRc(const utility::string_t& value) { m_Rc = value; m_RcIsSet = true; } bool PinEnergy::rcIsSet() const { return m_RcIsSet; } void PinEnergy::unsetRc() { m_RcIsSet = false; } double PinEnergy::getVoltage() const { return m_Voltage; } void PinEnergy::setVoltage(double value) { m_Voltage = value; m_VoltageIsSet = true; } bool PinEnergy::voltageIsSet() const { return m_VoltageIsSet; } void PinEnergy::unsetVoltage() { m_VoltageIsSet = false; } int32_t PinEnergy::getTemperature() const { return m_Temperature; } void PinEnergy::setTemperature(int32_t value) { m_Temperature = value; m_TemperatureIsSet = true; } bool PinEnergy::temperatureIsSet() const { return m_TemperatureIsSet; } void PinEnergy::unsetTemperature() { m_TemperatureIsSet = false; } utility::string_t PinEnergy::getWhen() const { return m_When; } void PinEnergy::setWhen(const utility::string_t& value) { m_When = value; m_WhenIsSet = true; } bool PinEnergy::whenIsSet() const { return m_WhenIsSet; } void PinEnergy::unsetWhen() { m_WhenIsSet = false; } std::vector<double>& PinEnergy::getIndex1() { return m_Index1; } void PinEnergy::setIndex1(std::vector<double> value) { m_Index1 = value; m_Index1IsSet = true; } bool PinEnergy::index1IsSet() const { return m_Index1IsSet; } void PinEnergy::unsetIndex1() { m_Index1IsSet = false; } utility::string_t PinEnergy::getVariable1() const { return m_Variable1; } void PinEnergy::setVariable1(const utility::string_t& value) { m_Variable1 = value; m_Variable1IsSet = true; } bool PinEnergy::variable1IsSet() const { return m_Variable1IsSet; } void PinEnergy::unsetVariable1() { m_Variable1IsSet = false; } std::vector<double>& PinEnergy::getIndex2() { return m_Index2; } void PinEnergy::setIndex2(std::vector<double> value) { m_Index2 = value; m_Index2IsSet = true; } bool PinEnergy::index2IsSet() const { return m_Index2IsSet; } void PinEnergy::unsetIndex2() { m_Index2IsSet = false; } utility::string_t PinEnergy::getVariable2() const { return m_Variable2; } void PinEnergy::setVariable2(const utility::string_t& value) { m_Variable2 = value; m_Variable2IsSet = true; } bool PinEnergy::variable2IsSet() const { return m_Variable2IsSet; } void PinEnergy::unsetVariable2() { m_Variable2IsSet = false; } std::vector<double>& PinEnergy::getRiseEnergy() { return m_Rise_energy; } void PinEnergy::setRiseEnergy(std::vector<double> value) { m_Rise_energy = value; m_Rise_energyIsSet = true; } bool PinEnergy::riseEnergyIsSet() const { return m_Rise_energyIsSet; } void PinEnergy::unsetRise_energy() { m_Rise_energyIsSet = false; } std::vector<double>& PinEnergy::getFallEnergy() { return m_Fall_energy; } void PinEnergy::setFallEnergy(std::vector<double> value) { m_Fall_energy = value; m_Fall_energyIsSet = true; } bool PinEnergy::fallEnergyIsSet() const { return m_Fall_energyIsSet; } void PinEnergy::unsetFall_energy() { m_Fall_energyIsSet = false; } std::vector<int32_t>& PinEnergy::getModes() { return m_Modes; } void PinEnergy::setModes(std::vector<int32_t> value) { m_Modes = value; m_ModesIsSet = true; } bool PinEnergy::modesIsSet() const { return m_ModesIsSet; } void PinEnergy::unsetModes() { m_ModesIsSet = false; } } }
28.377778
145
0.664653
thracesystems
045183dcd2e18e2989e72814937327efe7088073
7,643
cpp
C++
libraries/getopts/commandLineParser.cpp
dyollb/VegaFEM
83bb9e52f68dec5511393af0469abd85cfff4a7f
[ "BSD-3-Clause" ]
null
null
null
libraries/getopts/commandLineParser.cpp
dyollb/VegaFEM
83bb9e52f68dec5511393af0469abd85cfff4a7f
[ "BSD-3-Clause" ]
null
null
null
libraries/getopts/commandLineParser.cpp
dyollb/VegaFEM
83bb9e52f68dec5511393af0469abd85cfff4a7f
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************* * * * Vega FEM Simulation Library Version 4.0 * * * * "getopts" library , Copyright (C) 2018 USC * * All rights reserved. * * * * Code authors: Yijing Li, Jernej Barbic * * http://www.jernejbarbic.com/vega * * * * Research: Jernej Barbic, Hongyi Xu, Yijing Li, * * Danyong Zhao, Bohan Wang, * * Fun Shing Sin, Daniel Schroeder, * * Doug L. James, Jovan Popovic * * * * Funding: National Science Foundation, Link Foundation, * * Singapore-MIT GAMBIT Game Lab, * * Zumberge Research and Innovation Fund at USC, * * Sloan Foundation, Okawa Foundation, * * USC Annenberg Foundation * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the BSD-style license that is * * included with this library in the file LICENSE.txt * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file * * LICENSE.TXT for more details. * * * *************************************************************************/ #include "commandLineParser.h" #include <iostream> #include <string> #include <stdlib.h> #include <string.h> #include <errno.h> #include <stdio.h> using namespace std; CommandLineParser::CommandLineParser() {} void CommandLineParser::addOption(const string & name, int & value) { entries.push_back(Entry(name, INT, (void*)&value)); } void CommandLineParser::addOption(const string & name, char * value) { entries.push_back(Entry(name, CSTR, (void*)value)); } void CommandLineParser::addOption(const string & name, bool & value) { entries.push_back(Entry(name, BOOL, (void*)&value)); } void CommandLineParser::addOption(const std::string & name, vegalong & value) { entries.push_back(Entry(name, LONG, (void*)&value)); } void CommandLineParser::addOption(const std::string & name, float & value) { entries.push_back(Entry(name, FLOAT, (void*)&value)); } void CommandLineParser::addOption(const std::string & name, double & value) { entries.push_back(Entry(name, DOUBLE, (void*)&value)); } void CommandLineParser::addOption(const std::string & name, std::string & value) { entries.push_back(Entry(name, STRING, (void*)&value)); } int CommandLineParser::parse(int argc, char ** argv, int numSkipArg) { return parse(argc, (const char**)argv, numSkipArg); } int CommandLineParser::parse(int argc, const char ** argv, int numSkipArg) { for (int i = numSkipArg; i < argc; i++) { const char * arg = argv[i]; // option begins with '-' or '/' if ((*arg != '-') && (*arg != '/')) return (i); arg++; // skip '-' or '/' for (size_t j = 0; j < entries.size(); j++) //find options for this arg { //options are case sensitive!! size_t l = entries[j].name.size(); //printf("%s\n", opttable[j].sw); if (strncmp(arg, entries[j].name.data(), l) == 0) //found this option { const char * var = nullptr; //pointers to the input data for this option // bool standAloneData = false; // whether the data for this arg is in a separate string, like -v 123 // There's ambiguity when a negative number arg is next to a switch, like -f -48.9 // For now we only intepret it as two successive switches // A smarter implementation could be to forbid switch name to start with numbers, and check whether the second "switch" // starts with "-\d" // if a data string follows this arg string, like: -v 123 if ( (strlen(arg) == l) && ( (i+1 < argc) && (argv[i+1] != nullptr) && ( argv[i+1][0] != '-' && argv[i+1][0] != '/' ) ) ) { // go to the next data string i++; var = argv[i]; // standAloneData = true; } else { //copy the rest in this arg string, like: -v123 if ( ( *(arg+l)=='=' ) || (*(arg+l)==' ') ) // accept '=' or ' ' after the switch var = arg + l + 1; else var = arg + l; } // if (*var == '\0') // continue; //printf("%d %s\n",i, var); switch (entries[j].type) { case INT : if (*var != '\0') { *((int *)entries[j].value) = (int)strtol(var,nullptr,10); if (errno == ERANGE) return (i); } else // the data is absent. We consider it an error return i; break; case LONG : if (*var != '\0') { *((vegalong *)entries[j].value) = strtol(var,nullptr,10); if (errno == ERANGE) return (i); } else return i; break; case FLOAT : if (*var != '\0') { *((float *)entries[j].value) = (float)strtod(var,nullptr); if (errno == ERANGE) return (i); } else return i; break; case DOUBLE : if (*var != '\0') { *((double *)entries[j].value) = strtod(var,nullptr); if (errno == ERANGE) return (i); } else return i; break; // case OPTSUBOPT : // //option with more than 1 char as suboptions: // // /oail or /op // strcpy((char *)opttable[j].var, arg+l); // arg += strlen(arg)-1; // break; case CSTR : if (*var != '\0') strcpy((char *)entries[j].value, var); else return i; break; case STRING : if (*var != '\0') *((string*)(entries[j].value)) = var; else return i; break; case BOOL : //check a + or - after the sw: "/a- /b+" { bool boolValue = true; if ( *var == '-' ) boolValue = false; else boolValue = true; *((bool *)entries[j].value) = boolValue; break; } } break; //break the for } // end if (strncmp(arg, entries[j].name.data(), l) == 0) //found this option } // end for (size_t j = 0; j < entries.size(); j++) } return argc; } CommandLineParser::Entry::Entry(const std::string & n, Type t, void * v) : name(n), type(t), value(v) {}
35.059633
129
0.447861
dyollb
0452941871a83af5ba88c83fbedd86ff43b8d988
25,244
cpp
C++
modules/core/src/split.cpp
liqingshan/opencv
5e68f35500a859838ab8688bd3487cf9edece3f7
[ "BSD-3-Clause" ]
17
2016-03-16T08:48:30.000Z
2022-02-21T12:09:28.000Z
modules/core/src/split.cpp
nurisis/opencv
4378b4d03d8415a132b6675883957243f95d75ee
[ "BSD-3-Clause" ]
5
2017-10-15T15:44:47.000Z
2022-02-17T11:31:32.000Z
modules/core/src/split.cpp
nurisis/opencv
4378b4d03d8415a132b6675883957243f95d75ee
[ "BSD-3-Clause" ]
25
2018-09-26T08:51:13.000Z
2022-02-24T13:43:58.000Z
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html #include "precomp.hpp" #include "opencl_kernels_core.hpp" namespace cv { namespace hal { #if CV_NEON template<typename T> struct VSplit2; template<typename T> struct VSplit3; template<typename T> struct VSplit4; #define SPLIT2_KERNEL_TEMPLATE(name, data_type, reg_type, load_func, store_func) \ template<> \ struct name<data_type> \ { \ void operator()(const data_type* src, data_type* dst0, \ data_type* dst1) const \ { \ reg_type r = load_func(src); \ store_func(dst0, r.val[0]); \ store_func(dst1, r.val[1]); \ } \ } #define SPLIT3_KERNEL_TEMPLATE(name, data_type, reg_type, load_func, store_func) \ template<> \ struct name<data_type> \ { \ void operator()(const data_type* src, data_type* dst0, data_type* dst1, \ data_type* dst2) const \ { \ reg_type r = load_func(src); \ store_func(dst0, r.val[0]); \ store_func(dst1, r.val[1]); \ store_func(dst2, r.val[2]); \ } \ } #define SPLIT4_KERNEL_TEMPLATE(name, data_type, reg_type, load_func, store_func) \ template<> \ struct name<data_type> \ { \ void operator()(const data_type* src, data_type* dst0, data_type* dst1, \ data_type* dst2, data_type* dst3) const \ { \ reg_type r = load_func(src); \ store_func(dst0, r.val[0]); \ store_func(dst1, r.val[1]); \ store_func(dst2, r.val[2]); \ store_func(dst3, r.val[3]); \ } \ } SPLIT2_KERNEL_TEMPLATE(VSplit2, uchar , uint8x16x2_t, vld2q_u8 , vst1q_u8 ); SPLIT2_KERNEL_TEMPLATE(VSplit2, ushort, uint16x8x2_t, vld2q_u16, vst1q_u16); SPLIT2_KERNEL_TEMPLATE(VSplit2, int , int32x4x2_t, vld2q_s32, vst1q_s32); SPLIT2_KERNEL_TEMPLATE(VSplit2, int64 , int64x1x2_t, vld2_s64 , vst1_s64 ); SPLIT3_KERNEL_TEMPLATE(VSplit3, uchar , uint8x16x3_t, vld3q_u8 , vst1q_u8 ); SPLIT3_KERNEL_TEMPLATE(VSplit3, ushort, uint16x8x3_t, vld3q_u16, vst1q_u16); SPLIT3_KERNEL_TEMPLATE(VSplit3, int , int32x4x3_t, vld3q_s32, vst1q_s32); SPLIT3_KERNEL_TEMPLATE(VSplit3, int64 , int64x1x3_t, vld3_s64 , vst1_s64 ); SPLIT4_KERNEL_TEMPLATE(VSplit4, uchar , uint8x16x4_t, vld4q_u8 , vst1q_u8 ); SPLIT4_KERNEL_TEMPLATE(VSplit4, ushort, uint16x8x4_t, vld4q_u16, vst1q_u16); SPLIT4_KERNEL_TEMPLATE(VSplit4, int , int32x4x4_t, vld4q_s32, vst1q_s32); SPLIT4_KERNEL_TEMPLATE(VSplit4, int64 , int64x1x4_t, vld4_s64 , vst1_s64 ); #elif CV_SSE2 template <typename T> struct VSplit2 { VSplit2() : support(false) { } void operator()(const T *, T *, T *) const { } bool support; }; template <typename T> struct VSplit3 { VSplit3() : support(false) { } void operator()(const T *, T *, T *, T *) const { } bool support; }; template <typename T> struct VSplit4 { VSplit4() : support(false) { } void operator()(const T *, T *, T *, T *, T *) const { } bool support; }; #define SPLIT2_KERNEL_TEMPLATE(data_type, reg_type, cast_type, _mm_deinterleave, flavor) \ template <> \ struct VSplit2<data_type> \ { \ enum \ { \ ELEMS_IN_VEC = 16 / sizeof(data_type) \ }; \ \ VSplit2() \ { \ support = checkHardwareSupport(CV_CPU_SSE2); \ } \ \ void operator()(const data_type * src, \ data_type * dst0, data_type * dst1) const \ { \ reg_type v_src0 = _mm_loadu_##flavor((cast_type const *)(src)); \ reg_type v_src1 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC)); \ reg_type v_src2 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 2)); \ reg_type v_src3 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 3)); \ \ _mm_deinterleave(v_src0, v_src1, v_src2, v_src3); \ \ _mm_storeu_##flavor((cast_type *)(dst0), v_src0); \ _mm_storeu_##flavor((cast_type *)(dst0 + ELEMS_IN_VEC), v_src1); \ _mm_storeu_##flavor((cast_type *)(dst1), v_src2); \ _mm_storeu_##flavor((cast_type *)(dst1 + ELEMS_IN_VEC), v_src3); \ } \ \ bool support; \ } #define SPLIT3_KERNEL_TEMPLATE(data_type, reg_type, cast_type, _mm_deinterleave, flavor) \ template <> \ struct VSplit3<data_type> \ { \ enum \ { \ ELEMS_IN_VEC = 16 / sizeof(data_type) \ }; \ \ VSplit3() \ { \ support = checkHardwareSupport(CV_CPU_SSE2); \ } \ \ void operator()(const data_type * src, \ data_type * dst0, data_type * dst1, data_type * dst2) const \ { \ reg_type v_src0 = _mm_loadu_##flavor((cast_type const *)(src)); \ reg_type v_src1 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC)); \ reg_type v_src2 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 2)); \ reg_type v_src3 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 3)); \ reg_type v_src4 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 4)); \ reg_type v_src5 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 5)); \ \ _mm_deinterleave(v_src0, v_src1, v_src2, \ v_src3, v_src4, v_src5); \ \ _mm_storeu_##flavor((cast_type *)(dst0), v_src0); \ _mm_storeu_##flavor((cast_type *)(dst0 + ELEMS_IN_VEC), v_src1); \ _mm_storeu_##flavor((cast_type *)(dst1), v_src2); \ _mm_storeu_##flavor((cast_type *)(dst1 + ELEMS_IN_VEC), v_src3); \ _mm_storeu_##flavor((cast_type *)(dst2), v_src4); \ _mm_storeu_##flavor((cast_type *)(dst2 + ELEMS_IN_VEC), v_src5); \ } \ \ bool support; \ } #define SPLIT4_KERNEL_TEMPLATE(data_type, reg_type, cast_type, _mm_deinterleave, flavor) \ template <> \ struct VSplit4<data_type> \ { \ enum \ { \ ELEMS_IN_VEC = 16 / sizeof(data_type) \ }; \ \ VSplit4() \ { \ support = checkHardwareSupport(CV_CPU_SSE2); \ } \ \ void operator()(const data_type * src, data_type * dst0, data_type * dst1, \ data_type * dst2, data_type * dst3) const \ { \ reg_type v_src0 = _mm_loadu_##flavor((cast_type const *)(src)); \ reg_type v_src1 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC)); \ reg_type v_src2 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 2)); \ reg_type v_src3 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 3)); \ reg_type v_src4 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 4)); \ reg_type v_src5 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 5)); \ reg_type v_src6 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 6)); \ reg_type v_src7 = _mm_loadu_##flavor((cast_type const *)(src + ELEMS_IN_VEC * 7)); \ \ _mm_deinterleave(v_src0, v_src1, v_src2, v_src3, \ v_src4, v_src5, v_src6, v_src7); \ \ _mm_storeu_##flavor((cast_type *)(dst0), v_src0); \ _mm_storeu_##flavor((cast_type *)(dst0 + ELEMS_IN_VEC), v_src1); \ _mm_storeu_##flavor((cast_type *)(dst1), v_src2); \ _mm_storeu_##flavor((cast_type *)(dst1 + ELEMS_IN_VEC), v_src3); \ _mm_storeu_##flavor((cast_type *)(dst2), v_src4); \ _mm_storeu_##flavor((cast_type *)(dst2 + ELEMS_IN_VEC), v_src5); \ _mm_storeu_##flavor((cast_type *)(dst3), v_src6); \ _mm_storeu_##flavor((cast_type *)(dst3 + ELEMS_IN_VEC), v_src7); \ } \ \ bool support; \ } SPLIT2_KERNEL_TEMPLATE( uchar, __m128i, __m128i, _mm_deinterleave_epi8, si128); SPLIT2_KERNEL_TEMPLATE(ushort, __m128i, __m128i, _mm_deinterleave_epi16, si128); SPLIT2_KERNEL_TEMPLATE( int, __m128, float, _mm_deinterleave_ps, ps); SPLIT3_KERNEL_TEMPLATE( uchar, __m128i, __m128i, _mm_deinterleave_epi8, si128); SPLIT3_KERNEL_TEMPLATE(ushort, __m128i, __m128i, _mm_deinterleave_epi16, si128); SPLIT3_KERNEL_TEMPLATE( int, __m128, float, _mm_deinterleave_ps, ps); SPLIT4_KERNEL_TEMPLATE( uchar, __m128i, __m128i, _mm_deinterleave_epi8, si128); SPLIT4_KERNEL_TEMPLATE(ushort, __m128i, __m128i, _mm_deinterleave_epi16, si128); SPLIT4_KERNEL_TEMPLATE( int, __m128, float, _mm_deinterleave_ps, ps); #endif template<typename T> static void split_( const T* src, T** dst, int len, int cn ) { int k = cn % 4 ? cn % 4 : 4; int i, j; if( k == 1 ) { T* dst0 = dst[0]; if(cn == 1) { memcpy(dst0, src, len * sizeof(T)); } else { for( i = 0, j = 0 ; i < len; i++, j += cn ) dst0[i] = src[j]; } } else if( k == 2 ) { T *dst0 = dst[0], *dst1 = dst[1]; i = j = 0; #if CV_NEON if(cn == 2) { int inc_i = (sizeof(T) == 8)? 1: 16/sizeof(T); int inc_j = 2 * inc_i; VSplit2<T> vsplit; for( ; i < len - inc_i; i += inc_i, j += inc_j) vsplit(src + j, dst0 + i, dst1 + i); } #elif CV_SSE2 if (cn == 2) { int inc_i = 32/sizeof(T); int inc_j = 2 * inc_i; VSplit2<T> vsplit; if (vsplit.support) { for( ; i <= len - inc_i; i += inc_i, j += inc_j) vsplit(src + j, dst0 + i, dst1 + i); } } #endif for( ; i < len; i++, j += cn ) { dst0[i] = src[j]; dst1[i] = src[j+1]; } } else if( k == 3 ) { T *dst0 = dst[0], *dst1 = dst[1], *dst2 = dst[2]; i = j = 0; #if CV_NEON if(cn == 3) { int inc_i = (sizeof(T) == 8)? 1: 16/sizeof(T); int inc_j = 3 * inc_i; VSplit3<T> vsplit; for( ; i <= len - inc_i; i += inc_i, j += inc_j) vsplit(src + j, dst0 + i, dst1 + i, dst2 + i); } #elif CV_SSE2 if (cn == 3) { int inc_i = 32/sizeof(T); int inc_j = 3 * inc_i; VSplit3<T> vsplit; if (vsplit.support) { for( ; i <= len - inc_i; i += inc_i, j += inc_j) vsplit(src + j, dst0 + i, dst1 + i, dst2 + i); } } #endif for( ; i < len; i++, j += cn ) { dst0[i] = src[j]; dst1[i] = src[j+1]; dst2[i] = src[j+2]; } } else { T *dst0 = dst[0], *dst1 = dst[1], *dst2 = dst[2], *dst3 = dst[3]; i = j = 0; #if CV_NEON if(cn == 4) { int inc_i = (sizeof(T) == 8)? 1: 16/sizeof(T); int inc_j = 4 * inc_i; VSplit4<T> vsplit; for( ; i <= len - inc_i; i += inc_i, j += inc_j) vsplit(src + j, dst0 + i, dst1 + i, dst2 + i, dst3 + i); } #elif CV_SSE2 if (cn == 4) { int inc_i = 32/sizeof(T); int inc_j = 4 * inc_i; VSplit4<T> vsplit; if (vsplit.support) { for( ; i <= len - inc_i; i += inc_i, j += inc_j) vsplit(src + j, dst0 + i, dst1 + i, dst2 + i, dst3 + i); } } #endif for( ; i < len; i++, j += cn ) { dst0[i] = src[j]; dst1[i] = src[j+1]; dst2[i] = src[j+2]; dst3[i] = src[j+3]; } } for( ; k < cn; k += 4 ) { T *dst0 = dst[k], *dst1 = dst[k+1], *dst2 = dst[k+2], *dst3 = dst[k+3]; for( i = 0, j = k; i < len; i++, j += cn ) { dst0[i] = src[j]; dst1[i] = src[j+1]; dst2[i] = src[j+2]; dst3[i] = src[j+3]; } } } void split8u(const uchar* src, uchar** dst, int len, int cn ) { CALL_HAL(split8u, cv_hal_split8u, src,dst, len, cn) split_(src, dst, len, cn); } void split16u(const ushort* src, ushort** dst, int len, int cn ) { CALL_HAL(split16u, cv_hal_split16u, src,dst, len, cn) split_(src, dst, len, cn); } void split32s(const int* src, int** dst, int len, int cn ) { CALL_HAL(split32s, cv_hal_split32s, src,dst, len, cn) split_(src, dst, len, cn); } void split64s(const int64* src, int64** dst, int len, int cn ) { CALL_HAL(split64s, cv_hal_split64s, src,dst, len, cn) split_(src, dst, len, cn); } }} // cv::hal:: /****************************************************************************************\ * split & merge * \****************************************************************************************/ typedef void (*SplitFunc)(const uchar* src, uchar** dst, int len, int cn); static SplitFunc getSplitFunc(int depth) { static SplitFunc splitTab[] = { (SplitFunc)GET_OPTIMIZED(cv::hal::split8u), (SplitFunc)GET_OPTIMIZED(cv::hal::split8u), (SplitFunc)GET_OPTIMIZED(cv::hal::split16u), (SplitFunc)GET_OPTIMIZED(cv::hal::split16u), (SplitFunc)GET_OPTIMIZED(cv::hal::split32s), (SplitFunc)GET_OPTIMIZED(cv::hal::split32s), (SplitFunc)GET_OPTIMIZED(cv::hal::split64s), 0 }; return splitTab[depth]; } #ifdef HAVE_IPP namespace cv { static bool ipp_split(const Mat& src, Mat* mv, int channels) { #ifdef HAVE_IPP_IW CV_INSTRUMENT_REGION_IPP() if(channels != 3 && channels != 4) return false; if(src.dims <= 2) { IppiSize size = ippiSize(src.size()); void *dstPtrs[4] = {NULL}; size_t dstStep = mv[0].step; for(int i = 0; i < channels; i++) { dstPtrs[i] = mv[i].ptr(); if(dstStep != mv[i].step) return false; } return CV_INSTRUMENT_FUN_IPP(llwiCopySplit, src.ptr(), (int)src.step, dstPtrs, (int)dstStep, size, (int)src.elemSize1(), channels, 0) >= 0; } else { const Mat *arrays[5] = {NULL}; uchar *ptrs[5] = {NULL}; arrays[0] = &src; for(int i = 1; i < channels; i++) { arrays[i] = &mv[i-1]; } NAryMatIterator it(arrays, ptrs); IppiSize size = { (int)it.size, 1 }; for( size_t i = 0; i < it.nplanes; i++, ++it ) { if(CV_INSTRUMENT_FUN_IPP(llwiCopySplit, ptrs[0], 0, (void**)&ptrs[1], 0, size, (int)src.elemSize1(), channels, 0) < 0) return false; } return true; } #else CV_UNUSED(src); CV_UNUSED(mv); CV_UNUSED(channels); return false; #endif } } #endif void cv::split(const Mat& src, Mat* mv) { CV_INSTRUMENT_REGION() int k, depth = src.depth(), cn = src.channels(); if( cn == 1 ) { src.copyTo(mv[0]); return; } for( k = 0; k < cn; k++ ) { mv[k].create(src.dims, src.size, depth); } CV_IPP_RUN_FAST(ipp_split(src, mv, cn)); SplitFunc func = getSplitFunc(depth); CV_Assert( func != 0 ); size_t esz = src.elemSize(), esz1 = src.elemSize1(); size_t blocksize0 = (BLOCK_SIZE + esz-1)/esz; AutoBuffer<uchar> _buf((cn+1)*(sizeof(Mat*) + sizeof(uchar*)) + 16); const Mat** arrays = (const Mat**)(uchar*)_buf; uchar** ptrs = (uchar**)alignPtr(arrays + cn + 1, 16); arrays[0] = &src; for( k = 0; k < cn; k++ ) { arrays[k+1] = &mv[k]; } NAryMatIterator it(arrays, ptrs, cn+1); size_t total = it.size; size_t blocksize = std::min((size_t)CV_SPLIT_MERGE_MAX_BLOCK_SIZE(cn), cn <= 4 ? total : std::min(total, blocksize0)); for( size_t i = 0; i < it.nplanes; i++, ++it ) { for( size_t j = 0; j < total; j += blocksize ) { size_t bsz = std::min(total - j, blocksize); func( ptrs[0], &ptrs[1], (int)bsz, cn ); if( j + blocksize < total ) { ptrs[0] += bsz*esz; for( k = 0; k < cn; k++ ) ptrs[k+1] += bsz*esz1; } } } } #ifdef HAVE_OPENCL namespace cv { static bool ocl_split( InputArray _m, OutputArrayOfArrays _mv ) { int type = _m.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type), rowsPerWI = ocl::Device::getDefault().isIntel() ? 4 : 1; String dstargs, processelem, indexdecl; for (int i = 0; i < cn; ++i) { dstargs += format("DECLARE_DST_PARAM(%d)", i); indexdecl += format("DECLARE_INDEX(%d)", i); processelem += format("PROCESS_ELEM(%d)", i); } ocl::Kernel k("split", ocl::core::split_merge_oclsrc, format("-D T=%s -D OP_SPLIT -D cn=%d -D DECLARE_DST_PARAMS=%s" " -D PROCESS_ELEMS_N=%s -D DECLARE_INDEX_N=%s", ocl::memopTypeToStr(depth), cn, dstargs.c_str(), processelem.c_str(), indexdecl.c_str())); if (k.empty()) return false; Size size = _m.size(); _mv.create(cn, 1, depth); for (int i = 0; i < cn; ++i) _mv.create(size, depth, i); std::vector<UMat> dst; _mv.getUMatVector(dst); int argidx = k.set(0, ocl::KernelArg::ReadOnly(_m.getUMat())); for (int i = 0; i < cn; ++i) argidx = k.set(argidx, ocl::KernelArg::WriteOnlyNoSize(dst[i])); k.set(argidx, rowsPerWI); size_t globalsize[2] = { (size_t)size.width, ((size_t)size.height + rowsPerWI - 1) / rowsPerWI }; return k.run(2, globalsize, NULL, false); } } #endif void cv::split(InputArray _m, OutputArrayOfArrays _mv) { CV_INSTRUMENT_REGION() CV_OCL_RUN(_m.dims() <= 2 && _mv.isUMatVector(), ocl_split(_m, _mv)) Mat m = _m.getMat(); if( m.empty() ) { _mv.release(); return; } CV_Assert( !_mv.fixedType() || _mv.empty() || _mv.type() == m.depth() ); int depth = m.depth(), cn = m.channels(); _mv.create(cn, 1, depth); for (int i = 0; i < cn; ++i) _mv.create(m.dims, m.size.p, depth, i); std::vector<Mat> dst; _mv.getMatVector(dst); split(m, &dst[0]); }
42.786441
185
0.393797
liqingshan
0452ae4a768900c322fe1193c624b23be4479254
1,464
hpp
C++
src/aspell-60/common/filter_char.hpp
reydajp/build-spell
a88ffbb9ffedae3f20933b187c95851e47e0e4c3
[ "MIT" ]
31
2016-11-08T05:13:02.000Z
2022-02-23T19:13:01.000Z
src/aspell-60/common/filter_char.hpp
reydajp/build-spell
a88ffbb9ffedae3f20933b187c95851e47e0e4c3
[ "MIT" ]
6
2017-01-17T20:21:55.000Z
2021-09-02T07:36:18.000Z
src/aspell-60/common/filter_char.hpp
reydajp/build-spell
a88ffbb9ffedae3f20933b187c95851e47e0e4c3
[ "MIT" ]
5
2017-07-11T11:10:55.000Z
2022-02-14T01:55:16.000Z
#ifndef acommon_filter_char_hh #define acommon_filter_char_hh // This file is part of The New Aspell // Copyright (C) 2002 by Kevin Atkinson under the GNU LGPL license // version 2.0 or 2.1. You should have received a copy of the LGPL // license along with this library if you did not you can find // it at http://www.gnu.org/. namespace acommon { struct FilterChar { unsigned int chr; unsigned int width; // width must always be < 256 typedef unsigned int Chr; typedef unsigned int Width; explicit FilterChar(Chr c = 0, Width w = 1) : chr(c), width(w) {} FilterChar(Chr c, FilterChar o) : chr(c), width(o.width) {} static Width sum(const FilterChar * o, const FilterChar * stop) { Width total = 0; for (; o != stop; ++o) total += o->width; return total; } static Width sum(const FilterChar * o, unsigned int size) { return sum(o, o+size); } FilterChar(Chr c, const FilterChar * o, unsigned int size) : chr(c), width(sum(o,size)) {} FilterChar(Chr c, const FilterChar * o, const FilterChar * stop) : chr(c), width(sum(o,stop)) {} operator Chr () const {return chr;} FilterChar & operator= (Chr c) {chr = c; return *this;} }; static inline bool operator==(FilterChar lhs, FilterChar rhs) { return lhs.chr == rhs.chr; } static inline bool operator!=(FilterChar lhs, FilterChar rhs) { return lhs.chr != rhs.chr; } } #endif
28.705882
69
0.638661
reydajp
0455e1b953175e5fa7f25afc9b03beefbaadcd2b
3,559
inl
C++
runnable/Stack.inl
eladraz/morph
e80b93af449471fb2ca9e256188f9a92f631fbc2
[ "BSD-3-Clause" ]
4
2017-01-24T09:32:23.000Z
2021-08-20T03:29:54.000Z
runnable/Stack.inl
eladraz/morph
e80b93af449471fb2ca9e256188f9a92f631fbc2
[ "BSD-3-Clause" ]
null
null
null
runnable/Stack.inl
eladraz/morph
e80b93af449471fb2ca9e256188f9a92f631fbc2
[ "BSD-3-Clause" ]
1
2021-08-20T03:29:55.000Z
2021-08-20T03:29:55.000Z
/* * Copyright (c) 2008-2016, Integrity Project Ltd. 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 Integrity Project 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 */ /* * Stack.cpp * * Implementation file * * Author: Elad Raz <e@eladraz.com> */ #include "xStl/types.h" #include "data/exceptions.h" #include "runnable/Stack.h" template <class T, class Itr> void StackInfrastructor<T, Itr>::pop2null(uint amount) { if (amount == 0) return; if (isEmpty()) XSTL_THROW(ClrStackError); for (uint i = 0; i < amount; i++) { Itr b(m_stack.begin()); m_stack.remove(b); } } template <class T, class Itr> void StackInfrastructor<T, Itr>::push(const T& var) { m_stack.insert(var); } template <class T, class Itr> const T& StackInfrastructor<T, Itr>::peek() const { if (isEmpty()) XSTL_THROW(ClrStackError); return *m_stack.begin(); } template <class T, class Itr> T& StackInfrastructor<T, Itr>::getArg(uint index) { Itr j = m_stack.begin(); while (index > 0) { if (j == m_stack.end()) XSTL_THROW(ClrStackError); ++j; --index; } return *j; } template <class T, class Itr> T& StackInfrastructor<T, Itr>::tos() { if (isEmpty()) XSTL_THROW(ClrStackError); return *m_stack.begin(); } template <class T, class Itr> bool StackInfrastructor<T, Itr>::isEmpty() const { return m_stack.begin() == m_stack.end(); } template <class T, class Itr> uint StackInfrastructor<T, Itr>::getStackCount() const { return m_stack.length(); } template <class T, class Itr> cList<T>& StackInfrastructor<T, Itr>::getList() { return m_stack; } template <class T, class Itr> const Itr StackInfrastructor<T, Itr>::getTosPosition() { return m_stack.begin(); } template <class T, class Itr> void StackInfrastructor<T, Itr>::revertStack(const Itr& pos) { while (m_stack.begin() != pos) { if (isEmpty()) { // Error with stack reverting CHECK_FAIL(); } m_stack.remove(m_stack.begin()); } } template <class T, class Itr> void StackInfrastructor<T, Itr>::clear() { m_stack.removeAll(); }
25.421429
78
0.692329
eladraz
0455f1414c402e8cfef678358dc0fa8b56e2ad54
2,229
cpp
C++
FMODStudio/Source/FMODStudio/Private/FMODEvent.cpp
alessandrofama/ue4integration
074118424f95fde7455ca6de4e992a2608ead146
[ "MIT" ]
null
null
null
FMODStudio/Source/FMODStudio/Private/FMODEvent.cpp
alessandrofama/ue4integration
074118424f95fde7455ca6de4e992a2608ead146
[ "MIT" ]
null
null
null
FMODStudio/Source/FMODStudio/Private/FMODEvent.cpp
alessandrofama/ue4integration
074118424f95fde7455ca6de4e992a2608ead146
[ "MIT" ]
null
null
null
// Copyright (c), Firelight Technologies Pty, Ltd. 2012-2019. #include "FMODEvent.h" #include "FMODStudioModule.h" #include "fmod_studio.hpp" UFMODEvent::UFMODEvent(const FObjectInitializer &ObjectInitializer) : Super(ObjectInitializer) { } /** Get tags to show in content view */ void UFMODEvent::GetAssetRegistryTags(TArray<FAssetRegistryTag> &OutTags) const { Super::GetAssetRegistryTags(OutTags); if (IFMODStudioModule::Get().AreBanksLoaded()) { FMOD::Studio::EventDescription *EventDesc = IFMODStudioModule::Get().GetEventDescription(this, EFMODSystemContext::Max); bool bOneshot = false; bool bStream = false; bool b3D = false; if (EventDesc) { EventDesc->isOneshot(&bOneshot); EventDesc->isStream(&bStream); EventDesc->is3D(&b3D); } OutTags.Add(UObject::FAssetRegistryTag("Oneshot", bOneshot ? TEXT("True") : TEXT("False"), UObject::FAssetRegistryTag::TT_Alphabetical)); OutTags.Add(UObject::FAssetRegistryTag("Streaming", bStream ? TEXT("True") : TEXT("False"), UObject::FAssetRegistryTag::TT_Alphabetical)); OutTags.Add(UObject::FAssetRegistryTag("3D", b3D ? TEXT("True") : TEXT("False"), UObject::FAssetRegistryTag::TT_Alphabetical)); } } FString UFMODEvent::GetDesc() { return FString::Printf(TEXT("Event %s"), *AssetGuid.ToString(EGuidFormats::DigitsWithHyphensInBraces)); } void UFMODEvent::GetParameterDescriptions(TArray<FMOD_STUDIO_PARAMETER_DESCRIPTION> &Parameters) const { if (IFMODStudioModule::Get().AreBanksLoaded()) { FMOD::Studio::EventDescription *EventDesc = IFMODStudioModule::Get().GetEventDescription(this, EFMODSystemContext::Auditioning); if (EventDesc) { int ParameterCount; EventDesc->getParameterDescriptionCount(&ParameterCount); Parameters.SetNumUninitialized(ParameterCount); for (int ParameterIndex = 0; ParameterIndex < ParameterCount; ++ParameterIndex) { EventDesc->getParameterDescriptionByIndex(ParameterIndex, &Parameters[ParameterIndex]); } } } }
37.779661
147
0.665321
alessandrofama
0459c857420fa66ea62ffc1905429b1cee9363d5
1,379
cpp
C++
include/igl/png/readPNG.cpp
rushmash/libwetcloth
24f16481c68952c3d2a91acd6e3b74eb091b66bc
[ "BSD-3-Clause-Clear" ]
28
2017-03-01T04:09:18.000Z
2022-02-01T13:33:50.000Z
include/igl/png/readPNG.cpp
rushmash/libwetcloth
24f16481c68952c3d2a91acd6e3b74eb091b66bc
[ "BSD-3-Clause-Clear" ]
3
2017-03-09T05:22:49.000Z
2017-08-02T18:38:05.000Z
include/igl/png/readPNG.cpp
rushmash/libwetcloth
24f16481c68952c3d2a91acd6e3b74eb091b66bc
[ "BSD-3-Clause-Clear" ]
17
2017-03-01T14:00:01.000Z
2022-02-08T06:36:54.000Z
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2016 Daniele Panozzo <daniele.panozzo@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public License // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include "readPNG.h" #include <stb_image.h> IGL_INLINE bool igl::png::readPNG( const std::string png_file, Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& R, Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& G, Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& B, Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& A ) { int cols,rows,n; unsigned char *data = stbi_load(png_file.c_str(), &cols, &rows, &n, 4); if(data == NULL) { return false; } R.resize(cols,rows); G.resize(cols,rows); B.resize(cols,rows); A.resize(cols,rows); for (unsigned i=0; i<rows; ++i) { for (unsigned j=0; j<cols; ++j) { R(j,rows-1-i) = data[4*(j + cols * i) + 0]; G(j,rows-1-i) = data[4*(j + cols * i) + 1]; B(j,rows-1-i) = data[4*(j + cols * i) + 2]; A(j,rows-1-i) = data[4*(j + cols * i) + 3]; } } stbi_image_free(data); return true; } #ifdef IGL_STATIC_LIBRARY // Explicit template instantiation // generated by autoexplicit.sh #endif
28.729167
78
0.647571
rushmash
045bed84e41210b4c4afc5c4a6d6fc7f9ff0fd94
994
cpp
C++
venv/boost_1_73_0/libs/coroutine/example/asymmetric/simple.cpp
uosorio/heroku_face
7d6465e71dba17a15d8edaef520adb2fcd09d91e
[ "Apache-2.0" ]
106
2015-08-07T04:23:50.000Z
2020-12-27T18:25:15.000Z
3rdparty/boost_1_73_0/libs/coroutine/example/asymmetric/simple.cpp
qingkouwei/mediaones
cec475e1bfd5807b5351cc7e38d244ac5298ca16
[ "MIT" ]
130
2016-06-22T22:11:25.000Z
2020-11-29T20:24:09.000Z
3rdparty/boost_1_73_0/libs/coroutine/example/asymmetric/simple.cpp
qingkouwei/mediaones
cec475e1bfd5807b5351cc7e38d244ac5298ca16
[ "MIT" ]
41
2015-07-08T19:18:35.000Z
2021-01-14T16:39:56.000Z
#include <boost/coroutine/all.hpp> #include <cstdlib> #include <iostream> #include <boost/bind.hpp> #include "X.h" typedef boost::coroutines::asymmetric_coroutine< X& >::pull_type pull_coro_t; typedef boost::coroutines::asymmetric_coroutine< X& >::push_type push_coro_t; void fn1( push_coro_t & sink) { for ( int i = 0; i < 10; ++i) { X x( i); sink( x); } } void fn2( pull_coro_t & source) { while ( source) { X & x = source.get(); std::cout << "i = " << x.i << std::endl; source(); } } int main( int argc, char * argv[]) { { pull_coro_t source( fn1); while ( source) { X & x = source.get(); std::cout << "i = " << x.i << std::endl; source(); } } { push_coro_t sink( fn2); for ( int i = 0; i < 10; ++i) { X x( i); sink( x); } } std::cout << "Done" << std::endl; return EXIT_SUCCESS; }
18.407407
77
0.484909
uosorio
045c0ec66c0e55f83e66ae30b656194e5ba64852
2,841
cpp
C++
test/unit/adl/oct/cpu/add_cons_close_oper.unit.cpp
flisboac/adl
a29f4ab2652e8146d4f97fd10f52526e4bc3563c
[ "MIT" ]
2
2021-01-12T12:04:09.000Z
2022-03-21T10:09:54.000Z
test/unit/adl/oct/cpu/add_cons_close_oper.unit.cpp
flisboac/adl
a29f4ab2652e8146d4f97fd10f52526e4bc3563c
[ "MIT" ]
70
2017-02-25T16:37:48.000Z
2018-01-28T22:15:42.000Z
test/unit/adl/oct/cpu/add_cons_close_oper.unit.cpp
flisboac/adl
a29f4ab2652e8146d4f97fd10f52526e4bc3563c
[ "MIT" ]
null
null
null
// $flisboac 2018-01-14 #include "adl_catch.hpp" #include "adl/oct/cpu/closure_oper.hpp" #include "adl/oct/cpu/add_cons_close_oper.hpp" #include "adl/oct/cons.hpp" #include "adl/oct/system.hpp" #include "adl/oct/cpu/dense_dbm.hpp" #include "adl/oct/cpu/seq_context.hpp" using namespace adl::oct; using namespace adl::oct::cpu; using namespace adl::literals; using namespace adl::operators; using namespace adl::dsl; template <typename DbmType, typename OperType> static void add_cons(char const* type_name, DbmType& dbm, OperType&& oper) { using limits = typename DbmType::constant_limits; using constant_type = typename DbmType::constant_type; auto cons_close_sat = oper.get(); INFO("type_name = " << type_name << ", dbm = " << dbm.to_string()); REQUIRE((cons_close_sat)); for (auto k = dbm.first_var(); k <= dbm.last_var(); k++) { INFO(limits::raw_value(dbm.at(k, k))); REQUIRE( (dbm.at(k, k) == 0) ); // closure INFO(limits::raw_value(dbm.at(k, -k))); REQUIRE( (limits::is_even(dbm.at(k, -k))) ); // tight closure (unary constraints, all even) for (auto i = dbm.first_var(); i <= dbm.last_var(); i++) { INFO("dbm.at(k, i) = " << limits::raw_value(dbm.at(k, i))); INFO("dbm.at(k, -k) = " << limits::raw_value(dbm.at(k, -k))); INFO("dbm.at(-i, i) = " << limits::raw_value(dbm.at(-i, i))); REQUIRE( (dbm.at(k, i) <= (dbm.at(k, -k) / 2) + (dbm.at(-i, i) / 2)) ); // strong closure for (auto j = dbm.first_var(); j <= dbm.last_var(); j++) { REQUIRE( (dbm.at(i, j) <= dbm.at(i, k) + dbm.at(k, j)) ); // closure } } } }; template <typename FloatType> static void do_test(char const* type_name) { using limits = constant_limits<FloatType>; auto xi = 1_ov; auto xj = 2_ov; auto xdi = xi.to_counterpart(); auto xdj = xj.to_counterpart(); auto context = cpu::seq_context::make(); auto dbm = context.make_dbm<cpu::dense_dbm, FloatType>(xj); dbm.assign({ xi <= FloatType(3.0), xj <= FloatType(2.0), xi + xj <= FloatType(6.0) }); auto queue = context.make_queue(); auto closure = queue.make_oper<cpu::closure_oper>(dbm); REQUIRE( (closure.get()) ); add_cons( type_name, dbm, queue.make_oper<cpu::add_cons_close_oper>(dbm, -xi <= FloatType(3.0)) ); add_cons( type_name, dbm, queue.make_oper<cpu::add_cons_close_oper>(dbm, -xi - xj <= FloatType(5.0)) ); } TEST_CASE("unit:adl/oct/cpu/add_cons_close_oper.hpp", "[unit][oper][adl][adl/oct][adl/oct/cpu]") { //do_test<int>("int"); // TBD do_test<float>("float"); do_test<double>("double"); do_test<long double>("long double"); do_test<float_int>("float_int"); do_test<double_int>("double_int"); do_test<ldouble_int>("ldouble_int"); }
35.074074
139
0.613868
flisboac
045c1f5e1a51ba243bb541b7645cabb7237e545e
2,032
cpp
C++
plugins/opengl/src/texture/funcs/set_2d.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
plugins/opengl/src/texture/funcs/set_2d.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
plugins/opengl/src/texture/funcs/set_2d.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <sge/opengl/call.hpp> #include <sge/opengl/check_state.hpp> #include <sge/opengl/color_base_type.hpp> #include <sge/opengl/color_order.hpp> #include <sge/opengl/common.hpp> #include <sge/opengl/internal_color_format.hpp> #include <sge/opengl/texture/binding_fwd.hpp> #include <sge/opengl/texture/buffer_type.hpp> #include <sge/opengl/texture/surface_config_fwd.hpp> #include <sge/opengl/texture/funcs/set_2d.hpp> #include <sge/renderer/const_raw_pointer.hpp> #include <sge/renderer/dim2.hpp> #include <sge/renderer/texture/creation_failed.hpp> #include <sge/renderer/texture/mipmap/level.hpp> #include <fcppt/text.hpp> #include <fcppt/cast/size.hpp> #include <fcppt/cast/to_signed.hpp> #include <fcppt/cast/to_void_ptr.hpp> #include <fcppt/math/dim/output.hpp> void sge::opengl::texture::funcs::set_2d( sge::opengl::texture::binding const &, sge::opengl::texture::surface_config const &, sge::opengl::texture::buffer_type const _buffer_type, sge::opengl::color_order const _format, sge::opengl::color_base_type const _format_type, sge::opengl::internal_color_format const _internal_format, sge::renderer::texture::mipmap::level const _level, sge::renderer::dim2 const &_dim, sge::renderer::const_raw_pointer const _src) { sge::opengl::call( ::glTexImage2D, _buffer_type.get(), fcppt::cast::to_signed(_level.get()), _internal_format.get(), fcppt::cast::size<GLsizei>(fcppt::cast::to_signed(_dim.w())), fcppt::cast::size<GLsizei>(fcppt::cast::to_signed(_dim.h())), 0, _format.get(), _format_type.get(), fcppt::cast::to_void_ptr(_src)); SGE_OPENGL_CHECK_STATE( (fcppt::format(FCPPT_TEXT("Creation of texture with size %1% failed!")) % _dim).str(), sge::renderer::texture::creation_failed) }
38.339623
92
0.718012
cpreh
045c670d8919bd4d658a5b55e884390a99fe6a0a
4,818
cpp
C++
mainwindow.cpp
rossomah/waifu2x-converter-qt
1e203ad160f6e69874f1dd391cec534abdc36324
[ "MIT" ]
null
null
null
mainwindow.cpp
rossomah/waifu2x-converter-qt
1e203ad160f6e69874f1dd391cec534abdc36324
[ "MIT" ]
null
null
null
mainwindow.cpp
rossomah/waifu2x-converter-qt
1e203ad160f6e69874f1dd391cec534abdc36324
[ "MIT" ]
null
null
null
#include "mainwindow.h" #include "ui_mainwindow.h" #include "droplabel.h" #include "processdialog.h" #include "preferencesdialog.h" #include "aboutdialog.h" #include "processmodemodel.h" #include <QFileDialog> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), m_settings(new Waifu2xConverterQtSettings), m_procmode(new ProcessModeModel) { ui->setupUi(this); init(); } MainWindow::~MainWindow() { delete ui; } ProcessModeModel* MainWindow::processModeModel(){ return m_procmode; } void MainWindow::browseImage() { QFileDialog dialog(this, tr("Select image"), m_settings->lastUsedDir()); dialog.setAcceptMode(QFileDialog::AcceptOpen); dialog.setMimeTypeFilters({"image/jpeg", "image/png", "application/octet-stream"}); if (dialog.exec() == QFileDialog::Accepted){ QString filePath = dialog.selectedFiles().first(); m_settings->setLastUsedDir(QDir(filePath).absolutePath()); processImage(filePath); } } void MainWindow::processImage(const QString &imageFileName) { QString outputFileName; if (m_settings->isUseCustomFileName()) { outputFileName = browseSaveLocation(imageFileName); if (outputFileName.isEmpty()) return; } ProcessDialog dialog(imageFileName, ui->threadsBox->value(), ui->scaleRatioBox->value(), ui->noiseReductionLevel->value(), ui->imageProcessingModeBox->currentData().toString(), outputFileName, m_settings->modelDirectory(), this); dialog.exec(); } QString MainWindow::browseSaveLocation(const QString &inputImageFileName) { QDir dir(inputImageFileName); QString fileExtension; QFileDialog dialog(this, tr("Save")); dir.cdUp(); if (inputImageFileName.contains(".")) fileExtension = inputImageFileName.split(".").last(); dialog.setAcceptMode(QFileDialog::AcceptSave); dialog.setDirectory(dir.absolutePath()); dialog.selectFile(inputImageFileName); dialog.exec(); return dialog.selectedFiles().isEmpty() ? QString() : dialog.selectedFiles().first(); } void MainWindow::closeEvent(QCloseEvent *) { save(); } void MainWindow::save() { m_settings->setThreadsCount(ui->threadsBox->value()); m_settings->setScaleRatio(ui->scaleRatioBox->value()); m_settings->setNoiseReductionLevel(ui->noiseReductionLevel->value()); m_settings->setImageProcessingMode(ui->imageProcessingModeBox->currentData().toString()); } void MainWindow::toggleOptions(int boxIndex){ QString currentData = ui->imageProcessingModeBox->itemData(boxIndex).toString(); ui->noiseReductionLevel->setEnabled(currentData.contains("noise")); ui->scaleRatioBox->setEnabled(currentData.contains("scale")); } void MainWindow::init() { qApp->setApplicationDisplayName(tr("Waifu2x Converter Qt")); setWindowTitle(QApplication::applicationDisplayName()); auto* dropLabel = new DropLabel(this); ui->imageProcessingModeBox->setModel(m_procmode); connect(ui->action_Preferences, &QAction::triggered, [&]() { PreferencesDialog dialog; dialog.exec(); }); connect(ui->imageProcessingModeBox, SIGNAL(currentIndexChanged(int)),SLOT(toggleOptions(int))); connect(dropLabel, SIGNAL(fileDropped(QString)), this, SLOT(processImage(QString))); connect(ui->browseButton, SIGNAL(clicked(bool)), this, SLOT(browseImage())); connect(ui->action_Open_image, &QAction::triggered, this, &MainWindow::browseImage); connect(ui->action_About_waifu2x_converter_qt, &QAction::triggered, [&]() { AboutDialog dialog; dialog.exec(); }); connect(ui->actionAbout_Qt, &QAction::triggered, qApp, &QApplication::aboutQt); connect(ui->actionE_xit, &QAction::triggered, qApp, &QApplication::quit); ui->browseButton->setIcon(style()->standardIcon((QStyle::SP_DirOpenIcon))); ui->action_Open_image->setIcon(style()->standardIcon(QStyle::SP_DirOpenIcon)); ui->actionE_xit->setIcon(style()->standardIcon(QStyle::SP_DialogCloseButton)); ui->action_About_waifu2x_converter_qt->setIcon(style()->standardIcon(QStyle::SP_DialogHelpButton)); ui->dropLayout->insertWidget(0, dropLabel, 10); ui->threadsBox->setValue(m_settings->threadsCount()); ui->scaleRatioBox->setValue(m_settings->scaleRatio()); ui->noiseReductionLevel->setValue(m_settings->noiseReductionLevel()); int currDataIndex = ui->imageProcessingModeBox->findData(m_settings->imageProcessingMode()); ui->imageProcessingModeBox->setCurrentIndex(currDataIndex); }
34.170213
103
0.679743
rossomah
045d4d63848b049e7e86e47f4a829b066701d3df
454
cpp
C++
WonderMake/Object/DependencyDestructor.cpp
nicolasgustafsson/WonderMake
9661d5dab17cf98e06daf6ea77c5927db54d62f9
[ "MIT" ]
3
2020-03-27T15:25:19.000Z
2022-01-18T14:12:25.000Z
WonderMake/Object/DependencyDestructor.cpp
nicolasgustafsson/WonderMake
9661d5dab17cf98e06daf6ea77c5927db54d62f9
[ "MIT" ]
null
null
null
WonderMake/Object/DependencyDestructor.cpp
nicolasgustafsson/WonderMake
9661d5dab17cf98e06daf6ea77c5927db54d62f9
[ "MIT" ]
null
null
null
#include "pch.h" #include "DependencyDestructor.h" DependencyDestructor::DependencyDestructor(UniqueFunction<void(Object&, void*)> aDestroyFunc) noexcept : myDestroyFunc(std::move(aDestroyFunc)) {} void DependencyDestructor::Destroy(Object& aObject, SComponent& aComponent) { myDestroyFunc(aObject, &aComponent); } void DependencyDestructor::Destroy(Object& aObject, _BaseFunctionality& aFunctionality) { myDestroyFunc(aObject, &aFunctionality); }
26.705882
102
0.799559
nicolasgustafsson
0460535ea80b720c029d52957f7462d8f1437044
1,991
hpp
C++
src/main/include/cyng/async/task/task_builder.hpp
solosTec/cyng
3862a6b7a2b536d1f00fef20700e64170772dcff
[ "MIT" ]
null
null
null
src/main/include/cyng/async/task/task_builder.hpp
solosTec/cyng
3862a6b7a2b536d1f00fef20700e64170772dcff
[ "MIT" ]
null
null
null
src/main/include/cyng/async/task/task_builder.hpp
solosTec/cyng
3862a6b7a2b536d1f00fef20700e64170772dcff
[ "MIT" ]
null
null
null
/* * The MIT License (MIT) * * Copyright (c) 2017 Sylko Olzscher * */ #ifndef CYNG_ASYNC_TASK_BUILDER_HPP #define CYNG_ASYNC_TASK_BUILDER_HPP #include <cyng/async/task/task.hpp> #include <cyng/async/mux.h> #include <chrono> namespace cyng { namespace async { /** * Create a new task class */ template < typename T, typename ...Args > auto make_task(mux& m, Args &&... args) -> std::shared_ptr<task < T >> { typedef task < T > task_type; return std::make_shared< task_type >(m, std::forward<Args>(args)...); } /** * There are three options to start a task: * (1) sync - insert task into task list and call run() method * in the same thread. * * (2) async - insert task into task list and call run() method * in another thread. * * (3) delayed - insert task into task list and call run() method * from a timer callback. */ template < typename T, typename ...Args > std::pair<std::size_t, bool> start_task_sync(mux& m, Args &&... args) { auto tp = make_task<T>(m, std::forward<Args>(args)...); return std::make_pair(tp->get_id(), m.insert(tp, sync())); } template < typename T, typename ...Args > std::size_t start_task_detached(mux& m, Args &&... args) { auto tp = make_task<T>(m, std::forward<Args>(args)...); return (m.insert(tp, detach())) ? tp->get_id() : NO_TASK ; } template < typename T, typename R, typename P, typename ...Args > std::pair<std::size_t, bool> start_task_delayed(mux& m, std::chrono::duration<R, P> d, Args &&... args) { auto tp = make_task<T>(m, std::forward<Args>(args)...); if (m.insert(tp, none())) { tp->suspend(d); return std::make_pair(tp->get_id(), true); } return std::make_pair(tp->get_id(), false); } inline std::pair<std::size_t, bool> start_task_sync(mux& m, shared_task tp) { return std::make_pair(tp->get_id(), m.insert(tp, sync())); } } // async } #endif // CYNG_ASYNC_TASK_BUILDER_HPP
23.987952
105
0.618282
solosTec
04618b56167c2afb23b07fc7a8c03d94ac5d020e
4,753
cpp
C++
spaceship.cpp
shaungoh01/-Uni-Computer-Graphic-Assignemny
ec5098c1c2f30f3abacb8de663511f25a8b64d0b
[ "MIT" ]
null
null
null
spaceship.cpp
shaungoh01/-Uni-Computer-Graphic-Assignemny
ec5098c1c2f30f3abacb8de663511f25a8b64d0b
[ "MIT" ]
null
null
null
spaceship.cpp
shaungoh01/-Uni-Computer-Graphic-Assignemny
ec5098c1c2f30f3abacb8de663511f25a8b64d0b
[ "MIT" ]
null
null
null
#include <GL/glut.h> #include <stdlib.h> #include <time.h> #include <ctime> #include "spaceship.hpp" MySpaceShip::MySpaceShip() { //Setup Quadric Object pObj = gluNewQuadric(); gluQuadricNormals(pObj, GLU_SMOOTH); posx = 0.0f; posy = 10.0f; posz = 2.0f; roty = 0.0f; //initial velocity (in unit per second) velx = 0.0f; vely = 3.0f; velz = 0.0f; //velroty = 10.0f; } MySpaceShip::~MySpaceShip() { gluDeleteQuadric(pObj); } void MySpaceShip::draw() { glTranslatef(posx, posy, posz); glRotatef(timetick, 0.0f, 1.0f, 0.0f); srand(time(NULL)); glDisable(GL_CULL_FACE); //front glPushMatrix(); glTranslatef(0.0f, 10.0f, 0.0f); glColor3f(0.1f, 0.1f, 0.1f); gluCylinder(pObj, 5.0f, 0.0f, 10, 26, 5); glPopMatrix(); //body glPushMatrix(); glTranslatef(0.0f, 10.0f, -15.0f); glColor3f(rand()%45*0.1, rand()%45*0.1,rand()%45 * 0.01 ); gluCylinder(pObj, 5.0f, 5.0f, 15, 26, 5); glPopMatrix(); //back glPushMatrix(); glTranslatef(0.0f, 10.0f, -15.0f); glColor3f(1.0f, 1.0f, 1.0f); gluDisk(pObj, 0.0f, 5.0f, 26, 5); glPopMatrix(); //top mirror glPushMatrix(); glTranslatef(0.0f, 14.0f, -8.0f); glColor3f(0.0f, 1.0f, 1.0f); gluSphere(pObj,4.0f, 20, 20); glPopMatrix(); //left wing alpha glPushMatrix(); glTranslatef(10.0f, 10.0f, -2.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); glColor3f(0.1f, 0.1f, 0.1f); gluCylinder(pObj, 3.0f, 3.0f, 3, 26, 5); //fan1 glTranslatef(0.0f, -3.0f, 2.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); glColor3f(0.5f, 0.5f, 0.5f); gluCylinder(pObj, 0.5f, 0.5f, 6, 26, 5); //fan2 glTranslatef(3.0f, 1.0f, 3.0f); glRotatef(-90, 0.0f, 1.0f, 0.0f); glColor3f(0.5f, 0.5f, 0.5f); gluCylinder(pObj, 0.5f, 0.5f, 6, 26, 5); glPopMatrix(); //left wing beta glPushMatrix(); glTranslatef(10.0f, 10.0f, -12.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); glColor3f(0.1f, 0.1f, 0.1f); gluCylinder(pObj, 3.0f, 3.0f, 3, 26, 5); //fan1 glTranslatef(0.0f, -3.0f, 2.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); glColor3f(0.5f, 0.5f, 0.5f); gluCylinder(pObj, 0.5f, 0.5f, 6, 26, 5); //fan2 glTranslatef(3.0f, 1.0f, 3.0f); glRotatef(-90, 0.0f, 1.0f, 0.0f); glColor3f(0.5f, 0.5f, 0.5f); gluCylinder(pObj, 0.5f, 0.5f, 6, 26, 5); glPopMatrix(); //right wing alpha glPushMatrix(); glTranslatef(-10.0f, 10.0f, -2.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); glColor3f(0.1f, 0.1f, 0.1f); gluCylinder(pObj, 3.0f, 3.0f, 3, 26, 5); //fan1 glTranslatef(0.0f, -3.0f, 2.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); glColor3f(0.5f, 0.5f, 0.5f); gluCylinder(pObj, 0.5f, 0.5f, 6, 26, 5); //fan2 glTranslatef(3.0f, 1.0f, 3.0f); glRotatef(-90, 0.0f, 1.0f, 0.0f); glColor3f(0.5f, 0.5f, 0.5f); gluCylinder(pObj, 0.5f, 0.5f, 6, 26, 5); glPopMatrix(); //right wing beta glPushMatrix(); glTranslatef(-10.0f, 10.0f, -12.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); glColor3f(0.1f, 0.1f, 0.1f); gluCylinder(pObj, 3.0f, 3.0f, 3, 26, 5); //fan1 glTranslatef(0.0f, -3.0f, 2.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); glColor3f(0.5f, 0.5f, 0.5f); gluCylinder(pObj, 0.5f, 0.5f, 6, 26, 5); //fan2 glTranslatef(3.0f, 1.0f, 3.0f); glRotatef(-90, 0.0f, 1.0f, 0.0f); glColor3f(0.5f, 0.5f, 0.5f); gluCylinder(pObj, 0.5f, 0.5f, 6, 26, 5); glPopMatrix(); //exhaust pipe glPushMatrix(); glTranslatef(0.0f, 10.0f, -20.0f); glColor3f(0.1f, 0.1f, 0.1f); gluCylinder(pObj, 4.0f, 2.0f, 6, 26, 5); glPopMatrix(); //EP back glPushMatrix(); glTranslatef(0.0f, 10.0f, -20.0f); glColor3f(1.0f, 0.0f, 0.0f); gluDisk(pObj, 0.0f, 4.0f, 26, 5); glPopMatrix(); glEnable(GL_CULL_FACE); } void MySpaceShip::Movespaceship() { glPushMatrix(); glTranslatef(0.0f , tickMove , 0.0f ); //glRotatef(roty, 0.0f, 1.0f, 0.0f); draw(); glPopMatrix(); } void MySpaceShip::drawfence() { glDisable(GL_CULL_FACE); glPushMatrix(); glColor3f(1.0f, 1.0f, 0.0f); glTranslatef(0.0f, 0.0f, 0.0f); glRotatef(-90, 1.0f, 0.0f, 0.0f); gluCylinder(pObj, 25.0f, 25.0f, 7, 26, 5); glPopMatrix(); } //elapsetime in milisec void MySpaceShip::tickTime(long int elapseTime) { ticktick++; if(ticktick == 30){ if(tickMove < 51.0 && moveUp == 1){ ticktick =0; tickMove+= 5.0; if(tickMove >= 51.0) moveUp = 0; }else if(moveUp == 0){ ticktick=0; tickMove-= 5.0; if(tickMove < 0.0){ moveUp = 1; } } } }
24.626943
62
0.553124
shaungoh01
0461d4b23fd08dadbc6ccba03f980035da92353d
2,006
hpp
C++
libraries/chain/include/graphene/chain/protocol/son_wallet_withdraw.hpp
vampik33/peerplays
9fd18b32c413ad978f38f95a09b7eff7235a9c1b
[ "MIT" ]
45
2018-12-13T21:11:23.000Z
2022-03-28T09:21:44.000Z
libraries/chain/include/graphene/chain/protocol/son_wallet_withdraw.hpp
vampik33/peerplays
9fd18b32c413ad978f38f95a09b7eff7235a9c1b
[ "MIT" ]
279
2018-12-18T08:52:43.000Z
2022-03-24T19:03:29.000Z
libraries/chain/include/graphene/chain/protocol/son_wallet_withdraw.hpp
vampik33/peerplays
9fd18b32c413ad978f38f95a09b7eff7235a9c1b
[ "MIT" ]
25
2018-12-13T20:38:51.000Z
2022-03-25T09:45:58.000Z
#pragma once #include <graphene/chain/protocol/base.hpp> #include <graphene/chain/sidechain_defs.hpp> #include <fc/safe.hpp> namespace graphene { namespace chain { struct son_wallet_withdraw_create_operation : public base_operation { struct fee_parameters_type { uint64_t fee = 0; }; asset fee; account_id_type payer; son_id_type son_id; fc::time_point_sec timestamp; uint32_t block_num; sidechain_type sidechain; std::string peerplays_uid; std::string peerplays_transaction_id; chain::account_id_type peerplays_from; chain::asset peerplays_asset; sidechain_type withdraw_sidechain; std::string withdraw_address; std::string withdraw_currency; safe<int64_t> withdraw_amount; account_id_type fee_payer()const { return payer; } share_type calculate_fee(const fee_parameters_type& k)const { return 0; } }; struct son_wallet_withdraw_process_operation : public base_operation { struct fee_parameters_type { uint64_t fee = 0; }; asset fee; account_id_type payer; son_wallet_withdraw_id_type son_wallet_withdraw_id; account_id_type fee_payer()const { return payer; } share_type calculate_fee(const fee_parameters_type& k)const { return 0; } }; } } // namespace graphene::chain FC_REFLECT(graphene::chain::son_wallet_withdraw_create_operation::fee_parameters_type, (fee) ) FC_REFLECT(graphene::chain::son_wallet_withdraw_create_operation, (fee)(payer) (son_id) (timestamp) (block_num) (sidechain) (peerplays_uid) (peerplays_transaction_id) (peerplays_from) (peerplays_asset) (withdraw_sidechain) (withdraw_address) (withdraw_currency) (withdraw_amount) ) FC_REFLECT(graphene::chain::son_wallet_withdraw_process_operation::fee_parameters_type, (fee) ) FC_REFLECT(graphene::chain::son_wallet_withdraw_process_operation, (fee)(payer) (son_wallet_withdraw_id) )
35.192982
95
0.720339
vampik33
046339ccd708b23e61fa5cc526dd7bf97a3512d7
2,633
cc
C++
lite/arm/math/im2sequence.cc
banbishan/Paddle-Lite
02517c12c31609f413a1c47a83e25d3fbff07074
[ "Apache-2.0" ]
1
2019-08-21T05:54:42.000Z
2019-08-21T05:54:42.000Z
lite/arm/math/im2sequence.cc
banbishan/Paddle-Lite
02517c12c31609f413a1c47a83e25d3fbff07074
[ "Apache-2.0" ]
null
null
null
lite/arm/math/im2sequence.cc
banbishan/Paddle-Lite
02517c12c31609f413a1c47a83e25d3fbff07074
[ "Apache-2.0" ]
1
2019-10-11T09:34:49.000Z
2019-10-11T09:34:49.000Z
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "lite/arm/math/im2sequence.h" #include <arm_neon.h> #include "lite/utils/cp_logging.h" namespace paddle { namespace lite { namespace arm { namespace math { void im2sequence(const float* input, const int input_c, const int input_h, const int input_w, const int kernel_h, const int kernel_w, const int pad_top, const int pad_bottom, const int pad_left, const int pad_right, const int stride_h, const int stride_w, const int out_h, const int out_w, float* out, Context<TARGET(kARM)>* ctx) { int window_size = kernel_h * kernel_w; int out_rows = out_h * out_w; int out_cols = input_c * window_size; int H_pad = input_h + pad_top + pad_bottom; int W_pad = input_w + pad_left + pad_right; for (int h_id = 0; h_id < out_h; h_id++) { for (int w_id = 0; w_id < out_w; w_id++) { // consider dilation. int start_h = h_id * stride_h - pad_top; int start_w = w_id * stride_w - pad_left; for (int c_id = 0; c_id < input_c; c_id++) { for (int k_h_id = 0; k_h_id < kernel_h; k_h_id++) { int in_h_id = start_h + k_h_id; bool exceed_flag = (in_h_id < 0) || (in_h_id >= H_pad); int out_start_id = (h_id * out_w + w_id) * out_cols + c_id * window_size; for (int k_w_id = 0; k_w_id < kernel_w; k_w_id++) { int in_w_id = start_w + k_w_id; exceed_flag = exceed_flag || (in_w_id < 0) || (in_w_id >= W_pad); int input_id = (c_id * input_h + in_h_id) * input_w + in_w_id; int out_id = out_start_id + k_h_id * kernel_w + k_w_id; out[out_id] = exceed_flag ? 0.f : input[input_id]; } } } } } } } // namespace math } // namespace arm } // namespace lite } // namespace paddle
36.068493
77
0.590961
banbishan
0463ff21ce8758867f178b840135651d22ddf08f
1,305
cpp
C++
codeforce6/1079C. Playing Piano.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
codeforce6/1079C. Playing Piano.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
codeforce6/1079C. Playing Piano.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
/* Idea: - Dynamic Programming - If you reach the base case in the recursion, then you have an answer, so print it. - This method work if the dynamic programming answer is true or false. */ #include <bits/stdc++.h> using namespace std; int const N = 1e5 + 1; int n, a[N], dp[N][6]; vector<int> sol; int rec(int idx, int prv) { if(idx == n) { for(int i = 0; i < sol.size(); ++i) printf("%s%d", i == 0 ? "" : " ", sol[i]); puts(""); exit(0); } int &ret = dp[idx][prv]; if(ret != -1) return ret; ret = 0; if(a[idx] == a[idx - 1]) { for(int i = 1; i <= 5; ++i) if(i != prv) { sol.push_back(i); rec(idx + 1, i); sol.pop_back(); } } if(a[idx] > a[idx - 1]) { for(int i = prv + 1; i <= 5; ++i) { sol.push_back(i); rec(idx + 1, i); sol.pop_back(); } } if(a[idx] < a[idx - 1]) { for(int i = prv - 1; i >= 1; --i) { sol.push_back(i); rec(idx + 1, i); sol.pop_back(); } } return ret; } int main() { scanf("%d", &n); for(int i = 0; i < n; ++i) scanf("%d", a + i); memset(dp, -1, sizeof dp); for(int i = 1; i <= 5; ++i) { sol.push_back(i); if(rec(1, i)) return 0; sol.pop_back(); } puts("-1"); return 0; }
17.4
56
0.45977
khaled-farouk
046413bbc278e329cb381bd802c539133e0c2eff
1,987
hpp
C++
ngraph/src/ngraph/frontend/onnx_import/onnx_utils.hpp
anton-potapov/openvino
84119afe9a8c965e0a0cd920fff53aee67b05108
[ "Apache-2.0" ]
1
2020-10-13T22:49:18.000Z
2020-10-13T22:49:18.000Z
ngraph/src/ngraph/frontend/onnx_import/onnx_utils.hpp
anton-potapov/openvino
84119afe9a8c965e0a0cd920fff53aee67b05108
[ "Apache-2.0" ]
4
2021-04-01T08:29:48.000Z
2021-08-30T16:12:52.000Z
ngraph/src/ngraph/frontend/onnx_import/onnx_utils.hpp
anton-potapov/openvino
84119afe9a8c965e0a0cd920fff53aee67b05108
[ "Apache-2.0" ]
3
2021-03-09T08:27:29.000Z
2021-04-07T04:58:54.000Z
//***************************************************************************** // Copyright 2017-2020 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #pragma once #include <cstdint> #include <string> #include "core/operator_set.hpp" #include "utils/onnx_importer_visibility.hpp" namespace ngraph { namespace onnx_import { /// \brief Registers ONNX custom operator. /// The function performs the registration of external ONNX operator /// which is not part of ONNX importer. /// /// \note The operator must be registered before calling /// "import_onnx_model" functions. /// /// \param name The ONNX operator name. /// \param version The ONNX operator set version. /// \param domain The domain the ONNX operator is registered to. /// \param fn The function providing the implementation of the operator /// which transforms the single ONNX operator to an nGraph sub-graph. ONNX_IMPORTER_API void register_operator(const std::string& name, std::int64_t version, const std::string& domain, Operator fn); } // namespace onnx_import } // namespace ngraph
39.74
99
0.571213
anton-potapov
04652172919828de08f918ebb22c9ccef7308f03
555
cpp
C++
src/gui/PlayingScreen.cpp
ballcue/meanshift-motion-tracking
f59886a88626ace8b6fb1fb167690072c24cc17c
[ "MIT" ]
null
null
null
src/gui/PlayingScreen.cpp
ballcue/meanshift-motion-tracking
f59886a88626ace8b6fb1fb167690072c24cc17c
[ "MIT" ]
null
null
null
src/gui/PlayingScreen.cpp
ballcue/meanshift-motion-tracking
f59886a88626ace8b6fb1fb167690072c24cc17c
[ "MIT" ]
null
null
null
#include "../../include/gui/PlayingScreen.h" /* Derived-screen-specific additional frame processing for display*/ void PlayingScreen::processFrame(Mat& frame, const TrackingInfo& tracker) const { drawTrackingMarker ( frame, tracker.current() ); } void PlayingScreen::drawTrackingMarker(Mat& frame, const Point& center) const { /* "FREQUENCY POINTER" */ circle ( frame, center, dynconf.trackingMarkerRadius*0.25, StaticConfiguration::trackingMarkerColor, 10, CV_AA ); }
25.227273
81
0.652252
ballcue
046757461269f7f660ac56abc9f46522cc275abf
2,787
cpp
C++
src/bench/dsproof.cpp
EyeOfPython/bitcoin-cash-node
13f5ed384aae11eaffd1097a0e75beca2b54f93d
[ "MIT" ]
61
2020-02-23T01:19:16.000Z
2022-03-04T15:22:00.000Z
src/bench/dsproof.cpp
EyeOfPython/bitcoin-cash-node
13f5ed384aae11eaffd1097a0e75beca2b54f93d
[ "MIT" ]
null
null
null
src/bench/dsproof.cpp
EyeOfPython/bitcoin-cash-node
13f5ed384aae11eaffd1097a0e75beca2b54f93d
[ "MIT" ]
20
2020-03-01T02:35:17.000Z
2021-12-28T12:04:34.000Z
// Copyright (c) 2020-2021 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <bench/bench.h> #include <coins.h> #include <dsproof/dsproof.h> #include <key.h> #include <primitives/transaction.h> #include <random.h> #include <policy/policy.h> #include <script/script.h> #include <script/sighashtype.h> #include <script/sign.h> #include <script/standard.h> #include <limits> #include <optional> #include <vector> static void DoubleSpendProofCreate(benchmark::State &state) { CKey privKey, privKey2, privKey3; privKey.MakeNewKey(true); privKey2.MakeNewKey(true); privKey3.MakeNewKey(true); CMutableTransaction tx1, tx2; // make 2 huge tx's spending different fake inputs const uint64_t n_inputs = 3000; for (uint64_t i = 0; i < (n_inputs - 1); ++i) { tx1.vin.emplace_back(COutPoint{TxId(GetRandHash()), uint32_t(GetRand(n_inputs))}); tx2.vin.emplace_back(COutPoint{TxId(GetRandHash()), uint32_t(GetRand(n_inputs))}); } // make sure they spend a common input at the very end const COutPoint dupe{TxId(GetRandHash()), uint32_t(GetRand(n_inputs))}; tx1.vin.emplace_back(dupe); tx2.vin.emplace_back(tx1.vin.back()); tx1.vout.emplace_back(3 * COIN, GetScriptForDestination(privKey2.GetPubKey().GetID())); tx2.vout.emplace_back(2 * COIN, GetScriptForDestination(privKey3.GetPubKey().GetID())); std::optional<CTxOut> commonTxOut; // Sign transactions properly const SigHashType sigHashType = SigHashType().withForkId(); FlatSigningProvider keyStore; keyStore.pubkeys.emplace(privKey.GetPubKey().GetID(), privKey.GetPubKey()); keyStore.keys.emplace(privKey.GetPubKey().GetID(), privKey); for (auto *ptx : {&tx1, &tx2}) { auto &tx = *ptx; size_t i = 0; for (auto & txin : tx.vin) { const Coin coin(CTxOut{1 * COIN, GetScriptForDestination(privKey.GetPubKey().GetID())}, 123, false); SignatureData sigdata = DataFromTransaction(tx, i, coin.GetTxOut()); ProduceSignature(keyStore, MutableTransactionSignatureCreator(&tx, i, coin.GetTxOut().nValue, sigHashType), coin.GetTxOut().scriptPubKey, sigdata); UpdateInput(txin, sigdata); ++i; if (i == tx.vin.size() && !commonTxOut) commonTxOut = coin.GetTxOut(); } } assert(bool(commonTxOut)); const CTransaction ctx1{tx1}, ctx2{tx2}; while (state.KeepRunning()) { auto proof = DoubleSpendProof::create(ctx1, ctx2, dupe, &*commonTxOut); assert(!proof.isEmpty()); } } BENCHMARK(DoubleSpendProofCreate, 490);
35.730769
112
0.664514
EyeOfPython
046afc267fd2a398fe420ba1b20c4d957d9ecb61
2,075
cpp
C++
fft.cpp
SJ-magic-youtube-VisualProgrammer/46__oF_Audio_InOut
c98349955f2a516fafd2f72b303128cf305e74bf
[ "MIT" ]
1
2022-02-13T15:34:33.000Z
2022-02-13T15:34:33.000Z
fft.cpp
SJ-magic-youtube-VisualProgrammer/46__oF_Audio_InOut
c98349955f2a516fafd2f72b303128cf305e74bf
[ "MIT" ]
null
null
null
fft.cpp
SJ-magic-youtube-VisualProgrammer/46__oF_Audio_InOut
c98349955f2a516fafd2f72b303128cf305e74bf
[ "MIT" ]
null
null
null
/************************************************************ ************************************************************/ #include "fft.h" /************************************************************ ************************************************************/ /****************************** ******************************/ FFT::FFT() { } /****************************** ******************************/ FFT::~FFT() { } /****************************** ******************************/ void FFT::threadedFunction() { while(isThreadRunning()) { lock(); unlock(); sleep(THREAD_SLEEP_MS); } } /****************************** ******************************/ void FFT::setup(int AUDIO_BUF_SIZE) { /******************** ■std::vectorのresizeとassignの違い (C++) https://minus9d.hatenablog.com/entry/2021/02/07/175159 ********************/ vol_l.assign(AUDIO_BUF_SIZE, 0.0); vol_r.assign(AUDIO_BUF_SIZE, 0.0); } /****************************** ******************************/ void FFT::update() { } /****************************** ******************************/ void FFT::draw() { } /****************************** ******************************/ void FFT::SetVol(ofSoundBuffer & buffer) { lock(); if( (vol_l.size() < buffer.getNumFrames()) || (vol_r.size() < buffer.getNumFrames()) ){ printf("size of vol vector not enough\n"); fflush(stdout); }else{ for (size_t i = 0; i < buffer.getNumFrames(); i++){ vol_l[i] = buffer[i*2 + 0]; vol_r[i] = buffer[i*2 + 1]; } } unlock(); } /****************************** ******************************/ void FFT::GetVol(ofSoundBuffer & buffer, bool b_EnableAudioOut) { lock(); if( (vol_l.size() < buffer.getNumFrames()) || (vol_r.size() < buffer.getNumFrames()) ){ printf("size of vol vector not enough\n"); fflush(stdout); }else{ for (size_t i = 0; i < buffer.getNumFrames(); i++){ if(b_EnableAudioOut){ buffer[i*2 + 0] = vol_l[i]; buffer[i*2 + 1] = vol_r[i]; }else{ buffer[i*2 + 0] = 0; buffer[i*2 + 1] = 0; } } } unlock(); }
20.75
89
0.360482
SJ-magic-youtube-VisualProgrammer
046b065236406a07667a6ee6c8e615215e77a1ec
1,132
cpp
C++
CLRS/String/LongestPalindrome.cpp
ComputerProgrammerStorager/DataStructureAlgorithm
508f7e37898c907ea7ea6ec40749621a2349e93f
[ "MIT" ]
null
null
null
CLRS/String/LongestPalindrome.cpp
ComputerProgrammerStorager/DataStructureAlgorithm
508f7e37898c907ea7ea6ec40749621a2349e93f
[ "MIT" ]
null
null
null
CLRS/String/LongestPalindrome.cpp
ComputerProgrammerStorager/DataStructureAlgorithm
508f7e37898c907ea7ea6ec40749621a2349e93f
[ "MIT" ]
null
null
null
/* Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. Letters are case sensitive, for example, "Aa" is not considered a palindrome here. Example 1: Input: s = "abccccdd" Output: 7 Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7. Example 2: Input: s = "a" Output: 1 Example 3: Input: s = "bb" Output: 2 Constraints: 1 <= s.length <= 2000 s consists of lowercase and/or uppercase English letters only. */ // all even chars can be used to construct the string, but only one odd char can be added at last class Solution { public: int longestPalindrome(string s) { unordered_map<char,int> ch2freq; int res = 0; bool remainder = false; for ( auto c : s ) ch2freq[c]++; for ( auto it : ch2freq ) { if ( it.second % 2 ) { remainder = true; } res += (it.second / 2) * 2; } if ( remainder ) res++; return res; } };
21.358491
148
0.590989
ComputerProgrammerStorager
046bd4036f74b99487b2080e76d1afa8bbe8fdb2
1,385
cpp
C++
Desktop/CCore/src/video/GammaTable.cpp
SergeyStrukov/CCore-2-99
1eca5b9b2de067bbab43326718b877465ae664fe
[ "BSL-1.0" ]
1
2016-05-22T07:51:02.000Z
2016-05-22T07:51:02.000Z
Desktop/CCore/src/video/GammaTable.cpp
SergeyStrukov/CCore-2-99
1eca5b9b2de067bbab43326718b877465ae664fe
[ "BSL-1.0" ]
null
null
null
Desktop/CCore/src/video/GammaTable.cpp
SergeyStrukov/CCore-2-99
1eca5b9b2de067bbab43326718b877465ae664fe
[ "BSL-1.0" ]
null
null
null
/* GammaTable.cpp */ //---------------------------------------------------------------------------------------- // // Project: CCore 3.00 // // Tag: Desktop // // License: Boost Software License - Version 1.0 - August 17th, 2003 // // see http://www.boost.org/LICENSE_1_0.txt or the local copy // // Copyright (c) 2016 Sergey Strukov. All rights reserved. // //---------------------------------------------------------------------------------------- #include <CCore/inc/video/GammaTable.h> #include <math.h> namespace CCore { namespace Video { /* class GammaTable */ template <UIntType UInt> void GammaTable::Fill(PtrLen<UInt> table,double order) { double M=table.len-1; double V=MaxUInt<UInt>; for(ulen i=0; i<table.len ;i++) { double x=i/M; double y=pow(x,order); table[i]=UInt( round(V*y) ); } } GammaTable::GammaTable() noexcept { } GammaTable::~GammaTable() { } void GammaTable::fill(double order) { static const ulen DirectLen = ulen(1)<<8 ; static const ulen InverseLen = ulen(1)<<16 ; if( !direct.getLen() ) { SimpleArray<uint16> direct_(DirectLen); SimpleArray<uint8> inverse_(InverseLen); direct=std::move(direct_); inverse=std::move(inverse_); } Fill(Range(direct),order); Fill(Range(inverse),1/order); this->order=order; } } // namespace Video } // namespace CCore
19.507042
90
0.555235
SergeyStrukov
04706cb46ed3c950ab8932b1d70f314739814b7a
10,695
cc
C++
src/lslidar_ws/src/lslidar_c16/lslidar_c16_driver/src/input.cc
Louis-AD-git/racecar_ws
3c5cb561d1aee11d80a7f3847e0334e93f345513
[ "MIT" ]
null
null
null
src/lslidar_ws/src/lslidar_c16/lslidar_c16_driver/src/input.cc
Louis-AD-git/racecar_ws
3c5cb561d1aee11d80a7f3847e0334e93f345513
[ "MIT" ]
null
null
null
src/lslidar_ws/src/lslidar_c16/lslidar_c16_driver/src/input.cc
Louis-AD-git/racecar_ws
3c5cb561d1aee11d80a7f3847e0334e93f345513
[ "MIT" ]
null
null
null
/* * This file is part of lslidar_c16 driver. * * The driver 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. * * The driver 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 the driver. If not, see <http://www.gnu.org/licenses/>. */ #include "lslidar_c16_driver/input.h" extern volatile sig_atomic_t flag; namespace lslidar_c16_driver { static const size_t packet_size = sizeof(lslidar_c16_msgs::LslidarC16Packet().data); //////////////////////////////////////////////////////////////////////// // Input base class implementation //////////////////////////////////////////////////////////////////////// /** @brief constructor * * @param private_nh ROS private handle for calling node. * @param port UDP port number. */ Input::Input(ros::NodeHandle private_nh, uint16_t port) : private_nh_(private_nh), port_(port) { npkt_update_flag_ = false; cur_rpm_ = 0; return_mode_ = 1; private_nh.param("device_ip", devip_str_, std::string("")); if (!devip_str_.empty()) ROS_INFO_STREAM("Only accepting packets from IP address: " << devip_str_); } int Input::getRpm(void) { return cur_rpm_; } int Input::getReturnMode(void) { return return_mode_; } bool Input::getUpdateFlag(void) { return npkt_update_flag_; } void Input::clearUpdateFlag(void) { npkt_update_flag_ = false; } //////////////////////////////////////////////////////////////////////// // InputSocket class implementation //////////////////////////////////////////////////////////////////////// /** @brief constructor * * @param private_nh ROS private handle for calling node. * @param port UDP port number */ InputSocket::InputSocket(ros::NodeHandle private_nh, uint16_t port) : Input(private_nh, port) { sockfd_ = -1; if (!devip_str_.empty()) { inet_aton(devip_str_.c_str(), &devip_); } ROS_INFO_STREAM("Opening UDP socket: port " << port); sockfd_ = socket(PF_INET, SOCK_DGRAM, 0); if (sockfd_ == -1) { perror("socket"); // TODO: ROS_ERROR errno return; } int opt = 1; if (setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR, (const void*)&opt, sizeof(opt))) { perror("setsockopt error!\n"); return; } sockaddr_in my_addr; // my address information memset(&my_addr, 0, sizeof(my_addr)); // initialize to zeros my_addr.sin_family = AF_INET; // host byte order my_addr.sin_port = htons(port); // port in network byte order my_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill in my IP if (bind(sockfd_, (sockaddr*)&my_addr, sizeof(sockaddr)) == -1) { perror("bind"); // TODO: ROS_ERROR errno return; } if (fcntl(sockfd_, F_SETFL, O_NONBLOCK | FASYNC) < 0) { perror("non-block"); return; } } /** @brief destructor */ InputSocket::~InputSocket(void) { (void)close(sockfd_); } /** @brief Get one lslidar packet. */ int InputSocket::getPacket(lslidar_c16_msgs::LslidarC16Packet* pkt, const double time_offset) { double time1 = ros::Time::now().toSec(); struct pollfd fds[1]; fds[0].fd = sockfd_; fds[0].events = POLLIN; static const int POLL_TIMEOUT = 1200; // one second (in msec) sockaddr_in sender_address; socklen_t sender_address_len = sizeof(sender_address); while (flag == 1) // while (true) { // Receive packets that should now be available from the // socket using a blocking read. // poll() until input available do { int retval = poll(fds, 1, POLL_TIMEOUT); if (retval < 0) // poll() error? { if (errno != EINTR) ROS_ERROR("poll() error: %s", strerror(errno)); return 1; } if (retval == 0) // poll() timeout? { time_t curTime = time(NULL); struct tm *curTm = localtime(&curTime); char bufTime[30] = {0}; sprintf(bufTime,"%d-%d-%d %d:%d:%d", curTm->tm_year+1900, curTm->tm_mon+1, curTm->tm_mday, curTm->tm_hour, curTm->tm_min, curTm->tm_sec); ROS_WARN_THROTTLE(2, "%s lslidar poll() timeout", bufTime); /* char buffer_data[8] = "re-con"; memset(&sender_address, 0, sender_address_len); // initialize to zeros sender_address.sin_family = AF_INET; // host byte order sender_address.sin_port = htons(MSOP_DATA_PORT_NUMBER); // port in network byte order, set any value sender_address.sin_addr.s_addr = devip_.s_addr; // automatically fill in my IP sendto(sockfd_, &buffer_data, strlen(buffer_data), 0, (sockaddr*)&sender_address, sender_address_len); */ return 1; } if ((fds[0].revents & POLLERR) || (fds[0].revents & POLLHUP) || (fds[0].revents & POLLNVAL)) // device error? { ROS_ERROR("poll() reports lslidar error"); return 1; } } while ((fds[0].revents & POLLIN) == 0); ssize_t nbytes = recvfrom(sockfd_, &pkt->data[0], packet_size, 0, (sockaddr*)&sender_address, &sender_address_len); if (nbytes < 0) { if (errno != EWOULDBLOCK) { perror("recvfail"); ROS_INFO("recvfail"); return 1; } } else if ((size_t)nbytes == packet_size) { if (devip_str_ != "" && sender_address.sin_addr.s_addr != devip_.s_addr) continue; else break; // done } ROS_DEBUG_STREAM("incomplete lslidar packet read: " << nbytes << " bytes"); } if (flag == 0) { abort(); } if (pkt->data[0] == 0xA5 && pkt->data[1] == 0xFF && pkt->data[2] == 0x00 && pkt->data[3] == 0x5A) {//difop int rpm = (pkt->data[8]<<8)|pkt->data[9]; //ROS_INFO("rpm=%d",rpm); int mode = 1; if (cur_rpm_ != rpm || return_mode_ != mode) { cur_rpm_ = rpm; return_mode_ = mode; npkt_update_flag_ = true; } } // Average the times at which we begin and end reading. Use that to // estimate when the scan occurred. Add the time offset. double time2 = ros::Time::now().toSec(); pkt->stamp = ros::Time((time2 + time1) / 2.0 + time_offset); return 0; } //////////////////////////////////////////////////////////////////////// // InputPCAP class implementation //////////////////////////////////////////////////////////////////////// /** @brief constructor * * @param private_nh ROS private handle for calling node. * @param port UDP port number * @param packet_rate expected device packet frequency (Hz) * @param filename PCAP dump file name */ InputPCAP::InputPCAP(ros::NodeHandle private_nh, uint16_t port, double packet_rate, std::string filename, bool read_once, bool read_fast, double repeat_delay) : Input(private_nh, port), packet_rate_(packet_rate), filename_(filename) { pcap_ = NULL; empty_ = true; // get parameters using private node handle private_nh.param("read_once", read_once_, false); private_nh.param("read_fast", read_fast_, false); private_nh.param("repeat_delay", repeat_delay_, 0.0); if (read_once_) ROS_INFO("Read input file only once."); if (read_fast_) ROS_INFO("Read input file as quickly as possible."); if (repeat_delay_ > 0.0) ROS_INFO("Delay %.3f seconds before repeating input file.", repeat_delay_); // Open the PCAP dump file // ROS_INFO("Opening PCAP file \"%s\"", filename_.c_str()); ROS_INFO_STREAM("Opening PCAP file " << filename_); if ((pcap_ = pcap_open_offline(filename_.c_str(), errbuf_)) == NULL) { ROS_FATAL("Error opening lslidar socket dump file."); return; } std::stringstream filter; if (devip_str_ != "") // using specific IP? { filter << "src host " << devip_str_ << " && "; } filter << "udp dst port " << port; pcap_compile(pcap_, &pcap_packet_filter_, filter.str().c_str(), 1, PCAP_NETMASK_UNKNOWN); } /** destructor */ InputPCAP::~InputPCAP(void) { pcap_close(pcap_); } /** @brief Get one lslidar packet. */ int InputPCAP::getPacket(lslidar_c16_msgs::LslidarC16Packet* pkt, const double time_offset) { struct pcap_pkthdr* header; const u_char* pkt_data; // while (flag == 1) while (true) { int res; if ((res = pcap_next_ex(pcap_, &header, &pkt_data)) >= 0) { // Skip packets not for the correct port and from the // selected IP address. if (!devip_str_.empty() && (0 == pcap_offline_filter(&pcap_packet_filter_, header, pkt_data))) continue; // Keep the reader from blowing through the file. if (read_fast_ == false) packet_rate_.sleep(); memcpy(&pkt->data[0], pkt_data + 42, packet_size); if (pkt->data[0] == 0xA5 && pkt->data[1] == 0xFF && pkt->data[2] == 0x00 && pkt->data[3] == 0x5A) {//difop int rpm = (pkt->data[8]<<8)|pkt->data[9]; int mode = 1; if ((pkt->data[45] == 0x08 && pkt->data[46] == 0x02 && pkt->data[47] >= 0x09) || (pkt->data[45] > 0x08) || (pkt->data[45] == 0x08 && pkt->data[46] > 0x02)) { if (pkt->data[300] != 0x01 && pkt->data[300] != 0x02) { mode = 0; } } if (cur_rpm_ != rpm || return_mode_ != mode) { cur_rpm_ = rpm; return_mode_ = mode; npkt_update_flag_ = true; } } pkt->stamp = ros::Time::now(); // time_offset not considered here, as no // synchronization required empty_ = false; return 0; // success } if (empty_) // no data in file? { ROS_WARN("Error %d reading lslidar packet: %s", res, pcap_geterr(pcap_)); return -1; } if (read_once_) { ROS_INFO("end of file reached -- done reading."); return -1; } if (repeat_delay_ > 0.0) { ROS_INFO("end of file reached -- delaying %.3f seconds.", repeat_delay_); usleep(rint(repeat_delay_ * 1000000.0)); } ROS_DEBUG("replaying lslidar dump file"); // I can't figure out how to rewind the file, because it // starts with some kind of header. So, close the file // and reopen it with pcap. pcap_close(pcap_); pcap_ = pcap_open_offline(filename_.c_str(), errbuf_); empty_ = true; // maybe the file disappeared? } // loop back and try again if (flag == 0) { abort(); } } }
29.381868
119
0.595792
Louis-AD-git
0475b9e10e66b7ad25ad644ff30b647d9c410d2a
10,047
hpp
C++
src/libraries/core/containers/HashTables/HashSet/HashSet.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/containers/HashTables/HashSet/HashSet.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/containers/HashTables/HashSet/HashSet.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2011 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CAELUS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CAELUS. If not, see <http://www.gnu.org/licenses/>. Class CML::HashSet Description A HashTable with keys but without contents. Typedef CML::wordHashSet Description A HashSet with (the default) word keys. Typedef CML::labelHashSet Description A HashSet with label keys. \*---------------------------------------------------------------------------*/ #ifndef HashSet_H #define HashSet_H #include "HashTable.hpp" #include "nil.hpp" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace CML { /*---------------------------------------------------------------------------*\ Class HashSet Declaration \*---------------------------------------------------------------------------*/ template<class Key=word, class Hash=string::hash> class HashSet : public HashTable<nil, Key, Hash> { public: typedef typename HashTable<nil, Key, Hash>::iterator iterator; typedef typename HashTable<nil, Key, Hash>::const_iterator const_iterator; // Constructors //- Construct given initial size HashSet(const label size = 128) : HashTable<nil, Key, Hash>(size) {} //- Construct from Istream HashSet(Istream& is) : HashTable<nil, Key, Hash>(is) {} //- Construct from UList of Key HashSet(const UList<Key>&); //- Construct as copy HashSet(const HashSet<Key, Hash>& hs) : HashTable<nil, Key, Hash>(hs) {} //- Construct by transferring the parameter contents HashSet(const Xfer<HashSet<Key, Hash> >& hs) : HashTable<nil, Key, Hash>(hs) {} //- Construct by transferring the parameter contents HashSet(const Xfer<HashTable<nil, Key, Hash> >& hs) : HashTable<nil, Key, Hash>(hs) {} //- Construct from the keys of another HashTable, // the type of values held is arbitrary. template<class AnyType, class AnyHash> HashSet(const HashTable<AnyType, Key, AnyHash>&); // Member Functions // Edit //- Insert a new entry bool insert(const Key& key) { return HashTable<nil, Key, Hash>::insert(key, nil()); } //- Insert keys from a UList of Key // Return the number of new elements inserted label insert(const UList<Key>&); //- Same as insert (cannot overwrite nil content) bool set(const Key& key) { return insert(key); } //- Same as insert (cannot overwrite nil content) label set(const UList<Key>& lst) { return insert(lst); } //- Unset the specified key - same as erase bool unset(const Key& key) { return HashTable<nil, Key, Hash>::erase(key); } // Member Operators //- Return true if the entry exists, same as found() inline bool operator[](const Key&) const; //- Equality. Two hashtables are equal when their contents are equal. // Independent of table size or order. bool operator==(const HashSet<Key, Hash>&) const; //- The opposite of the equality operation. bool operator!=(const HashSet<Key, Hash>&) const; //- Combine entries from HashSets void operator|=(const HashSet<Key, Hash>&); //- Only retain entries found in both HashSets void operator&=(const HashSet<Key, Hash>&); //- Only retain unique entries (xor) void operator^=(const HashSet<Key, Hash>&); //- Add entries listed in the given HashSet to this HashSet inline void operator+=(const HashSet<Key, Hash>& rhs) { this->operator|=(rhs); } //- Remove entries listed in the given HashSet from this HashSet void operator-=(const HashSet<Key, Hash>&); }; // Global Operators //- Combine entries from HashSets template<class Key, class Hash> HashSet<Key,Hash> operator| ( const HashSet<Key,Hash>& hash1, const HashSet<Key,Hash>& hash2 ); //- Create a HashSet that only contains entries found in both HashSets template<class Key, class Hash> HashSet<Key,Hash> operator& ( const HashSet<Key,Hash>& hash1, const HashSet<Key,Hash>& hash2 ); //- Create a HashSet that only contains unique entries (xor) template<class Key, class Hash> HashSet<Key,Hash> operator^ ( const HashSet<Key,Hash>& hash1, const HashSet<Key,Hash>& hash2 ); //- A HashSet with word keys. typedef HashSet<> wordHashSet; //- A HashSet with label keys. typedef HashSet<label, Hash<label> > labelHashSet; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace CML // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #ifndef HashSet_C #define HashSet_C #include "HashSet.hpp" // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // template<class Key, class Hash> CML::HashSet<Key, Hash>::HashSet(const UList<Key>& lst) : HashTable<nil, Key, Hash>(2*lst.size()) { forAll(lst, elemI) { this->insert(lst[elemI]); } } template<class Key, class Hash> template<class AnyType, class AnyHash> CML::HashSet<Key, Hash>::HashSet ( const HashTable<AnyType, Key, AnyHash>& h ) : HashTable<nil, Key, Hash>(h.size()) { for ( typename HashTable<AnyType, Key, AnyHash>::const_iterator cit = h.cbegin(); cit != h.cend(); ++cit ) { this->insert(cit.key()); } } // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // template<class Key, class Hash> CML::label CML::HashSet<Key, Hash>::insert(const UList<Key>& lst) { label count = 0; forAll(lst, elemI) { if (this->insert(lst[elemI])) { ++count; } } return count; } // * * * * * * * * * * * * * * * Member Operators * * * * * * * * * * * * * // template<class Key, class Hash> inline bool CML::HashSet<Key, Hash>::operator[](const Key& key) const { return this->found(key); } template<class Key, class Hash> bool CML::HashSet<Key, Hash>::operator==(const HashSet<Key, Hash>& rhs) const { // Are all lhs elements in rhs? for (const_iterator iter = this->cbegin(); iter != this->cend(); ++iter) { if (!rhs.found(iter.key())) { return false; } } // Are all rhs elements in lhs? for (const_iterator iter = rhs.cbegin(); iter != rhs.cend(); ++iter) { if (!this->found(iter.key())) { return false; } } return true; } template<class Key, class Hash> bool CML::HashSet<Key, Hash>::operator!=(const HashSet<Key, Hash>& rhs) const { return !(this->operator==(rhs)); } template<class Key, class Hash> void CML::HashSet<Key, Hash>::operator|=(const HashSet<Key, Hash>& rhs) { // Add rhs elements into lhs for (const_iterator iter = rhs.cbegin(); iter != rhs.cend(); ++iter) { this->insert(iter.key()); } } template<class Key, class Hash> void CML::HashSet<Key, Hash>::operator&=(const HashSet<Key, Hash>& rhs) { // Remove elements not also found in rhs for (iterator iter = this->begin(); iter != this->end(); ++iter) { if (!rhs.found(iter.key())) { this->erase(iter); } } } template<class Key, class Hash> void CML::HashSet<Key, Hash>::operator^=(const HashSet<Key, Hash>& rhs) { // Add missed rhs elements, remove duplicate elements for (const_iterator iter = rhs.cbegin(); iter != rhs.cend(); ++iter) { if (this->found(iter.key())) { this->erase(iter.key()); } else { this->insert(iter.key()); } } } // same as HashTable::erase() template<class Key, class Hash> void CML::HashSet<Key, Hash>::operator-=(const HashSet<Key, Hash>& rhs) { // Remove rhs elements from lhs for (const_iterator iter = rhs.cbegin(); iter != rhs.cend(); ++iter) { this->erase(iter.key()); } } /* * * * * * * * * * * * * * * * Global operators * * * * * * * * * * * * * */ template<class Key, class Hash> CML::HashSet<Key, Hash> CML::operator| ( const HashSet<Key, Hash>& hash1, const HashSet<Key, Hash>& hash2 ) { HashSet<Key, Hash> out(hash1); out |= hash2; return out; } template<class Key, class Hash> CML::HashSet<Key, Hash> CML::operator& ( const HashSet<Key, Hash>& hash1, const HashSet<Key, Hash>& hash2 ) { HashSet<Key, Hash> out(hash1); out &= hash2; return out; } template<class Key, class Hash> CML::HashSet<Key, Hash> CML::operator^ ( const HashSet<Key, Hash>& hash1, const HashSet<Key, Hash>& hash2 ) { HashSet<Key, Hash> out(hash1); out ^= hash2; return out; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
23.695755
79
0.538071
MrAwesomeRocks
0475e337dbdad96a692616f58bd13ae0ef379153
5,797
cpp
C++
Source/AllProjects/Drivers/GenProto/Server/GenProtoS_CallResponse.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
51
2020-12-26T18:17:16.000Z
2022-03-15T04:29:35.000Z
Source/AllProjects/Drivers/GenProto/Server/GenProtoS_CallResponse.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
null
null
null
Source/AllProjects/Drivers/GenProto/Server/GenProtoS_CallResponse.cpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
4
2020-12-28T07:24:39.000Z
2021-12-29T12:09:37.000Z
// // FILE NAME: GenProtoS_CallResponse.cpp // // AUTHOR: Dean Roddey // // CREATED: 11/24/2003 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2020 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This file implements a simple class that represents a call/response // exchange with the target device. // // CAVEATS/GOTCHAS: // // LOG: // // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include "GenProtoS_.hpp" // --------------------------------------------------------------------------- // Magic macros // --------------------------------------------------------------------------- RTTIDecls(TGenProtoCallRep,TObject) // --------------------------------------------------------------------------- // CLASS: TGenProtoCallRep // PREFIX: clrp // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TGenProtoCallRep: Constructors and Destructor // --------------------------------------------------------------------------- TGenProtoCallRep::TGenProtoCallRep() : m_c4MillisPeriod(0) , m_c4MillisToWait(0) , m_c4NextPoll(TTime::c4Millis()) , m_pqryToSend(nullptr) , m_prepToExpect(nullptr) { } TGenProtoCallRep:: TGenProtoCallRep( TGenProtoQuery* const pqryToSend , TGenProtoReply* const prepToExpect , const tCIDLib::TCard4 c4MillisToWait) : m_c4MillisPeriod(0) , m_c4MillisToWait(c4MillisToWait) , m_c4NextPoll(TTime::c4Millis()) , m_pqryToSend(pqryToSend) , m_prepToExpect(prepToExpect) { } TGenProtoCallRep:: TGenProtoCallRep( TGenProtoQuery* const pqryToSend , TGenProtoReply* const prepToExpect , const tCIDLib::TCard4 c4MillisToWait , const tCIDLib::TCard4 c4MillisPeriod) : m_c4MillisPeriod(c4MillisPeriod) , m_c4MillisToWait(c4MillisToWait) , m_c4NextPoll(TTime::c4Millis()) , m_pqryToSend(pqryToSend) , m_prepToExpect(prepToExpect) { } TGenProtoCallRep::TGenProtoCallRep(const TGenProtoCallRep& clrpToCopy) : m_c4MillisPeriod(clrpToCopy.m_c4MillisPeriod) , m_c4MillisToWait(clrpToCopy.m_c4MillisToWait) , m_c4NextPoll(clrpToCopy.m_c4NextPoll) , m_pqryToSend(clrpToCopy.m_pqryToSend) , m_prepToExpect(clrpToCopy.m_prepToExpect) { } TGenProtoCallRep::~TGenProtoCallRep() { // We don't own the query/reply pointers, so do nothing } // --------------------------------------------------------------------------- // TGenProtoCallRep: Public operators // --------------------------------------------------------------------------- TGenProtoCallRep& TGenProtoCallRep::operator=(const TGenProtoCallRep& clrpToAssign) { if (this != &clrpToAssign) { // We don't own the query and reply pointers, so we can shallow copy m_c4MillisPeriod = clrpToAssign.m_c4MillisPeriod; m_c4MillisToWait = clrpToAssign.m_c4MillisToWait; m_c4NextPoll = clrpToAssign.m_c4NextPoll; m_pqryToSend = clrpToAssign.m_pqryToSend; m_prepToExpect = clrpToAssign.m_prepToExpect; } return *this; } // --------------------------------------------------------------------------- // TGenProtoCallRep: Public, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::TBoolean TGenProtoCallRep::bExpectsReply() const { return (m_prepToExpect != nullptr); } tCIDLib::TCard4 TGenProtoCallRep::c4MillisPeriod() const { return m_c4MillisPeriod; } tCIDLib::TCard4 TGenProtoCallRep::c4MillisToWait() const { return m_c4MillisToWait; } tCIDLib::TCard4 TGenProtoCallRep::c4NextPollTime() const { return m_c4NextPoll; } const TGenProtoQuery& TGenProtoCallRep::qryToSend() const { CIDAssert(m_pqryToSend != nullptr, L"m_pqryToSend data is null"); return *m_pqryToSend; } TGenProtoQuery& TGenProtoCallRep::qryToSend() { CIDAssert(m_pqryToSend != nullptr, L"m_pqryToSend data is null"); return *m_pqryToSend; } const TGenProtoReply& TGenProtoCallRep::repToExpect() const { // This is optional, so throw if not set if (!m_prepToExpect) { facGenProtoS().ThrowErr ( CID_FILE , CID_LINE , kGPDErrs::errcRunT_NoReplyDefined , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::NotReady , m_pqryToSend->strKey() ); } return *m_prepToExpect; } TGenProtoReply& TGenProtoCallRep::repToExpect() { // This is optional, so throw if not set if (!m_prepToExpect) { facGenProtoS().ThrowErr ( CID_FILE , CID_LINE , kGPDErrs::errcRunT_NoReplyDefined , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::NotReady , m_pqryToSend->strKey() ); } return *m_prepToExpect; } tCIDLib::TVoid TGenProtoCallRep::ResetPollTime() { m_c4NextPoll = TTime::c4Millis() + m_c4MillisPeriod; } tCIDLib::TVoid TGenProtoCallRep::Set( TGenProtoQuery* const pqryToSend , TGenProtoReply* const prepToExpect , const tCIDLib::TCard4 c4MillisToWait) { // We don't own the pointers, so no cleanup of old code is required m_c4MillisToWait = c4MillisToWait; m_pqryToSend = pqryToSend; m_prepToExpect = prepToExpect; }
26.962791
78
0.558737
MarkStega
04779e597994f9724d6ccdd8b42e5a4fb6b7c904
8,607
cpp
C++
drivers/ltr559/ltr559.cpp
graeme-winter/pimoroni-pico
b36784c03bf39e829f9c0b3444eb6051181bb76c
[ "MIT" ]
null
null
null
drivers/ltr559/ltr559.cpp
graeme-winter/pimoroni-pico
b36784c03bf39e829f9c0b3444eb6051181bb76c
[ "MIT" ]
null
null
null
drivers/ltr559/ltr559.cpp
graeme-winter/pimoroni-pico
b36784c03bf39e829f9c0b3444eb6051181bb76c
[ "MIT" ]
null
null
null
#include "ltr559.hpp" #include <algorithm> namespace pimoroni { lookup::lookup(std::initializer_list<uint16_t> values) : lut(values) { } uint8_t lookup::index(uint16_t value) { auto it = find(lut.begin(), lut.end(), value); if(it == lut.end()) return 0; return it - lut.begin(); } uint16_t lookup::value(uint8_t index) { return lut[index]; } pimoroni::lookup LTR559::lookup_led_current({5, 10, 20, 50, 100}); pimoroni::lookup LTR559::lookup_led_duty_cycle({25, 50, 75, 100}); pimoroni::lookup LTR559::lookup_led_pulse_freq({30, 40, 50, 60, 70, 80, 90, 100}); pimoroni::lookup LTR559::lookup_proximity_meas_rate({10, 50, 70, 100, 200, 500, 1000, 2000}); pimoroni::lookup LTR559::lookup_light_integration_time({100, 50, 200, 400, 150, 250, 300, 350}); pimoroni::lookup LTR559::lookup_light_repeat_rate({50, 100, 200, 500, 1000, 2000}); pimoroni::lookup LTR559::lookup_light_gain({1, 2, 4, 8, 0, 0, 48, 96}); bool LTR559::init() { i2c_init(i2c, 400000); gpio_set_function(sda, GPIO_FUNC_I2C); gpio_pull_up(sda); gpio_set_function(scl, GPIO_FUNC_I2C); gpio_pull_up(scl); if(interrupt != PIN_UNUSED) { gpio_set_function(interrupt, GPIO_FUNC_SIO); gpio_set_dir(interrupt, GPIO_IN); gpio_pull_up(interrupt); } reset(); interrupts(true, true); // 50mA, 1.0 duty cycle, 30Hz, 1 pulse proximity_led(50, 1.0, 30, 1); // enabled, gain 4x light_control(true, 4); // enabled, saturation indicator enabled proximity_control(true, true); // 100ms measurement rate proximity_measurement_rate(100); // 50ms integration time and repeat rate light_measurement_rate(50, 50); light_threshold(0xFFFF, 0x0000); proximity_threshold(0x7FFF, 0x7FFF); proximity_offset(0); return true; } void LTR559::reset() { set_bits(LTR559_ALS_CONTROL, LTR559_ALS_CONTROL_SW_RESET_BIT); while(get_bits(LTR559_ALS_CONTROL, LTR559_ALS_CONTROL_SW_RESET_BIT)) { sleep_ms(100); } } i2c_inst_t* LTR559::get_i2c() const { return i2c; } int LTR559::get_sda() const { return sda; } int LTR559::get_scl() const { return scl; } int LTR559::get_int() const { return interrupt; } uint8_t LTR559::part_id() { uint8_t part_id; read_bytes(LTR559_PART_ID, &part_id, 1); return (part_id >> LTR559_PART_ID_PART_NUMBER_SHIFT) & LTR559_PART_ID_PART_NUMBER_MASK; } uint8_t LTR559::revision_id() { uint8_t revision_id; read_bytes(LTR559_PART_ID, &revision_id, 1); return revision_id & LTR559_PART_ID_REVISION_MASK; } uint8_t LTR559::manufacturer_id() { uint8_t manufacturer; read_bytes(LTR559_MANUFACTURER_ID, &manufacturer, 1); return manufacturer; } bool LTR559::get_reading() { bool has_updated = false; uint8_t status; this->read_bytes(LTR559_ALS_PS_STATUS, &status, 1); bool als_int = (status >> LTR559_ALS_PS_STATUS_ALS_INTERRUPT_BIT) & 0b1; bool ps_int = (status >> LTR559_ALS_PS_STATUS_PS_INTERRUPT_BIT) & 0b1; bool als_data = (status >> LTR559_ALS_PS_STATUS_ALS_DATA_BIT) & 0b1; bool ps_data = (status >> LTR559_ALS_PS_STATUS_PS_DATA_BIT) & 0b1; if(ps_int || ps_data) { has_updated = true; uint16_t ps0; read_bytes(LTR559_PS_DATA, (uint8_t *)&ps0, 2); ps0 &= LTR559_PS_DATA_MASK; data.proximity = ps0; } if(als_int || als_data) { has_updated = true; uint16_t als[2]; read_bytes(LTR559_ALS_DATA_CH1, (uint8_t *)&als, 4); data.als0 = als[1]; data.als1 = als[0]; data.gain = this->lookup_light_gain.value((status >> LTR559_ALS_PS_STATUS_ALS_GAIN_SHIFT) & LTR559_ALS_PS_STATUS_ALS_GAIN_MASK); data.ratio = 101.0f; if((uint32_t)data.als0 + data.als1 > 0) { data.ratio = (float)data.als1 * 100.0f / ((float)data.als1 + data.als0); } uint8_t ch_idx = 3; if(this->data.ratio < 45) ch_idx = 0; else if(data.ratio < 64) ch_idx = 1; else if (data.ratio < 85) ch_idx = 2; float lux = ((int32_t)data.als0 * ch0_c[ch_idx]) - ((int32_t)data.als1 * ch1_c[ch_idx]); lux /= (float)this->data.integration_time / 100.0f; lux /= (float)this->data.gain; data.lux = (uint16_t)(lux / 10000.0f); } return has_updated; } void LTR559::interrupts(bool light, bool proximity) { uint8_t buf = 0; buf |= 0b1 << LTR559_INTERRUPT_POLARITY_BIT; buf |= (uint8_t)light << LTR559_INTERRUPT_ALS_BIT; buf |= (uint8_t)proximity << LTR559_INTERRUPT_PS_BIT; write_bytes(LTR559_INTERRUPT, &buf, 1); } void LTR559::proximity_led(uint8_t current, uint8_t duty_cycle, uint8_t pulse_freq, uint8_t num_pulses) { current = lookup_led_current.index(current); duty_cycle = lookup_led_duty_cycle.index(duty_cycle); duty_cycle <<= LTR559_PS_LED_DUTY_CYCLE_SHIFT; pulse_freq = lookup_led_pulse_freq.index(pulse_freq); pulse_freq <<= LTR559_PS_LED_PULSE_FREQ_SHIFT; uint8_t buf = current | duty_cycle | pulse_freq; write_bytes(LTR559_PS_LED, &buf, 1); buf = num_pulses & LTR559_PS_N_PULSES_MASK; write_bytes(LTR559_PS_N_PULSES, &buf, 1); } void LTR559::light_control(bool active, uint8_t gain) { uint8_t buf = 0; gain = lookup_light_gain.index(gain); buf |= gain << LTR559_ALS_CONTROL_GAIN_SHIFT; if(active) buf |= (0b1 << LTR559_ALS_CONTROL_MODE_BIT); else buf &= ~(0b1 << LTR559_ALS_CONTROL_MODE_BIT); write_bytes(LTR559_ALS_CONTROL, &buf, 1); } void LTR559::proximity_control(bool active, bool saturation_indicator) { uint8_t buf = 0; read_bytes(LTR559_PS_CONTROL, &buf, 1); if(active) buf |= LTR559_PS_CONTROL_ACTIVE_MASK; else buf &= ~LTR559_PS_CONTROL_ACTIVE_MASK; if(saturation_indicator) buf |= 0b1 << LTR559_PS_CONTROL_SATURATION_INDICATOR_ENABLE_BIT; else buf &= ~(0b1 << LTR559_PS_CONTROL_SATURATION_INDICATOR_ENABLE_BIT); write_bytes(LTR559_PS_CONTROL, &buf, 1); } void LTR559::light_threshold(uint16_t lower, uint16_t upper) { lower = __builtin_bswap16(lower); upper = __builtin_bswap16(upper); write_bytes(LTR559_ALS_THRESHOLD_LOWER, (uint8_t *)&lower, 2); write_bytes(LTR559_ALS_THRESHOLD_UPPER, (uint8_t *)&upper, 2); } void LTR559::proximity_threshold(uint16_t lower, uint16_t upper) { lower = uint16_to_bit12(lower); upper = uint16_to_bit12(upper); write_bytes(LTR559_PS_THRESHOLD_LOWER, (uint8_t *)&lower, 2); write_bytes(LTR559_PS_THRESHOLD_UPPER, (uint8_t *)&upper, 2); } void LTR559::light_measurement_rate(uint16_t integration_time, uint16_t rate) { data.integration_time = integration_time; integration_time = lookup_light_integration_time.index(integration_time); rate = lookup_light_repeat_rate.index(rate); uint8_t buf = 0; buf |= rate; buf |= integration_time << LTR559_ALS_MEAS_RATE_INTEGRATION_TIME_SHIFT; write_bytes(LTR559_ALS_MEAS_RATE, &buf, 1); } void LTR559::proximity_measurement_rate(uint16_t rate) { uint8_t buf = lookup_proximity_meas_rate.index(rate); write_bytes(LTR559_PS_MEAS_RATE, &buf, 1); } void LTR559::proximity_offset(uint16_t offset) { offset &= LTR559_PS_OFFSET_MASK; write_bytes(LTR559_PS_OFFSET, (uint8_t *)&offset, 1); } uint16_t LTR559::bit12_to_uint16(uint16_t value) { return ((value & 0xFF00) >> 8) | ((value & 0x000F) << 8); } uint16_t LTR559::uint16_to_bit12(uint16_t value) { return ((value & 0xFF) << 8) | ((value & 0xF00) >> 8); } // i2c functions int LTR559::write_bytes(uint8_t reg, uint8_t *buf, int len) { uint8_t buffer[len + 1]; buffer[0] = reg; for(int x = 0; x < len; x++) { buffer[x + 1] = buf[x]; } return i2c_write_blocking(i2c, address, buffer, len + 1, false); }; int LTR559::read_bytes(uint8_t reg, uint8_t *buf, int len) { i2c_write_blocking(i2c, address, &reg, 1, true); i2c_read_blocking(i2c, address, buf, len, false); return len; }; uint8_t LTR559::get_bits(uint8_t reg, uint8_t shift, uint8_t mask) { uint8_t value; read_bytes(reg, &value, 1); return value & (mask << shift); } void LTR559::set_bits(uint8_t reg, uint8_t shift, uint8_t mask) { uint8_t value; read_bytes(reg, &value, 1); value |= mask << shift; write_bytes(reg, &value, 1); } void LTR559::clear_bits(uint8_t reg, uint8_t shift, uint8_t mask) { uint8_t value; read_bytes(reg, &value, 1); value &= ~(mask << shift); write_bytes(reg, &value, 1); } }
29.782007
134
0.6748
graeme-winter
0477bfe3bfb99bb68a28ed27a46514de63b86af7
749
cpp
C++
math/common_divisor/common_divisor.cpp
tsung1271232/581_homework
36b36b3380ed5161b3e28e3b7999a1d620736da1
[ "MIT" ]
null
null
null
math/common_divisor/common_divisor.cpp
tsung1271232/581_homework
36b36b3380ed5161b3e28e3b7999a1d620736da1
[ "MIT" ]
null
null
null
math/common_divisor/common_divisor.cpp
tsung1271232/581_homework
36b36b3380ed5161b3e28e3b7999a1d620736da1
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int main() { int ncase; cin>>ncase; while(ncase--) { int q1,r1,q2,r2; cin>>q1>>r1>>q2>>r2; int divisor[2000] = {},smaller,larger; if(q1 - r1 > q2 - r2) { larger = q1 - r1; smaller = q2 - r2; } else { larger = q2 - r2; smaller = q1 - r1; } int i; for(i = 1; i <= smaller; i++) { if(smaller % i == 0 && larger % i == 0) divisor[i]++; else continue; } for(i=1;i<=smaller;i++) { if(divisor[i]!=0) cout<<i<<" "; } } return 0; }
18.725
51
0.35247
tsung1271232
04793ebe7db7522cc1ddf61cec31cbe68b55cba3
916
cpp
C++
src/widget.cpp
FuSoftware/QOsuBut
cf89ee66a23efcddf94b6e38b7c708059e026995
[ "MIT" ]
null
null
null
src/widget.cpp
FuSoftware/QOsuBut
cf89ee66a23efcddf94b6e38b7c708059e026995
[ "MIT" ]
null
null
null
src/widget.cpp
FuSoftware/QOsuBut
cf89ee66a23efcddf94b6e38b7c708059e026995
[ "MIT" ]
null
null
null
#include "widget.h" Widget::Widget(QWidget *parent): QWidget(parent) { QVBoxLayout *l = new QVBoxLayout(this); le = new QLineEdit(this); label = new QLabel("Placeholder",this); labelTime = new QLabel(this); le->setValidator(new QIntValidator(0,100000,this)); l->addWidget(le); l->addWidget(labelTime); l->addWidget(label); w = new WindowHandler("osu.exe"); connect(le,SIGNAL(returnPressed()),this,SLOT(setPid())); QTimer *t = new QTimer(this); t->setInterval(50); connect(t,SIGNAL(timeout()),this,SLOT(refreshScreen())); t->start(); } Widget::~Widget() { } void Widget::setPid() { w->setPid(le->text().toLong()); } void Widget::refreshScreen() { QTime t; t.start(); QPixmap p = w->getProcessScreen(); labelTime->setText(QString::number(t.elapsed()) + QString("ms")); label->setPixmap(p.scaled(600,600,Qt::KeepAspectRatio)); }
20.818182
69
0.635371
FuSoftware
0479ae356ddb676f9c1536348c8dc55e8a105920
5,619
cpp
C++
B2G/gecko/xpcom/reflect/xptcall/src/md/win32/xptcstubs_x86_64.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/gecko/xpcom/reflect/xptcall/src/md/win32/xptcstubs_x86_64.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/gecko/xpcom/reflect/xptcall/src/md/win32/xptcstubs_x86_64.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Implement shared vtbl methods. */ #include "xptcprivate.h" #include "xptiprivate.h" /* * This is for Windows XP 64-Bit Edition / Server 2003 for AMD64 or later. */ extern "C" nsresult PrepareAndDispatch(nsXPTCStubBase* self, uint32_t methodIndex, uint64_t* args, uint64_t *gprData, double *fprData) { #define PARAM_BUFFER_COUNT 16 // // "this" pointer is first parameter, so parameter count is 3. // #define PARAM_GPR_COUNT 3 #define PARAM_FPR_COUNT 3 nsXPTCMiniVariant paramBuffer[PARAM_BUFFER_COUNT]; nsXPTCMiniVariant* dispatchParams = NULL; const nsXPTMethodInfo* info = NULL; uint8_t paramCount; uint8_t i; nsresult result = NS_ERROR_FAILURE; NS_ASSERTION(self,"no self"); self->mEntry->GetMethodInfo(uint16_t(methodIndex), &info); NS_ASSERTION(info,"no method info"); paramCount = info->GetParamCount(); // // setup variant array pointer // if(paramCount > PARAM_BUFFER_COUNT) dispatchParams = new nsXPTCMiniVariant[paramCount]; else dispatchParams = paramBuffer; NS_ASSERTION(dispatchParams,"no place for params"); uint64_t* ap = args; uint32_t iCount = 0; for(i = 0; i < paramCount; i++) { const nsXPTParamInfo& param = info->GetParam(i); const nsXPTType& type = param.GetType(); nsXPTCMiniVariant* dp = &dispatchParams[i]; if(param.IsOut() || !type.IsArithmetic()) { if (iCount < PARAM_GPR_COUNT) dp->val.p = (void*)gprData[iCount++]; else dp->val.p = (void*)*ap++; continue; } // else switch(type) { case nsXPTType::T_I8: if (iCount < PARAM_GPR_COUNT) dp->val.i8 = (int8_t)gprData[iCount++]; else dp->val.i8 = *((int8_t*)ap++); break; case nsXPTType::T_I16: if (iCount < PARAM_GPR_COUNT) dp->val.i16 = (int16_t)gprData[iCount++]; else dp->val.i16 = *((int16_t*)ap++); break; case nsXPTType::T_I32: if (iCount < PARAM_GPR_COUNT) dp->val.i32 = (int32_t)gprData[iCount++]; else dp->val.i32 = *((int32_t*)ap++); break; case nsXPTType::T_I64: if (iCount < PARAM_GPR_COUNT) dp->val.i64 = (int64_t)gprData[iCount++]; else dp->val.i64 = *((int64_t*)ap++); break; case nsXPTType::T_U8: if (iCount < PARAM_GPR_COUNT) dp->val.u8 = (uint8_t)gprData[iCount++]; else dp->val.u8 = *((uint8_t*)ap++); break; case nsXPTType::T_U16: if (iCount < PARAM_GPR_COUNT) dp->val.u16 = (uint16_t)gprData[iCount++]; else dp->val.u16 = *((uint16_t*)ap++); break; case nsXPTType::T_U32: if (iCount < PARAM_GPR_COUNT) dp->val.u32 = (uint32_t)gprData[iCount++]; else dp->val.u32 = *((uint32_t*)ap++); break; case nsXPTType::T_U64: if (iCount < PARAM_GPR_COUNT) dp->val.u64 = (uint64_t)gprData[iCount++]; else dp->val.u64 = *((uint64_t*)ap++); break; case nsXPTType::T_FLOAT: if (iCount < PARAM_FPR_COUNT) // The value in xmm register is already prepared to // be retrieved as a float. Therefore, we pass the // value verbatim, as a double without conversion. dp->val.d = (double)fprData[iCount++]; else dp->val.f = *((float*)ap++); break; case nsXPTType::T_DOUBLE: if (iCount < PARAM_FPR_COUNT) dp->val.d = (double)fprData[iCount++]; else dp->val.d = *((double*)ap++); break; case nsXPTType::T_BOOL: if (iCount < PARAM_GPR_COUNT) // We need cast to uint8_t to remove garbage on upper 56-bit // at first. dp->val.b = (bool)(uint8_t)gprData[iCount++]; else dp->val.b = *((bool*)ap++); break; case nsXPTType::T_CHAR: if (iCount < PARAM_GPR_COUNT) dp->val.c = (char)gprData[iCount++]; else dp->val.c = *((char*)ap++); break; case nsXPTType::T_WCHAR: if (iCount < PARAM_GPR_COUNT) dp->val.wc = (wchar_t)gprData[iCount++]; else dp->val.wc = *((wchar_t*)ap++); break; default: NS_ERROR("bad type"); break; } } result = self->mOuter->CallMethod((uint16_t)methodIndex, info, dispatchParams); if(dispatchParams != paramBuffer) delete [] dispatchParams; return result; } #define STUB_ENTRY(n) /* defined in the assembly file */ #define SENTINEL_ENTRY(n) \ nsresult nsXPTCStubBase::Sentinel##n() \ { \ NS_ERROR("nsXPTCStubBase::Sentinel called"); \ return NS_ERROR_NOT_IMPLEMENTED; \ } #include "xptcstubsdef.inc" void xptc_dummy() { }
28.378788
83
0.529632
wilebeast
047a6ff5a909f0cf85b1b390a77f767a6ab4beae
2,158
cc
C++
third_party/webrtc/src/chromium/src/chromecast/browser/cast_permission_manager.cc
bopopescu/webrtc-streaming-node
727a441204344ff596401b0253caac372b714d91
[ "MIT" ]
8
2016-02-08T11:59:31.000Z
2020-05-31T15:19:54.000Z
third_party/webrtc/src/chromium/src/chromecast/browser/cast_permission_manager.cc
bopopescu/webrtc-streaming-node
727a441204344ff596401b0253caac372b714d91
[ "MIT" ]
1
2021-05-05T11:11:31.000Z
2021-05-05T11:11:31.000Z
third_party/webrtc/src/chromium/src/chromecast/browser/cast_permission_manager.cc
bopopescu/webrtc-streaming-node
727a441204344ff596401b0253caac372b714d91
[ "MIT" ]
7
2016-02-09T09:28:14.000Z
2020-07-25T19:03:36.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromecast/browser/cast_permission_manager.h" #include "base/callback.h" #include "base/logging.h" #include "content/public/browser/permission_type.h" namespace chromecast { namespace shell { CastPermissionManager::CastPermissionManager() : content::PermissionManager() { } CastPermissionManager::~CastPermissionManager() { } void CastPermissionManager::RequestPermission( content::PermissionType permission, content::RenderFrameHost* render_frame_host, int request_id, const GURL& origin, bool user_gesture, const base::Callback<void(content::PermissionStatus)>& callback) { LOG(INFO) << __FUNCTION__ << ": " << static_cast<int>(permission); callback.Run(content::PermissionStatus::PERMISSION_STATUS_GRANTED); } void CastPermissionManager::CancelPermissionRequest( content::PermissionType permission, content::RenderFrameHost* render_frame_host, int request_id, const GURL& origin) { } void CastPermissionManager::ResetPermission( content::PermissionType permission, const GURL& requesting_origin, const GURL& embedding_origin) { } content::PermissionStatus CastPermissionManager::GetPermissionStatus( content::PermissionType permission, const GURL& requesting_origin, const GURL& embedding_origin) { LOG(INFO) << __FUNCTION__ << ": " << static_cast<int>(permission); return content::PermissionStatus::PERMISSION_STATUS_GRANTED; } void CastPermissionManager::RegisterPermissionUsage( content::PermissionType permission, const GURL& requesting_origin, const GURL& embedding_origin) { } int CastPermissionManager::SubscribePermissionStatusChange( content::PermissionType permission, const GURL& requesting_origin, const GURL& embedding_origin, const base::Callback<void(content::PermissionStatus)>& callback) { return -1; } void CastPermissionManager::UnsubscribePermissionStatusChange( int subscription_id) { } } // namespace shell } // namespace chromecast
29.561644
73
0.76506
bopopescu
047abf09bdf3505d2fa2557e82e6bf7802596554
4,918
cpp
C++
aes_main.cpp
cxrasdfg/aes-des
d634da18b5dbf02e99fafd71c6d925e855291f21
[ "MIT" ]
null
null
null
aes_main.cpp
cxrasdfg/aes-des
d634da18b5dbf02e99fafd71c6d925e855291f21
[ "MIT" ]
null
null
null
aes_main.cpp
cxrasdfg/aes-des
d634da18b5dbf02e99fafd71c6d925e855291f21
[ "MIT" ]
null
null
null
// // Created by theppsh on 17-4-13. // #include <iostream> #include <iomanip> #include "src/aes.hpp" #include "src/triple_des.hpp" int main(int argc,char ** args){ /**aes 加密*/ /// 128位全0的秘钥 u_char key_block[]={0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0 }; u_char plain_block[] = {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08, 0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18, }; u_char cipher_block[16]; AES aes_test(key_block); std::cout<<"********** aes 加密测试 **********"<<std::endl; std::memcpy(cipher_block,plain_block,16); aes_test.Cipher(cipher_block); auto cout_default_flags = std::cout.flags(); for(int i=0;i<16;i++){ std::cout<<std::hex<<std::internal<<std::showbase<<std::setw(4)<<std::setfill('0')<<int(cipher_block[i])<<" "; } std::cout.setf(cout_default_flags); std::cout<<std::endl; std::cout<<std::endl; std::cout<<"********** aes 解密测试 **********"<<std::endl; std::memcpy(plain_block,cipher_block,16); aes_test.InvCipher(plain_block); for(int i=0;i<16;i++){ std::cout<<std::hex<<std::internal<<std::showbase<<std::setw(4)<<std::setfill('0')<<int(plain_block[i])<<" "; } std::cout<<std::endl; std::cout.setf(cout_default_flags); /// ***aes加密文件测试 *** std::cout<<std::endl; std::cout<<"******** aes 加密文件测试 ********"<<std::endl; std::string plain_txt= "/media/C/课程与作业/网络安全/实验课/实验一/aes_and_des/resoureces/plain.txt"; std::string cipher_txt = "/media/C/课程与作业/网络安全/实验课/实验一/aes_and_des/resoureces/cipher.txt"; std::string decipher_txt = "/media/C/课程与作业/网络安全/实验课/实验一/aes_and_des/resoureces/decipher.txt"; aes_test.CipherFile(plain_txt,cipher_txt); std::cout<<std::endl; std::cout<<"******** 解密文件测试 ********"<<std::endl; aes_test.InvCipherFile(cipher_txt,decipher_txt); [](const std::string & file_path1,const std::string file_path2){ std::fstream f1,f2; f1.open(file_path1); f2.open(file_path2); assert(f1.is_open()); assert(f2.is_open()); f1.seekg(0,std::ios::end); f2.seekg(0,std::ios::end); int f1_size = static_cast<int>(f1.tellg()); int f2_size = static_cast<int>(f2.tellg()); std::shared_ptr<char> f1_file_buffer(new char[f1_size+1]); std::shared_ptr<char> f2_file_buffer(new char[f2_size+1]); f1.seekg(0,std::ios::beg); f2.seekg(0,std::ios::beg); f1.read(f1_file_buffer.get(),f1_size); f2.read(f2_file_buffer.get(),f2_size); f1_file_buffer.get()[f1_size]='\0'; f2_file_buffer.get()[f2_size]='\0'; if(std::strcmp(f1_file_buffer.get(),f2_file_buffer.get())!=0){ std::cout<<"文件加密解密后的文件与原来的文件不一致"<<std::endl; exit(0); }else{ std::cout<<"文件加密解密通过!"<<std::endl; } }(plain_txt,decipher_txt); /// aes 与 des 的加密解密的速度的测试 均加密128位即16个byete的数据 std::cout<<std::endl; std::cout<<"******** ase & 3des ecb加密解密的速度的测试****** "<< std::endl; int enc_times =100000; //加密而次数s // 先测试 des { u_char des_bit_keys[64]; u_char des_sub_keys[16][48]; auto t1= std::chrono::system_clock::now(); for (int _time =0 ; _time < enc_times; _time++){ des::Char8ToBit64(key_block,des_bit_keys); des::DES_MakeSubKeys(des_bit_keys,des_sub_keys); _3_des::_3_DES_EncryptBlock(plain_block,key_block,key_block,key_block,cipher_block); _3_des::_3_DES_EncryptBlock(plain_block+8,key_block,key_block,key_block,cipher_block+8); //des的块是8个字节也就是64位的。。。 _3_des::_3_DES_DecryptBlock(cipher_block,key_block,key_block,key_block,plain_block); _3_des::_3_DES_DecryptBlock(cipher_block+8,key_block,key_block,key_block,plain_block+8); } auto t2 = std::chrono::system_clock::now(); float total_time = std::chrono::duration_cast<std::chrono::nanoseconds>(t2-t1).count()/1000.0f/1000.0f; std::cout<<"加密解密128位数消息"<<enc_times<<"次, 3_des-ecb总共花费了:"<<total_time<<" ms"<<std::endl; std::cout<<"加密解密128位数消息"<<enc_times<<"次, 3_des-ecb平均花费了:"<<total_time/enc_times<<" ms"<<std::endl; } // 再测试aes { auto t1 =std::chrono::system_clock::now(); for(int _time = 0; _time<enc_times;_time++){ aes_test.Cipher(plain_block); memcpy(cipher_block,plain_block,16); aes_test.InvCipher(cipher_block); memcpy(plain_block,cipher_block,16); } auto t2 = std::chrono::system_clock::now(); float total_time = std::chrono::duration_cast<std::chrono::nanoseconds>(t2-t1).count()/1000.0f/1000.0f; std::cout<<"加密解密128位数消息"<<enc_times<<"次, aes总共花费了:"<<total_time<<" ms"<<std::endl; std::cout<<"加密解密128位数消息"<<enc_times<<"次, aes平均花费了:"<<total_time/enc_times<<" ms"<<std::endl; } return 0; }
33.917241
123
0.603904
cxrasdfg
047fb2c64eae3736eec741f519400de9348f1f1f
960
cpp
C++
Cpp/145_binary_tree_postorder_traversal/solution2.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
1
2015-12-19T23:05:35.000Z
2015-12-19T23:05:35.000Z
Cpp/145_binary_tree_postorder_traversal/solution2.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
null
null
null
Cpp/145_binary_tree_postorder_traversal/solution2.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
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> postorderTraversal(TreeNode* root) { vector<int> res; if (!root) return res; stack<TreeNode*> st; TreeNode* lastVisited(NULL); while (!st.empty() || root) { if (root) { st.push(root); root = root->left; } else { auto peek = st.top(); if (peek->right && lastVisited != peek->right) root = peek->right; else { res.push_back(peek->val); lastVisited = peek; st.pop(); } } } return res; } };
23.414634
82
0.402083
zszyellow
0481fc084fe09bf1a197622a2abe5288d0e392f8
1,659
hpp
C++
core/storage/trie/impl/polkadot_trie_batch.hpp
Lederstrumpf/kagome
a5050ca04577c0570e21ce7322cc010153b6fe29
[ "Apache-2.0" ]
null
null
null
core/storage/trie/impl/polkadot_trie_batch.hpp
Lederstrumpf/kagome
a5050ca04577c0570e21ce7322cc010153b6fe29
[ "Apache-2.0" ]
null
null
null
core/storage/trie/impl/polkadot_trie_batch.hpp
Lederstrumpf/kagome
a5050ca04577c0570e21ce7322cc010153b6fe29
[ "Apache-2.0" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef KAGOME_CORE_STORAGE_TRIE_IMPL_POLKADOT_TRIE_BATCH_HPP #define KAGOME_CORE_STORAGE_TRIE_IMPL_POLKADOT_TRIE_BATCH_HPP #include "common/buffer.hpp" #include "storage/face/write_batch.hpp" #include "storage/trie/impl/polkadot_trie_db.hpp" namespace kagome::storage::trie { class PolkadotTrieBatch : public face::WriteBatch<common::Buffer, common::Buffer> { enum class Action { PUT, REMOVE }; struct Command { Action action; common::Buffer key{}; // value is unnecessary when action is REMOVE common::Buffer value{}; }; public: explicit PolkadotTrieBatch(PolkadotTrieDb &trie); ~PolkadotTrieBatch() override = default; // value will be copied outcome::result<void> put(const common::Buffer &key, const common::Buffer &value) override; outcome::result<void> put(const common::Buffer &key, common::Buffer &&value) override; outcome::result<void> remove(const common::Buffer &key) override; outcome::result<void> commit() override; void clear() override; bool is_empty() const; private: outcome::result<PolkadotTrieDb::NodePtr> applyPut(PolkadotTrie &trie, const common::Buffer &key, common::Buffer &&value); outcome::result<PolkadotTrieDb::NodePtr> applyRemove(PolkadotTrie &trie, const common::Buffer &key); PolkadotTrieDb &storage_; std::list<Command> commands_; }; } // namespace kagome::storage::trie #endif // KAGOME_CORE_STORAGE_TRIE_IMPL_POLKADOT_TRIE_BATCH_HPP
30.163636
104
0.694394
Lederstrumpf
0483595ad4e4751bb81fe67379e81b88004ac9d7
17,761
cpp
C++
test/uri_builder_test.cpp
chfast/uri
c6dd135801061b641531bf23e971131904cb15a3
[ "BSL-1.0" ]
null
null
null
test/uri_builder_test.cpp
chfast/uri
c6dd135801061b641531bf23e971131904cb15a3
[ "BSL-1.0" ]
null
null
null
test/uri_builder_test.cpp
chfast/uri
c6dd135801061b641531bf23e971131904cb15a3
[ "BSL-1.0" ]
null
null
null
// Copyright (c) Glyn Matthews 2012, 2013, 2014. // Copyright 2012 Google, Inc. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <gtest/gtest.h> #include <network/uri.hpp> #include "string_utility.hpp" TEST(builder_test, empty_uri_doesnt_throw) { network::uri_builder builder; ASSERT_NO_THROW(builder.uri()); } TEST(builder_test, empty_uri) { network::uri_builder builder; network::uri instance(builder); ASSERT_TRUE(instance.empty()); } TEST(builder_test, simple_uri_doesnt_throw) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_NO_THROW(builder.uri()); } TEST(builder_test, simple_uri) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_EQ("http://www.example.com/", builder.uri()); } TEST(builder_test, simple_uri_has_scheme) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_TRUE(builder.uri().scheme()); } TEST(builder_test, simple_uri_scheme_value) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_EQ("http", *builder.uri().scheme()); } TEST(builder_test, simple_uri_has_no_user_info) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_FALSE(builder.uri().user_info()); } TEST(builder_test, simple_uri_has_host) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_TRUE(builder.uri().host()); } TEST(builder_test, simple_uri_host_value) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_EQ("www.example.com", *builder.uri().host()); } TEST(builder_test, simple_uri_has_no_port) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_FALSE(builder.uri().port()); } TEST(builder_test, simple_uri_has_path) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_TRUE(builder.uri().path()); } TEST(builder_test, simple_uri_path_value) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_EQ("/", *builder.uri().path()); } TEST(builder_test, simple_uri_has_no_query) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_FALSE(builder.uri().query()); } TEST(builder_test, simple_uri_has_no_fragment) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_FALSE(builder.uri().fragment()); } TEST(builder_test, simple_opaque_uri_doesnt_throw) { network::uri_builder builder; builder .scheme("mailto") .path("john.doe@example.com") ; ASSERT_NO_THROW(builder.uri()); } TEST(builder_test, simple_opaque_uri) { network::uri_builder builder; builder .scheme("mailto") .path("john.doe@example.com") ; ASSERT_EQ("mailto:john.doe@example.com", builder.uri()); } TEST(builder_test, simple_opaque_uri_has_scheme) { network::uri_builder builder; builder .scheme("mailto") .path("john.doe@example.com") ; ASSERT_TRUE(builder.uri().scheme()); } TEST(builder_test, simple_opaque_uri_scheme_value) { network::uri_builder builder; builder .scheme("mailto") .path("john.doe@example.com") ; ASSERT_EQ("mailto", *builder.uri().scheme()); } TEST(builder_test, relative_hierarchical_uri_doesnt_throw) { network::uri_builder builder; builder .host("www.example.com") .path("/") ; ASSERT_NO_THROW(builder.uri()); } TEST(builder_test, relative_hierarchical_uri) { network::uri_builder builder; builder .host("www.example.com") .path("/") ; ASSERT_EQ("www.example.com/", builder.uri()); } TEST(builder_test, relative_opaque_uri_doesnt_throw) { network::uri_builder builder; builder .path("john.doe@example.com") ; ASSERT_NO_THROW(builder.uri()); } TEST(builder_test, relative_opaque_uri) { network::uri_builder builder; builder .path("john.doe@example.com") ; ASSERT_EQ("john.doe@example.com", builder.uri()); } TEST(builder_test, full_uri_doesnt_throw) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_NO_THROW(builder.uri()); } TEST(builder_test, full_uri) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_EQ("http://user:password@www.example.com:80/path?query#fragment", builder.uri()); } TEST(builder_test, full_uri_has_scheme) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_TRUE(builder.uri().scheme()); } TEST(builder_test, full_uri_scheme_value) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_EQ("http", *builder.uri().scheme()); } TEST(builder_test, full_uri_has_user_info) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_TRUE(builder.uri().user_info()); } TEST(builder_test, full_uri_user_info_value) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_EQ("user:password", *builder.uri().user_info()); } TEST(builder_test, full_uri_has_host) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_TRUE(builder.uri().host()); } TEST(builder_test, full_uri_host_value) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_EQ("www.example.com", *builder.uri().host()); } TEST(builder_test, full_uri_has_port) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_TRUE(builder.uri().port()); } TEST(builder_test, full_uri_has_path) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_TRUE(builder.uri().path()); } TEST(builder_test, full_uri_path_value) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_EQ("/path", *builder.uri().path()); } TEST(builder_test, full_uri_has_query) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_TRUE(builder.uri().query()); } TEST(builder_test, full_uri_query_value) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_EQ("query", *builder.uri().query()); } TEST(builder_test, full_uri_has_fragment) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_TRUE(builder.uri().fragment()); } TEST(builder_test, full_uri_fragment_value) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_EQ("fragment", *builder.uri().fragment()); } TEST(builder_test, relative_uri) { network::uri_builder builder; builder .host("www.example.com") .path("/") ; ASSERT_EQ("www.example.com/", builder.uri()); } TEST(builder_test, relative_uri_scheme) { network::uri_builder builder; builder .host("www.example.com") .path("/") ; ASSERT_FALSE(builder.uri().scheme()); } TEST(builder_test, authority) { network::uri_builder builder; builder .scheme("http") .authority("www.example.com:8080") .path("/") ; ASSERT_EQ("http://www.example.com:8080/", builder.uri()); ASSERT_EQ("www.example.com", *builder.uri().host()); ASSERT_EQ("8080", *builder.uri().port()); } TEST(builder_test, relative_uri_has_host) { network::uri_builder builder; builder .host("www.example.com") .path("/") ; ASSERT_TRUE(builder.uri().host()); } TEST(builder_test, relative_uri_host_value) { network::uri_builder builder; builder .host("www.example.com") .path("/") ; ASSERT_EQ("www.example.com", *builder.uri().host()); } TEST(builder_test, relative_uri_has_path) { network::uri_builder builder; builder .host("www.example.com") .path("/") ; ASSERT_TRUE(builder.uri().path()); } TEST(builder_test, relative_uri_path_value) { network::uri_builder builder; builder .host("www.example.com") .path("/") ; ASSERT_EQ("/", *builder.uri().path()); } TEST(builder_test, build_relative_uri_with_path_query_and_fragment) { network::uri_builder builder; builder .path("/path/") .query("key", "value") .fragment("fragment") ; ASSERT_EQ("/path/", *builder.uri().path()); ASSERT_EQ("key=value", *builder.uri().query()); ASSERT_EQ("fragment", *builder.uri().fragment()); } TEST(builder_test, build_uri_with_capital_scheme) { network::uri_builder builder; builder .scheme("HTTP") .host("www.example.com") .path("/") ; ASSERT_EQ("http://www.example.com/", builder.uri()); } TEST(builder_test, build_uri_with_capital_host) { network::uri_builder builder; builder .scheme("http") .host("WWW.EXAMPLE.COM") .path("/") ; ASSERT_EQ("http://www.example.com/", builder.uri()); } TEST(builder_test, build_uri_with_unencoded_path) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/A path with spaces") ; ASSERT_EQ("http://www.example.com/A%20path%20with%20spaces", builder.uri()); } TEST(builder_test, DISABLED_builder_uri_and_remove_dot_segments_from_path) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/A/./path/") ; ASSERT_EQ("http://www.example.com/A/path/", builder.uri()); } TEST(builder_test, build_uri_with_qmark_in_path) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/?/") ; ASSERT_EQ("http://www.example.com/%3F/", builder.uri()); } TEST(builder_test, build_uri_with_hash_in_path) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/#/") ; ASSERT_EQ("http://www.example.com/%23/", builder.uri()); } TEST(builder_test, DISABLED_build_uri_from_filesystem_path) { network::uri_builder builder; builder .scheme("file") .path(boost::filesystem::path("/path/to/a/file.html")) ; ASSERT_EQ("file:///path/to/a/file.html", builder.uri()); } TEST(builder_test, build_http_uri_from_filesystem_path) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path(boost::filesystem::path("/path/to/a/file.html")) ; ASSERT_EQ("http://www.example.com/path/to/a/file.html", builder.uri()); } TEST(builder_test, DISABLED_build_uri_from_filesystem_path_with_encoded_chars) { network::uri_builder builder; builder .scheme("file") .path(boost::filesystem::path("/path/to/a/file with spaces.html")) ; ASSERT_EQ("file:///path/to/a/file%20with%20spaces.html", builder.uri()); } TEST(builder_test, DISABLED_build_uri_with_encoded_unreserved_characters) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/%7Eglynos/") ; ASSERT_EQ("http://www.example.com/~glynos/", builder.uri()); } TEST(builder_test, simple_port) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .port(8000) .path("/") ; ASSERT_EQ("http://www.example.com:8000/", builder.uri()); } // This seems to work, but I don't want to add the Boost.System // dependency just for this. TEST(builder_test, build_uri_with_ipv4_address) { using namespace boost::asio::ip; network::uri_builder builder; builder .scheme("http") .host(address_v4::loopback()) .path("/") ; ASSERT_EQ("http://127.0.0.1/", builder.uri()); } TEST(builder_test, build_uri_with_ipv6_address) { using namespace boost::asio::ip; network::uri_builder builder; builder .scheme("http") .host(address_v6::loopback()) .path("/") ; ASSERT_EQ("http://[::1]/", builder.uri()); } TEST(builder_test, build_uri_with_query_item) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .query("a", "1") .path("/") ; ASSERT_EQ("http://www.example.com/?a=1", builder.uri()); } TEST(builder_test, build_uri_with_multiple_query_items) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .query("a", "1") .query("b", "2") .path("/") ; ASSERT_EQ("http://www.example.com/?a=1&b=2", builder.uri()); } //TEST(builder_test, build_uri_with_multiple_query_items_with_int_values) { // network::uri_builder builder; // builder // .scheme("http") // .host("www.example.com") // .query("a", 1) // .query("b", 2) // .path("/") // ; // ASSERT_EQ("http://www.example.com/?a=1&b=2", builder.uri()); //} TEST(builder_test, construct_from_existing_uri) { network::uri instance("http://www.example.com/"); network::uri_builder builder(instance); ASSERT_EQ("http://www.example.com/", builder.uri()); } TEST(builder_test, build_from_existing_uri) { network::uri instance("http://www.example.com/"); network::uri_builder builder(instance); builder.query("a", "1").query("b", "2").fragment("fragment"); ASSERT_EQ("http://www.example.com/?a=1&b=2#fragment", builder.uri()); } TEST(builder_test, authority_port_test) { network::uri_builder builder; builder .scheme("https") .authority("www.example.com") ; ASSERT_EQ("www.example.com", *builder.uri().authority()); } TEST(builder_test, clear_user_info_test) { network::uri instance("http://user:password@www.example.com:80/path?query#fragment"); network::uri_builder builder(instance); builder.clear_user_info(); ASSERT_EQ("http://www.example.com:80/path?query#fragment", builder.uri()); } TEST(builder_test, clear_port_test) { network::uri instance("http://user:password@www.example.com:80/path?query#fragment"); network::uri_builder builder(instance); builder.clear_port(); ASSERT_EQ("http://user:password@www.example.com/path?query#fragment", builder.uri()); } TEST(builder_test, clear_path_test) { network::uri instance("http://user:password@www.example.com:80/path?query#fragment"); network::uri_builder builder(instance); builder.clear_path(); ASSERT_EQ("http://user:password@www.example.com:80?query#fragment", builder.uri()); } TEST(builder_test, clear_query_test) { network::uri instance("http://user:password@www.example.com:80/path?query#fragment"); network::uri_builder builder(instance); builder.clear_query(); ASSERT_EQ("http://user:password@www.example.com:80/path#fragment", builder.uri()); } TEST(builder_test, clear_fragment_test) { network::uri instance("http://user:password@www.example.com:80/path?query#fragment"); network::uri_builder builder(instance); builder.clear_fragment(); ASSERT_EQ("http://user:password@www.example.com:80/path?query", builder.uri()); } TEST(builder_test, empty_username) { std::string user_info(":"); network::uri_builder builder; builder.scheme("ftp").host("127.0.0.1").user_info(user_info); ASSERT_EQ("ftp://:@127.0.0.1", builder.uri()); } TEST(builder_test, path_should_be_prefixed_with_slash) { std::string path("relative"); network::uri_builder builder; builder.scheme("ftp").host("127.0.0.1").path(path); ASSERT_EQ("ftp://127.0.0.1/relative", builder.uri()); } TEST(builder_test, path_should_be_prefixed_with_slash_2) { network::uri_builder builder; builder .scheme("ftp").host("127.0.0.1").path("noleadingslash/foo.txt"); ASSERT_EQ("/noleadingslash/foo.txt", *builder.uri().path()); }
23.776439
90
0.659422
chfast
04839dfd4e02508c8895013f0fcaf725a3d87a91
200
cpp
C++
content/rcpp_advanced_I/rnorm_manual.cpp
mfasiolo/sc2-2019
0fe0c4e1f65ac35c1f38e8f4ea071c76bce4a586
[ "MIT" ]
5
2020-02-25T07:38:08.000Z
2021-06-22T16:15:03.000Z
content/rcpp_advanced_I/rnorm_manual.cpp
mfasiolo/sc2-2019
0fe0c4e1f65ac35c1f38e8f4ea071c76bce4a586
[ "MIT" ]
null
null
null
content/rcpp_advanced_I/rnorm_manual.cpp
mfasiolo/sc2-2019
0fe0c4e1f65ac35c1f38e8f4ea071c76bce4a586
[ "MIT" ]
2
2020-02-25T07:38:10.000Z
2020-04-26T06:02:14.000Z
#include <Rcpp.h> using namespace Rcpp; RcppExport SEXP rnorm_manual(SEXP n) { NumericVector out( as<int>(n) ); RNGScope rngScope; out = rnorm(as<int>(n), 0.0, 1.0); return out; }
15.384615
38
0.63
mfasiolo
04848621f09ec43b5e6fd5bfa67a27a3096fd2b9
2,807
hpp
C++
include/chapter-4/square_matrix_multiply/square_matrix_multiply_recursive.hpp
zero4drift/CLRS_Cpp_Implementations
efafbb34fb9f83dedecdcf01395def27fd64a33a
[ "MIT" ]
null
null
null
include/chapter-4/square_matrix_multiply/square_matrix_multiply_recursive.hpp
zero4drift/CLRS_Cpp_Implementations
efafbb34fb9f83dedecdcf01395def27fd64a33a
[ "MIT" ]
null
null
null
include/chapter-4/square_matrix_multiply/square_matrix_multiply_recursive.hpp
zero4drift/CLRS_Cpp_Implementations
efafbb34fb9f83dedecdcf01395def27fd64a33a
[ "MIT" ]
null
null
null
// Only for matrix with dimension 2, 4, 8, 16... #ifndef SQUARE_MATRIX_MULTIPLY_RECURSIVE_H #define SQUARE_MATRIX_MULTIPLY_RECURSIVE_H #include <utility> namespace CLRS { template <typename T, std::size_t n> void divide_matrix_4(T (&a)[n][n], T (&b)[n/2][n/2], T (&c)[n/2][n/2], T (&d)[n/2][n/2], T (&e)[n/2][n/2]) { for(std::size_t i = 0; i != n / 2; ++i) for(std::size_t j = 0; j != n / 2; ++j) b[i][j] = a[i][j]; for(std::size_t i = 0; i != n / 2; ++i) for(std::size_t j = n / 2; j != n; ++j) c[i][j - n/2] = a[i][j]; for(std::size_t i = n / 2; i != n; ++i) for(std::size_t j = 0; j != n / 2; ++j) d[i - n/2][j] = a[i][j]; for(std::size_t i = n / 2; i != n; ++i) for(std::size_t j = n / 2; j != n; ++j) e[i - n/2][j - n/2] = a[i][j]; } template <typename T, std::size_t n> void combine_matrix_4(T (&a)[n][n], T (&b)[n/2][n/2], T (&c)[n/2][n/2], T (&d)[n/2][n/2], T (&e)[n/2][n/2]) { for(std::size_t i = 0; i != n / 2; ++i) for(std::size_t j = 0; j != n / 2; ++j) { a[i][j] = b[i][j]; a[i][j + n/2] = c[i][j]; a[i + n/2][j] = d[i][j]; a[i + n/2][j + n/2] = e[i][j]; } } template <typename T, std::size_t n> void add_matrix(T (&c)[n][n], T (&a)[n][n], T (&b)[n][n]) { for(std::size_t i = 0; i != n; ++i) for(std::size_t j = 0; j != n; ++j) c[i][j] = a[i][j] + b[i][j]; } template <typename T> void square_matrix_multiply_recursive(T (&a)[1][1], T (&b)[1][1], T (&c)[1][1]) // more specific function template for recursive base case when n equals 1. { c[0][0] = a[0][0] * b[0][0]; } template <typename T, std::size_t n> void square_matrix_multiply_recursive(T (&a)[n][n], T (&b)[n][n], T (&c)[n][n]) { T a00[n/2][n/2]; T a01[n/2][n/2]; T a10[n/2][n/2]; T a11[n/2][n/2]; divide_matrix_4(a, a00, a01, a10, a11); T b00[n/2][n/2]; T b01[n/2][n/2]; T b10[n/2][n/2]; T b11[n/2][n/2]; divide_matrix_4(b, b00, b01, b10, b11); T temp1[n/2][n/2]; T temp2[n/2][n/2]; square_matrix_multiply_recursive(a00, b00, temp1); square_matrix_multiply_recursive(a01, b10, temp2); T c00[n/2][n/2]; add_matrix(c00, temp1, temp2); square_matrix_multiply_recursive(a00, b01, temp1); square_matrix_multiply_recursive(a01, b11, temp2); T c01[n/2][n/2]; add_matrix(c01, temp1, temp2); square_matrix_multiply_recursive(a10, b00, temp1); square_matrix_multiply_recursive(a11, b10, temp2); T c10[n/2][n/2]; add_matrix(c10, temp1, temp2); square_matrix_multiply_recursive(a10, b01, temp1); square_matrix_multiply_recursive(a11, b11, temp2); T c11[n/2][n/2]; add_matrix(c11, temp1, temp2); combine_matrix_4(c, c00, c01, c10, c11); } } #endif
28.07
82
0.526541
zero4drift
0486ad6de881a87ab53291a8a8d2f8c110f20b2e
3,996
hpp
C++
includes/tools.hpp
Antip003/irc
973c4e1ee3d231c6aca1a434a735f236d4d55e77
[ "MIT" ]
1
2021-11-29T21:41:10.000Z
2021-11-29T21:41:10.000Z
includes/tools.hpp
Antip003/irc
973c4e1ee3d231c6aca1a434a735f236d4d55e77
[ "MIT" ]
null
null
null
includes/tools.hpp
Antip003/irc
973c4e1ee3d231c6aca1a434a735f236d4d55e77
[ "MIT" ]
null
null
null
#ifndef TOOLS_HPP # define TOOLS_HPP # include <string> # include <vector> # include "client.hpp" # include <list> # include "ircserv.hpp" typedef std::vector<std::string> t_strvect; typedef std::list<Client>::iterator t_citer; /****************************************************/ /* additional tools helping the server (tools.cpp) */ /****************************************************/ t_citer ft_findclientfd(t_citer const &begin, t_citer const &end, int fd); t_citer ft_findnick(t_citer const &begin, t_citer const &end, std::string const &nick); t_server *find_server_by_fd(int fd, IRCserv *serv); Client *find_client_by_nick(std::string const &nick, IRCserv *serv); Client *find_client_by_fd(int fd, IRCserv *serv); Channel *find_channel_by_name(const std::string &name, IRCserv *serv); t_server *find_server_by_mask(std::string const &mask, IRCserv *serv); t_server *find_server_by_name(std::string const &name, IRCserv *serv); Client *find_client_by_user_or_nick_and_host(std::string const &str, IRCserv *serv); Client *find_client_by_info(std::string const &info, IRCserv *serv); t_server *find_server_by_token(std::string const &token, IRCserv *serv); t_service *find_service_by_name(std::string const &name, IRCserv *serv); t_service *find_service_by_fd(int fd, IRCserv *serv); std::string get_servername_by_mask(std::string const &mask, IRCserv *serv); std::string get_servername_by_token(std::string const &token, IRCserv *serv); std::string get_hopcount_by_token(std::string const &token, IRCserv *serv); std::string ft_buildmsg(std::string const &from, std::string const &msgcode, std::string const &to, std::string const &cmd, std::string const &msg); void addtonickhistory(IRCserv *serv, t_citer const client); int nick_forward(IRCserv *serv, Client *client); bool remove_channel(Channel *channel, IRCserv *serv); bool remove_client_by_ptr(Client *ptr, IRCserv *serv); bool remove_client_by_nick(std::string const &nick, IRCserv *serv); void remove_server_by_name(std::string const &servername, IRCserv *serv); void self_cmd_squit(int fd, t_fd &fdref, IRCserv *serv); void self_cmd_quit(int fd, t_fd &fdref, IRCserv *serv, std::string const &reason); void self_service_quit(int fd, t_fd &fdref, IRCserv *serv); /****************************************************/ /* string manipulation functions (stringtools.cpp) */ /****************************************************/ t_strvect ft_splitstring(std::string msg, std::string const &delim); t_strvect ft_splitstring(std::string str, char delim); t_strvect ft_splitstringbyany(std::string msg, std::string const &delim); /** * ft_splitcmdbyspace * splits until the second occurance of ':' symbol * (special for irc msg format) */ t_strvect ft_splitcmdbyspace(std::string msg); std::string strvect_to_string(const t_strvect &split, char delim = ' ', size_t pos = 0, size_t len = std::string::npos); bool match(const char *s1, const char *s2); bool match(std::string const &s1, std::string const &s2); std::string ft_strtoupper(std::string const &str); std::string ft_strtolower(std::string const &str); std::string get_nick_from_info(std::string const &info); std::string get_mask_reply(Channel *channel, Client *client, std::string mode, IRCserv *serv); bool is_valid_mask(std::string mask); bool is_valid_serv_host_mask(std::string mask); // ft_tostring std::string ft_tostring(int val); std::string ft_tostring(long val); std::string ft_tostring(uint val); std::string ft_tostring(ulong val); // ft_sto* int ft_stoi(std::string const &str); long ft_stol(std::string const &str); uint ft_stou(std::string const &str); ulong ft_stoul(std::string const &str); /****************************************************/ /* time related functions (timetools.cpp) */ /****************************************************/ time_t ft_getcompiletime(void); time_t ft_getcurrenttime(void); std::string ft_timetostring(time_t rawtime); #endif
44.4
94
0.689189
Antip003
0486e86fa99138b7b45cf130d87e921ac515cd78
2,237
cc
C++
src/error_unittest.cc
PA-CAF/android_external_libweave
92e485f4b0b8311dc5b527798194170ab14614a4
[ "BSD-3-Clause" ]
null
null
null
src/error_unittest.cc
PA-CAF/android_external_libweave
92e485f4b0b8311dc5b527798194170ab14614a4
[ "BSD-3-Clause" ]
null
null
null
src/error_unittest.cc
PA-CAF/android_external_libweave
92e485f4b0b8311dc5b527798194170ab14614a4
[ "BSD-3-Clause" ]
3
2018-04-23T13:47:49.000Z
2018-10-21T08:16:19.000Z
// Copyright 2015 The Weave 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 <weave/error.h> #include <gtest/gtest.h> namespace weave { namespace { ErrorPtr GenerateNetworkError() { tracked_objects::Location loc("GenerateNetworkError", "error_unittest.cc", 15, ::tracked_objects::GetProgramCounter()); return Error::Create(loc, "not_found", "Resource not found"); } ErrorPtr GenerateHttpError() { ErrorPtr inner = GenerateNetworkError(); return Error::Create(FROM_HERE, "404", "Not found", std::move(inner)); } } // namespace TEST(Error, Single) { ErrorPtr err = GenerateNetworkError(); EXPECT_EQ("not_found", err->GetCode()); EXPECT_EQ("Resource not found", err->GetMessage()); EXPECT_EQ("GenerateNetworkError", err->GetLocation().function_name); EXPECT_EQ("error_unittest.cc", err->GetLocation().file_name); EXPECT_EQ(15, err->GetLocation().line_number); EXPECT_EQ(nullptr, err->GetInnerError()); EXPECT_TRUE(err->HasError("not_found")); EXPECT_FALSE(err->HasError("404")); EXPECT_FALSE(err->HasError("bar")); } TEST(Error, Nested) { ErrorPtr err = GenerateHttpError(); EXPECT_EQ("404", err->GetCode()); EXPECT_EQ("Not found", err->GetMessage()); EXPECT_NE(nullptr, err->GetInnerError()); EXPECT_TRUE(err->HasError("not_found")); EXPECT_TRUE(err->HasError("404")); EXPECT_FALSE(err->HasError("bar")); } TEST(Error, Clone) { ErrorPtr err = GenerateHttpError(); ErrorPtr clone = err->Clone(); const Error* error1 = err.get(); const Error* error2 = clone.get(); while (error1 && error2) { EXPECT_NE(error1, error2); EXPECT_EQ(error1->GetCode(), error2->GetCode()); EXPECT_EQ(error1->GetMessage(), error2->GetMessage()); EXPECT_EQ(error1->GetLocation().function_name, error2->GetLocation().function_name); EXPECT_EQ(error1->GetLocation().file_name, error2->GetLocation().file_name); EXPECT_EQ(error1->GetLocation().line_number, error2->GetLocation().line_number); error1 = error1->GetInnerError(); error2 = error2->GetInnerError(); } EXPECT_EQ(error1, error2); } } // namespace weave
31.957143
80
0.690657
PA-CAF
048bd0fb8b0f89822a91dd6eaedb9dbc39a9568e
8,856
cpp
C++
src/storage/test/ChainUpdateEdgeTest.cpp
wahello/nebula
e319615ca192925031867e4ca024b38b19a718c5
[ "Apache-2.0" ]
8,586
2019-05-15T07:25:51.000Z
2022-03-31T13:49:27.000Z
src/storage/test/ChainUpdateEdgeTest.cpp
wahello/nebula
e319615ca192925031867e4ca024b38b19a718c5
[ "Apache-2.0" ]
3,078
2019-05-15T08:14:02.000Z
2022-03-31T11:39:51.000Z
src/storage/test/ChainUpdateEdgeTest.cpp
wahello/nebula
e319615ca192925031867e4ca024b38b19a718c5
[ "Apache-2.0" ]
880
2019-05-15T07:36:10.000Z
2022-03-31T03:43:02.000Z
/* Copyright (c) 2021 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License. */ #include <folly/Benchmark.h> #include <folly/Format.h> #include <folly/String.h> #include <folly/container/Enumerate.h> #include <folly/init/Init.h> #include <gtest/gtest.h> #include <thrift/lib/cpp/util/EnumUtils.h> #include "common/fs/TempDir.h" #include "mock/MockCluster.h" #include "mock/MockData.h" #include "storage/CommonUtils.h" #include "storage/mutate/UpdateEdgeProcessor.h" #include "storage/test/ChainTestUtils.h" #include "storage/test/QueryTestUtils.h" #include "storage/test/TestUtils.h" #include "storage/transaction/ChainAddEdgesGroupProcessor.h" #include "storage/transaction/ChainAddEdgesProcessorLocal.h" #include "storage/transaction/ChainResumeProcessor.h" #include "storage/transaction/ChainUpdateEdgeProcessorRemote.h" #include "storage/transaction/ConsistUtil.h" namespace nebula { namespace storage { // using Code = ::nebula::cpp2::ErrorCode; constexpr int32_t mockSpaceId = 1; constexpr int32_t mockPartNum = 6; constexpr int32_t mockSpaceVidLen = 32; ChainTestUtils gTestUtil; ChainUpdateEdgeTestHelper helper; TEST(ChainUpdateEdgeTest, updateTest1) { fs::TempDir rootPath("/tmp/UpdateEdgeTest.XXXXXX"); mock::MockCluster cluster; cluster.initStorageKV(rootPath.path()); auto* env = cluster.storageEnv_.get(); auto mClient = MetaClientTestUpdater::makeDefaultMetaClient(); env->metaClient_ = mClient.get(); auto parts = cluster.getTotalParts(); EXPECT_TRUE(QueryTestUtils::mockEdgeData(env, parts, mockSpaceVidLen)); LOG(INFO) << "Test updateTest1..."; auto req = helper.makeDefaultRequest(); env->txnMan_->iClient_ = FakeInternalStorageClient::instance(env); auto reversedRequest = helper.reverseRequest(env, req); auto* proc = new FakeChainUpdateProcessor(env); LOG(INFO) << "proc: " << proc; auto f = proc->getFuture(); proc->process(req); auto resp = std::move(f).get(); EXPECT_TRUE(helper.checkResp2(resp)); EXPECT_TRUE(helper.checkRequestUpdated(env, req)); EXPECT_TRUE(helper.checkRequestUpdated(env, reversedRequest)); EXPECT_TRUE(helper.edgeExist(env, req)); EXPECT_FALSE(helper.primeExist(env, req)); EXPECT_FALSE(helper.doublePrimeExist(env, req)); } TEST(ChainUpdateEdgeTest, updateTest2) { fs::TempDir rootPath("/tmp/UpdateEdgeTest.XXXXXX"); mock::MockCluster cluster; cluster.initStorageKV(rootPath.path()); auto* env = cluster.storageEnv_.get(); auto mClient = MetaClientTestUpdater::makeDefaultMetaClient(); env->metaClient_ = mClient.get(); auto parts = cluster.getTotalParts(); EXPECT_TRUE(QueryTestUtils::mockEdgeData(env, parts, mockSpaceVidLen)); LOG(INFO) << "Test UpdateEdgeRequest..."; auto goodRequest = helper.makeDefaultRequest(); EXPECT_TRUE(helper.edgeExist(env, goodRequest)); EXPECT_FALSE(helper.primeExist(env, goodRequest)); EXPECT_FALSE(helper.doublePrimeExist(env, goodRequest)); auto badRequest = helper.makeInvalidRequest(); auto* proc = new FakeChainUpdateProcessor(env); auto f = proc->getFuture(); proc->rcProcessRemote = Code::E_KEY_NOT_FOUND; proc->process(badRequest); auto resp = std::move(f).get(); EXPECT_EQ(1, (*resp.result_ref()).failed_parts.size()); EXPECT_FALSE(helper.checkResp2(resp)); EXPECT_FALSE(helper.edgeExist(env, badRequest)); EXPECT_FALSE(helper.primeExist(env, badRequest)); EXPECT_FALSE(helper.doublePrimeExist(env, badRequest)); } TEST(ChainUpdateEdgeTest, updateTest3) { fs::TempDir rootPath("/tmp/UpdateEdgeTest.XXXXXX"); mock::MockCluster cluster; cluster.initStorageKV(rootPath.path()); auto* env = cluster.storageEnv_.get(); auto mClient = MetaClientTestUpdater::makeDefaultMetaClient(); env->metaClient_ = mClient.get(); auto parts = cluster.getTotalParts(); EXPECT_TRUE(QueryTestUtils::mockEdgeData(env, parts, mockSpaceVidLen)); LOG(INFO) << "Test UpdateEdgeRequest..."; auto goodRequest = helper.makeDefaultRequest(); EXPECT_TRUE(helper.edgeExist(env, goodRequest)); EXPECT_FALSE(helper.primeExist(env, goodRequest)); EXPECT_FALSE(helper.doublePrimeExist(env, goodRequest)); auto* proc = new FakeChainUpdateProcessor(env); auto f = proc->getFuture(); proc->rcProcessRemote = Code::SUCCEEDED; proc->rcProcessLocal = Code::SUCCEEDED; proc->process(goodRequest); auto resp = std::move(f).get(); EXPECT_TRUE(helper.edgeExist(env, goodRequest)); EXPECT_TRUE(helper.primeExist(env, goodRequest)); EXPECT_FALSE(helper.doublePrimeExist(env, goodRequest)); } TEST(ChainUpdateEdgeTest, updateTest4) { fs::TempDir rootPath("/tmp/UpdateEdgeTest.XXXXXX"); mock::MockCluster cluster; cluster.initStorageKV(rootPath.path()); auto* env = cluster.storageEnv_.get(); auto mClient = MetaClientTestUpdater::makeDefaultMetaClient(); env->metaClient_ = mClient.get(); auto parts = cluster.getTotalParts(); EXPECT_TRUE(QueryTestUtils::mockEdgeData(env, parts, mockSpaceVidLen)); LOG(INFO) << "Test UpdateEdgeRequest..."; auto goodRequest = helper.makeDefaultRequest(); EXPECT_TRUE(helper.edgeExist(env, goodRequest)); EXPECT_FALSE(helper.primeExist(env, goodRequest)); EXPECT_FALSE(helper.doublePrimeExist(env, goodRequest)); auto* proc = new FakeChainUpdateProcessor(env); auto f = proc->getFuture(); proc->rcProcessRemote = Code::E_RPC_FAILURE; proc->process(goodRequest); auto resp = std::move(f).get(); EXPECT_TRUE(helper.edgeExist(env, goodRequest)); EXPECT_FALSE(helper.primeExist(env, goodRequest)); EXPECT_TRUE(helper.doublePrimeExist(env, goodRequest)); } } // namespace storage } // namespace nebula int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); folly::init(&argc, &argv, false); google::SetStderrLogging(google::INFO); return RUN_ALL_TESTS(); } // ***** Test Plan ***** /** * @brief updateTest1 (update a normal edge will succeed) * previous update * prepareLocal succeed succeed * processRemote succeed succeed * processLocal succeed succeed * expect: edge true * edge prime false * double prime false * prop changed true */ /** * @brief updateTest2 (update non-exist edge will fail) * previous update * prepareLocal failed succeed * processRemote skip succeed * processLocal failed succeed * expect: edge false * edge prime false * double prime false * prop changed true */ /** * @brief updateTest3 (remote update failed will not change anything) * previous update * prepareLocal succeed succeed * processRemote skip failed * processLocal skip failed * expect: edge true * edge prime true * double prime false * prop changed false */ /** * @brief updateTest4 (remote update outdate will add double prime) * previous update * prepareLocal succeed succeed * processRemote skip outdate * processLocal skip succeed * expect: edge true * edge prime false * double prime true * prop changed false */ // /** // * @brief updateTest5 (update1 + resume) // * previous update // * prepareLocal succeed succeed // * processRemote skip succeed // * processLocal succeed succeed // * expect: edge true // * edge prime false // * double prime false // * prop changed true // */ // /** // * @brief updateTest6 (update2 + resume) // * previous update // * prepareLocal failed succeed // * processRemote skip succeed // * processLocal failed succeed // * expect: edge false // * edge prime false // * double prime false // * prop changed true // */ // /** // * @brief updateTest7 (updateTest3 + resume) // * previous resume // * prepareLocal succeed succeed // * processRemote skip failed // * processLocal skip failed // * expect: edge true // * edge prime true // * double prime false // * prop changed false // */ // /** // * @brief updateTest8 // * previous resume // * prepareLocal succeed succeed // * processRemote skip outdate // * processLocal skip succeed // * expect: edge true // * edge prime false // * double prime true // * prop changed false // */ // ***** End Test Plan *****
33.044776
73
0.662037
wahello
04906ae0faf8bee958edcd67b81fb1a79a92cc14
7,451
cpp
C++
pxr/base/lib/gf/wrapTransform.cpp
navefx/YuksUSD
56c2e1def36ee07121f4ecb349c1626472b3c338
[ "AML" ]
18
2017-10-28T22:37:48.000Z
2022-01-26T12:00:24.000Z
pxr/base/lib/gf/wrapTransform.cpp
piscees/USD
65320d266057ae0a68626217f54a0298ac092799
[ "AML" ]
1
2021-08-14T23:57:51.000Z
2021-08-14T23:57:51.000Z
pxr/base/lib/gf/wrapTransform.cpp
piscees/USD
65320d266057ae0a68626217f54a0298ac092799
[ "AML" ]
4
2018-06-14T18:14:59.000Z
2021-09-13T22:20:50.000Z
// // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "pxr/pxr.h" #include "pxr/base/gf/matrix4d.h" #include "pxr/base/gf/rotation.h" #include "pxr/base/gf/transform.h" #include "pxr/base/gf/vec3d.h" #include "pxr/base/tf/pyUtils.h" #include "pxr/base/tf/wrapTypeHelpers.h" #include <boost/python/args.hpp> #include <boost/python/class.hpp> #include <boost/python/copy_const_reference.hpp> #include <boost/python/init.hpp> #include <boost/python/operators.hpp> #include <boost/python/return_arg.hpp> #include <string> using std::string; using std::vector; using namespace boost::python; PXR_NAMESPACE_USING_DIRECTIVE namespace { static GfVec3d _NoTranslation() { return GfVec3d(0,0,0); } static GfVec3d _IdentityScale() { return GfVec3d(1,1,1); } static GfRotation _NoRotation() { return GfRotation( GfVec3d::XAxis(), 0.0 ); } static string _Repr(GfTransform const &self) { string prefix = TF_PY_REPR_PREFIX + "Transform("; string indent(prefix.size(), ' '); // Use keyword args for clarity. // Only use args that do not match the defaults. vector<string> kwargs; if (self.GetTranslation() != _NoTranslation()) kwargs.push_back( "translation = " + TfPyRepr(self.GetTranslation()) ); if (self.GetRotation() != _NoRotation()) kwargs.push_back( "rotation = " + TfPyRepr(self.GetRotation()) ); if (self.GetScale() != _IdentityScale()) kwargs.push_back( "scale = " + TfPyRepr(self.GetScale()) ); if (self.GetPivotPosition() != _NoTranslation()) kwargs.push_back( "pivotPosition = " + TfPyRepr(self.GetPivotPosition()) ); if (self.GetPivotOrientation() != _NoRotation()) kwargs.push_back( "pivotOrientation = " + TfPyRepr(self.GetPivotOrientation()) ); return prefix + TfStringJoin(kwargs, string(", \n" + indent).c_str()) + ")"; } } // anonymous namespace void wrapTransform() { typedef GfTransform This; class_<This>( "Transform", init<>() ) .def(init<const GfVec3d&, const GfRotation&, const GfVec3d&, const GfVec3d&, const GfRotation&> ((args("translation") = _NoTranslation(), args("rotation") = _NoRotation(), args("scale") = _IdentityScale(), args("pivotPosition") = _NoTranslation(), args("pivotOrientation") = _NoRotation()), "Initializer used by 3x code.")) // This is the constructor used by 2x code. Leave the initial // arguments as non-default to force the user to provide enough // values to indicate her intentions. .def(init<const GfVec3d &, const GfRotation &, const GfRotation&, const GfVec3d &, const GfVec3d &> ((args("scale"), args("pivotOrientation"), args("rotation"), args("pivotPosition"), args("translation")), "Initializer used by old 2x code. (Deprecated)")) .def(init<const GfMatrix4d &>()) .def( TfTypePythonClass() ) .def( "Set", (This & (This::*)( const GfVec3d &, const GfRotation &, const GfVec3d &, const GfVec3d &, const GfRotation & ))( &This::Set ), return_self<>(), (args("translation") = _NoTranslation(), args("rotation") = _NoRotation(), args("scale") = _IdentityScale(), args("pivotPosition") = _NoTranslation(), args("pivotOrientation") = _NoRotation())) .def( "Set", (This & (This::*)( const GfVec3d &, const GfRotation &, const GfRotation &, const GfVec3d &, const GfVec3d &))&This::Set, return_self<>(), (args("scale"), args("pivotOrientation"), args("rotation"), args("pivotPosition"), args("translation")), "Set method used by old 2x code. (Deprecated)") .def( "SetMatrix", &This::SetMatrix, return_self<>() ) .def( "GetMatrix", &This::GetMatrix ) .def( "SetIdentity", &This::SetIdentity, return_self<>() ) .add_property( "translation", make_function (&This::GetTranslation, return_value_policy<return_by_value>()), &This::SetTranslation ) .add_property( "rotation", make_function (&This::GetRotation, return_value_policy<return_by_value>()), &This::SetRotation ) .add_property( "scale", make_function (&This::GetScale, return_value_policy<return_by_value>()), &This::SetScale ) .add_property( "pivotPosition", make_function (&This::GetPivotPosition, return_value_policy<return_by_value>()), &This::SetPivotPosition ) .add_property( "pivotOrientation", make_function (&This::GetPivotOrientation, return_value_policy<return_by_value>()), &This::SetPivotOrientation ) .def("GetTranslation", &This::GetTranslation, return_value_policy<return_by_value>()) .def("SetTranslation", &This::SetTranslation ) .def("GetRotation", &This::GetRotation, return_value_policy<return_by_value>()) .def("SetRotation", &This::SetRotation) .def("GetScale", &This::GetScale, return_value_policy<return_by_value>()) .def("SetScale", &This::SetScale ) .def("GetPivotPosition", &This::GetPivotPosition, return_value_policy<return_by_value>()) .def("SetPivotPosition", &This::SetPivotPosition ) .def("GetPivotOrientation", &This::GetPivotOrientation, return_value_policy<return_by_value>()) .def("SetPivotOrientation", &This::SetPivotOrientation ) .def( str(self) ) .def( self == self ) .def( self != self ) .def( self *= self ) .def( self * self ) .def("__repr__", _Repr) ; }
37.255
80
0.584351
navefx
0493347ebe519410f53cd5c82463ebfa6062dcd3
58,391
cpp
C++
pdfium_lib/pdfium/third_party/icu/source/tools/genrb/reslist.cpp
qingqibing/vs_pdfium
6d009d478c3e761fac49b357d81532c3ed7aad9f
[ "BSD-3-Clause" ]
25
2019-05-07T16:16:40.000Z
2022-03-30T09:04:00.000Z
pdfium_lib/pdfium/third_party/icu/source/tools/genrb/reslist.cpp
qingqibing/vs_pdfium
6d009d478c3e761fac49b357d81532c3ed7aad9f
[ "BSD-3-Clause" ]
4
2020-10-20T13:09:56.000Z
2021-04-10T00:23:35.000Z
deps/icu-small/source/tools/genrb/reslist.cpp
krithiva/node-http-demo1
1e75bbc2009bbe49d5ac3b5aad333dcc57c41d56
[ "Apache-2.0" ]
11
2019-09-11T20:43:10.000Z
2022-03-30T09:04:01.000Z
// © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /* ******************************************************************************* * * Copyright (C) 2000-2015, International Business Machines * Corporation and others. All Rights Reserved. * ******************************************************************************* * * File reslist.cpp * * Modification History: * * Date Name Description * 02/21/00 weiv Creation. ******************************************************************************* */ // Safer use of UnicodeString. #ifndef UNISTR_FROM_CHAR_EXPLICIT # define UNISTR_FROM_CHAR_EXPLICIT explicit #endif // Less important, but still a good idea. #ifndef UNISTR_FROM_STRING_EXPLICIT # define UNISTR_FROM_STRING_EXPLICIT explicit #endif #include <assert.h> #include <stdio.h> #include "unicode/localpointer.h" #include "reslist.h" #include "unewdata.h" #include "unicode/ures.h" #include "unicode/putil.h" #include "errmsg.h" #include "uarrsort.h" #include "uelement.h" #include "uhash.h" #include "uinvchar.h" #include "ustr_imp.h" #include "unicode/utf16.h" /* * Align binary data at a 16-byte offset from the start of the resource bundle, * to be safe for any data type it may contain. */ #define BIN_ALIGNMENT 16 // This numeric constant must be at least 1. // If StringResource.fNumUnitsSaved == 0 then the string occurs only once, // and it makes no sense to move it to the pool bundle. // The larger the threshold for fNumUnitsSaved // the smaller the savings, and the smaller the pool bundle. // We trade some total size reduction to reduce the pool bundle a bit, // so that one can reasonably save data size by // removing bundle files without rebuilding the pool bundle. // This can also help to keep the pool and total (pool+local) string indexes // within 16 bits, that is, within range of Table16 and Array16 containers. #ifndef GENRB_MIN_16BIT_UNITS_SAVED_FOR_POOL_STRING # define GENRB_MIN_16BIT_UNITS_SAVED_FOR_POOL_STRING 10 #endif U_NAMESPACE_USE static UBool gIncludeCopyright = FALSE; static UBool gUsePoolBundle = FALSE; static UBool gIsDefaultFormatVersion = TRUE; static int32_t gFormatVersion = 3; /* How do we store string values? */ enum { STRINGS_UTF16_V1, /* formatVersion 1: int length + UChars + NUL + padding to 4 bytes */ STRINGS_UTF16_V2 /* formatVersion 2 & up: optional length in 1..3 UChars + UChars + NUL */ }; static const int32_t MAX_IMPLICIT_STRING_LENGTH = 40; /* do not store the length explicitly for such strings */ static const ResFile kNoPoolBundle; /* * res_none() returns the address of kNoResource, * for use in non-error cases when no resource is to be added to the bundle. * (NULL is used in error cases.) */ static SResource kNoResource; // TODO: const static UDataInfo dataInfo= { sizeof(UDataInfo), 0, U_IS_BIG_ENDIAN, U_CHARSET_FAMILY, sizeof(UChar), 0, {0x52, 0x65, 0x73, 0x42}, /* dataFormat="ResB" */ {1, 3, 0, 0}, /* formatVersion */ {1, 4, 0, 0} /* dataVersion take a look at version inside parsed resb*/ }; static const UVersionInfo gFormatVersions[4] = { /* indexed by a major-formatVersion integer */ { 0, 0, 0, 0 }, { 1, 3, 0, 0 }, { 2, 0, 0, 0 }, { 3, 0, 0, 0 } }; // Remember to update genrb.h GENRB_VERSION when changing the data format. // (Or maybe we should remove GENRB_VERSION and report the ICU version number?) static uint8_t calcPadding(uint32_t size) { /* returns space we need to pad */ return (uint8_t) ((size % sizeof(uint32_t)) ? (sizeof(uint32_t) - (size % sizeof(uint32_t))) : 0); } void setIncludeCopyright(UBool val){ gIncludeCopyright=val; } UBool getIncludeCopyright(void){ return gIncludeCopyright; } void setFormatVersion(int32_t formatVersion) { gIsDefaultFormatVersion = FALSE; gFormatVersion = formatVersion; } int32_t getFormatVersion() { return gFormatVersion; } void setUsePoolBundle(UBool use) { gUsePoolBundle = use; } // TODO: return const pointer, or find another way to express "none" struct SResource* res_none() { return &kNoResource; } SResource::SResource() : fType(URES_NONE), fWritten(FALSE), fRes(RES_BOGUS), fRes16(-1), fKey(-1), fKey16(-1), line(0), fNext(NULL) { ustr_init(&fComment); } SResource::SResource(SRBRoot *bundle, const char *tag, int8_t type, const UString* comment, UErrorCode &errorCode) : fType(type), fWritten(FALSE), fRes(RES_BOGUS), fRes16(-1), fKey(bundle != NULL ? bundle->addTag(tag, errorCode) : -1), fKey16(-1), line(0), fNext(NULL) { ustr_init(&fComment); if(comment != NULL) { ustr_cpy(&fComment, comment, &errorCode); } } SResource::~SResource() { ustr_deinit(&fComment); } ContainerResource::~ContainerResource() { SResource *current = fFirst; while (current != NULL) { SResource *next = current->fNext; delete current; current = next; } } TableResource::~TableResource() {} // TODO: clarify that containers adopt new items, even in error cases; use LocalPointer void TableResource::add(SResource *res, int linenumber, UErrorCode &errorCode) { if (U_FAILURE(errorCode) || res == NULL || res == &kNoResource) { return; } /* remember this linenumber to report to the user if there is a duplicate key */ res->line = linenumber; /* here we need to traverse the list */ ++fCount; /* is the list still empty? */ if (fFirst == NULL) { fFirst = res; res->fNext = NULL; return; } const char *resKeyString = fRoot->fKeys + res->fKey; SResource *current = fFirst; SResource *prev = NULL; while (current != NULL) { const char *currentKeyString = fRoot->fKeys + current->fKey; int diff; /* * formatVersion 1: compare key strings in native-charset order * formatVersion 2 and up: compare key strings in ASCII order */ if (gFormatVersion == 1 || U_CHARSET_FAMILY == U_ASCII_FAMILY) { diff = uprv_strcmp(currentKeyString, resKeyString); } else { diff = uprv_compareInvCharsAsAscii(currentKeyString, resKeyString); } if (diff < 0) { prev = current; current = current->fNext; } else if (diff > 0) { /* we're either in front of the list, or in the middle */ if (prev == NULL) { /* front of the list */ fFirst = res; } else { /* middle of the list */ prev->fNext = res; } res->fNext = current; return; } else { /* Key already exists! ERROR! */ error(linenumber, "duplicate key '%s' in table, first appeared at line %d", currentKeyString, current->line); errorCode = U_UNSUPPORTED_ERROR; return; } } /* end of list */ prev->fNext = res; res->fNext = NULL; } ArrayResource::~ArrayResource() {} void ArrayResource::add(SResource *res) { if (res != NULL && res != &kNoResource) { if (fFirst == NULL) { fFirst = res; } else { fLast->fNext = res; } fLast = res; ++fCount; } } PseudoListResource::~PseudoListResource() {} void PseudoListResource::add(SResource *res) { if (res != NULL && res != &kNoResource) { res->fNext = fFirst; fFirst = res; ++fCount; } } StringBaseResource::StringBaseResource(SRBRoot *bundle, const char *tag, int8_t type, const UChar *value, int32_t len, const UString* comment, UErrorCode &errorCode) : SResource(bundle, tag, type, comment, errorCode) { if (len == 0 && gFormatVersion > 1) { fRes = URES_MAKE_EMPTY_RESOURCE(type); fWritten = TRUE; return; } fString.setTo(ConstChar16Ptr(value), len); fString.getTerminatedBuffer(); // Some code relies on NUL-termination. if (U_SUCCESS(errorCode) && fString.isBogus()) { errorCode = U_MEMORY_ALLOCATION_ERROR; } } StringBaseResource::StringBaseResource(SRBRoot *bundle, int8_t type, const icu::UnicodeString &value, UErrorCode &errorCode) : SResource(bundle, NULL, type, NULL, errorCode), fString(value) { if (value.isEmpty() && gFormatVersion > 1) { fRes = URES_MAKE_EMPTY_RESOURCE(type); fWritten = TRUE; return; } fString.getTerminatedBuffer(); // Some code relies on NUL-termination. if (U_SUCCESS(errorCode) && fString.isBogus()) { errorCode = U_MEMORY_ALLOCATION_ERROR; } } // Pool bundle string, alias the buffer. Guaranteed NUL-terminated and not empty. StringBaseResource::StringBaseResource(int8_t type, const UChar *value, int32_t len, UErrorCode &errorCode) : SResource(NULL, NULL, type, NULL, errorCode), fString(TRUE, value, len) { assert(len > 0); assert(!fString.isBogus()); } StringBaseResource::~StringBaseResource() {} static int32_t U_CALLCONV string_hash(const UElement key) { const StringResource *res = static_cast<const StringResource *>(key.pointer); return res->fString.hashCode(); } static UBool U_CALLCONV string_comp(const UElement key1, const UElement key2) { const StringResource *res1 = static_cast<const StringResource *>(key1.pointer); const StringResource *res2 = static_cast<const StringResource *>(key2.pointer); return res1->fString == res2->fString; } StringResource::~StringResource() {} AliasResource::~AliasResource() {} IntResource::IntResource(SRBRoot *bundle, const char *tag, int32_t value, const UString* comment, UErrorCode &errorCode) : SResource(bundle, tag, URES_INT, comment, errorCode) { fValue = value; fRes = URES_MAKE_RESOURCE(URES_INT, value & RES_MAX_OFFSET); fWritten = TRUE; } IntResource::~IntResource() {} IntVectorResource::IntVectorResource(SRBRoot *bundle, const char *tag, const UString* comment, UErrorCode &errorCode) : SResource(bundle, tag, URES_INT_VECTOR, comment, errorCode), fCount(0), fArray(new uint32_t[RESLIST_MAX_INT_VECTOR]) { if (fArray == NULL) { errorCode = U_MEMORY_ALLOCATION_ERROR; return; } } IntVectorResource::~IntVectorResource() { delete[] fArray; } void IntVectorResource::add(int32_t value, UErrorCode &errorCode) { if (U_SUCCESS(errorCode)) { fArray[fCount++] = value; } } BinaryResource::BinaryResource(SRBRoot *bundle, const char *tag, uint32_t length, uint8_t *data, const char* fileName, const UString* comment, UErrorCode &errorCode) : SResource(bundle, tag, URES_BINARY, comment, errorCode), fLength(length), fData(NULL), fFileName(NULL) { if (U_FAILURE(errorCode)) { return; } if (fileName != NULL && *fileName != 0){ fFileName = new char[uprv_strlen(fileName)+1]; if (fFileName == NULL) { errorCode = U_MEMORY_ALLOCATION_ERROR; return; } uprv_strcpy(fFileName, fileName); } if (length > 0) { fData = new uint8_t[length]; if (fData == NULL) { errorCode = U_MEMORY_ALLOCATION_ERROR; return; } uprv_memcpy(fData, data, length); } else { if (gFormatVersion > 1) { fRes = URES_MAKE_EMPTY_RESOURCE(URES_BINARY); fWritten = TRUE; } } } BinaryResource::~BinaryResource() { delete[] fData; delete[] fFileName; } /* Writing Functions */ void StringResource::handlePreflightStrings(SRBRoot *bundle, UHashtable *stringSet, UErrorCode &errorCode) { assert(fSame == NULL); fSame = static_cast<StringResource *>(uhash_get(stringSet, this)); if (fSame != NULL) { // This is a duplicate of a pool bundle string or of an earlier-visited string. if (++fSame->fNumCopies == 1) { assert(fSame->fWritten); int32_t poolStringIndex = (int32_t)RES_GET_OFFSET(fSame->fRes); if (poolStringIndex >= bundle->fPoolStringIndexLimit) { bundle->fPoolStringIndexLimit = poolStringIndex + 1; } } return; } /* Put this string into the set for finding duplicates. */ fNumCopies = 1; uhash_put(stringSet, this, this, &errorCode); if (bundle->fStringsForm != STRINGS_UTF16_V1) { int32_t len = length(); if (len <= MAX_IMPLICIT_STRING_LENGTH && !U16_IS_TRAIL(fString[0]) && fString.indexOf((UChar)0) < 0) { /* * This string will be stored without an explicit length. * Runtime will detect !U16_IS_TRAIL(s[0]) and call u_strlen(). */ fNumCharsForLength = 0; } else if (len <= 0x3ee) { fNumCharsForLength = 1; } else if (len <= 0xfffff) { fNumCharsForLength = 2; } else { fNumCharsForLength = 3; } bundle->f16BitStringsLength += fNumCharsForLength + len + 1; /* +1 for the NUL */ } } void ContainerResource::handlePreflightStrings(SRBRoot *bundle, UHashtable *stringSet, UErrorCode &errorCode) { for (SResource *current = fFirst; current != NULL; current = current->fNext) { current->preflightStrings(bundle, stringSet, errorCode); } } void SResource::preflightStrings(SRBRoot *bundle, UHashtable *stringSet, UErrorCode &errorCode) { if (U_FAILURE(errorCode)) { return; } if (fRes != RES_BOGUS) { /* * The resource item word was already precomputed, which means * no further data needs to be written. * This might be an integer, or an empty string/binary/etc. */ return; } handlePreflightStrings(bundle, stringSet, errorCode); } void SResource::handlePreflightStrings(SRBRoot * /*bundle*/, UHashtable * /*stringSet*/, UErrorCode & /*errorCode*/) { /* Neither a string nor a container. */ } int32_t SRBRoot::makeRes16(uint32_t resWord) const { if (resWord == 0) { return 0; /* empty string */ } uint32_t type = RES_GET_TYPE(resWord); int32_t offset = (int32_t)RES_GET_OFFSET(resWord); if (type == URES_STRING_V2) { assert(offset > 0); if (offset < fPoolStringIndexLimit) { if (offset < fPoolStringIndex16Limit) { return offset; } } else { offset = offset - fPoolStringIndexLimit + fPoolStringIndex16Limit; if (offset <= 0xffff) { return offset; } } } return -1; } int32_t SRBRoot::mapKey(int32_t oldpos) const { const KeyMapEntry *map = fKeyMap; if (map == NULL) { return oldpos; } int32_t i, start, limit; /* do a binary search for the old, pre-compactKeys() key offset */ start = fUsePoolBundle->fKeysCount; limit = start + fKeysCount; while (start < limit - 1) { i = (start + limit) / 2; if (oldpos < map[i].oldpos) { limit = i; } else { start = i; } } assert(oldpos == map[start].oldpos); return map[start].newpos; } /* * Only called for UTF-16 v1 strings and duplicate UTF-16 v2 strings. * For unique UTF-16 v2 strings, write16() sees fRes != RES_BOGUS * and exits early. */ void StringResource::handleWrite16(SRBRoot * /*bundle*/) { SResource *same; if ((same = fSame) != NULL) { /* This is a duplicate. */ assert(same->fRes != RES_BOGUS && same->fWritten); fRes = same->fRes; fWritten = same->fWritten; } } void ContainerResource::writeAllRes16(SRBRoot *bundle) { for (SResource *current = fFirst; current != NULL; current = current->fNext) { bundle->f16BitUnits.append((UChar)current->fRes16); } fWritten = TRUE; } void ArrayResource::handleWrite16(SRBRoot *bundle) { if (fCount == 0 && gFormatVersion > 1) { fRes = URES_MAKE_EMPTY_RESOURCE(URES_ARRAY); fWritten = TRUE; return; } int32_t res16 = 0; for (SResource *current = fFirst; current != NULL; current = current->fNext) { current->write16(bundle); res16 |= current->fRes16; } if (fCount <= 0xffff && res16 >= 0 && gFormatVersion > 1) { fRes = URES_MAKE_RESOURCE(URES_ARRAY16, bundle->f16BitUnits.length()); bundle->f16BitUnits.append((UChar)fCount); writeAllRes16(bundle); } } void TableResource::handleWrite16(SRBRoot *bundle) { if (fCount == 0 && gFormatVersion > 1) { fRes = URES_MAKE_EMPTY_RESOURCE(URES_TABLE); fWritten = TRUE; return; } /* Find the smallest table type that fits the data. */ int32_t key16 = 0; int32_t res16 = 0; for (SResource *current = fFirst; current != NULL; current = current->fNext) { current->write16(bundle); key16 |= current->fKey16; res16 |= current->fRes16; } if(fCount > (uint32_t)bundle->fMaxTableLength) { bundle->fMaxTableLength = fCount; } if (fCount <= 0xffff && key16 >= 0) { if (res16 >= 0 && gFormatVersion > 1) { /* 16-bit count, key offsets and values */ fRes = URES_MAKE_RESOURCE(URES_TABLE16, bundle->f16BitUnits.length()); bundle->f16BitUnits.append((UChar)fCount); for (SResource *current = fFirst; current != NULL; current = current->fNext) { bundle->f16BitUnits.append((UChar)current->fKey16); } writeAllRes16(bundle); } else { /* 16-bit count, 16-bit key offsets, 32-bit values */ fTableType = URES_TABLE; } } else { /* 32-bit count, key offsets and values */ fTableType = URES_TABLE32; } } void PseudoListResource::handleWrite16(SRBRoot * /*bundle*/) { fRes = URES_MAKE_EMPTY_RESOURCE(URES_TABLE); fWritten = TRUE; } void SResource::write16(SRBRoot *bundle) { if (fKey >= 0) { // A tagged resource has a non-negative key index into the parsed key strings. // compactKeys() built a map from parsed key index to the final key index. // After the mapping, negative key indexes are used for shared pool bundle keys. fKey = bundle->mapKey(fKey); // If the key index fits into a Key16 for a Table or Table16, // then set the fKey16 field accordingly. // Otherwise keep it at -1. if (fKey >= 0) { if (fKey < bundle->fLocalKeyLimit) { fKey16 = fKey; } } else { int32_t poolKeyIndex = fKey & 0x7fffffff; if (poolKeyIndex <= 0xffff) { poolKeyIndex += bundle->fLocalKeyLimit; if (poolKeyIndex <= 0xffff) { fKey16 = poolKeyIndex; } } } } /* * fRes != RES_BOGUS: * The resource item word was already precomputed, which means * no further data needs to be written. * This might be an integer, or an empty or UTF-16 v2 string, * an empty binary, etc. */ if (fRes == RES_BOGUS) { handleWrite16(bundle); } // Compute fRes16 for precomputed as well as just-computed fRes. fRes16 = bundle->makeRes16(fRes); } void SResource::handleWrite16(SRBRoot * /*bundle*/) { /* Only a few resource types write 16-bit units. */ } /* * Only called for UTF-16 v1 strings, and for aliases. * For UTF-16 v2 strings, preWrite() sees fRes != RES_BOGUS * and exits early. */ void StringBaseResource::handlePreWrite(uint32_t *byteOffset) { /* Write the UTF-16 v1 string. */ fRes = URES_MAKE_RESOURCE(fType, *byteOffset >> 2); *byteOffset += 4 + (length() + 1) * U_SIZEOF_UCHAR; } void IntVectorResource::handlePreWrite(uint32_t *byteOffset) { if (fCount == 0 && gFormatVersion > 1) { fRes = URES_MAKE_EMPTY_RESOURCE(URES_INT_VECTOR); fWritten = TRUE; } else { fRes = URES_MAKE_RESOURCE(URES_INT_VECTOR, *byteOffset >> 2); *byteOffset += (1 + fCount) * 4; } } void BinaryResource::handlePreWrite(uint32_t *byteOffset) { uint32_t pad = 0; uint32_t dataStart = *byteOffset + sizeof(fLength); if (dataStart % BIN_ALIGNMENT) { pad = (BIN_ALIGNMENT - dataStart % BIN_ALIGNMENT); *byteOffset += pad; /* pad == 4 or 8 or 12 */ } fRes = URES_MAKE_RESOURCE(URES_BINARY, *byteOffset >> 2); *byteOffset += 4 + fLength; } void ContainerResource::preWriteAllRes(uint32_t *byteOffset) { for (SResource *current = fFirst; current != NULL; current = current->fNext) { current->preWrite(byteOffset); } } void ArrayResource::handlePreWrite(uint32_t *byteOffset) { preWriteAllRes(byteOffset); fRes = URES_MAKE_RESOURCE(URES_ARRAY, *byteOffset >> 2); *byteOffset += (1 + fCount) * 4; } void TableResource::handlePreWrite(uint32_t *byteOffset) { preWriteAllRes(byteOffset); if (fTableType == URES_TABLE) { /* 16-bit count, 16-bit key offsets, 32-bit values */ fRes = URES_MAKE_RESOURCE(URES_TABLE, *byteOffset >> 2); *byteOffset += 2 + fCount * 6; } else { /* 32-bit count, key offsets and values */ fRes = URES_MAKE_RESOURCE(URES_TABLE32, *byteOffset >> 2); *byteOffset += 4 + fCount * 8; } } void SResource::preWrite(uint32_t *byteOffset) { if (fRes != RES_BOGUS) { /* * The resource item word was already precomputed, which means * no further data needs to be written. * This might be an integer, or an empty or UTF-16 v2 string, * an empty binary, etc. */ return; } handlePreWrite(byteOffset); *byteOffset += calcPadding(*byteOffset); } void SResource::handlePreWrite(uint32_t * /*byteOffset*/) { assert(FALSE); } /* * Only called for UTF-16 v1 strings, and for aliases. For UTF-16 v2 strings, * write() sees fWritten and exits early. */ void StringBaseResource::handleWrite(UNewDataMemory *mem, uint32_t *byteOffset) { /* Write the UTF-16 v1 string. */ int32_t len = length(); udata_write32(mem, len); udata_writeUString(mem, getBuffer(), len + 1); *byteOffset += 4 + (len + 1) * U_SIZEOF_UCHAR; fWritten = TRUE; } void ContainerResource::writeAllRes(UNewDataMemory *mem, uint32_t *byteOffset) { uint32_t i = 0; for (SResource *current = fFirst; current != NULL; ++i, current = current->fNext) { current->write(mem, byteOffset); } assert(i == fCount); } void ContainerResource::writeAllRes32(UNewDataMemory *mem, uint32_t *byteOffset) { for (SResource *current = fFirst; current != NULL; current = current->fNext) { udata_write32(mem, current->fRes); } *byteOffset += fCount * 4; } void ArrayResource::handleWrite(UNewDataMemory *mem, uint32_t *byteOffset) { writeAllRes(mem, byteOffset); udata_write32(mem, fCount); *byteOffset += 4; writeAllRes32(mem, byteOffset); } void IntVectorResource::handleWrite(UNewDataMemory *mem, uint32_t *byteOffset) { udata_write32(mem, fCount); for(uint32_t i = 0; i < fCount; ++i) { udata_write32(mem, fArray[i]); } *byteOffset += (1 + fCount) * 4; } void BinaryResource::handleWrite(UNewDataMemory *mem, uint32_t *byteOffset) { uint32_t pad = 0; uint32_t dataStart = *byteOffset + sizeof(fLength); if (dataStart % BIN_ALIGNMENT) { pad = (BIN_ALIGNMENT - dataStart % BIN_ALIGNMENT); udata_writePadding(mem, pad); /* pad == 4 or 8 or 12 */ *byteOffset += pad; } udata_write32(mem, fLength); if (fLength > 0) { udata_writeBlock(mem, fData, fLength); } *byteOffset += 4 + fLength; } void TableResource::handleWrite(UNewDataMemory *mem, uint32_t *byteOffset) { writeAllRes(mem, byteOffset); if(fTableType == URES_TABLE) { udata_write16(mem, (uint16_t)fCount); for (SResource *current = fFirst; current != NULL; current = current->fNext) { udata_write16(mem, current->fKey16); } *byteOffset += (1 + fCount)* 2; if ((fCount & 1) == 0) { /* 16-bit count and even number of 16-bit key offsets need padding before 32-bit resource items */ udata_writePadding(mem, 2); *byteOffset += 2; } } else /* URES_TABLE32 */ { udata_write32(mem, fCount); for (SResource *current = fFirst; current != NULL; current = current->fNext) { udata_write32(mem, (uint32_t)current->fKey); } *byteOffset += (1 + fCount)* 4; } writeAllRes32(mem, byteOffset); } void SResource::write(UNewDataMemory *mem, uint32_t *byteOffset) { if (fWritten) { assert(fRes != RES_BOGUS); return; } handleWrite(mem, byteOffset); uint8_t paddingSize = calcPadding(*byteOffset); if (paddingSize > 0) { udata_writePadding(mem, paddingSize); *byteOffset += paddingSize; } fWritten = TRUE; } void SResource::handleWrite(UNewDataMemory * /*mem*/, uint32_t * /*byteOffset*/) { assert(FALSE); } void SRBRoot::write(const char *outputDir, const char *outputPkg, char *writtenFilename, int writtenFilenameLen, UErrorCode &errorCode) { UNewDataMemory *mem = NULL; uint32_t byteOffset = 0; uint32_t top, size; char dataName[1024]; int32_t indexes[URES_INDEX_TOP]; compactKeys(errorCode); /* * Add padding bytes to fKeys so that fKeysTop is 4-aligned. * Safe because the capacity is a multiple of 4. */ while (fKeysTop & 3) { fKeys[fKeysTop++] = (char)0xaa; } /* * In URES_TABLE, use all local key offsets that fit into 16 bits, * and use the remaining 16-bit offsets for pool key offsets * if there are any. * If there are no local keys, then use the whole 16-bit space * for pool key offsets. * Note: This cannot be changed without changing the major formatVersion. */ if (fKeysBottom < fKeysTop) { if (fKeysTop <= 0x10000) { fLocalKeyLimit = fKeysTop; } else { fLocalKeyLimit = 0x10000; } } else { fLocalKeyLimit = 0; } UHashtable *stringSet; if (gFormatVersion > 1) { stringSet = uhash_open(string_hash, string_comp, string_comp, &errorCode); if (U_SUCCESS(errorCode) && fUsePoolBundle != NULL && fUsePoolBundle->fStrings != NULL) { for (SResource *current = fUsePoolBundle->fStrings->fFirst; current != NULL; current = current->fNext) { StringResource *sr = static_cast<StringResource *>(current); sr->fNumCopies = 0; sr->fNumUnitsSaved = 0; uhash_put(stringSet, sr, sr, &errorCode); } } fRoot->preflightStrings(this, stringSet, errorCode); } else { stringSet = NULL; } if (fStringsForm == STRINGS_UTF16_V2 && f16BitStringsLength > 0) { compactStringsV2(stringSet, errorCode); } uhash_close(stringSet); if (U_FAILURE(errorCode)) { return; } int32_t formatVersion = gFormatVersion; if (fPoolStringIndexLimit != 0) { int32_t sum = fPoolStringIndexLimit + fLocalStringIndexLimit; if ((sum - 1) > RES_MAX_OFFSET) { errorCode = U_BUFFER_OVERFLOW_ERROR; return; } if (fPoolStringIndexLimit < 0x10000 && sum <= 0x10000) { // 16-bit indexes work for all pool + local strings. fPoolStringIndex16Limit = fPoolStringIndexLimit; } else { // Set the pool index threshold so that 16-bit indexes work // for some pool strings and some local strings. fPoolStringIndex16Limit = (int32_t)( ((int64_t)fPoolStringIndexLimit * 0xffff) / sum); } } else if (gIsDefaultFormatVersion && formatVersion == 3 && !fIsPoolBundle) { // If we just default to formatVersion 3 // but there are no pool bundle strings to share // and we do not write a pool bundle, // then write formatVersion 2 which is just as good. formatVersion = 2; } fRoot->write16(this); if (f16BitUnits.isBogus()) { errorCode = U_MEMORY_ALLOCATION_ERROR; return; } if (f16BitUnits.length() & 1) { f16BitUnits.append((UChar)0xaaaa); /* pad to multiple of 4 bytes */ } /* all keys have been mapped */ uprv_free(fKeyMap); fKeyMap = NULL; byteOffset = fKeysTop + f16BitUnits.length() * 2; fRoot->preWrite(&byteOffset); /* total size including the root item */ top = byteOffset; if (writtenFilename && writtenFilenameLen) { *writtenFilename = 0; } if (writtenFilename) { int32_t off = 0, len = 0; if (outputDir) { len = (int32_t)uprv_strlen(outputDir); if (len > writtenFilenameLen) { len = writtenFilenameLen; } uprv_strncpy(writtenFilename, outputDir, len); } if (writtenFilenameLen -= len) { off += len; writtenFilename[off] = U_FILE_SEP_CHAR; if (--writtenFilenameLen) { ++off; if(outputPkg != NULL) { uprv_strcpy(writtenFilename+off, outputPkg); off += (int32_t)uprv_strlen(outputPkg); writtenFilename[off] = '_'; ++off; } len = (int32_t)uprv_strlen(fLocale); if (len > writtenFilenameLen) { len = writtenFilenameLen; } uprv_strncpy(writtenFilename + off, fLocale, len); if (writtenFilenameLen -= len) { off += len; len = 5; if (len > writtenFilenameLen) { len = writtenFilenameLen; } uprv_strncpy(writtenFilename + off, ".res", len); } } } } if(outputPkg) { uprv_strcpy(dataName, outputPkg); uprv_strcat(dataName, "_"); uprv_strcat(dataName, fLocale); } else { uprv_strcpy(dataName, fLocale); } uprv_memcpy(dataInfo.formatVersion, gFormatVersions + formatVersion, sizeof(UVersionInfo)); mem = udata_create(outputDir, "res", dataName, &dataInfo, (gIncludeCopyright==TRUE)? U_COPYRIGHT_STRING:NULL, &errorCode); if(U_FAILURE(errorCode)){ return; } /* write the root item */ udata_write32(mem, fRoot->fRes); /* * formatVersion 1.1 (ICU 2.8): * write int32_t indexes[] after root and before the key strings * to make it easier to parse resource bundles in icuswap or from Java etc. */ uprv_memset(indexes, 0, sizeof(indexes)); indexes[URES_INDEX_LENGTH]= fIndexLength; indexes[URES_INDEX_KEYS_TOP]= fKeysTop>>2; indexes[URES_INDEX_RESOURCES_TOP]= (int32_t)(top>>2); indexes[URES_INDEX_BUNDLE_TOP]= indexes[URES_INDEX_RESOURCES_TOP]; indexes[URES_INDEX_MAX_TABLE_LENGTH]= fMaxTableLength; /* * formatVersion 1.2 (ICU 3.6): * write indexes[URES_INDEX_ATTRIBUTES] with URES_ATT_NO_FALLBACK set or not set * the memset() above initialized all indexes[] to 0 */ if (fNoFallback) { indexes[URES_INDEX_ATTRIBUTES]=URES_ATT_NO_FALLBACK; } /* * formatVersion 2.0 (ICU 4.4): * more compact string value storage, optional pool bundle */ if (URES_INDEX_16BIT_TOP < fIndexLength) { indexes[URES_INDEX_16BIT_TOP] = (fKeysTop>>2) + (f16BitUnits.length()>>1); } if (URES_INDEX_POOL_CHECKSUM < fIndexLength) { if (fIsPoolBundle) { indexes[URES_INDEX_ATTRIBUTES] |= URES_ATT_IS_POOL_BUNDLE | URES_ATT_NO_FALLBACK; uint32_t checksum = computeCRC((const char *)(fKeys + fKeysBottom), (uint32_t)(fKeysTop - fKeysBottom), 0); if (f16BitUnits.length() <= 1) { // no pool strings to checksum } else if (U_IS_BIG_ENDIAN) { checksum = computeCRC(reinterpret_cast<const char *>(f16BitUnits.getBuffer()), (uint32_t)f16BitUnits.length() * 2, checksum); } else { // Swap to big-endian so we get the same checksum on all platforms // (except for charset family, due to the key strings). UnicodeString s(f16BitUnits); s.append((UChar)1); // Ensure that we own this buffer. assert(!s.isBogus()); uint16_t *p = const_cast<uint16_t *>(reinterpret_cast<const uint16_t *>(s.getBuffer())); for (int32_t count = f16BitUnits.length(); count > 0; --count) { uint16_t x = *p; *p++ = (uint16_t)((x << 8) | (x >> 8)); } checksum = computeCRC((const char *)p, (uint32_t)f16BitUnits.length() * 2, checksum); } indexes[URES_INDEX_POOL_CHECKSUM] = (int32_t)checksum; } else if (gUsePoolBundle) { indexes[URES_INDEX_ATTRIBUTES] |= URES_ATT_USES_POOL_BUNDLE; indexes[URES_INDEX_POOL_CHECKSUM] = fUsePoolBundle->fChecksum; } } // formatVersion 3 (ICU 56): // share string values via pool bundle strings indexes[URES_INDEX_LENGTH] |= fPoolStringIndexLimit << 8; // bits 23..0 -> 31..8 indexes[URES_INDEX_ATTRIBUTES] |= (fPoolStringIndexLimit >> 12) & 0xf000; // bits 27..24 -> 15..12 indexes[URES_INDEX_ATTRIBUTES] |= fPoolStringIndex16Limit << 16; /* write the indexes[] */ udata_writeBlock(mem, indexes, fIndexLength*4); /* write the table key strings */ udata_writeBlock(mem, fKeys+fKeysBottom, fKeysTop-fKeysBottom); /* write the v2 UTF-16 strings, URES_TABLE16 and URES_ARRAY16 */ udata_writeBlock(mem, f16BitUnits.getBuffer(), f16BitUnits.length()*2); /* write all of the bundle contents: the root item and its children */ byteOffset = fKeysTop + f16BitUnits.length() * 2; fRoot->write(mem, &byteOffset); assert(byteOffset == top); size = udata_finish(mem, &errorCode); if(top != size) { fprintf(stderr, "genrb error: wrote %u bytes but counted %u\n", (int)size, (int)top); errorCode = U_INTERNAL_PROGRAM_ERROR; } } /* Opening Functions */ TableResource* table_open(struct SRBRoot *bundle, const char *tag, const struct UString* comment, UErrorCode *status) { LocalPointer<TableResource> res(new TableResource(bundle, tag, comment, *status), *status); return U_SUCCESS(*status) ? res.orphan() : NULL; } ArrayResource* array_open(struct SRBRoot *bundle, const char *tag, const struct UString* comment, UErrorCode *status) { LocalPointer<ArrayResource> res(new ArrayResource(bundle, tag, comment, *status), *status); return U_SUCCESS(*status) ? res.orphan() : NULL; } struct SResource *string_open(struct SRBRoot *bundle, const char *tag, const UChar *value, int32_t len, const struct UString* comment, UErrorCode *status) { LocalPointer<SResource> res( new StringResource(bundle, tag, value, len, comment, *status), *status); return U_SUCCESS(*status) ? res.orphan() : NULL; } struct SResource *alias_open(struct SRBRoot *bundle, const char *tag, UChar *value, int32_t len, const struct UString* comment, UErrorCode *status) { LocalPointer<SResource> res( new AliasResource(bundle, tag, value, len, comment, *status), *status); return U_SUCCESS(*status) ? res.orphan() : NULL; } IntVectorResource *intvector_open(struct SRBRoot *bundle, const char *tag, const struct UString* comment, UErrorCode *status) { LocalPointer<IntVectorResource> res( new IntVectorResource(bundle, tag, comment, *status), *status); return U_SUCCESS(*status) ? res.orphan() : NULL; } struct SResource *int_open(struct SRBRoot *bundle, const char *tag, int32_t value, const struct UString* comment, UErrorCode *status) { LocalPointer<SResource> res(new IntResource(bundle, tag, value, comment, *status), *status); return U_SUCCESS(*status) ? res.orphan() : NULL; } struct SResource *bin_open(struct SRBRoot *bundle, const char *tag, uint32_t length, uint8_t *data, const char* fileName, const struct UString* comment, UErrorCode *status) { LocalPointer<SResource> res( new BinaryResource(bundle, tag, length, data, fileName, comment, *status), *status); return U_SUCCESS(*status) ? res.orphan() : NULL; } SRBRoot::SRBRoot(const UString *comment, UBool isPoolBundle, UErrorCode &errorCode) : fRoot(NULL), fLocale(NULL), fIndexLength(0), fMaxTableLength(0), fNoFallback(FALSE), fStringsForm(STRINGS_UTF16_V1), fIsPoolBundle(isPoolBundle), fKeys(NULL), fKeyMap(NULL), fKeysBottom(0), fKeysTop(0), fKeysCapacity(0), fKeysCount(0), fLocalKeyLimit(0), f16BitUnits(), f16BitStringsLength(0), fUsePoolBundle(&kNoPoolBundle), fPoolStringIndexLimit(0), fPoolStringIndex16Limit(0), fLocalStringIndexLimit(0), fWritePoolBundle(NULL) { if (U_FAILURE(errorCode)) { return; } if (gFormatVersion > 1) { // f16BitUnits must start with a zero for empty resources. // We might be able to omit it if there are no empty 16-bit resources. f16BitUnits.append((UChar)0); } fKeys = (char *) uprv_malloc(sizeof(char) * KEY_SPACE_SIZE); if (isPoolBundle) { fRoot = new PseudoListResource(this, errorCode); } else { fRoot = new TableResource(this, NULL, comment, errorCode); } if (fKeys == NULL || fRoot == NULL || U_FAILURE(errorCode)) { if (U_SUCCESS(errorCode)) { errorCode = U_MEMORY_ALLOCATION_ERROR; } return; } fKeysCapacity = KEY_SPACE_SIZE; /* formatVersion 1.1 and up: start fKeysTop after the root item and indexes[] */ if (gUsePoolBundle || isPoolBundle) { fIndexLength = URES_INDEX_POOL_CHECKSUM + 1; } else if (gFormatVersion >= 2) { fIndexLength = URES_INDEX_16BIT_TOP + 1; } else /* formatVersion 1 */ { fIndexLength = URES_INDEX_ATTRIBUTES + 1; } fKeysBottom = (1 /* root */ + fIndexLength) * 4; uprv_memset(fKeys, 0, fKeysBottom); fKeysTop = fKeysBottom; if (gFormatVersion == 1) { fStringsForm = STRINGS_UTF16_V1; } else { fStringsForm = STRINGS_UTF16_V2; } } /* Closing Functions */ void res_close(struct SResource *res) { delete res; } SRBRoot::~SRBRoot() { delete fRoot; uprv_free(fLocale); uprv_free(fKeys); uprv_free(fKeyMap); } /* Misc Functions */ void SRBRoot::setLocale(UChar *locale, UErrorCode &errorCode) { if(U_FAILURE(errorCode)) { return; } uprv_free(fLocale); fLocale = (char*) uprv_malloc(sizeof(char) * (u_strlen(locale)+1)); if(fLocale == NULL) { errorCode = U_MEMORY_ALLOCATION_ERROR; return; } u_UCharsToChars(locale, fLocale, u_strlen(locale)+1); } const char * SRBRoot::getKeyString(int32_t key) const { if (key < 0) { return fUsePoolBundle->fKeys + (key & 0x7fffffff); } else { return fKeys + key; } } const char * SResource::getKeyString(const SRBRoot *bundle) const { if (fKey == -1) { return NULL; } return bundle->getKeyString(fKey); } const char * SRBRoot::getKeyBytes(int32_t *pLength) const { *pLength = fKeysTop - fKeysBottom; return fKeys + fKeysBottom; } int32_t SRBRoot::addKeyBytes(const char *keyBytes, int32_t length, UErrorCode &errorCode) { int32_t keypos; if (U_FAILURE(errorCode)) { return -1; } if (length < 0 || (keyBytes == NULL && length != 0)) { errorCode = U_ILLEGAL_ARGUMENT_ERROR; return -1; } if (length == 0) { return fKeysTop; } keypos = fKeysTop; fKeysTop += length; if (fKeysTop >= fKeysCapacity) { /* overflow - resize the keys buffer */ fKeysCapacity += KEY_SPACE_SIZE; fKeys = static_cast<char *>(uprv_realloc(fKeys, fKeysCapacity)); if(fKeys == NULL) { errorCode = U_MEMORY_ALLOCATION_ERROR; return -1; } } uprv_memcpy(fKeys + keypos, keyBytes, length); return keypos; } int32_t SRBRoot::addTag(const char *tag, UErrorCode &errorCode) { int32_t keypos; if (U_FAILURE(errorCode)) { return -1; } if (tag == NULL) { /* no error: the root table and array items have no keys */ return -1; } keypos = addKeyBytes(tag, (int32_t)(uprv_strlen(tag) + 1), errorCode); if (U_SUCCESS(errorCode)) { ++fKeysCount; } return keypos; } static int32_t compareInt32(int32_t lPos, int32_t rPos) { /* * Compare possibly-negative key offsets. Don't just return lPos - rPos * because that is prone to negative-integer underflows. */ if (lPos < rPos) { return -1; } else if (lPos > rPos) { return 1; } else { return 0; } } static int32_t U_CALLCONV compareKeySuffixes(const void *context, const void *l, const void *r) { const struct SRBRoot *bundle=(const struct SRBRoot *)context; int32_t lPos = ((const KeyMapEntry *)l)->oldpos; int32_t rPos = ((const KeyMapEntry *)r)->oldpos; const char *lStart = bundle->getKeyString(lPos); const char *lLimit = lStart; const char *rStart = bundle->getKeyString(rPos); const char *rLimit = rStart; int32_t diff; while (*lLimit != 0) { ++lLimit; } while (*rLimit != 0) { ++rLimit; } /* compare keys in reverse character order */ while (lStart < lLimit && rStart < rLimit) { diff = (int32_t)(uint8_t)*--lLimit - (int32_t)(uint8_t)*--rLimit; if (diff != 0) { return diff; } } /* sort equal suffixes by descending key length */ diff = (int32_t)(rLimit - rStart) - (int32_t)(lLimit - lStart); if (diff != 0) { return diff; } /* Sort pool bundle keys first (negative oldpos), and otherwise keys in parsing order. */ return compareInt32(lPos, rPos); } static int32_t U_CALLCONV compareKeyNewpos(const void * /*context*/, const void *l, const void *r) { return compareInt32(((const KeyMapEntry *)l)->newpos, ((const KeyMapEntry *)r)->newpos); } static int32_t U_CALLCONV compareKeyOldpos(const void * /*context*/, const void *l, const void *r) { return compareInt32(((const KeyMapEntry *)l)->oldpos, ((const KeyMapEntry *)r)->oldpos); } void SRBRoot::compactKeys(UErrorCode &errorCode) { KeyMapEntry *map; char *keys; int32_t i; int32_t keysCount = fUsePoolBundle->fKeysCount + fKeysCount; if (U_FAILURE(errorCode) || fKeysCount == 0 || fKeyMap != NULL) { return; } map = (KeyMapEntry *)uprv_malloc(keysCount * sizeof(KeyMapEntry)); if (map == NULL) { errorCode = U_MEMORY_ALLOCATION_ERROR; return; } keys = (char *)fUsePoolBundle->fKeys; for (i = 0; i < fUsePoolBundle->fKeysCount; ++i) { map[i].oldpos = (int32_t)(keys - fUsePoolBundle->fKeys) | 0x80000000; /* negative oldpos */ map[i].newpos = 0; while (*keys != 0) { ++keys; } /* skip the key */ ++keys; /* skip the NUL */ } keys = fKeys + fKeysBottom; for (; i < keysCount; ++i) { map[i].oldpos = (int32_t)(keys - fKeys); map[i].newpos = 0; while (*keys != 0) { ++keys; } /* skip the key */ ++keys; /* skip the NUL */ } /* Sort the keys so that each one is immediately followed by all of its suffixes. */ uprv_sortArray(map, keysCount, (int32_t)sizeof(KeyMapEntry), compareKeySuffixes, this, FALSE, &errorCode); /* * Make suffixes point into earlier, longer strings that contain them * and mark the old, now unused suffix bytes as deleted. */ if (U_SUCCESS(errorCode)) { keys = fKeys; for (i = 0; i < keysCount;) { /* * This key is not a suffix of the previous one; * keep this one and delete the following ones that are * suffixes of this one. */ const char *key; const char *keyLimit; int32_t j = i + 1; map[i].newpos = map[i].oldpos; if (j < keysCount && map[j].oldpos < 0) { /* Key string from the pool bundle, do not delete. */ i = j; continue; } key = getKeyString(map[i].oldpos); for (keyLimit = key; *keyLimit != 0; ++keyLimit) {} for (; j < keysCount && map[j].oldpos >= 0; ++j) { const char *k; char *suffix; const char *suffixLimit; int32_t offset; suffix = keys + map[j].oldpos; for (suffixLimit = suffix; *suffixLimit != 0; ++suffixLimit) {} offset = static_cast<int32_t>((keyLimit - key) - (suffixLimit - suffix)); if (offset < 0) { break; /* suffix cannot be longer than the original */ } /* Is it a suffix of the earlier, longer key? */ for (k = keyLimit; suffix < suffixLimit && *--k == *--suffixLimit;) {} if (suffix == suffixLimit && *k == *suffixLimit) { map[j].newpos = map[i].oldpos + offset; /* yes, point to the earlier key */ /* mark the suffix as deleted */ while (*suffix != 0) { *suffix++ = 1; } *suffix = 1; } else { break; /* not a suffix, restart from here */ } } i = j; } /* * Re-sort by newpos, then modify the key characters array in-place * to squeeze out unused bytes, and readjust the newpos offsets. */ uprv_sortArray(map, keysCount, (int32_t)sizeof(KeyMapEntry), compareKeyNewpos, NULL, FALSE, &errorCode); if (U_SUCCESS(errorCode)) { int32_t oldpos, newpos, limit; oldpos = newpos = fKeysBottom; limit = fKeysTop; /* skip key offsets that point into the pool bundle rather than this new bundle */ for (i = 0; i < keysCount && map[i].newpos < 0; ++i) {} if (i < keysCount) { while (oldpos < limit) { if (keys[oldpos] == 1) { ++oldpos; /* skip unused bytes */ } else { /* adjust the new offsets for keys starting here */ while (i < keysCount && map[i].newpos == oldpos) { map[i++].newpos = newpos; } /* move the key characters to their new position */ keys[newpos++] = keys[oldpos++]; } } assert(i == keysCount); } fKeysTop = newpos; /* Re-sort once more, by old offsets for binary searching. */ uprv_sortArray(map, keysCount, (int32_t)sizeof(KeyMapEntry), compareKeyOldpos, NULL, FALSE, &errorCode); if (U_SUCCESS(errorCode)) { /* key size reduction by limit - newpos */ fKeyMap = map; map = NULL; } } } uprv_free(map); } static int32_t U_CALLCONV compareStringSuffixes(const void * /*context*/, const void *l, const void *r) { const StringResource *left = *((const StringResource **)l); const StringResource *right = *((const StringResource **)r); const UChar *lStart = left->getBuffer(); const UChar *lLimit = lStart + left->length(); const UChar *rStart = right->getBuffer(); const UChar *rLimit = rStart + right->length(); int32_t diff; /* compare keys in reverse character order */ while (lStart < lLimit && rStart < rLimit) { diff = (int32_t)*--lLimit - (int32_t)*--rLimit; if (diff != 0) { return diff; } } /* sort equal suffixes by descending string length */ return right->length() - left->length(); } static int32_t U_CALLCONV compareStringLengths(const void * /*context*/, const void *l, const void *r) { const StringResource *left = *((const StringResource **)l); const StringResource *right = *((const StringResource **)r); int32_t diff; /* Make "is suffix of another string" compare greater than a non-suffix. */ diff = (int)(left->fSame != NULL) - (int)(right->fSame != NULL); if (diff != 0) { return diff; } /* sort by ascending string length */ diff = left->length() - right->length(); if (diff != 0) { return diff; } // sort by descending size reduction diff = right->fNumUnitsSaved - left->fNumUnitsSaved; if (diff != 0) { return diff; } // sort lexically return left->fString.compare(right->fString); } void StringResource::writeUTF16v2(int32_t base, UnicodeString &dest) { int32_t len = length(); fRes = URES_MAKE_RESOURCE(URES_STRING_V2, base + dest.length()); fWritten = TRUE; switch(fNumCharsForLength) { case 0: break; case 1: dest.append((UChar)(0xdc00 + len)); break; case 2: dest.append((UChar)(0xdfef + (len >> 16))); dest.append((UChar)len); break; case 3: dest.append((UChar)0xdfff); dest.append((UChar)(len >> 16)); dest.append((UChar)len); break; default: break; /* will not occur */ } dest.append(fString); dest.append((UChar)0); } void SRBRoot::compactStringsV2(UHashtable *stringSet, UErrorCode &errorCode) { if (U_FAILURE(errorCode)) { return; } // Store the StringResource pointers in an array for // easy sorting and processing. // We enumerate a set of strings, so there are no duplicates. int32_t count = uhash_count(stringSet); LocalArray<StringResource *> array(new StringResource *[count], errorCode); if (U_FAILURE(errorCode)) { return; } for (int32_t pos = UHASH_FIRST, i = 0; i < count; ++i) { array[i] = (StringResource *)uhash_nextElement(stringSet, &pos)->key.pointer; } /* Sort the strings so that each one is immediately followed by all of its suffixes. */ uprv_sortArray(array.getAlias(), count, (int32_t)sizeof(struct SResource **), compareStringSuffixes, NULL, FALSE, &errorCode); if (U_FAILURE(errorCode)) { return; } /* * Make suffixes point into earlier, longer strings that contain them. * Temporarily use fSame and fSuffixOffset for suffix strings to * refer to the remaining ones. */ for (int32_t i = 0; i < count;) { /* * This string is not a suffix of the previous one; * write this one and subsume the following ones that are * suffixes of this one. */ StringResource *res = array[i]; res->fNumUnitsSaved = (res->fNumCopies - 1) * res->get16BitStringsLength(); // Whole duplicates of pool strings are already account for in fPoolStringIndexLimit, // see StringResource::handlePreflightStrings(). int32_t j; for (j = i + 1; j < count; ++j) { StringResource *suffixRes = array[j]; /* Is it a suffix of the earlier, longer string? */ if (res->fString.endsWith(suffixRes->fString)) { assert(res->length() != suffixRes->length()); // Set strings are unique. if (suffixRes->fWritten) { // Pool string, skip. } else if (suffixRes->fNumCharsForLength == 0) { /* yes, point to the earlier string */ suffixRes->fSame = res; suffixRes->fSuffixOffset = res->length() - suffixRes->length(); if (res->fWritten) { // Suffix-share res which is a pool string. // Compute the resource word and collect the maximum. suffixRes->fRes = res->fRes + res->fNumCharsForLength + suffixRes->fSuffixOffset; int32_t poolStringIndex = (int32_t)RES_GET_OFFSET(suffixRes->fRes); if (poolStringIndex >= fPoolStringIndexLimit) { fPoolStringIndexLimit = poolStringIndex + 1; } suffixRes->fWritten = TRUE; } res->fNumUnitsSaved += suffixRes->fNumCopies * suffixRes->get16BitStringsLength(); } else { /* write the suffix by itself if we need explicit length */ } } else { break; /* not a suffix, restart from here */ } } i = j; } /* * Re-sort the strings by ascending length (except suffixes last) * to optimize for URES_TABLE16 and URES_ARRAY16: * Keep as many as possible within reach of 16-bit offsets. */ uprv_sortArray(array.getAlias(), count, (int32_t)sizeof(struct SResource **), compareStringLengths, NULL, FALSE, &errorCode); if (U_FAILURE(errorCode)) { return; } if (fIsPoolBundle) { // Write strings that are sufficiently shared. // Avoid writing other strings. int32_t numStringsWritten = 0; int32_t numUnitsSaved = 0; int32_t numUnitsNotSaved = 0; for (int32_t i = 0; i < count; ++i) { StringResource *res = array[i]; // Maximum pool string index when suffix-sharing the last character. int32_t maxStringIndex = f16BitUnits.length() + res->fNumCharsForLength + res->length() - 1; if (res->fNumUnitsSaved >= GENRB_MIN_16BIT_UNITS_SAVED_FOR_POOL_STRING && maxStringIndex < RES_MAX_OFFSET) { res->writeUTF16v2(0, f16BitUnits); ++numStringsWritten; numUnitsSaved += res->fNumUnitsSaved; } else { numUnitsNotSaved += res->fNumUnitsSaved; res->fRes = URES_MAKE_EMPTY_RESOURCE(URES_STRING); res->fWritten = TRUE; } } if (f16BitUnits.isBogus()) { errorCode = U_MEMORY_ALLOCATION_ERROR; } if (getShowWarning()) { // not quiet printf("number of shared strings: %d\n", (int)numStringsWritten); printf("16-bit units for strings: %6d = %6d bytes\n", (int)f16BitUnits.length(), (int)f16BitUnits.length() * 2); printf("16-bit units saved: %6d = %6d bytes\n", (int)numUnitsSaved, (int)numUnitsSaved * 2); printf("16-bit units not saved: %6d = %6d bytes\n", (int)numUnitsNotSaved, (int)numUnitsNotSaved * 2); } } else { assert(fPoolStringIndexLimit <= fUsePoolBundle->fStringIndexLimit); /* Write the non-suffix strings. */ int32_t i; for (i = 0; i < count && array[i]->fSame == NULL; ++i) { StringResource *res = array[i]; if (!res->fWritten) { int32_t localStringIndex = f16BitUnits.length(); if (localStringIndex >= fLocalStringIndexLimit) { fLocalStringIndexLimit = localStringIndex + 1; } res->writeUTF16v2(fPoolStringIndexLimit, f16BitUnits); } } if (f16BitUnits.isBogus()) { errorCode = U_MEMORY_ALLOCATION_ERROR; return; } if (fWritePoolBundle != NULL && gFormatVersion >= 3) { PseudoListResource *poolStrings = static_cast<PseudoListResource *>(fWritePoolBundle->fRoot); for (i = 0; i < count && array[i]->fSame == NULL; ++i) { assert(!array[i]->fString.isEmpty()); StringResource *poolString = new StringResource(fWritePoolBundle, array[i]->fString, errorCode); if (poolString == NULL) { errorCode = U_MEMORY_ALLOCATION_ERROR; break; } poolStrings->add(poolString); } } /* Write the suffix strings. Make each point to the real string. */ for (; i < count; ++i) { StringResource *res = array[i]; if (res->fWritten) { continue; } StringResource *same = res->fSame; assert(res->length() != same->length()); // Set strings are unique. res->fRes = same->fRes + same->fNumCharsForLength + res->fSuffixOffset; int32_t localStringIndex = (int32_t)RES_GET_OFFSET(res->fRes) - fPoolStringIndexLimit; // Suffixes of pool strings have been set already. assert(localStringIndex >= 0); if (localStringIndex >= fLocalStringIndexLimit) { fLocalStringIndexLimit = localStringIndex + 1; } res->fWritten = TRUE; } } // +1 to account for the initial zero in f16BitUnits assert(f16BitUnits.length() <= (f16BitStringsLength + 1)); }
34.469303
174
0.590228
qingqibing
0496310fb225f7616890d7c45f263ff8ff9a1313
2,205
cpp
C++
Tema1-2/ED11/source.cpp
Yule1223/Data-Structure
90197a9f9d19332f3d2e240185bba6540eaa754d
[ "MIT" ]
null
null
null
Tema1-2/ED11/source.cpp
Yule1223/Data-Structure
90197a9f9d19332f3d2e240185bba6540eaa754d
[ "MIT" ]
null
null
null
Tema1-2/ED11/source.cpp
Yule1223/Data-Structure
90197a9f9d19332f3d2e240185bba6540eaa754d
[ "MIT" ]
null
null
null
// Yule Zhang #include <iostream> #include <fstream> using namespace std; #include "queue_eda.h" template <typename T> class listaPlus : public queue<T> { using Nodo = typename queue<T>::Nodo; public: void mezclar(listaPlus<T> & l1, listaPlus<T> & l2) { if (l1.nelems == 0) {//Si l1 es vacia this->prim = l2.prim; this->ult = l2.ult; } else if (l2.nelems == 0) {//Si l2 es vacia this->prim = l1.prim; this->ult = l1.ult; } else {//Si ni l1 ni l2 son vacias Nodo* nodo1 = l1.prim; Nodo* nodo2 = l2.prim; if (nodo1->elem <= nodo2->elem) { this->prim = nodo1; nodo1 = nodo1->sig; } else { this->prim = nodo2; nodo2 = nodo2->sig; } Nodo* nodo = this->prim; while (nodo1 != nullptr && nodo2 != nullptr) { if (nodo1->elem <= nodo2->elem) { nodo->sig = nodo1; nodo1 = nodo1->sig; nodo = nodo->sig; } else { nodo->sig = nodo2; nodo2 = nodo2->sig; nodo = nodo->sig; } } while (nodo1 != nullptr) { nodo->sig = nodo1; nodo1 = nodo1->sig; nodo = nodo->sig; } while (nodo2 != nullptr) { nodo->sig = nodo2; nodo2 = nodo2->sig; nodo = nodo->sig; } } this->nelems = l1.nelems + l2.nelems; l1.prim = l1.ult = nullptr; l2.prim = l2.ult = nullptr; l1.nelems = l2.nelems = 0; } void print() const { Nodo* aux = this->prim; while (aux != nullptr) { cout << aux->elem << ' '; aux = aux->sig; } cout << endl; } }; void resuelveCaso() { int n; cin >> n;//Leer datos de entrada listaPlus<int> l1;//Primera lista listaPlus<int> l2;//Segunda lista while (n != 0) { l1.push(n); cin >> n; } int m; cin >> m; while (m != 0) { l2.push(m); cin >> m; } listaPlus<int> l;//Lista final l.mezclar(l1, l2); l.print(); } int main() { // ajustes para que cin extraiga directamente de un fichero #ifndef DOMJUDGE std::ifstream in("casos.txt"); auto cinbuf = std::cin.rdbuf(in.rdbuf()); #endif int numCasos; std::cin >> numCasos; for (int i = 0; i < numCasos; ++i) resuelveCaso(); // para dejar todo como estaba al principio #ifndef DOMJUDGE std::cin.rdbuf(cinbuf); system("PAUSE"); #endif return 0; }
18.22314
61
0.569161
Yule1223
0496a3661681dbbbe22c4edf4d044121fb63df10
4,217
hpp
C++
Assignment7/Material.hpp
fuzhanzhan/Games101
9345d70283c44649e0fd99975361a2909ef4bdbe
[ "MIT" ]
9
2020-07-27T12:03:38.000Z
2021-11-01T09:26:31.000Z
Assignment7/Material.hpp
fuzhanzhan/Games101
9345d70283c44649e0fd99975361a2909ef4bdbe
[ "MIT" ]
null
null
null
Assignment7/Material.hpp
fuzhanzhan/Games101
9345d70283c44649e0fd99975361a2909ef4bdbe
[ "MIT" ]
8
2020-08-20T02:56:56.000Z
2022-03-06T12:09:35.000Z
#ifndef RAYTRACING_MATERIAL_H #define RAYTRACING_MATERIAL_H #include "Vector.hpp" enum class MaterialType { DIFFUSE }; class Material { private: // Compute reflection direction Vector3f reflect(const Vector3f &I, const Vector3f &N) const { return I - 2 * I.dot(N) * N; } // Compute refraction direction using Snell's law // // We need to handle with care the two possible situations: // // - When the ray is inside the object // // - When the ray is outside. // // If the ray is outside, you need to make cosi positive cosi = -N.I // // If the ray is inside, you need to invert the refractive indices and negate the normal N Vector3f refract(const Vector3f &I, const Vector3f &N, const float &ior) const { float cosi = clamp(-1, 1, I.dot(N)); float etai = 1, etat = ior; Vector3f n = N; if (cosi < 0) { cosi = -cosi; } else { std::swap(etai, etat); n = -N; } float eta = etai / etat; float k = 1 - eta * eta * (1 - cosi * cosi); return k < 0 ? 0 : eta * I + (eta * cosi - sqrt(k)) * n; } // Compute Fresnel equation // // \param I is the incident view direction // // \param N is the normal at the intersection point // // \param ior is the material refractive index // // \param[out] kr is the amount of light reflected void fresnel(const Vector3f &I, const Vector3f &N, const float &ior, float &kr) const { float cosi = clamp(-1, 1, I.dot(N)); float etai = 1, etat = ior; if (cosi > 0) { std::swap(etai, etat); } // Compute sini using Snell's law float sint = etai / etat * sqrtf(std::max(0.f, 1 - cosi * cosi)); // Total internal reflection if (sint >= 1) { kr = 1; } else { float cost = sqrtf(std::max(0.f, 1 - sint * sint)); cosi = fabsf(cosi); float Rs = ((etat * cosi) - (etai * cost)) / ((etat * cosi) + (etai * cost)); float Rp = ((etai * cosi) - (etat * cost)) / ((etai * cosi) + (etat * cost)); kr = (Rs * Rs + Rp * Rp) / 2; } // As a consequence of the conservation of energy, transmittance is given by: // kt = 1 - kr; } Vector3f toWorld(const Vector3f &a, const Vector3f &N) { Vector3f B, C; if (std::fabs(N.x) > std::fabs(N.y)) { float invLen = 1.0f / std::sqrt(N.x * N.x + N.z * N.z); C = Vector3f(N.z * invLen, 0.0f, -N.x * invLen); } else { float invLen = 1.0f / std::sqrt(N.y * N.y + N.z * N.z); C = Vector3f(0.0f, N.z * invLen, -N.y * invLen); } B = C.cross(N); return a.x * B + a.y * C + a.z * N; } public: MaterialType m_type; Vector3f emit; float ior; Vector3f Kd, Ks; float specularExponent; //Texture tex; Material(MaterialType t = MaterialType::DIFFUSE, Vector3f e = Vector3f(0, 0, 0)) { m_type = t; emit = e; } inline bool hasEmit() { return emit.length() > EPSILON ? true : false; } // sample a ray by Material properties inline Vector3f sample(const Vector3f &wi, const Vector3f &N); // given a ray, calculate the PdF of this ray inline float pdf(const Vector3f &wi, const Vector3f &wo, const Vector3f &N); // given a ray, calculate the contribution of this ray inline Vector3f eval(const Vector3f &wi, const Vector3f &wo, const Vector3f &N); }; Vector3f Material::sample(const Vector3f &wi, const Vector3f &N) { switch (m_type) { case MaterialType::DIFFUSE: { // uniform sample on the hemisphere float x_1 = get_random_float(), x_2 = get_random_float(); float z = std::fabs(1.0f - 2.0f * x_1); float r = std::sqrt(1.0f - z * z), phi = 2 * M_PI * x_2; Vector3f localRay(r * std::cos(phi), r * std::sin(phi), z); return toWorld(localRay, N); break; } } } float Material::pdf(const Vector3f &wi, const Vector3f &wo, const Vector3f &N) { switch (m_type) { case MaterialType::DIFFUSE: { // uniform sample probability 1 / (2 * PI) if (wo.dot(N) > 0.0f) return 0.5f / M_PI; else return 0.0f; break; } } } Vector3f Material::eval(const Vector3f &wi, const Vector3f &wo, const Vector3f &N) { switch (m_type) { case MaterialType::DIFFUSE: { // calculate the contribution of diffuse model float cosalpha = wo.dot(N); if (cosalpha > 0.0f) { Vector3f diffuse = Kd / M_PI; return diffuse; } else return Vector3f(0.0f); break; } } } #endif //RAYTRACING_MATERIAL_H
24.805882
91
0.626749
fuzhanzhan
0496d38d5ca036a3d9eb921750231320620b7f96
1,726
hpp
C++
Headers/Internal/position.hpp
YarikTH/cpp-io-impl
faf62a578ceeae2ce41818aae8172da67ec00456
[ "BSL-1.0" ]
1
2022-02-15T02:58:58.000Z
2022-02-15T02:58:58.000Z
Headers/Internal/position.hpp
YarikTH/cpp-io-impl
faf62a578ceeae2ce41818aae8172da67ec00456
[ "BSL-1.0" ]
null
null
null
Headers/Internal/position.hpp
YarikTH/cpp-io-impl
faf62a578ceeae2ce41818aae8172da67ec00456
[ "BSL-1.0" ]
1
2021-12-19T13:25:43.000Z
2021-12-19T13:25:43.000Z
/// \file /// \brief Internal header file that contains implementation of the position /// class. /// \author Lyberta /// \copyright BSLv1. #pragma once namespace std::io { constexpr position::position(streamoff off) noexcept : m_position{off} { } constexpr position::position(offset off) noexcept : m_position{off.value()} { } constexpr streamoff position::value() const noexcept { return m_position; } constexpr position& position::operator++() noexcept { ++m_position; return *this; } constexpr position position::operator++(int) noexcept { position temp{*this}; ++(*this); return temp; } constexpr position& position::operator--() noexcept { --m_position; return *this; } constexpr position position::operator--(int) noexcept { position temp{*this}; --(*this); return temp; } constexpr position& position::operator+=(offset rhs) noexcept { m_position += rhs.value(); return *this; } constexpr position& position::operator-=(offset rhs) noexcept { m_position -= rhs.value(); return *this; } constexpr position position::max() noexcept { return position{numeric_limits<streamoff>::max()}; } constexpr bool operator==(position lhs, position rhs) noexcept { return lhs.value() == rhs.value(); } constexpr strong_ordering operator<=>(position lhs, position rhs) noexcept { return lhs.value() <=> rhs.value(); } constexpr position operator+(position lhs, offset rhs) noexcept { return lhs += rhs; } constexpr position operator+(offset lhs, position rhs) noexcept { return rhs += lhs; } constexpr position operator-(position lhs, offset rhs) noexcept { return lhs -= rhs; } constexpr offset operator-(position lhs, position rhs) noexcept { return offset{lhs.value() - rhs.value()}; } }
17.089109
76
0.715527
YarikTH
0496d52dffcf4e9d830b241efcac8cc3b80f8d64
3,271
hh
C++
hackt_docker/hackt/src/Object/inst/null_collection_type_manager.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/Object/inst/null_collection_type_manager.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/Object/inst/null_collection_type_manager.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
/** \file "Object/inst/null_collection_type_manager.hh" Template class for instance_collection's type manager. $Id: null_collection_type_manager.hh,v 1.12 2007/04/15 05:52:19 fang Exp $ */ #ifndef __HAC_OBJECT_INST_NULL_COLLECTION_TYPE_MANAGER_H__ #define __HAC_OBJECT_INST_NULL_COLLECTION_TYPE_MANAGER_H__ #include <iosfwd> #include "Object/type/canonical_type_fwd.hh" // just for conditional #include "util/persistent_fwd.hh" #include "util/boolean_types.hh" #include "util/memory/pointer_classes_fwd.hh" namespace HAC { namespace entity { class const_param_expr_list; using std::istream; using std::ostream; using util::good_bool; using util::bad_bool; using util::persistent_object_manager; using util::memory::count_ptr; class footprint; template <class> struct class_traits; //============================================================================= /** Appropriate for built-in types with no template parameters. Pretty much only useful to bool. TODO: write a quick raw-type comparison without having to construct canonical type. */ template <class Tag> class null_collection_type_manager { private: typedef null_collection_type_manager<Tag> this_type; typedef class_traits<Tag> traits_type; protected: typedef typename traits_type::instance_collection_generic_type instance_collection_generic_type; typedef typename traits_type::instance_collection_parameter_type instance_collection_parameter_type; typedef typename traits_type::type_ref_ptr_type type_ref_ptr_type; typedef typename traits_type::resolved_type_ref_type resolved_type_ref_type; // has no type parameter struct dumper; void collect_transient_info_base(persistent_object_manager&) const { } void write_object_base(const persistent_object_manager&, ostream&) const { } void load_object_base(const persistent_object_manager&, istream&) { } public: // distinguish internal type from canonical_type /** Only used internally with collections. */ instance_collection_parameter_type __get_raw_type(void) const { return instance_collection_parameter_type(); } resolved_type_ref_type get_resolved_canonical_type(void) const; good_bool complete_type_definition_footprint( const count_ptr<const const_param_expr_list>&) const { return good_bool(true); } bool is_complete_type(void) const { return true; } bool is_relaxed_type(void) const { return false; } // bool doesn't have a footprint static good_bool create_definition_footprint( const instance_collection_parameter_type&, const footprint& /* top */) { return good_bool(true); } protected: bool must_be_collectibly_type_equivalent(const this_type&) const { return true; } bad_bool check_type(const instance_collection_parameter_type&) const { return bad_bool(false); } /** \param t type must be resolved constant. \pre first time called for the collection. */ good_bool commit_type_first_time( const instance_collection_parameter_type&) const { return good_bool(true); } }; // end struct null_collection_type_manager //============================================================================= } // end namespace entity } // end namespace HAC #endif // __HAC_OBJECT_INST_NULL_COLLECTION_TYPE_MANAGER_H__
25.960317
79
0.751758
broken-wheel
0497d04d2c4ad58f8791a6a61ff6243094718e14
13,504
cc
C++
ortools/linear_solver/gurobi_environment.cc
sreesubbash/or-tools
701496e45d54fa9938afeedec43089314d93ec11
[ "Apache-2.0" ]
null
null
null
ortools/linear_solver/gurobi_environment.cc
sreesubbash/or-tools
701496e45d54fa9938afeedec43089314d93ec11
[ "Apache-2.0" ]
null
null
null
ortools/linear_solver/gurobi_environment.cc
sreesubbash/or-tools
701496e45d54fa9938afeedec43089314d93ec11
[ "Apache-2.0" ]
null
null
null
// Copyright 2010-2018 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 "ortools/linear_solver/gurobi_environment.h" #include <string> #include "absl/status/status.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "ortools/base/logging.h" #include "ortools/linear_solver/linear_solver.h" namespace operations_research { absl::Status LoadGurobiEnvironment(GRBenv** env) { constexpr int GRB_OK = 0; const char kGurobiEnvErrorMsg[] = "Could not load Gurobi environment. Is gurobi correctly installed and " "licensed on this machine?"; if (GRBloadenv(env, nullptr) != 0 || *env == nullptr) { return absl::FailedPreconditionError( absl::StrFormat("%s %s", kGurobiEnvErrorMsg, GRBgeterrormsg(*env))); } return absl::OkStatus(); } std::function<int(GRBmodel*, int, int*, double*, double, double, const char*)> GRBaddrangeconstr = nullptr; std::function<int(GRBmodel* model, int numnz, int* vind, double* vval, double obj, double lb, double ub, char vtype, const char* varname)> GRBaddvar = nullptr; std::function<int(GRBmodel*, int, int, int*, int*, double*, double*, double*, double*, char*, char**)> GRBaddvars = nullptr; std::function<int(GRBmodel* model, int numchgs, int* cind, int* vind, double* val)> GRBchgcoeffs = nullptr; std::function<void(GRBenv*)> GRBfreeenv = nullptr; std::function<int(GRBmodel*)> GRBfreemodel = nullptr; std::function<int(GRBmodel*, const char*, int, char*)> GRBgetcharattrelement = nullptr; std::function<int(GRBmodel*, const char*, double*)> GRBgetdblattr = nullptr; std::function<int(GRBmodel*, const char*, int, int, double*)> GRBgetdblattrarray = nullptr; std::function<int(GRBmodel*, const char*, int, double*)> GRBgetdblattrelement = nullptr; std::function<int(GRBenv*, const char*, double*)> GRBgetdblparam = nullptr; std::function<GRBenv*(GRBmodel*)> GRBgetenv = nullptr; std::function<char*(GRBenv*)> GRBgeterrormsg = nullptr; std::function<int(GRBmodel*, const char*, int*)> GRBgetintattr = nullptr; std::function<int(GRBmodel*, const char*, int, int*)> GRBgetintattrelement = nullptr; std::function<int(GRBenv**, const char*)> GRBloadenv = nullptr; std::function<int(GRBenv*, GRBmodel**, const char*, int numvars, double*, double*, double*, char*, char**)> GRBnewmodel = nullptr; std::function<int(GRBmodel*)> GRBoptimize = nullptr; std::function<int(GRBenv*, const char*)> GRBreadparams = nullptr; std::function<int(GRBenv*)> GRBresetparams = nullptr; std::function<int(GRBmodel*, const char*, int, char)> GRBsetcharattrelement = nullptr; std::function<int(GRBmodel*, const char*, double)> GRBsetdblattr = nullptr; std::function<int(GRBmodel*, const char*, int, double)> GRBsetdblattrelement = nullptr; std::function<int(GRBenv*, const char*, double)> GRBsetdblparam = nullptr; std::function<int(GRBmodel*, const char*, int)> GRBsetintattr = nullptr; std::function<int(GRBenv*, const char*, int)> GRBsetintparam = nullptr; std::function<void(GRBmodel*)> GRBterminate = nullptr; std::function<int(GRBmodel*)> GRBupdatemodel = nullptr; std::function<void(int*, int*, int*)> GRBversion = nullptr; std::function<int(GRBmodel*, const char*)> GRBwrite = nullptr; std::function<int(void* cbdata, int where, int what, void* resultP)> GRBcbget = nullptr; std::function<int(void* cbdata, int cutlen, const int* cutind, const double* cutval, char cutsense, double cutrhs)> GRBcbcut = nullptr; std::function<int(void* cbdata, int lazylen, const int* lazyind, const double* lazyval, char lazysense, double lazyrhs)> GRBcblazy = nullptr; std::function<int(void* cbdata, const double* solution, double* objvalP)> GRBcbsolution = nullptr; std::function<int(GRBmodel* model, int numnz, int* cind, double* cval, char sense, double rhs, const char* constrname)> GRBaddconstr = nullptr; std::function<int(GRBmodel* model, const char* name, int binvar, int binval, int nvars, const int* vars, const double* vals, char sense, double rhs)> GRBaddgenconstrIndicator = nullptr; std::function<int(GRBmodel* model, const char* attrname, int element, int newvalue)> GRBsetintattrelement = nullptr; std::function<int(GRBmodel* model, int(STDCALL* cb)(CB_ARGS), void* usrdata)> GRBsetcallbackfunc = nullptr; std::function<int(GRBenv* env, const char* paramname, const char* value)> GRBsetparam = nullptr; std::function<int(GRBmodel* model, int numsos, int nummembers, int* types, int* beg, int* ind, double* weight)> GRBaddsos = nullptr; std::function<int(GRBmodel* model, int numlnz, int* lind, double* lval, int numqnz, int* qrow, int* qcol, double* qval, char sense, double rhs, const char* QCname)> GRBaddqconstr = nullptr; std::function<int(GRBmodel* model, const char* name, int resvar, int nvars, const int* vars, double constant)> GRBaddgenconstrMax = nullptr; std::function<int(GRBmodel* model, const char* name, int resvar, int nvars, const int* vars, double constant)> GRBaddgenconstrMin = nullptr; std::function<int(GRBmodel* model, const char* name, int resvar, int argvar)> GRBaddgenconstrAbs = nullptr; std::function<int(GRBmodel* model, const char* name, int resvar, int nvars, const int* vars)> GRBaddgenconstrAnd = nullptr; std::function<int(GRBmodel* model, const char* name, int resvar, int nvars, const int* vars)> GRBaddgenconstrOr = nullptr; std::function<int(GRBmodel* model, int numqnz, int* qrow, int* qcol, double* qval)> GRBaddqpterms = nullptr; std::unique_ptr<DynamicLibrary> gurobi_dynamic_library; std::string gurobi_library_path; void LoadGurobiFunctions() { gurobi_dynamic_library->GetFunction(&GRBaddrangeconstr, NAMEOF(GRBaddrangeconstr)); gurobi_dynamic_library->GetFunction(&GRBaddvar, NAMEOF(GRBaddvar)); gurobi_dynamic_library->GetFunction(&GRBaddvars, NAMEOF(GRBaddvars)); gurobi_dynamic_library->GetFunction(&GRBchgcoeffs, NAMEOF(GRBchgcoeffs)); gurobi_dynamic_library->GetFunction(&GRBfreeenv, NAMEOF(GRBfreeenv)); gurobi_dynamic_library->GetFunction(&GRBfreemodel, NAMEOF(GRBfreemodel)); gurobi_dynamic_library->GetFunction(&GRBgetcharattrelement, NAMEOF(GRBgetcharattrelement)); gurobi_dynamic_library->GetFunction(&GRBgetdblattr, NAMEOF(GRBgetdblattr)); gurobi_dynamic_library->GetFunction(&GRBgetdblattrarray, NAMEOF(GRBgetdblattrarray)); gurobi_dynamic_library->GetFunction(&GRBgetdblattrelement, NAMEOF(GRBgetdblattrelement)); gurobi_dynamic_library->GetFunction(&GRBgetdblparam, NAMEOF(GRBgetdblparam)); gurobi_dynamic_library->GetFunction(&GRBgetenv, NAMEOF(GRBgetenv)); gurobi_dynamic_library->GetFunction(&GRBgeterrormsg, NAMEOF(GRBgeterrormsg)); gurobi_dynamic_library->GetFunction(&GRBgetintattr, NAMEOF(GRBgetintattr)); gurobi_dynamic_library->GetFunction(&GRBgetintattrelement, NAMEOF(GRBgetintattrelement)); gurobi_dynamic_library->GetFunction(&GRBloadenv, NAMEOF(GRBloadenv)); gurobi_dynamic_library->GetFunction(&GRBnewmodel, NAMEOF(GRBnewmodel)); gurobi_dynamic_library->GetFunction(&GRBoptimize, NAMEOF(GRBoptimize)); gurobi_dynamic_library->GetFunction(&GRBreadparams, NAMEOF(GRBreadparams)); gurobi_dynamic_library->GetFunction(&GRBresetparams, NAMEOF(GRBresetparams)); gurobi_dynamic_library->GetFunction(&GRBsetcharattrelement, NAMEOF(GRBsetcharattrelement)); gurobi_dynamic_library->GetFunction(&GRBsetdblattr, NAMEOF(GRBsetdblattr)); gurobi_dynamic_library->GetFunction(&GRBsetdblattrelement, NAMEOF(GRBsetdblattrelement)); gurobi_dynamic_library->GetFunction(&GRBsetdblparam, NAMEOF(GRBsetdblparam)); gurobi_dynamic_library->GetFunction(&GRBsetintattr, NAMEOF(GRBsetintattr)); gurobi_dynamic_library->GetFunction(&GRBsetintparam, NAMEOF(GRBsetintparam)); gurobi_dynamic_library->GetFunction(&GRBterminate, NAMEOF(GRBterminate)); gurobi_dynamic_library->GetFunction(&GRBupdatemodel, NAMEOF(GRBupdatemodel)); gurobi_dynamic_library->GetFunction(&GRBversion, NAMEOF(GRBversion)); gurobi_dynamic_library->GetFunction(&GRBwrite, NAMEOF(GRBwrite)); gurobi_dynamic_library->GetFunction(&GRBcbget, NAMEOF(GRBcbget)); gurobi_dynamic_library->GetFunction(&GRBcbcut, NAMEOF(GRBcbcut)); gurobi_dynamic_library->GetFunction(&GRBcblazy, NAMEOF(GRBcblazy)); gurobi_dynamic_library->GetFunction(&GRBcbsolution, NAMEOF(GRBcbsolution)); gurobi_dynamic_library->GetFunction(&GRBaddconstr, NAMEOF(GRBaddconstr)); gurobi_dynamic_library->GetFunction(&GRBaddgenconstrIndicator, NAMEOF(GRBaddgenconstrIndicator)); gurobi_dynamic_library->GetFunction(&GRBsetintattrelement, NAMEOF(GRBsetintattrelement)); gurobi_dynamic_library->GetFunction(&GRBsetcallbackfunc, NAMEOF(GRBsetcallbackfunc)); gurobi_dynamic_library->GetFunction(&GRBsetparam, NAMEOF(GRBsetparam)); gurobi_dynamic_library->GetFunction(&GRBaddsos, NAMEOF(GRBaddsos)); gurobi_dynamic_library->GetFunction(&GRBaddqconstr, NAMEOF(GRBaddqconstr)); gurobi_dynamic_library->GetFunction(&GRBaddgenconstrMax, NAMEOF(GRBaddgenconstrMax)); gurobi_dynamic_library->GetFunction(&GRBaddgenconstrMin, NAMEOF(GRBaddgenconstrMin)); gurobi_dynamic_library->GetFunction(&GRBaddgenconstrAbs, NAMEOF(GRBaddgenconstrAbs)); gurobi_dynamic_library->GetFunction(&GRBaddgenconstrAnd, NAMEOF(GRBaddgenconstrAnd)); gurobi_dynamic_library->GetFunction(&GRBaddgenconstrOr, NAMEOF(GRBaddgenconstrOr)); gurobi_dynamic_library->GetFunction(&GRBaddqpterms, NAMEOF(GRBaddqpterms)); } bool LoadSpecificGurobiLibrary(const std::string& full_library_path) { CHECK(gurobi_dynamic_library.get() != nullptr); VLOG(1) << "Try to load from " << full_library_path; return gurobi_dynamic_library->TryToLoad(full_library_path); } namespace { const std::vector<std::vector<std::string>> GurobiVersionLib = { {"911", "91"}, {"910", "91"}, {"903", "90"}, {"902", "90"}}; } bool SearchForGurobiDynamicLibrary() { if (!gurobi_library_path.empty() && LoadSpecificGurobiLibrary(gurobi_library_path)) { return true; } const char* gurobi_home_from_env = getenv("GUROBI_HOME"); for (const std::vector<std::string>& version_lib : GurobiVersionLib) { const std::string& dir = version_lib[0]; const std::string& number = version_lib[1]; #if defined(_MSC_VER) // Windows if (gurobi_home_from_env != nullptr && LoadSpecificGurobiLibrary(absl::StrCat( gurobi_home_from_env, "\\bin\\gurobi", number, ".dll"))) { return true; } if (LoadSpecificGurobiLibrary( absl::StrCat("C:\\Program Files\\gurobi", dir, "\\win64\\bin\\gurobi", number, ".dll"))) { return true; } #elif defined(__APPLE__) // OS X if (gurobi_home_from_env != nullptr && LoadSpecificGurobiLibrary(absl::StrCat( gurobi_home_from_env, "/lib/libgurobi", number, ".dylib"))) { return true; } if (LoadSpecificGurobiLibrary(absl::StrCat( "/Library/gurobi", dir, "/mac64/lib/libgurobi", number, ".dylib"))) { return true; } #elif defined(__GNUC__) // Linux if (gurobi_home_from_env != nullptr && LoadSpecificGurobiLibrary(absl::StrCat( gurobi_home_from_env, "/lib/libgurobi", number, ".so"))) { return true; } if (gurobi_home_from_env != nullptr && LoadSpecificGurobiLibrary(absl::StrCat( gurobi_home_from_env, "/lib64/libgurobi", number, ".so"))) { return true; } #endif } return false; } bool MPSolver::LoadGurobiSharedLibrary() { if (gurobi_dynamic_library.get() != nullptr) { return gurobi_dynamic_library->LibraryIsLoaded(); } gurobi_dynamic_library.reset(new DynamicLibrary()); if (SearchForGurobiDynamicLibrary()) { LoadGurobiFunctions(); return true; } return false; } void MPSolver::SetGurobiLibraryPath(const std::string& full_library_path) { gurobi_library_path = full_library_path; } bool MPSolver::GurobiIsCorrectlyInstalled() { if (!LoadGurobiSharedLibrary()) return false; GRBenv* env; if (GRBloadenv(&env, nullptr) != 0 || env == nullptr) return false; GRBfreeenv(env); return true; } } // namespace operations_research
46.405498
79
0.696905
sreesubbash
0498a0059f0712aab13c2c83503a43ae907fdc50
6,712
cpp
C++
libs/log/example/doc/extension_filter_parser_custom_rel.cpp
Manu343726/boost-cmake
009c3843b49a56880d988ffdca6d909f881edb3d
[ "BSL-1.0" ]
1,155
2015-01-10T19:04:33.000Z
2022-03-30T12:30:30.000Z
libs/log/example/doc/extension_filter_parser_custom_rel.cpp
Manu343726/boost-cmake
009c3843b49a56880d988ffdca6d909f881edb3d
[ "BSL-1.0" ]
618
2015-01-02T01:39:26.000Z
2022-03-28T15:18:40.000Z
libs/log/example/doc/extension_filter_parser_custom_rel.cpp
Manu343726/boost-cmake
009c3843b49a56880d988ffdca6d909f881edb3d
[ "BSL-1.0" ]
228
2015-01-13T12:55:42.000Z
2022-03-30T11:11:05.000Z
/* * Copyright Andrey Semashev 2007 - 2015. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ #include <string> #include <iostream> #include <stdexcept> #include <boost/smart_ptr/shared_ptr.hpp> #include <boost/smart_ptr/make_shared_object.hpp> #include <boost/lexical_cast.hpp> #include <boost/phoenix.hpp> #include <boost/log/core.hpp> #include <boost/log/expressions.hpp> #include <boost/log/attributes/attribute_name.hpp> #include <boost/log/attributes/scoped_attribute.hpp> #include <boost/log/sources/logger.hpp> #include <boost/log/sources/record_ostream.hpp> #include <boost/log/utility/value_ref.hpp> #include <boost/log/utility/formatting_ostream.hpp> #include <boost/log/utility/manipulators/add_value.hpp> #include <boost/log/utility/setup/filter_parser.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/utility/setup/console.hpp> namespace logging = boost::log; namespace attrs = boost::log::attributes; namespace src = boost::log::sources; namespace expr = boost::log::expressions; namespace sinks = boost::log::sinks; namespace keywords = boost::log::keywords; struct point { float m_x, m_y; point() : m_x(0.0f), m_y(0.0f) {} point(float x, float y) : m_x(x), m_y(y) {} }; bool operator== (point const& left, point const& right); bool operator!= (point const& left, point const& right); template< typename CharT, typename TraitsT > std::basic_ostream< CharT, TraitsT >& operator<< (std::basic_ostream< CharT, TraitsT >& strm, point const& p); template< typename CharT, typename TraitsT > std::basic_istream< CharT, TraitsT >& operator>> (std::basic_istream< CharT, TraitsT >& strm, point& p); const float epsilon = 0.0001f; bool operator== (point const& left, point const& right) { return (left.m_x - epsilon <= right.m_x && left.m_x + epsilon >= right.m_x) && (left.m_y - epsilon <= right.m_y && left.m_y + epsilon >= right.m_y); } bool operator!= (point const& left, point const& right) { return !(left == right); } template< typename CharT, typename TraitsT > std::basic_ostream< CharT, TraitsT >& operator<< (std::basic_ostream< CharT, TraitsT >& strm, point const& p) { if (strm.good()) strm << "(" << p.m_x << ", " << p.m_y << ")"; return strm; } template< typename CharT, typename TraitsT > std::basic_istream< CharT, TraitsT >& operator>> (std::basic_istream< CharT, TraitsT >& strm, point& p) { if (strm.good()) { CharT left_brace = static_cast< CharT >(0), comma = static_cast< CharT >(0), right_brace = static_cast< CharT >(0); strm.setf(std::ios_base::skipws); strm >> left_brace >> p.m_x >> comma >> p.m_y >> right_brace; if (left_brace != '(' || comma != ',' || right_brace != ')') strm.setstate(std::ios_base::failbit); } return strm; } //[ example_extension_filter_parser_rectangle_definition struct rectangle { point m_top_left, m_bottom_right; }; template< typename CharT, typename TraitsT > std::basic_ostream< CharT, TraitsT >& operator<< (std::basic_ostream< CharT, TraitsT >& strm, rectangle const& r); template< typename CharT, typename TraitsT > std::basic_istream< CharT, TraitsT >& operator>> (std::basic_istream< CharT, TraitsT >& strm, rectangle& r); //] template< typename CharT, typename TraitsT > std::basic_ostream< CharT, TraitsT >& operator<< (std::basic_ostream< CharT, TraitsT >& strm, rectangle const& r) { if (strm.good()) strm << "{" << r.m_top_left << " - " << r.m_bottom_right << "}"; return strm; } template< typename CharT, typename TraitsT > std::basic_istream< CharT, TraitsT >& operator>> (std::basic_istream< CharT, TraitsT >& strm, rectangle& r) { if (strm.good()) { CharT left_brace = static_cast< CharT >(0), dash = static_cast< CharT >(0), right_brace = static_cast< CharT >(0); strm.setf(std::ios_base::skipws); strm >> left_brace >> r.m_top_left >> dash >> r.m_bottom_right >> right_brace; if (left_brace != '{' || dash != '-' || right_brace != '}') strm.setstate(std::ios_base::failbit); } return strm; } //[ example_extension_custom_filter_factory_with_custom_rel // The function checks if the point is inside the rectangle bool is_in_rectangle(logging::value_ref< point > const& p, rectangle const& r) { if (p) { return p->m_x >= r.m_top_left.m_x && p->m_x <= r.m_bottom_right.m_x && p->m_y >= r.m_top_left.m_y && p->m_y <= r.m_bottom_right.m_y; } return false; } // Custom point filter factory class point_filter_factory : public logging::filter_factory< char > { public: logging::filter on_exists_test(logging::attribute_name const& name) { return expr::has_attr< point >(name); } logging::filter on_equality_relation(logging::attribute_name const& name, string_type const& arg) { return expr::attr< point >(name) == boost::lexical_cast< point >(arg); } logging::filter on_inequality_relation(logging::attribute_name const& name, string_type const& arg) { return expr::attr< point >(name) != boost::lexical_cast< point >(arg); } logging::filter on_custom_relation(logging::attribute_name const& name, string_type const& rel, string_type const& arg) { if (rel == "is_in_rectangle") { return boost::phoenix::bind(&is_in_rectangle, expr::attr< point >(name), boost::lexical_cast< rectangle >(arg)); } throw std::runtime_error("Unsupported filter relation: " + rel); } }; void init_factories() { //<- logging::register_simple_formatter_factory< point, char >("Coordinates"); //-> logging::register_filter_factory("Coordinates", boost::make_shared< point_filter_factory >()); } //] void init_logging() { init_factories(); logging::add_console_log ( std::clog, keywords::filter = "%Coordinates% is_in_rectangle \"{(0, 0) - (20, 20)}\"", keywords::format = "%TimeStamp% %Coordinates% %Message%" ); logging::add_common_attributes(); } int main(int, char*[]) { init_logging(); src::logger lg; // We have to use scoped attributes in order coordinates to be passed to filters { BOOST_LOG_SCOPED_LOGGER_TAG(lg, "Coordinates", point(10, 10)); BOOST_LOG(lg) << "Hello, world with coordinates (10, 10)!"; } { BOOST_LOG_SCOPED_LOGGER_TAG(lg, "Coordinates", point(50, 50)); BOOST_LOG(lg) << "Hello, world with coordinates (50, 50)!"; // this message will be suppressed by filter } return 0; }
32.901961
124
0.664631
Manu343726
0498cc5bacee21925336a1fad6909f61c7f36d94
4,361
hpp
C++
Support/Modules/GSRoot/StackInfo.hpp
graphisoft-python/TextEngine
20c2ff53877b20fdfe2cd51ce7abdab1ff676a70
[ "Apache-2.0" ]
3
2019-07-15T10:54:54.000Z
2020-01-25T08:24:51.000Z
Support/Modules/GSRoot/StackInfo.hpp
graphisoft-python/GSRoot
008fac2c6bf601ca96e7096705e25b10ba4d3e75
[ "Apache-2.0" ]
null
null
null
Support/Modules/GSRoot/StackInfo.hpp
graphisoft-python/GSRoot
008fac2c6bf601ca96e7096705e25b10ba4d3e75
[ "Apache-2.0" ]
1
2020-09-26T03:17:22.000Z
2020-09-26T03:17:22.000Z
// ********************************************************************************************************************* // Description: Stack Information // // Module: GSRoot // Namespace: GS // Contact person: MM // // SG compatible // ********************************************************************************************************************* #if !defined (STACKINFO_HPP) #define STACKINFO_HPP #pragma once // from GSRoot #include "Definitions.hpp" #if defined (WINDOWS) #include "IntelStackWalkWin.hpp" #endif #include "LoadedModuleListDefs.hpp" namespace StackInfoPrivate { GSROOT_DLL_EXPORT UInt32 CalculateStackHash (void* const addresses[], UInt32 MaxStackDepth, UInt32* pSigIndex); GSROOT_DLL_EXPORT UInt16 GetCallStack (Int32 ignoreDepth, UInt16 maxDepth, void* address[]); GSROOT_DLL_EXPORT void* RVAToVA (const LoadedModuleListDefs::RVAOrVA& rva); GSROOT_DLL_EXPORT GS::IntPtr GetCurrentUsageDebugInfo (); GSROOT_DLL_EXPORT UInt16 CaptureStackBackTr (Int32 ignoreDepth, UInt16 maxDepth, void* address[]); } // namespace StackInfoPrivate namespace GS { // --------------------------------------------------------------------------------------------------------------------- // StackInfo struct, saved into the allocated memory blocks // --------------------------------------------------------------------------------------------------------------------- template <UInt16 MaxCallDepth> class StackInfoCustomDepth { public: typedef UInt8 WalkType; enum WalkTypes { FastWalkRVA, // Store relative addresses, plus module IDs FastWalk, // Store absolute addresses DbgHelpWalk // Rely on dbghelp.dll's stack walk (absolute addresses) }; private: enum { Signature = 'STCK' }; union AddressReference { LoadedModuleListDefs::RVAOrVA rva; void* absoluteAddress; }; UInt32 signature; UInt16 depth; WalkType type; AddressReference addresses[MaxCallDepth]; GS::UIntPtr usageDebugInfo; public: explicit StackInfoCustomDepth (Int32 ignoreDepth = 0, UInt16 maxDepth = MaxCallDepth, WalkType walkType = FastWalk); bool IsValid () const { return signature == Signature; } UInt32 GetStackHashCode (UInt32* pSigIndex) const; UInt32 GetDepth () const { return depth; } void* GetAbsoluteAddress (Int32 i) const; GS::UIntPtr GetUsageDebugInfo () const { return usageDebugInfo; } }; typedef StackInfoCustomDepth<20> StackInfo; } // namespace GS // --------------------------------------------------------------------------------------------------------------------- // StackInfo class implementation // --------------------------------------------------------------------------------------------------------------------- template <UInt16 MaxCallDepth> GS::StackInfoCustomDepth<MaxCallDepth>::StackInfoCustomDepth (Int32 ignoreDepth, UInt16 maxDepth, WalkType walkType) : signature (Signature), depth (maxDepth), type (walkType) { memset (addresses, 0, sizeof addresses); usageDebugInfo = StackInfoPrivate::GetCurrentUsageDebugInfo (); if (maxDepth == 0) { return; } #if defined (WINDOWS) switch (type) { case FastWalkRVA: depth = GS::IntelStackWalk (nullptr, ignoreDepth, maxDepth, &addresses->rva, Relative); break; case FastWalk: depth = StackInfoPrivate::CaptureStackBackTr (ignoreDepth, maxDepth, &addresses->absoluteAddress); break; case DbgHelpWalk: depth = StackInfoPrivate::GetCallStack (ignoreDepth, maxDepth, &addresses->absoluteAddress); break; } #elif defined (macintosh) || defined (__linux__) UNUSED_PARAMETER (ignoreDepth); #endif } template <UInt16 MaxCallDepth> void* GS::StackInfoCustomDepth<MaxCallDepth>::GetAbsoluteAddress (Int32 i) const { return type == FastWalkRVA ? StackInfoPrivate::RVAToVA (addresses[i].rva) : addresses[i].absoluteAddress; } template <UInt16 MaxCallDepth> UInt32 GS::StackInfoCustomDepth<MaxCallDepth>::GetStackHashCode (UInt32* pSigIndex) const { if (type == FastWalkRVA) { void* absoluteAddresses[MaxCallDepth]; for (UInt32 i = 0; i < MaxCallDepth; ++i) absoluteAddresses[i] = StackInfoPrivate::RVAToVA (addresses[i].rva); return StackInfoPrivate::CalculateStackHash (absoluteAddresses, MaxCallDepth, pSigIndex); } else { return StackInfoPrivate::CalculateStackHash (&addresses->absoluteAddress, MaxCallDepth, pSigIndex); } } #endif
30.284722
120
0.62371
graphisoft-python
0498d8a8dc6e8deff8fcd2f26aff14da0ddabebe
1,447
cc
C++
DNSRecordType.cc
shuLhan/libvos
831491b197fa8f267fd94966d406596896e6f25c
[ "BSD-3-Clause" ]
1
2017-09-14T13:31:16.000Z
2017-09-14T13:31:16.000Z
DNSRecordType.cc
shuLhan/libvos
831491b197fa8f267fd94966d406596896e6f25c
[ "BSD-3-Clause" ]
null
null
null
DNSRecordType.cc
shuLhan/libvos
831491b197fa8f267fd94966d406596896e6f25c
[ "BSD-3-Clause" ]
5
2015-04-11T02:59:06.000Z
2021-03-03T19:45:39.000Z
/** * Copyright 2017 M. Shulhan (ms@kilabit.info). All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "DNSRecordType.hh" namespace vos { const char* DNSRecordType::__cname = "DNSRecordType"; const int DNSRecordType::SIZE = 22; const char* DNSRecordType::NAMES[DNSRecordType::SIZE] = { "A" ,"NS" ,"MD" ,"MF", "CNAME" , "SOA" ,"MB" ,"MG" ,"MR", "NULL" , "WKS" ,"PTR" ,"HINFO","MINFO","MX" , "TXT" ,"AAAA" ,"SRV" ,"AXFR" ,"MAILB" , "MAILA" ,"*" }; const int DNSRecordType::VALUES[DNSRecordType::SIZE] = { 1 ,2 ,3 ,4 ,5 , 6 ,7 ,8 ,9 ,10 , 11 ,12 ,13 ,14 ,15 , 16 ,28 ,33 ,252 ,253 , 254 ,255 }; DNSRecordType::DNSRecordType() : Object() {} DNSRecordType::~DNSRecordType() {} /** * `GET_NAME()` will search list of record type with value is `type` and * return their NAME representation. * * It will return NULL if no match found. */ const char* DNSRecordType::GET_NAME(const int type) { int x = 0; for (; x < SIZE; x++) { if (VALUES[x] == type) { return NAMES[x]; } } return NULL; } /** * `GET_VALUE()` will search list of record type that match with `name` and * return their TYPE representation. * * It will return -1 if no match found. */ int DNSRecordType::GET_VALUE(const char* name) { int x = 0; for (; x < SIZE; x++) { if (strcasecmp(NAMES[x], name) == 0) { return VALUES[x]; } } return -1; } }
19.039474
75
0.615757
shuLhan
049949e220d8f31825a76a600514a0de3d2b3cdd
10,584
cpp
C++
Source/System/auth/nsal.cpp
blgrossMS/xbox-live-api
17c586336e11f0fa3a2a3f3acd665b18c5487b24
[ "MIT" ]
2
2021-07-17T13:34:20.000Z
2022-01-09T00:55:51.000Z
Source/System/auth/nsal.cpp
blgrossMS/xbox-live-api
17c586336e11f0fa3a2a3f3acd665b18c5487b24
[ "MIT" ]
null
null
null
Source/System/auth/nsal.cpp
blgrossMS/xbox-live-api
17c586336e11f0fa3a2a3f3acd665b18c5487b24
[ "MIT" ]
1
2018-11-18T08:32:40.000Z
2018-11-18T08:32:40.000Z
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "pch.h" #include "nsal.h" #include "xtitle_service.h" NAMESPACE_MICROSOFT_XBOX_SERVICES_SYSTEM_CPP_BEGIN template<typename T> void add_endpoint_helper( _In_ std::vector<T>& endpoints, _In_ nsal_protocol protocol, _In_ const string_t& hostName, _In_ nsal_host_name_type hostNameType, _In_ int port, _In_ const string_t& path, _In_ const string_t& relyingParty, _In_ const string_t& subRelyingParty, _In_ const string_t& tokenType, _In_ int signaturePolicyIndex) { // First check if there's already a match nsal_endpoint_info newInfo(relyingParty, subRelyingParty, tokenType, signaturePolicyIndex); for (auto endpoint = endpoints.begin(); endpoint != endpoints.end(); endpoint++) { if (endpoint->is_same(protocol, hostName, port)) { nsal_endpoint_info existingInfo; if (endpoint->get_info_for_exact_path(path, existingInfo)) { // The endpoint already exists, make sure all the info about it matches if (existingInfo == newInfo) { return; } else { throw std::runtime_error("endpoints conflict"); } } else { // The specific path does not exist so add it endpoint->add_info(path, newInfo); return; } } } // No matching endpoints so we create a new one. endpoints.emplace_back(protocol, hostName, hostNameType, port); endpoints.back().add_info(path, newInfo); } void nsal::add_endpoint( _In_ nsal_protocol protocol, _In_ const string_t& hostName, _In_ nsal_host_name_type hostNameType, _In_ int port, _In_ const string_t& path, _In_ const string_t& relyingParty, _In_ const string_t& subRelyingParty, _In_ const string_t& tokenType, _In_ int signaturePolicyIndex) { switch (hostNameType) { case nsal_host_name_type::fqdn: add_endpoint_helper<fqdn_nsal_endpoint>( m_fqdnEndpoints, protocol, hostName, hostNameType, port, path, relyingParty, subRelyingParty, tokenType, signaturePolicyIndex); break; case nsal_host_name_type::wildcard: add_endpoint_helper<wildcard_nsal_endpoint>( m_wildcardEndpoints, protocol, hostName, hostNameType, port, path, relyingParty, subRelyingParty, tokenType, signaturePolicyIndex); break; case nsal_host_name_type::ip: add_endpoint_helper<ip_nsal_endpoint>( m_ipEndpoints, protocol, hostName, hostNameType, port, path, relyingParty, subRelyingParty, tokenType, signaturePolicyIndex); break; case nsal_host_name_type::cidr: add_endpoint_helper<cidr_nsal_endpoint>( m_cidrEndpoints, protocol, hostName, hostNameType, port, path, relyingParty, subRelyingParty, tokenType, signaturePolicyIndex); break; default: throw std::runtime_error("unsupported host name type"); } } template<typename TEndpoint, typename THostName> bool get_helper( _In_ const std::vector<TEndpoint>& endpoints, _In_ nsal_protocol protocol, _In_ const THostName& hostName, _In_ int port, _In_ const string_t& path, _Out_ nsal_endpoint_info& info) { for (auto endpoint = endpoints.begin(); endpoint != endpoints.end(); endpoint++) { if (endpoint->is_match(protocol, hostName, port)) { return endpoint->get_info(path, info); } } return false; } bool nsal::get_endpoint( _In_ web::http::uri& uri, _Out_ nsal_endpoint_info& info) const { nsal_protocol protocol = nsal::deserialize_protocol(uri.scheme()); int port = nsal::get_port(protocol, uri.port()); return get_endpoint(protocol, uri.host(), port, uri.path(), info); } bool nsal::get_endpoint( _In_ nsal_protocol protocol, _In_ const string_t& hostName, _In_ int port, _In_ const string_t& path, _Out_ nsal_endpoint_info& info) const { string_t hostNameWithoutEnv = hostName; string_t dnet = _T(".dnet"); size_t f = hostNameWithoutEnv.find(dnet); if ( f != string_t::npos ) { hostNameWithoutEnv.replace(f, dnet.length(), _T("")); } ip_address ipAddr; if (ip_address::try_parse(hostNameWithoutEnv, ipAddr)) { if (get_helper(m_ipEndpoints, protocol, ipAddr, port, path, info)) { return true; } if (get_helper(m_cidrEndpoints, protocol, ipAddr, port, path, info)) { return true; } } else { if (get_helper(m_fqdnEndpoints, protocol, hostNameWithoutEnv, port, path, info)) { return true; } if (get_helper(m_wildcardEndpoints, protocol, hostNameWithoutEnv, port, path, info)) { return true; } } return false; } void nsal::add_signature_policy(_In_ const signature_policy& signaturePolicy) { m_signaturePolicies.push_back(signaturePolicy); } const signature_policy& nsal::get_signature_policy(_In_ int index) const { return m_signaturePolicies[index]; } nsal_protocol nsal::deserialize_protocol(_In_ const utility::string_t& str) { if (_T("https") == str) return nsal_protocol::https; if (_T("http") == str) return nsal_protocol::http; if (_T("tcp") == str) return nsal_protocol::tcp; if (_T("udp") == str) return nsal_protocol::udp; if (_T("wss") == str) return nsal_protocol::wss; throw web::json::json_exception(_T("Invalid protocol for NSAL endpoint")); } nsal_host_name_type nsal::deserialize_host_name_type(_In_ const utility::string_t& str) { if (_T("fqdn") == str) return nsal_host_name_type::fqdn; if (_T("wildcard") == str) return nsal_host_name_type::wildcard; if (_T("ip") == str) return nsal_host_name_type::ip; if (_T("cidr") == str) return nsal_host_name_type::cidr; throw web::json::json_exception(_T("Invalid NSAL host name type")); } int nsal::deserialize_port(_In_ nsal_protocol protocol, _In_ const web::json::value& json) { int port = utils::extract_json_int(json, _T("Port"), false, 0); return nsal::get_port(protocol, port); } int nsal::get_port( _In_ nsal_protocol protocol, _In_ int port ) { if (port == 0) { switch (protocol) { case nsal_protocol::https: return 443; case nsal_protocol::http: case nsal_protocol::wss: return 80; default: throw web::json::json_exception(_T("Must specify port when protocol is not http or https")); } } return port; } void nsal::deserialize_endpoint( _In_ nsal& nsal, _In_ const web::json::value& endpoint) { utility::string_t relyingParty(utils::extract_json_string(endpoint, _T("RelyingParty"))); if (relyingParty.empty()) { // If there's no RP, we don't care since there's no token to attach return; } utility::string_t subRelyingParty(utils::extract_json_string(endpoint, _T("SubRelyingParty"))); nsal_protocol protocol(nsal::deserialize_protocol(utils::extract_json_string(endpoint, _T("Protocol"), true))); nsal_host_name_type hostNameType(deserialize_host_name_type(utils::extract_json_string(endpoint, _T("HostType"), true))); int port = deserialize_port(protocol, endpoint); nsal.add_endpoint( protocol, utils::extract_json_string(endpoint, _T("Host"), true), hostNameType, port, utils::extract_json_string(endpoint, _T("Path")), relyingParty, subRelyingParty, utils::extract_json_string(endpoint, _T("TokenType"), true), utils::extract_json_int(endpoint, _T("SignaturePolicyIndex"), false, -1)); } void nsal::deserialize_signature_policy(_In_ nsal& nsal, _In_ const web::json::value& json) { std::error_code errc = xbox_live_error_code::no_error; int version = utils::extract_json_int(json, _T("Version"), true); int maxBodyBytes = utils::extract_json_int(json, _T("MaxBodyBytes"), true); std::vector<string_t> extraHeaders( utils::extract_json_vector<string_t>(utils::json_string_extractor, json, _T("ExtraHeaders"), errc, false)); nsal.add_signature_policy(signature_policy(version, maxBodyBytes, extraHeaders)); } nsal nsal::deserialize(_In_ const web::json::value& json) { nsal nsal; auto& jsonObj(json.as_object()); auto it = jsonObj.find(_T("SignaturePolicies")); if (it != jsonObj.end()) { web::json::array signaturePolicies(it->second.as_array()); for (auto it2 = signaturePolicies.begin(); it2 != signaturePolicies.end(); ++it2) { deserialize_signature_policy(nsal, *it2); } } it = jsonObj.find(_T("EndPoints")); if (it != jsonObj.end()) { web::json::array endpoints(it->second.as_array()); for (auto it2 = endpoints.begin(); it2 != endpoints.end(); ++it2) { deserialize_endpoint(nsal, *it2); } } nsal.add_endpoint( nsal_protocol::wss, _T("*.xboxlive.com"), nsal_host_name_type::wildcard, 80, string_t(), _T("http://xboxlive.com"), string_t(), _T("JWT"), 0 ); nsal._Sort_wildcard_endpoints(); return nsal; } void nsal::_Sort_wildcard_endpoints() { std::sort( m_wildcardEndpoints.begin(), m_wildcardEndpoints.end(), [](_In_ const wildcard_nsal_endpoint& lhs, _In_ const wildcard_nsal_endpoint& rhs) -> bool { return lhs.length() > rhs.length(); }); } NAMESPACE_MICROSOFT_XBOX_SERVICES_SYSTEM_CPP_END
29.157025
125
0.616875
blgrossMS
049c7c6bf5fa81b209230f55f8236cdcf3fd46e6
13,043
cpp
C++
tesseract-ocr/wordrec/seam.cpp
danauclair/CardScan
bc8cad5485e67d78419bb757d668bf5b73231b8d
[ "BSD-3-Clause", "MIT" ]
28
2015-04-09T04:17:29.000Z
2019-05-28T11:59:22.000Z
tesseract-ocr/wordrec/seam.cpp
danauclair/CardScan
bc8cad5485e67d78419bb757d668bf5b73231b8d
[ "BSD-3-Clause", "MIT" ]
2
2017-03-23T11:44:57.000Z
2017-12-09T04:02:54.000Z
tesseract-ocr/wordrec/seam.cpp
danauclair/CardScan
bc8cad5485e67d78419bb757d668bf5b73231b8d
[ "BSD-3-Clause", "MIT" ]
17
2015-01-20T08:37:00.000Z
2019-02-04T02:55:30.000Z
/* -*-C-*- ******************************************************************************** * * File: seam.c (Formerly seam.c) * Description: * Author: Mark Seaman, OCR Technology * Created: Fri Oct 16 14:37:00 1987 * Modified: Fri May 17 16:30:13 1991 (Mark Seaman) marks@hpgrlt * Language: C * Package: N/A * Status: Reusable Software Component * * (c) Copyright 1987, Hewlett-Packard Company. ** 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. * *********************************************************************************/ /*---------------------------------------------------------------------- I n c l u d e s ----------------------------------------------------------------------*/ #include "seam.h" #include "callcpp.h" #include "structures.h" #include "makechop.h" #ifdef __UNIX__ #include <assert.h> #endif /*---------------------------------------------------------------------- V a r i a b l e s ----------------------------------------------------------------------*/ #define NUM_STARTING_SEAMS 20 #define SEAMBLOCK 100 /* Cells per block */ makestructure (newseam, free_seam, printseam, SEAM, freeseam, SEAMBLOCK, "SEAM", seamcount); /*---------------------------------------------------------------------- Public Function Code ----------------------------------------------------------------------*/ /** * @name point_in_split * * Check to see if either of these points are present in the current * split. * @returns TRUE if one of them is split. */ bool point_in_split(SPLIT *split, EDGEPT *point1, EDGEPT *point2) { return ((split) ? ((exact_point (split->point1, point1) || exact_point (split->point1, point2) || exact_point (split->point2, point1) || exact_point (split->point2, point2)) ? TRUE : FALSE) : FALSE); } /** * @name point_in_seam * * Check to see if either of these points are present in the current * seam. * @returns TRUE if one of them is. */ bool point_in_seam(SEAM *seam, SPLIT *split) { return (point_in_split (seam->split1, split->point1, split->point2) || point_in_split (seam->split2, split->point1, split->point2) || point_in_split (seam->split3, split->point1, split->point2)); } /** * @name add_seam * * Add another seam to a collection of seams. */ SEAMS add_seam(SEAMS seam_list, SEAM *seam) { return (array_push (seam_list, seam)); } /** * @name combine_seam * * Combine two seam records into a single seam. Move the split * references from the second seam to the first one. The argument * convention is patterned after strcpy. */ void combine_seams(SEAM *dest_seam, SEAM *source_seam) { dest_seam->priority += source_seam->priority; dest_seam->location += source_seam->location; dest_seam->location /= 2; if (source_seam->split1) { if (!dest_seam->split1) dest_seam->split1 = source_seam->split1; else if (!dest_seam->split2) dest_seam->split2 = source_seam->split1; else if (!dest_seam->split3) dest_seam->split3 = source_seam->split1; else cprintf ("combine_seam: Seam is too crowded, can't be combined !\n"); } if (source_seam->split2) { if (!dest_seam->split2) dest_seam->split2 = source_seam->split2; else if (!dest_seam->split3) dest_seam->split3 = source_seam->split2; else cprintf ("combine_seam: Seam is too crowded, can't be combined !\n"); } if (source_seam->split3) { if (!dest_seam->split3) dest_seam->split3 = source_seam->split3; else cprintf ("combine_seam: Seam is too crowded, can't be combined !\n"); } free_seam(source_seam); } /** * @name delete_seam * * Free this seam record and the splits that are attached to it. */ void delete_seam(void *arg) { //SEAM *seam) SEAM *seam = (SEAM *) arg; if (seam) { if (seam->split1) delete_split (seam->split1); if (seam->split2) delete_split (seam->split2); if (seam->split3) delete_split (seam->split3); free_seam(seam); } } /** * @name free_seam_list * * Free all the seams that have been allocated in this list. Reclaim * the memory for each of the splits as well. */ void free_seam_list(SEAMS seam_list) { int x; array_loop (seam_list, x) delete_seam (array_value (seam_list, x)); array_free(seam_list); } /** * @name test_insert_seam * * @returns true if insert_seam will succeed. */ bool test_insert_seam(SEAMS seam_list, int index, TBLOB *left_blob, TBLOB *first_blob) { SEAM *test_seam; TBLOB *blob; int test_index; int list_length; list_length = array_count (seam_list); for (test_index = 0, blob = first_blob->next; test_index < index; test_index++, blob = blob->next) { test_seam = (SEAM *) array_value (seam_list, test_index); if (test_index + test_seam->widthp < index && test_seam->widthp + test_index == index - 1 && account_splits_right(test_seam, blob) < 0) return false; } for (test_index = index, blob = left_blob->next; test_index < list_length; test_index++, blob = blob->next) { test_seam = (SEAM *) array_value (seam_list, test_index); if (test_index - test_seam->widthn >= index && test_index - test_seam->widthn == index && account_splits_left(test_seam, first_blob, blob) < 0) return false; } return true; } /** * @name insert_seam * * Add another seam to a collection of seams at a particular location * in the seam array. */ SEAMS insert_seam(SEAMS seam_list, int index, SEAM *seam, TBLOB *left_blob, TBLOB *first_blob) { SEAM *test_seam; TBLOB *blob; int test_index; int list_length; list_length = array_count (seam_list); for (test_index = 0, blob = first_blob->next; test_index < index; test_index++, blob = blob->next) { test_seam = (SEAM *) array_value (seam_list, test_index); if (test_index + test_seam->widthp >= index) { test_seam->widthp++; /*got in the way */ } else if (test_seam->widthp + test_index == index - 1) { test_seam->widthp = account_splits_right(test_seam, blob); if (test_seam->widthp < 0) { cprintf ("Failed to find any right blob for a split!\n"); print_seam("New dud seam", seam); print_seam("Failed seam", test_seam); } } } for (test_index = index, blob = left_blob->next; test_index < list_length; test_index++, blob = blob->next) { test_seam = (SEAM *) array_value (seam_list, test_index); if (test_index - test_seam->widthn < index) { test_seam->widthn++; /*got in the way */ } else if (test_index - test_seam->widthn == index) { test_seam->widthn = account_splits_left(test_seam, first_blob, blob); if (test_seam->widthn < 0) { cprintf ("Failed to find any left blob for a split!\n"); print_seam("New dud seam", seam); print_seam("Failed seam", test_seam); } } } return (array_insert (seam_list, index, seam)); } /** * @name account_splits_right * * Account for all the splits by looking to the right. * in the blob list. */ int account_splits_right(SEAM *seam, TBLOB *blob) { inT8 found_em[3]; inT8 width; found_em[0] = seam->split1 == NULL; found_em[1] = seam->split2 == NULL; found_em[2] = seam->split3 == NULL; if (found_em[0] && found_em[1] && found_em[2]) return 0; width = 0; do { if (!found_em[0]) found_em[0] = find_split_in_blob (seam->split1, blob); if (!found_em[1]) found_em[1] = find_split_in_blob (seam->split2, blob); if (!found_em[2]) found_em[2] = find_split_in_blob (seam->split3, blob); if (found_em[0] && found_em[1] && found_em[2]) { return width; } width++; blob = blob->next; } while (blob != NULL); return -1; } /** * @name account_splits_left * * Account for all the splits by looking to the left. * in the blob list. */ int account_splits_left(SEAM *seam, TBLOB *blob, TBLOB *end_blob) { static inT32 depth = 0; static inT8 width; static inT8 found_em[3]; if (blob != end_blob) { depth++; account_splits_left (seam, blob->next, end_blob); depth--; } else { found_em[0] = seam->split1 == NULL; found_em[1] = seam->split2 == NULL; found_em[2] = seam->split3 == NULL; width = 0; } if (!found_em[0]) found_em[0] = find_split_in_blob (seam->split1, blob); if (!found_em[1]) found_em[1] = find_split_in_blob (seam->split2, blob); if (!found_em[2]) found_em[2] = find_split_in_blob (seam->split3, blob); if (!found_em[0] || !found_em[1] || !found_em[2]) { width++; if (depth == 0) { width = -1; } } return width; } /** * @name find_split_in_blob * * @returns TRUE if the split is somewhere in this blob. */ bool find_split_in_blob(SPLIT *split, TBLOB *blob) { TESSLINE *outline; #if 0 for (outline = blob->outlines; outline != NULL; outline = outline->next) if (is_split_outline (outline, split)) return TRUE; return FALSE; #endif for (outline = blob->outlines; outline != NULL; outline = outline->next) if (point_in_outline(split->point1, outline)) break; if (outline == NULL) return FALSE; for (outline = blob->outlines; outline != NULL; outline = outline->next) if (point_in_outline(split->point2, outline)) return TRUE; return FALSE; } /** * @name join_two_seams * * Merge these two seams into a new seam. Duplicate the split records * in both of the input seams. Return the resultant seam. */ SEAM *join_two_seams(SEAM *seam1, SEAM *seam2) { SEAM *result = NULL; SEAM *temp; assert(seam1 &&seam2); if (((seam1->split3 == NULL && seam2->split2 == NULL) || (seam1->split2 == NULL && seam2->split3 == NULL) || seam1->split1 == NULL || seam2->split1 == NULL) && (!shared_split_points (seam1, seam2))) { clone_seam(result, seam1); clone_seam(temp, seam2); combine_seams(result, temp); } return (result); } /** * @name new_seam * * Create a structure for a "seam" between two blobs. This data * structure may actually hold up to three different splits. * Initailization of this record is done by this routine. */ SEAM *new_seam(PRIORITY priority, int x_location, SPLIT *split1, SPLIT *split2, SPLIT *split3) { SEAM *seam; seam = newseam (); seam->priority = priority; seam->location = x_location; seam->widthp = 0; seam->widthn = 0; seam->split1 = split1; seam->split2 = split2; seam->split3 = split3; return (seam); } /** * @name new_seam_list * * Create a collection of seam records in an array. */ SEAMS new_seam_list() { return (array_new (NUM_STARTING_SEAMS)); } /** * @name print_seam * * Print a list of splits. Show the coordinates of both points in * each split. */ void print_seam(const char *label, SEAM *seam) { if (seam) { cprintf(label); cprintf (" %6.2f @ %5d, p=%d, n=%d ", seam->priority, seam->location, seam->widthp, seam->widthn); print_split (seam->split1); if (seam->split2) { cprintf (", "); print_split (seam->split2); if (seam->split3) { cprintf (", "); print_split (seam->split3); } } cprintf ("\n"); } } /** * @name print_seams * * Print a list of splits. Show the coordinates of both points in * each split. */ void print_seams(const char *label, SEAMS seams) { int x; char number[CHARS_PER_LINE]; if (seams) { cprintf ("%s\n", label); array_loop(seams, x) { sprintf (number, "%2d: ", x); print_seam (number, (SEAM *) array_value (seams, x)); } cprintf ("\n"); } } /** * @name shared_split_points * * Check these two seams to make sure that neither of them have two * points in common. Return TRUE if any of the same points are present * in any of the splits of both seams. */ int shared_split_points(SEAM *seam1, SEAM *seam2) { if (seam1 == NULL || seam2 == NULL) return (FALSE); if (seam2->split1 == NULL) return (FALSE); if (point_in_seam (seam1, seam2->split1)) return (TRUE); if (seam2->split2 == NULL) return (FALSE); if (point_in_seam (seam1, seam2->split2)) return (TRUE); if (seam2->split3 == NULL) return (FALSE); if (point_in_seam (seam1, seam2->split3)) return (TRUE); return (FALSE); }
26.892784
83
0.602162
danauclair
049ea0bcd0d257b8808756b083ed5d198d882ade
5,081
hxx
C++
TubeTKLib/Filtering/tubeTreeFilters.hxx
jsdelivrbot/ITKTubeTK
b89403a7178ed6635e7860bec4f2eb009dd70711
[ "Apache-2.0" ]
null
null
null
TubeTKLib/Filtering/tubeTreeFilters.hxx
jsdelivrbot/ITKTubeTK
b89403a7178ed6635e7860bec4f2eb009dd70711
[ "Apache-2.0" ]
null
null
null
TubeTKLib/Filtering/tubeTreeFilters.hxx
jsdelivrbot/ITKTubeTK
b89403a7178ed6635e7860bec4f2eb009dd70711
[ "Apache-2.0" ]
null
null
null
/*========================================================================= Library: TubeTK Copyright 2010 Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. All rights reserved. Licensed under the Apache License, Version 2.0 ( the "License" ); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ #ifndef __tubeTreeFilters_hxx #define __tubeTreeFilters_hxx #include "itkNumericTraits.h" namespace tube { //------------------------------------------------------------------------ template< unsigned int VDimension > void TreeFilters< VDimension >:: FillGap( typename TubeGroupType::Pointer & pTubeGroup, char InterpolationMethod ) { char tubeName[] = "Tube"; TubeListPointerType pTubeList = pTubeGroup->GetChildren( pTubeGroup->GetMaximumDepth(), tubeName ); for( typename TubeGroupType::ChildrenListType::iterator itSourceTubes = pTubeList->begin(); itSourceTubes != pTubeList->end(); ++itSourceTubes ) { TubePointerType pCurTube = dynamic_cast< TubeType * >( itSourceTubes->GetPointer() ); TubeIdType curParentTubeId = pCurTube->GetParentId(); TubePointType* parentNearestPoint = NULL; if( pCurTube->GetRoot() == false && curParentTubeId != pTubeGroup->GetId() ) { //find parent target tube for( typename TubeGroupType::ChildrenListType::iterator itTubes = pTubeList->begin(); itTubes != pTubeList->end(); ++itTubes ) { TubePointerType pTube = dynamic_cast< TubeType * >( itTubes->GetPointer() ); if( pTube->GetId() == curParentTubeId ) { double minDistance = itk::NumericTraits<double>::max(); int flag =-1; for( unsigned int index = 0; index < pTube->GetNumberOfPoints(); ++index ) { TubePointType* tubePoint = dynamic_cast< TubePointType* >( pTube->GetPoint( index ) ); PositionType tubePointPosition = tubePoint->GetPosition(); double distance = tubePointPosition.SquaredEuclideanDistanceTo( pCurTube->GetPoint( 0 )->GetPosition() ); if( minDistance > distance ) { minDistance = distance; parentNearestPoint = tubePoint; flag = 1; } distance = tubePointPosition.SquaredEuclideanDistanceTo( pCurTube->GetPoint( pCurTube->GetNumberOfPoints() - 1 ) ->GetPosition() ); if( minDistance > distance ) { minDistance = distance; parentNearestPoint = tubePoint; flag = 2; } } TubePointListType newTubePoints; if( flag == 1 ) { TubePointType* childTubeStartPoint = dynamic_cast< TubePointType* >( pCurTube->GetPoint( 0 ) ); InterpolatePath( parentNearestPoint, childTubeStartPoint, newTubePoints, InterpolationMethod ); TubePointListType targetTubePoints = pCurTube->GetPoints(); pCurTube->Clear(); for( unsigned int index = 0; index < newTubePoints.size(); ++index ) { pCurTube->GetPoints().push_back( newTubePoints[ index ] ); } for( unsigned int i = 0; i < targetTubePoints.size(); ++i ) { pCurTube->GetPoints().push_back( targetTubePoints[ i ] ); } } if( flag == 2 ) { TubePointType* childTubeEndPoint = dynamic_cast< TubePointType* > ( pCurTube->GetPoint( pCurTube->GetNumberOfPoints() - 1 ) ); InterpolatePath( parentNearestPoint, childTubeEndPoint, newTubePoints, InterpolationMethod ); for( int index = newTubePoints.size() - 1; index >= 0; index-- ) { pCurTube->GetPoints().push_back( newTubePoints[ index ] ); } } break; } } } } } //------------------------------------------------------------------------ template< unsigned int VDimension > void TreeFilters< VDimension >:: InterpolatePath( typename TubeType::TubePointType * parentNearestPoint, typename TubeType::TubePointType * itkNotUsed( childEndPoint ), typename TubeType::PointListType & newTubePoints, char InterpolationMethod ) { if( InterpolationMethod == 'S' ) { newTubePoints.push_back( *parentNearestPoint ); } return; } } // End namespace tube #endif // End !defined( __tubeTreeFilters_hxx )
34.80137
76
0.577249
jsdelivrbot
04a0c1f364bbab22b649626a6bb56e4280a83040
13,991
tpp
C++
core/src/partition/partitioned_petsc_vec/02_partitioned_petsc_vec_for_hyperelasticity_get_string.tpp
maierbn/opendihu
577650e2f6b36a7306766b0f4176f8124458cbf0
[ "MIT" ]
17
2018-11-25T19:29:34.000Z
2021-09-20T04:46:22.000Z
core/src/partition/partitioned_petsc_vec/02_partitioned_petsc_vec_for_hyperelasticity_get_string.tpp
maierbn/opendihu
577650e2f6b36a7306766b0f4176f8124458cbf0
[ "MIT" ]
1
2020-11-12T15:15:58.000Z
2020-12-29T15:29:24.000Z
core/src/partition/partitioned_petsc_vec/02_partitioned_petsc_vec_for_hyperelasticity_get_string.tpp
maierbn/opendihu
577650e2f6b36a7306766b0f4176f8124458cbf0
[ "MIT" ]
4
2018-10-17T12:18:10.000Z
2021-05-28T13:24:20.000Z
#include "partition/partitioned_petsc_vec/02_partitioned_petsc_vec_for_hyperelasticity.h" #include "utility/mpi_utility.h" // ---- incompressible case ---- template<typename DisplacementsFunctionSpaceType, typename PressureFunctionSpaceType, typename Term, int nComponents> std::string PartitionedPetscVecForHyperelasticity<DisplacementsFunctionSpaceType,PressureFunctionSpaceType,Term,nComponents,std::enable_if_t<Term::isIncompressible,Term>>:: getString(bool horizontal, std::string vectorName) const { // do not assemble a horizontal string for console in release mode, because this is only needed for debugging output //#ifdef NDEBUG // if (horizontal) // return std::string(""); //#endif #ifndef NDEBUG std::stringstream result; int ownRankNo = this->meshPartition_->ownRankNo(); // the master rank collects all data and writes the file if (ownRankNo == 0) { // handle displacement values std::vector<std::vector<global_no_t>> dofNosGlobalNatural(this->meshPartition_->nRanks()); std::vector<std::vector<double>> values(this->meshPartition_->nRanks()); std::vector<int> nDofsOnRank(this->meshPartition_->nRanks()); std::vector<int> nPressureDofsOnRank(this->meshPartition_->nRanks()); VLOG(1) << "values: " << values; // handle own rank // get dof nos in global natural ordering int nDofsLocalWithoutGhosts = this->meshPartition_->nDofsLocalWithoutGhosts(); nDofsOnRank[0] = nDofsLocalWithoutGhosts; std::vector<global_no_t> dofNosGlobalNaturalOwn; this->meshPartition_->getDofNosGlobalNatural(dofNosGlobalNaturalOwn); dofNosGlobalNatural[0].resize(nDofsLocalWithoutGhosts); std::copy(dofNosGlobalNaturalOwn.begin(), dofNosGlobalNaturalOwn.end(), dofNosGlobalNatural[0].begin()); // get displacement values values[0].resize(nComponents*nDofsLocalWithoutGhosts); for (int i = 0; i < nComponents; i++) { this->getValues(i, nDofsLocalWithoutGhosts, this->meshPartition_->dofNosLocal().data(), values[0].data() + i*nDofsLocalWithoutGhosts); } VLOG(1) << "get own displacement values: " << values; for (int rankNo = 0; rankNo < this->meshPartition_->nRanks(); rankNo++) { VLOG(1) << "rank " << rankNo; if (rankNo == 0) continue; // receive number of dofs on rank MPIUtility::handleReturnValue(MPI_Recv(&nDofsOnRank[rankNo], 1, MPI_INT, rankNo, 0, this->meshPartition_->rankSubset()->mpiCommunicator(), MPI_STATUS_IGNORE), "MPI_Recv"); VLOG(1) << ", nDofsOnRank: " << nDofsOnRank[rankNo]; VLOG(1) << "recv from " << rankNo << " " << nDofsOnRank[rankNo] << " dofs and displacements values"; // receive dof nos dofNosGlobalNatural[rankNo].resize(nDofsOnRank[rankNo]); MPIUtility::handleReturnValue(MPI_Recv(dofNosGlobalNatural[rankNo].data(), nDofsOnRank[rankNo], MPI_UNSIGNED_LONG_LONG, rankNo, 0, this->meshPartition_->rankSubset()->mpiCommunicator(), MPI_STATUS_IGNORE), "MPI_Recv"); VLOG(1) << "received displacements dofs: " << dofNosGlobalNatural[rankNo]; // receive values values[rankNo].resize(nComponents*nDofsOnRank[rankNo]); MPIUtility::handleReturnValue(MPI_Recv(values[rankNo].data(), nComponents*nDofsOnRank[rankNo], MPI_DOUBLE, rankNo, 0, this->meshPartition_->rankSubset()->mpiCommunicator(), MPI_STATUS_IGNORE), "MPI_Recv"); VLOG(1) << "received displacements values: " << values[rankNo]; } VLOG(1) << "values: " << values; // handle pressure values std::vector<std::vector<global_no_t>> dofNosGlobalNaturalPressure(this->meshPartition_->nRanks()); std::vector<std::vector<double>> valuesPressure(this->meshPartition_->nRanks()); // handle own rank // get global natural dof nos for pressure nDofsLocalWithoutGhosts = this->meshPartitionPressure_->nDofsLocalWithoutGhosts(); nPressureDofsOnRank[0] = nDofsLocalWithoutGhosts; VLOG(1) << "nRanks: " << this->meshPartition_->nRanks() << ", nDofsLocalWithoutGhosts: " << nDofsLocalWithoutGhosts; std::vector<global_no_t> dofNosGlobalNaturalPressureOwn; this->meshPartitionPressure_->getDofNosGlobalNatural(dofNosGlobalNaturalPressureOwn); dofNosGlobalNaturalPressure[0].resize(nDofsLocalWithoutGhosts); std::copy(dofNosGlobalNaturalPressureOwn.begin(), dofNosGlobalNaturalPressureOwn.end(), dofNosGlobalNaturalPressure[0].begin()); // get pressure values valuesPressure[0].resize(nDofsLocalWithoutGhosts); this->getValues(componentNoPressure_, nDofsLocalWithoutGhosts, this->meshPartitionPressure_->dofNosLocal().data(), valuesPressure[0].data()); // loop over other ranks for (int rankNo = 0; rankNo < this->meshPartitionPressure_->nRanks(); rankNo++) { if (rankNo == 0) continue; // receive number of dofs on rank VLOG(1) << "pressure rank " << rankNo << " n dofs: " << nPressureDofsOnRank[rankNo]; // receive number of dofs on rank MPIUtility::handleReturnValue(MPI_Recv(&nPressureDofsOnRank[rankNo], 1, MPI_INT, rankNo, 0, this->meshPartition_->rankSubset()->mpiCommunicator(), MPI_STATUS_IGNORE), "MPI_Recv"); VLOG(1) << "recv from " << rankNo << " " << nPressureDofsOnRank[rankNo] << " dofs and pressure values"; // receive dof nos dofNosGlobalNaturalPressure[rankNo].resize(nPressureDofsOnRank[rankNo]); MPIUtility::handleReturnValue(MPI_Recv(dofNosGlobalNaturalPressure[rankNo].data(), nPressureDofsOnRank[rankNo], MPI_UNSIGNED_LONG_LONG, rankNo, 0, this->meshPartitionPressure_->rankSubset()->mpiCommunicator(), MPI_STATUS_IGNORE), "MPI_Recv"); VLOG(1) << "received pressureDofs: " << dofNosGlobalNaturalPressure[rankNo]; // receive values valuesPressure[rankNo].resize(nPressureDofsOnRank[rankNo]); MPIUtility::handleReturnValue(MPI_Recv(valuesPressure[rankNo].data(), nPressureDofsOnRank[rankNo], MPI_DOUBLE, rankNo, 0, this->meshPartitionPressure_->rankSubset()->mpiCommunicator(), MPI_STATUS_IGNORE), "MPI_Recv"); VLOG(1) << "received pressure values: " << valuesPressure[rankNo]; } // sort displacement values according to global natural dof no std::vector<std::pair<global_no_t,std::array<double,nComponents>>> displacementEntries; displacementEntries.reserve(this->nEntriesGlobal_); for (int rankNo = 0; rankNo < this->meshPartition_->nRanks(); rankNo++) { assert(nDofsOnRank[rankNo] == dofNosGlobalNatural[rankNo].size()); for (int i = 0; i < nDofsOnRank[rankNo]; i++) { std::pair<global_no_t,std::array<double,nComponents>> displacementEntry; displacementEntry.first = dofNosGlobalNatural[rankNo][i]; std::array<double,nComponents> valuesDof; for (int componentNo = 0; componentNo < nComponents; componentNo++) { valuesDof[componentNo] = values[rankNo][componentNo*nDofsOnRank[rankNo] + i]; } displacementEntry.second = valuesDof; displacementEntries.push_back(displacementEntry); } } // sort list according to dof no.s std::sort(displacementEntries.begin(), displacementEntries.end(), [&](std::pair<global_no_t,std::array<double,nComponents>> a, std::pair<global_no_t,std::array<double,nComponents>> b) { return a.first < b.first; }); // sort pressure values according to global natural dof no std::vector<std::pair<global_no_t,double>> pressureEntries; pressureEntries.reserve(this->nEntriesGlobal_); for (int rankNo = 0; rankNo < this->meshPartitionPressure_->nRanks(); rankNo++) { int nDofsOnRank = dofNosGlobalNaturalPressure[rankNo].size(); for (int i = 0; i < nDofsOnRank; i++) { pressureEntries.push_back(std::pair<global_no_t,double>( dofNosGlobalNaturalPressure[rankNo][i], valuesPressure[rankNo][i] )); } } // sort list according to dof no.s std::sort(pressureEntries.begin(), pressureEntries.end(), [&](std::pair<global_no_t,double> a, std::pair<global_no_t,double> b) { return a.first < b.first; }); if (VLOG_IS_ON(1)) { VLOG(1) << "dofNosGlobalNatural: " << dofNosGlobalNatural; VLOG(1) << "values: " << values; VLOG(1) << "nDofsOnRank: " << nDofsOnRank; VLOG(1) << "nPressureDofsOnRank: " << nPressureDofsOnRank; VLOG(1) << "valuesPressure: " << valuesPressure; VLOG(1) << "displacementEntries: " << displacementEntries; VLOG(1) << "pressureEntries: " << pressureEntries; } // write file std::string newline = "\n"; std::string separator = ", "; std::array<std::string,nComponents> componentNames; componentNames[0] = "ux"; componentNames[1] = "uy"; componentNames[2] = "uz"; if (nComponents == 6) { componentNames[3] = "vx"; componentNames[4] = "vy"; componentNames[5] = "vz"; } if (horizontal) { newline = ""; separator = ", "; result << std::endl; } else { result << vectorName << "r" << this->meshPartitionPressure_->nRanks() << " = ["; } // loop over not-pressure components (u and possibly v) for (int componentNo = 0; componentNo < nComponents; componentNo++) { // start of component if (horizontal) { result << componentNames[componentNo] << " = [" << newline; // print e.g. "ux = [" } // write displacement values for (int i = 0; i < displacementEntries.size(); i++) { if (i != 0) result << separator; result << displacementEntries[i].first << ":" << (fabs(displacementEntries[i].second[componentNo]) < 1e-13? 0 : displacementEntries[i].second[componentNo]); } // end of component if (horizontal) { result << newline << "]; " << std::endl; } else { result << ", ...\n "; } } if (horizontal) { result << " p = [" << newline; } else { result << ", ...\n "; } for (int i = 0; i < pressureEntries.size(); i++) { if (i != 0) result << separator; result << pressureEntries[i].first << ":" << (fabs(pressureEntries[i].second) < 1e-13? 0 : pressureEntries[i].second); } if (horizontal) { result << newline << "];" << std::endl; } else { result << "]; " << std::endl; } } else { // all other ranks send the data to rank 0 int nDofsLocalWithoutGhosts = this->meshPartition_->nDofsLocalWithoutGhosts(); // send number of local dofs MPIUtility::handleReturnValue(MPI_Send(&nDofsLocalWithoutGhosts, 1, MPI_INT, 0, 0, this->meshPartition_->rankSubset()->mpiCommunicator()), "MPI_Send"); // send global natural dof nos for displacements std::vector<global_no_t> dofNosGlobalNatural; this->meshPartition_->getDofNosGlobalNatural(dofNosGlobalNatural); assert(dofNosGlobalNatural.size() == nDofsLocalWithoutGhosts); VLOG(1) << "send to 0 " << nDofsLocalWithoutGhosts << " dofs and displacements values"; MPIUtility::handleReturnValue(MPI_Send(dofNosGlobalNatural.data(), nDofsLocalWithoutGhosts, MPI_UNSIGNED_LONG_LONG, 0, 0, this->meshPartition_->rankSubset()->mpiCommunicator()), "MPI_Send"); VLOG(1) << "sent displacements dofs: " << dofNosGlobalNatural; // send displacement values std::vector<double> values(nComponents*nDofsLocalWithoutGhosts); for (int componentNo = 0; componentNo < nComponents; componentNo++) { this->getValues(componentNo, nDofsLocalWithoutGhosts, this->meshPartition_->dofNosLocal().data(), values.data() + componentNo*nDofsLocalWithoutGhosts); } MPIUtility::handleReturnValue(MPI_Send(values.data(), nComponents*nDofsLocalWithoutGhosts, MPI_DOUBLE, 0, 0, this->meshPartition_->rankSubset()->mpiCommunicator()), "MPI_Send"); VLOG(1) << "sent displacements values: " << values; nDofsLocalWithoutGhosts = this->meshPartitionPressure_->nDofsLocalWithoutGhosts(); // send number of local pressure dofs MPIUtility::handleReturnValue(MPI_Send(&nDofsLocalWithoutGhosts, 1, MPI_INT, 0, 0, this->meshPartition_->rankSubset()->mpiCommunicator()), "MPI_Send"); // send global natural dof nos for pressure VLOG(1) << "send to 0 " << nDofsLocalWithoutGhosts << " pressure dofs and values"; std::vector<global_no_t> dofNosGlobalNaturalPressure; this->meshPartitionPressure_->getDofNosGlobalNatural(dofNosGlobalNaturalPressure); assert(dofNosGlobalNaturalPressure.size() == nDofsLocalWithoutGhosts); MPIUtility::handleReturnValue(MPI_Send(dofNosGlobalNaturalPressure.data(), nDofsLocalWithoutGhosts, MPI_UNSIGNED_LONG_LONG, 0, 0, this->meshPartitionPressure_->rankSubset()->mpiCommunicator()), "MPI_Send"); VLOG(1) << "sent pressure dofs: " << dofNosGlobalNaturalPressure; // send pressure values std::vector<double> valuesPressure(nDofsLocalWithoutGhosts); this->getValues(componentNoPressure_, nDofsLocalWithoutGhosts, this->meshPartitionPressure_->dofNosLocal().data(), valuesPressure.data()); MPIUtility::handleReturnValue(MPI_Send(valuesPressure.data(), nDofsLocalWithoutGhosts, MPI_DOUBLE, 0, 0, this->meshPartitionPressure_->rankSubset()->mpiCommunicator()), "MPI_Send"); VLOG(1) << "sent pressure values: " << valuesPressure; } return result.str(); #else // in release mode, do not gather all the data from all processes return std::string(""); #endif }
39.522599
172
0.656136
maierbn
04a215e75fdac863c10659c6fb47a586cef69589
20,135
cpp
C++
src/qt/qtwebkit/Tools/DumpRenderTree/blackberry/TestRunnerBlackBerry.cpp
viewdy/phantomjs
eddb0db1d253fd0c546060a4555554c8ee08c13c
[ "BSD-3-Clause" ]
1
2015-05-27T13:52:20.000Z
2015-05-27T13:52:20.000Z
src/qt/qtwebkit/Tools/DumpRenderTree/blackberry/TestRunnerBlackBerry.cpp
mrampersad/phantomjs
dca6f77a36699eb4e1c46f7600cca618f01b0ac3
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtwebkit/Tools/DumpRenderTree/blackberry/TestRunnerBlackBerry.cpp
mrampersad/phantomjs
dca6f77a36699eb4e1c46f7600cca618f01b0ac3
[ "BSD-3-Clause" ]
1
2017-03-19T13:03:23.000Z
2017-03-19T13:03:23.000Z
/* * Copyright (C) 2009, 2010, 2012 Research In Motion Limited. All rights reserved. * * This library 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 library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "TestRunner.h" #include "DatabaseTracker.h" #include "Document.h" #include "DocumentLoader.h" #include "DocumentMarker.h" #include "DumpRenderTree.h" #include "DumpRenderTreeBlackBerry.h" #include "DumpRenderTreeSupport.h" #include "EditingBehaviorTypes.h" #include "EditorClientBlackBerry.h" #include "Element.h" #include "Frame.h" #include "HTMLInputElement.h" #include "JSElement.h" #include "KURL.h" #include "NotImplemented.h" #include "Page.h" #include "RenderTreeAsText.h" #include "SchemeRegistry.h" #include "SecurityOrigin.h" #include "SecurityPolicy.h" #include "Settings.h" #include "WorkQueue.h" #include "WorkQueueItem.h" #include <JavaScriptCore/APICast.h> #include <SharedPointer.h> #include <WebPage.h> #include <WebSettings.h> #include <wtf/OwnArrayPtr.h> #include <wtf/text/CString.h> using WebCore::toElement; using WebCore::toJS; TestRunner::~TestRunner() { } void TestRunner::addDisallowedURL(JSStringRef url) { UNUSED_PARAM(url); notImplemented(); } void TestRunner::clearAllDatabases() { #if ENABLE(DATABASE) WebCore::DatabaseTracker::tracker().deleteAllDatabases(); #endif } void TestRunner::clearBackForwardList() { BlackBerry::WebKit::DumpRenderTree::currentInstance()->page()->clearBackForwardList(true); } void TestRunner::clearPersistentUserStyleSheet() { notImplemented(); } JSStringRef TestRunner::copyDecodedHostName(JSStringRef name) { UNUSED_PARAM(name); notImplemented(); return 0; } JSStringRef TestRunner::copyEncodedHostName(JSStringRef name) { UNUSED_PARAM(name); notImplemented(); return 0; } void TestRunner::dispatchPendingLoadRequests() { notImplemented(); } void TestRunner::display() { notImplemented(); } static String jsStringRefToWebCoreString(JSStringRef str) { size_t strArrSize = JSStringGetMaximumUTF8CStringSize(str); OwnArrayPtr<char> strArr = adoptArrayPtr(new char[strArrSize]); JSStringGetUTF8CString(str, strArr.get(), strArrSize); return String::fromUTF8(strArr.get()); } void TestRunner::execCommand(JSStringRef name, JSStringRef value) { if (!mainFrame) return; String nameStr = jsStringRefToWebCoreString(name); String valueStr = jsStringRefToWebCoreString(value); mainFrame->editor()->command(nameStr).execute(valueStr); } bool TestRunner::isCommandEnabled(JSStringRef name) { if (!mainFrame) return false; String nameStr = jsStringRefToWebCoreString(name); return mainFrame->editor()->command(nameStr).isEnabled(); } void TestRunner::keepWebHistory() { notImplemented(); } void TestRunner::notifyDone() { if (m_waitToDump && (!topLoadingFrame || BlackBerry::WebKit::DumpRenderTree::currentInstance()->loadFinished()) && !WorkQueue::shared()->count()) dump(); m_waitToDump = false; waitForPolicy = false; } JSStringRef TestRunner::pathToLocalResource(JSContextRef, JSStringRef url) { return JSStringRetain(url); } void TestRunner::queueLoad(JSStringRef url, JSStringRef target) { size_t urlArrSize = JSStringGetMaximumUTF8CStringSize(url); OwnArrayPtr<char> urlArr = adoptArrayPtr(new char[urlArrSize]); JSStringGetUTF8CString(url, urlArr.get(), urlArrSize); WebCore::KURL base = mainFrame->loader()->documentLoader()->response().url(); WebCore::KURL absolute(base, urlArr.get()); JSRetainPtr<JSStringRef> absoluteURL(Adopt, JSStringCreateWithUTF8CString(absolute.string().utf8().data())); WorkQueue::shared()->queue(new LoadItem(absoluteURL.get(), target)); } void TestRunner::setAcceptsEditing(bool acceptsEditing) { BlackBerry::WebKit::DumpRenderTree::currentInstance()->setAcceptsEditing(acceptsEditing); } void TestRunner::setAppCacheMaximumSize(unsigned long long quota) { UNUSED_PARAM(quota); notImplemented(); } void TestRunner::setAuthorAndUserStylesEnabled(bool enable) { mainFrame->page()->settings()->setAuthorAndUserStylesEnabled(enable); } void TestRunner::setCacheModel(int) { notImplemented(); } void TestRunner::setCustomPolicyDelegate(bool setDelegate, bool permissive) { BlackBerry::WebKit::DumpRenderTree::currentInstance()->setCustomPolicyDelegate(setDelegate, permissive); } void TestRunner::clearApplicationCacheForOrigin(OpaqueJSString*) { // FIXME: Implement to support deleting all application caches for an origin. notImplemented(); } long long TestRunner::localStorageDiskUsageForOrigin(JSStringRef) { // FIXME: Implement to support getting disk usage in bytes for an origin. notImplemented(); return 0; } JSValueRef TestRunner::originsWithApplicationCache(JSContextRef context) { // FIXME: Implement to get origins that contain application caches. notImplemented(); return JSValueMakeUndefined(context); } void TestRunner::setDatabaseQuota(unsigned long long quota) { if (!mainFrame) return; WebCore::DatabaseTracker::tracker().setQuota(mainFrame->document()->securityOrigin(), quota); } void TestRunner::setDomainRelaxationForbiddenForURLScheme(bool forbidden, JSStringRef scheme) { WebCore::SchemeRegistry::setDomainRelaxationForbiddenForURLScheme(forbidden, jsStringRefToWebCoreString(scheme)); } void TestRunner::setIconDatabaseEnabled(bool iconDatabaseEnabled) { UNUSED_PARAM(iconDatabaseEnabled); notImplemented(); } void TestRunner::setMainFrameIsFirstResponder(bool flag) { UNUSED_PARAM(flag); notImplemented(); } void TestRunner::setPersistentUserStyleSheetLocation(JSStringRef path) { UNUSED_PARAM(path); notImplemented(); } void TestRunner::setPopupBlockingEnabled(bool flag) { BlackBerry::WebKit::DumpRenderTree::currentInstance()->page()->settings()->setJavaScriptOpenWindowsAutomatically(!flag); } void TestRunner::setPrivateBrowsingEnabled(bool flag) { UNUSED_PARAM(flag); notImplemented(); } void TestRunner::setXSSAuditorEnabled(bool flag) { BlackBerry::WebKit::DumpRenderTree::currentInstance()->page()->settings()->setXSSAuditorEnabled(flag); } void TestRunner::setTabKeyCyclesThroughElements(bool cycles) { if (!mainFrame) return; mainFrame->page()->setTabKeyCyclesThroughElements(cycles); } void TestRunner::setUseDashboardCompatibilityMode(bool flag) { UNUSED_PARAM(flag); notImplemented(); } void TestRunner::setUserStyleSheetEnabled(bool flag) { UNUSED_PARAM(flag); notImplemented(); } void TestRunner::setUserStyleSheetLocation(JSStringRef path) { String pathStr = jsStringRefToWebCoreString(path); BlackBerry::WebKit::DumpRenderTree::currentInstance()->page()->settings()->setUserStyleSheetLocation(pathStr); } void TestRunner::waitForPolicyDelegate() { setCustomPolicyDelegate(true, true); setWaitToDump(true); waitForPolicy = true; } size_t TestRunner::webHistoryItemCount() { SharedArray<BlackBerry::WebKit::WebPage::BackForwardEntry> backForwardList; BlackBerry::WebKit::DumpRenderTree::currentInstance()->page()->getBackForwardList(backForwardList); return backForwardList.length(); } int TestRunner::windowCount() { notImplemented(); return 0; } void TestRunner::setWaitToDump(bool waitToDump) { // Change from 30s to 35s because some test cases in multipart need 30 seconds, // refer to http/tests/multipart/resources/multipart-wait-before-boundary.php please. static const double kWaitToDumpWatchdogInterval = 35.0; m_waitToDump = waitToDump; if (m_waitToDump) BlackBerry::WebKit::DumpRenderTree::currentInstance()->setWaitToDumpWatchdog(kWaitToDumpWatchdogInterval); } void TestRunner::setWindowIsKey(bool windowIsKey) { m_windowIsKey = windowIsKey; notImplemented(); } void TestRunner::removeAllVisitedLinks() { notImplemented(); } void TestRunner::overridePreference(JSStringRef key, JSStringRef value) { if (!mainFrame) return; String keyStr = jsStringRefToWebCoreString(key); String valueStr = jsStringRefToWebCoreString(value); if (keyStr == "WebKitUsesPageCachePreferenceKey") BlackBerry::WebKit::DumpRenderTree::currentInstance()->page()->settings()->setMaximumPagesInCache(1); else if (keyStr == "WebKitUsePreHTML5ParserQuirks") mainFrame->page()->settings()->setUsePreHTML5ParserQuirks(true); else if (keyStr == "WebKitTabToLinksPreferenceKey") DumpRenderTreeSupport::setLinksIncludedInFocusChain(valueStr == "true" || valueStr == "1"); else if (keyStr == "WebKitHyperlinkAuditingEnabled") mainFrame->page()->settings()->setHyperlinkAuditingEnabled(valueStr == "true" || valueStr == "1"); else if (keyStr == "WebSocketsEnabled") BlackBerry::WebKit::DumpRenderTree::currentInstance()->page()->settings()->setWebSocketsEnabled(valueStr == "true" || valueStr == "1"); else if (keyStr == "WebKitDefaultTextEncodingName") BlackBerry::WebKit::DumpRenderTree::currentInstance()->page()->settings()->setDefaultTextEncodingName(valueStr); else if (keyStr == "WebKitDisplayImagesKey") BlackBerry::WebKit::DumpRenderTree::currentInstance()->page()->settings()->setLoadsImagesAutomatically(valueStr == "true" || valueStr == "1"); } void TestRunner::setAlwaysAcceptCookies(bool alwaysAcceptCookies) { UNUSED_PARAM(alwaysAcceptCookies); notImplemented(); } void TestRunner::setMockGeolocationPosition(double latitude, double longitude, double accuracy, bool providesAltitude, double altitude, bool providesAltitudeAccuracy, double altitudeAccuracy, bool providesHeading, double heading, bool providesSpeed, double speed) { DumpRenderTreeSupport::setMockGeolocationPosition(BlackBerry::WebKit::DumpRenderTree::currentInstance()->page(), latitude, longitude, accuracy, providesAltitude, altitude, providesAltitudeAccuracy, altitudeAccuracy, providesHeading, heading, providesSpeed, speed); } void TestRunner::setMockGeolocationPositionUnavailableError(JSStringRef message) { String messageStr = jsStringRefToWebCoreString(message); DumpRenderTreeSupport::setMockGeolocationPositionUnavailableError(BlackBerry::WebKit::DumpRenderTree::currentInstance()->page(), messageStr); } void TestRunner::showWebInspector() { notImplemented(); } void TestRunner::closeWebInspector() { notImplemented(); } void TestRunner::evaluateInWebInspector(long callId, JSStringRef script) { UNUSED_PARAM(callId); UNUSED_PARAM(script); notImplemented(); } void TestRunner::evaluateScriptInIsolatedWorldAndReturnValue(unsigned worldID, JSObjectRef globalObject, JSStringRef script) { UNUSED_PARAM(worldID); UNUSED_PARAM(globalObject); UNUSED_PARAM(script); notImplemented(); } void TestRunner::evaluateScriptInIsolatedWorld(unsigned worldID, JSObjectRef globalObject, JSStringRef script) { UNUSED_PARAM(worldID); UNUSED_PARAM(globalObject); UNUSED_PARAM(script); notImplemented(); } void TestRunner::addUserScript(JSStringRef source, bool runAtStart, bool allFrames) { UNUSED_PARAM(source); UNUSED_PARAM(runAtStart); UNUSED_PARAM(allFrames); notImplemented(); } void TestRunner::addUserStyleSheet(JSStringRef, bool) { notImplemented(); } void TestRunner::setScrollbarPolicy(JSStringRef, JSStringRef) { notImplemented(); } void TestRunner::setWebViewEditable(bool) { notImplemented(); } void TestRunner::authenticateSession(JSStringRef, JSStringRef, JSStringRef) { notImplemented(); } bool TestRunner::callShouldCloseOnWebView() { notImplemented(); return false; } void TestRunner::setSpatialNavigationEnabled(bool) { notImplemented(); } void TestRunner::addOriginAccessWhitelistEntry(JSStringRef sourceOrigin, JSStringRef destinationProtocol, JSStringRef destinationHost, bool allowDestinationSubdomains) { WebCore::SecurityPolicy::addOriginAccessWhitelistEntry(*WebCore::SecurityOrigin::createFromString(jsStringRefToWebCoreString(sourceOrigin)), jsStringRefToWebCoreString(destinationProtocol), jsStringRefToWebCoreString(destinationHost), allowDestinationSubdomains); } void TestRunner::removeOriginAccessWhitelistEntry(JSStringRef sourceOrigin, JSStringRef destinationProtocol, JSStringRef destinationHost, bool allowDestinationSubdomains) { WebCore::SecurityPolicy::removeOriginAccessWhitelistEntry(*WebCore::SecurityOrigin::createFromString(jsStringRefToWebCoreString(sourceOrigin)), jsStringRefToWebCoreString(destinationProtocol), jsStringRefToWebCoreString(destinationHost), allowDestinationSubdomains); } void TestRunner::setAllowFileAccessFromFileURLs(bool enabled) { if (!mainFrame) return; mainFrame->page()->settings()->setAllowFileAccessFromFileURLs(enabled); } void TestRunner::setAllowUniversalAccessFromFileURLs(bool enabled) { if (!mainFrame) return; mainFrame->page()->settings()->setAllowUniversalAccessFromFileURLs(enabled); } void TestRunner::apiTestNewWindowDataLoadBaseURL(JSStringRef, JSStringRef) { notImplemented(); } void TestRunner::apiTestGoToCurrentBackForwardItem() { notImplemented(); } void TestRunner::setJavaScriptCanAccessClipboard(bool flag) { BlackBerry::WebKit::DumpRenderTree::currentInstance()->page()->setJavaScriptCanAccessClipboard(flag); } void TestRunner::setPluginsEnabled(bool) { notImplemented(); } void TestRunner::abortModal() { notImplemented(); } void TestRunner::clearAllApplicationCaches() { notImplemented(); } void TestRunner::setApplicationCacheOriginQuota(unsigned long long) { notImplemented(); } void TestRunner::setMockDeviceOrientation(bool canProvideAlpha, double alpha, bool canProvideBeta, double beta, bool canProvideGamma, double gamma) { DumpRenderTreeSupport::setMockDeviceOrientation(BlackBerry::WebKit::DumpRenderTree::currentInstance()->page(), canProvideAlpha, alpha, canProvideBeta, beta, canProvideGamma, gamma); } void TestRunner::addMockSpeechInputResult(JSStringRef, double, JSStringRef) { notImplemented(); } void TestRunner::setGeolocationPermission(bool allow) { setGeolocationPermissionCommon(allow); DumpRenderTreeSupport::setMockGeolocationPermission(BlackBerry::WebKit::DumpRenderTree::currentInstance()->page(), allow); } void TestRunner::setViewModeMediaFeature(const JSStringRef) { notImplemented(); } void TestRunner::setSerializeHTTPLoads(bool) { // FIXME: Implement if needed for https://bugs.webkit.org/show_bug.cgi?id=50758. notImplemented(); } void TestRunner::setTextDirection(JSStringRef) { notImplemented(); } void TestRunner::goBack() { // FIXME: implement to enable loader/navigation-while-deferring-loads.html notImplemented(); } void TestRunner::setDefersLoading(bool) { // FIXME: implement to enable loader/navigation-while-deferring-loads.html notImplemented(); } JSValueRef TestRunner::originsWithLocalStorage(JSContextRef context) { notImplemented(); return JSValueMakeUndefined(context); } void TestRunner::observeStorageTrackerNotifications(unsigned) { notImplemented(); } void TestRunner::syncLocalStorage() { notImplemented(); } void TestRunner::deleteAllLocalStorage() { notImplemented(); } int TestRunner::numberOfPendingGeolocationPermissionRequests() { return DumpRenderTreeSupport::numberOfPendingGeolocationPermissionRequests(BlackBerry::WebKit::DumpRenderTree::currentInstance()->page()); } bool TestRunner::findString(JSContextRef context, JSStringRef target, JSObjectRef optionsArray) { WebCore::FindOptions options = 0; String nameStr = jsStringRefToWebCoreString(target); JSRetainPtr<JSStringRef> lengthPropertyName(Adopt, JSStringCreateWithUTF8CString("length")); size_t length = 0; if (optionsArray) { JSValueRef lengthValue = JSObjectGetProperty(context, optionsArray, lengthPropertyName.get(), 0); if (!JSValueIsNumber(context, lengthValue)) return false; length = static_cast<size_t>(JSValueToNumber(context, lengthValue, 0)); } for (size_t i = 0; i < length; ++i) { JSValueRef value = JSObjectGetPropertyAtIndex(context, optionsArray, i, 0); if (!JSValueIsString(context, value)) continue; JSRetainPtr<JSStringRef> optionName(Adopt, JSValueToStringCopy(context, value, 0)); if (JSStringIsEqualToUTF8CString(optionName.get(), "CaseInsensitive")) options |= WebCore::CaseInsensitive; else if (JSStringIsEqualToUTF8CString(optionName.get(), "AtWordStarts")) options |= WebCore::AtWordStarts; else if (JSStringIsEqualToUTF8CString(optionName.get(), "TreatMedialCapitalAsWordStart")) options |= WebCore::TreatMedialCapitalAsWordStart; else if (JSStringIsEqualToUTF8CString(optionName.get(), "Backwards")) options |= WebCore::Backwards; else if (JSStringIsEqualToUTF8CString(optionName.get(), "WrapAround")) options |= WebCore::WrapAround; else if (JSStringIsEqualToUTF8CString(optionName.get(), "StartInSelection")) options |= WebCore::StartInSelection; } // FIXME: we don't need to call WebPage::findNextString(), this is a workaround // so that test platform/blackberry/editing/text-iterator/findString-markers.html can pass. // Our layout tests assume find will wrap and highlight all matches. BlackBerry::WebKit::DumpRenderTree::currentInstance()->page()->findNextString(nameStr.utf8().data(), !(options & WebCore::Backwards), !(options & WebCore::CaseInsensitive), true /* wrap */, true /* highlightAllMatches */, false /* selectActiveMatchOnClear */); return mainFrame->page()->findString(nameStr, options); } void TestRunner::deleteLocalStorageForOrigin(JSStringRef) { // FIXME: Implement. } void TestRunner::setValueForUser(JSContextRef context, JSValueRef nodeObject, JSStringRef value) { JSC::ExecState* exec = toJS(context); WebCore::Element* element = toElement(toJS(exec, nodeObject)); if (!element) return; WebCore::HTMLInputElement* inputElement = element->toInputElement(); if (!inputElement) return; inputElement->setValueForUser(jsStringRefToWebCoreString(value)); } long long TestRunner::applicationCacheDiskUsageForOrigin(JSStringRef) { // FIXME: Implement to support getting disk usage by all application caches for an origin. return 0; } void TestRunner::addChromeInputField() { } void TestRunner::removeChromeInputField() { } void TestRunner::focusWebView() { } void TestRunner::setBackingScaleFactor(double) { } void TestRunner::setMockSpeechInputDumpRect(bool) { } void TestRunner::grantWebNotificationPermission(JSStringRef) { } void TestRunner::denyWebNotificationPermission(JSStringRef) { } void TestRunner::removeAllWebNotificationPermissions() { } void TestRunner::simulateWebNotificationClick(JSValueRef) { } void TestRunner::simulateLegacyWebNotificationClick(JSStringRef) { } void TestRunner::resetPageVisibility() { notImplemented(); } void TestRunner::setPageVisibility(const char*) { notImplemented(); } void TestRunner::setAutomaticLinkDetectionEnabled(bool) { notImplemented(); } void TestRunner::setStorageDatabaseIdleInterval(double) { // FIXME: Implement this. notImplemented(); } void TestRunner::closeIdleLocalStorageDatabases() { notImplemented(); }
28.20028
268
0.754209
viewdy
04a2bea699c47c2db9a3cd4905a84798ec55ef08
9,011
hh
C++
include/maxscale/server.hh
crspecter/MaxScale
471fa20a09ebc954fc3304500037b6b55dbbf9f1
[ "BSD-3-Clause" ]
1
2021-02-07T01:57:32.000Z
2021-02-07T01:57:32.000Z
include/maxscale/server.hh
crspecter/MaxScale
471fa20a09ebc954fc3304500037b6b55dbbf9f1
[ "BSD-3-Clause" ]
null
null
null
include/maxscale/server.hh
crspecter/MaxScale
471fa20a09ebc954fc3304500037b6b55dbbf9f1
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2018 MariaDB Corporation Ab * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file and at www.mariadb.com/bsl11. * * Change Date: 2025-01-25 * * On the date above, in accordance with the Business Source License, use * of this software will be governed by version 2 or later of the General * Public License. */ #pragma once #include <maxscale/ccdefs.hh> #include <mutex> #include <string> #include <unordered_map> #include <maxscale/config_common.hh> #include <maxscale/ssl.hh> #include <maxscale/target.hh> /** * Server configuration parameters names */ extern const char CN_MONITORPW[]; extern const char CN_MONITORUSER[]; extern const char CN_PERSISTMAXTIME[]; extern const char CN_PERSISTPOOLMAX[]; extern const char CN_PROXY_PROTOCOL[]; /** * The SERVER structure defines a backend server. Each server has a name * or IP address for the server, a port that the server listens on and * the name of a protocol module that is loaded to implement the protocol * between the gateway and the server. */ class SERVER : public mxs::Target { public: /** * Stores server version info. Encodes/decodes to/from the version number received from the server. * Also stores the version string and parses information from it. Assumed to rarely change, so reads * are not synchronized. */ class VersionInfo { public: enum class Type { UNKNOWN, /**< Not connected yet */ MYSQL, /**< MySQL 5.5 or later. */ MARIADB, /**< MariaDB 5.5 or later */ XPAND, /**< Xpand node */ BLR /**< Binlog router */ }; struct Version { uint64_t total {0}; /**< Total version number received from server */ uint32_t major {0}; /**< Major version */ uint32_t minor {0}; /**< Minor version */ uint32_t patch {0}; /**< Patch version */ }; /** * Reads in version data. Deduces server type from version string. * * @param version_num Version number from server * @param version_string Version string from server */ void set(uint64_t version_num, const std::string& version_string); /** * Return true if the server is a real database and can process queries. Returns false if server * type is unknown or if the server is a binlogrouter. * * @return True if server is a real database */ bool is_database() const; Type type() const; const Version& version_num() const; const char* version_string() const; private: static const int MAX_VERSION_LEN = 256; mutable std::mutex m_lock; /**< Protects against concurrent writing */ Version m_version_num; /**< Numeric version */ Type m_type {Type::UNKNOWN}; /**< Server type */ char m_version_str[MAX_VERSION_LEN + 1] {'\0'}; /**< Server version string */ }; struct PoolStats { int n_persistent = 0; /**< Current persistent pool */ uint64_t n_new_conn = 0; /**< Times the current pool was empty */ uint64_t n_from_pool = 0; /**< Times when a connection was available from the pool */ int persistmax = 0; /**< Maximum pool size actually achieved since startup */ }; /** * Find a server with the specified name. * * @param name Name of the server * @return The server or NULL if not found */ static SERVER* find_by_unique_name(const std::string& name); /** * Find several servers with the names specified in an array. The returned array is equal in size * to the server_names-array. If any server name was not found, then the corresponding element * will be NULL. * * @param server_names An array of server names * @return Array of servers */ static std::vector<SERVER*> server_find_by_unique_names(const std::vector<std::string>& server_names); virtual ~SERVER() = default; /** * Get server address */ virtual const char* address() const = 0; /** * Get server port */ virtual int port() const = 0; /** * Get server extra port */ virtual int extra_port() const = 0; /** * Is proxy protocol in use? */ virtual bool proxy_protocol() const = 0; /** * Set proxy protocol * * @param proxy_protocol Whether proxy protocol is used */ virtual void set_proxy_protocol(bool proxy_protocol) = 0; /** * Get server character set * * @return The numeric character set or 0 if no character set has been read */ virtual uint8_t charset() const = 0; /** * Set server character set * * @param charset Character set to set */ virtual void set_charset(uint8_t charset) = 0; /** * Connection pool statistics * * @return A reference to the pool statistics object */ virtual PoolStats& pool_stats() = 0; /** * Check if server has disk space threshold settings. * * @return True if limits exist */ virtual bool have_disk_space_limits() const = 0; /** * Get a copy of disk space limit settings. * * @return A copy of settings */ virtual DiskSpaceLimits get_disk_space_limits() const = 0; /** * Is persistent connection pool enabled. * * @return True if enabled */ virtual bool persistent_conns_enabled() const = 0; /** * Update server version. * * @param version_num New numeric version * @param version_str New version string */ virtual void set_version(uint64_t version_num, const std::string& version_str) = 0; /** * Get version information. The contents of the referenced object may change at any time, * although in practice this is rare. * * @return Version information */ virtual const VersionInfo& info() const = 0; /** * Update server address. * * @param address The new address */ virtual bool set_address(const std::string& address) = 0; /** * Update the server port. * * @param new_port New port. The value is not checked but should generally be 1 -- 65535. */ virtual void set_port(int new_port) = 0; /** * Update the server extra port. * * @param new_port New port. The value is not checked but should generally be 1 -- 65535. */ virtual void set_extra_port(int new_port) = 0; /** * @brief Check if a server points to a local MaxScale service * * @return True if the server points to a local MaxScale service */ virtual bool is_mxs_service() const = 0; /** * Set current ping * * @param ping Ping in milliseconds */ virtual void set_ping(int64_t ping) = 0; /** * Set replication lag * * @param lag The current replication lag in seconds */ virtual void set_replication_lag(int64_t lag) = 0; // TODO: Don't expose this to the modules and instead destroy the server // via ServerManager (currently needed by xpandmon) virtual void deactivate() = 0; /** * Set a status bit in the server without locking * * @param bit The bit to set for the server */ virtual void set_status(uint64_t bit) = 0; /** * Clear a status bit in the server without locking * * @param bit The bit to clear for the server */ virtual void clear_status(uint64_t bit) = 0; /** * Assign server status * * @param status Status to assign */ virtual void assign_status(uint64_t status) = 0; /** * Get SSL provider */ virtual const mxs::SSLProvider& ssl() const = 0; virtual mxs::SSLProvider& ssl() = 0; /** * Set server variables * * @param variables Variables and their values to set */ virtual void set_variables(std::unordered_map<std::string, std::string>&& variables) = 0; /** * Get server variable * * @param key Variable name to get * * @return Variable value or empty string if it was not found */ virtual std::string get_variable(const std::string& key) const = 0; /** * Set GTID positions * * @param positions List of pairs for the domain and the GTID position for it */ virtual void set_gtid_list(const std::vector<std::pair<uint32_t, uint64_t>>& positions) = 0; /** * Remove all stored GTID positions */ virtual void clear_gtid_list() = 0; /** * Get current server priority * * This should be used to decide which server is chosen as a master. Currently only galeramon uses it. */ virtual int64_t priority() const = 0; };
28.247649
106
0.610032
crspecter
04a5b3d2a1ab865d6ffc452ef13cb12de16bfc01
2,144
cpp
C++
working-plan/delegates/date-delegate.cpp
lgsilva3087/working-plan
cd79f45dc23ac997c9a48d23c3a373461a11ae58
[ "MIT" ]
null
null
null
working-plan/delegates/date-delegate.cpp
lgsilva3087/working-plan
cd79f45dc23ac997c9a48d23c3a373461a11ae58
[ "MIT" ]
null
null
null
working-plan/delegates/date-delegate.cpp
lgsilva3087/working-plan
cd79f45dc23ac997c9a48d23c3a373461a11ae58
[ "MIT" ]
null
null
null
/* * Created on: Sept 15, 2012 * Author: guille */ #include "date-delegate.h" #include <utils.h> #include <QDateEdit> DateDelegate::DateDelegate() : QStyledItemDelegate() { } void DateDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { int epoch = index.model()->index(index.row(), index.column()).data().toInt(); QDateTime dateTime = utils::toDateTime(epoch); if (option.state & QStyle::State_Selected) { painter->fillRect(option.rect, option.palette.highlight()); painter->save(); painter->setPen(option.palette.highlightedText().color()); } painter->drawText(QRect(option.rect.topLeft(), option.rect.bottomRight()), Qt::AlignCenter, dateTime.date().toString("dd/MM/yyyy")); if (option.state & QStyle::State_Selected) painter->restore(); } QWidget *DateDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &/* option */, const QModelIndex & /*index*/) const { QDateEdit *editor = new QDateEdit(parent); editor->setFrame(false); editor->setDisplayFormat("dd/MM/yyyy"); editor->setCalendarPopup(true); return editor; } void DateDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QDate value = utils::toDate(index.model()->data(index, Qt::EditRole).toInt()); QDateEdit *edit = static_cast<QDateEdit*>(editor); edit->setDate(value); } void DateDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QDateEdit *edit = static_cast<QDateEdit*>(editor); int value = utils::toDateStamp(edit->date()); model->setData(index, value, Qt::EditRole); } void DateDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &/* index */) const { editor->setGeometry(option.rect); } DateDelegate::~DateDelegate() { }
28.586667
94
0.623134
lgsilva3087
04a827c85eee25d051ca1e13b0d6f68c263a4f04
642
cc
C++
code/render/physics/physicsbody.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
67
2015-03-30T19:56:16.000Z
2022-03-11T13:52:17.000Z
code/render/physics/physicsbody.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
5
2015-04-15T17:17:33.000Z
2016-02-11T00:40:17.000Z
code/render/physics/physicsbody.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
34
2015-03-30T15:08:00.000Z
2021-09-23T05:55:10.000Z
//------------------------------------------------------------------------------ // physicsbody.cc // (C) 2012-2016 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "stdneb.h" #include "physics/physicsbody.h" namespace Physics { #if (__USE_BULLET__) __ImplementClass(Physics::PhysicsBody, 'PHBO', Bullet::BulletBody); #elif(__USE_PHYSX__) __ImplementClass(Physics::PhysicsBody, 'PHBO', PhysX::PhysXBody); #elif(__USE_HAVOK__) __ImplementClass(Physics::PhysicsBody, 'PHBO', Havok::HavokBody); #else #error "Physics::PhysicsBody not implemented" #endif }
33.789474
80
0.573209
gscept
04aa6d5d23d6a0cd6eeaf4f8339101ab1adf2c54
6,105
cc
C++
test/main.cc
michaelkuk/uv-secnet
2048f63dcafa6713fbc0e7c7d258cfa6ca74a7a5
[ "MIT" ]
1
2019-04-27T15:24:13.000Z
2019-04-27T15:24:13.000Z
test/main.cc
michaelkuk/uv-secnet
2048f63dcafa6713fbc0e7c7d258cfa6ca74a7a5
[ "MIT" ]
null
null
null
test/main.cc
michaelkuk/uv-secnet
2048f63dcafa6713fbc0e7c7d258cfa6ca74a7a5
[ "MIT" ]
null
null
null
#include "uv_secnet.hh" #include <iostream> #include <functional> #include <string> #include <sstream> #include <uv.h> #include <memory.h> #include <memory> #include <http_parser.h> typedef struct { int counter = 0; std::shared_ptr<uv_secnet::IConnection> conn = 0; uv_timer_t* timer = nullptr; uv_tcp_t* tcpHandle = nullptr; sockaddr_in* addr = nullptr; uv_secnet::IConnectionObserver* obs = nullptr; } secnet_ctx_s; typedef secnet_ctx_s secnet_ctx_t; void freeHandle(uv_handle_t* handle) { free(handle); } void initCtx (secnet_ctx_t* ctx) { ctx->counter = 0; ctx->conn = nullptr; ctx->timer = (uv_timer_t*)malloc(sizeof(uv_timer_t)); ctx->tcpHandle = (uv_tcp_t*)malloc(sizeof(uv_tcp_t)); ctx->addr = (sockaddr_in*)malloc(sizeof(sockaddr_in)); ctx->obs = new uv_secnet::IConnectionObserver(); uv_timer_init(uv_default_loop(), ctx->timer); uv_tcp_init(uv_default_loop(), ctx->tcpHandle); ctx->timer->data = ctx; ctx->tcpHandle->data = ctx; } void freeCtx(secnet_ctx_t* ctx) { free(ctx->timer); uv_close((uv_handle_t*) ctx->tcpHandle, freeHandle); ctx->conn = nullptr; free(ctx->addr); delete ctx->obs; free(ctx); } void timerTick(uv_timer_t* handle) { auto ctx = (secnet_ctx_t*) handle->data; if(++ctx->counter == 20) { std::cout << "Reached final tick, stopping counter" << std::endl; uv_timer_stop(handle); ctx->conn->close(); } else { std::cout << "Processing tick #" << ctx->counter << std::endl; std::stringstream ss; ss << "Hello from C++ tick #" << ctx->counter << std::endl; auto sd = ss.str(); int sl = sd.length(); char* data = (char*)malloc(sl + 1); strcpy(data, sd.c_str()); ctx->conn->write(uv_secnet::Buffer::makeShared(data, sl+1)); } } void connectCb(uv_connect_t* req, int status) { if(status != 0) { std::cout << "Connection Error: " << uv_err_name(status) << std::endl; } else { auto ctx = (secnet_ctx_t*) req->data; auto ssl_ctx = uv_secnet::TLSContext::getDefault(); // ctx->conn = ssl_ctx->secureClientConnection(uv_secnet::TCPConnection::create((uv_stream_t*)req->handle), "google.com"); ctx->conn = uv_secnet::TCPConnection::create((uv_stream_t*)req->handle); ctx->conn->initialize(ctx->obs); uv_secnet::HTTPObject obj("http://locahost:9999/post"); obj.setHeader("Connection", "Upgrade") ->setHeader("Upgrade", "websocket") ->setHeader("Sec-WebSocket-Key", "2BMqVIxuwA32Yuh1ydRutw==") ->setHeader("Sec-WebSocket-Version", "13"); ctx->conn->write(obj.toBuffer()); ctx->conn->close(); } free(req); } void runLoop() { uv_loop_t* loop = uv_default_loop(); secnet_ctx_t* ctx = (secnet_ctx_t*)malloc(sizeof(secnet_ctx_t)); initCtx(ctx); uv_ip4_addr("127.0.0.1", 9999, ctx->addr); // uv_ip4_addr("216.58.201.110", 443, ctx->addr); uv_connect_t* cReq = (uv_connect_t*)malloc(sizeof(uv_connect_t)); cReq->data = ctx; uv_tcp_connect(cReq, ctx->tcpHandle, (sockaddr*)ctx->addr, connectCb); uv_run(loop, UV_RUN_DEFAULT); freeCtx(ctx); } void testUri(std::string url) { auto uri = uv_secnet::Url::parse(url); return; } void on_addr_info(uv_getaddrinfo_t* req, int status, struct addrinfo* res) { auto i4 = AF_INET; auto i6 = AF_INET6; if (status != 0) { char e[1024]; uv_err_name_r(status, e, 1024); std::cout << e << std::endl; return; } if (res->ai_family == AF_INET) { std::cout << inet_ntoa(((sockaddr_in*)res->ai_addr)->sin_addr) << ":" << ((sockaddr_in*)res->ai_addr)->sin_port << std::endl; } std::cout << "DONE!" << std::endl; } class LogObserver : public uv_secnet::IClientObserver { public: uv_secnet::HTTPObject* o; uv_secnet::TCPClient* c; LogObserver() : o(nullptr), c(nullptr) {}; virtual void onClientStatusChanged(uv_secnet::IClient::STATUS status) { std::cout << "Client status changed" << std::endl; }; // <0 - do not reconnect, 0 - reconnect now, >0 - reconnect delay virtual int onClientError(uv_secnet::IClient::ERR, std::string err) { std::cout << "Error: " << err << std::endl; } virtual void onClientData(uv_secnet::buffer_ptr_t data) { // std::cout << "Got data::" << std::endl << std::string(data->base, data->len) << std::endl; } virtual void onClientConnectionStatusChanged(uv_secnet::IClient::CONNECTION_STATUS status) { if (status == uv_secnet::IClient::CONNECTION_STATUS::OPEN) { std::cout << "Connected" << std::endl; c->send(o->toBuffer()); c->close(); } std::cout << "Connection status changed" << std::endl; } }; int main () { // std::string s("https://admin:fickmich@localhost:443/something?query=string"); // runLoop(); // auto buf = uv_secnet::safe_alloc<char>(16); // uv_secnet::randomBytes(buf, 16); // auto data = uv_secnet::vendor::base64_encode((unsigned char*)buf, 16); // std::string body("Text payload, yeah baby!"); // auto buf = uv_secnet::Buffer::makeShared(const_cast<char*>(body.c_str()), body.length()); // uv_secnet::HTTPObject obj(s); // obj.createBody("text/plain", buf) // ->setHeader("X-Auth-Token", "trlalala") // ->setHeader("User-Agent", "fucking_C++_baby!"); // auto b = obj.toBuffer(); // // std::cout << std::string(d, one.length() + two.length()); // std::cout << std::string(b->base, b->len); // std::cout << data << std::endl; uv_loop_t* loop = uv_default_loop(); // uv_secnet::TLSTransform::debug = true; std::string host("https://google.com:443/"); LogObserver o; uv_secnet::TCPClient client(loop, host, &o); auto httpO = uv_secnet::HTTPObject(host); httpO.setHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/73.0.3683.86 Chrome/73.0.3683.86 Safari/537.36"); httpO.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"); o.o = &httpO; o.c = &client; client.enableTLS(); client.connect(); uv_run(loop, UV_RUN_DEFAULT); return 0; }
27.5
169
0.642588
michaelkuk
04abc62efa52d9dcd6d838c93265f6fc16bea6d9
5,461
cpp
C++
src/OSGB.cpp
embarktrucks/GeographicLib
1521a463e44843790abbf21aa6e214b93bbf01df
[ "MIT" ]
null
null
null
src/OSGB.cpp
embarktrucks/GeographicLib
1521a463e44843790abbf21aa6e214b93bbf01df
[ "MIT" ]
null
null
null
src/OSGB.cpp
embarktrucks/GeographicLib
1521a463e44843790abbf21aa6e214b93bbf01df
[ "MIT" ]
null
null
null
/** * \file OSGB.cpp * \brief Implementation for geographic_lib::OSGB class * * Copyright (c) Charles Karney (2010-2017) <charles@karney.com> and licensed * under the MIT/X11 License. For more information, see * https://geographiclib.sourceforge.io/ **********************************************************************/ #include <geographic_lib/OSGB.hpp> #include <geographic_lib/Utility.hpp> namespace geographic_lib { using namespace std; const char* const OSGB::letters_ = "ABCDEFGHJKLMNOPQRSTUVWXYZ"; const char* const OSGB::digits_ = "0123456789"; const TransverseMercator& OSGB::OSGBTM() { static const TransverseMercator osgbtm(MajorRadius(), Flattening(), CentralScale()); return osgbtm; } Math::real OSGB::computenorthoffset() { real x, y; static const real northoffset = ( OSGBTM().Forward(real(0), OriginLatitude(), real(0), x, y), FalseNorthing() - y ); return northoffset; } void OSGB::GridReference(real x, real y, int prec, std::string& gridref) { CheckCoords(x, y); if (!(prec >= 0 && prec <= maxprec_)) throw GeographicErr("OSGB precision " + Utility::str(prec) + " not in [0, " + Utility::str(int(maxprec_)) + "]"); if (Math::isnan(x) || Math::isnan(y)) { gridref = "INVALID"; return; } char grid[2 + 2 * maxprec_]; int xh = int(floor(x / tile_)), yh = int(floor(y / tile_)); real xf = x - tile_ * xh, yf = y - tile_ * yh; xh += tileoffx_; yh += tileoffy_; int z = 0; grid[z++] = letters_[(tilegrid_ - (yh / tilegrid_) - 1) * tilegrid_ + (xh / tilegrid_)]; grid[z++] = letters_[(tilegrid_ - (yh % tilegrid_) - 1) * tilegrid_ + (xh % tilegrid_)]; // Need extra real because, since C++11, pow(float, int) returns double real mult = real(pow(real(base_), max(tilelevel_ - prec, 0))); int ix = int(floor(xf / mult)), iy = int(floor(yf / mult)); for (int c = min(prec, int(tilelevel_)); c--;) { grid[z + c] = digits_[ ix % base_ ]; ix /= base_; grid[z + c + prec] = digits_[ iy % base_ ]; iy /= base_; } if (prec > tilelevel_) { xf -= floor(xf / mult); yf -= floor(yf / mult); mult = real(pow(real(base_), prec - tilelevel_)); ix = int(floor(xf * mult)); iy = int(floor(yf * mult)); for (int c = prec - tilelevel_; c--;) { grid[z + c + tilelevel_] = digits_[ ix % base_ ]; ix /= base_; grid[z + c + tilelevel_ + prec] = digits_[ iy % base_ ]; iy /= base_; } } int mlen = z + 2 * prec; gridref.resize(mlen); copy(grid, grid + mlen, gridref.begin()); } void OSGB::GridReference(const std::string& gridref, real& x, real& y, int& prec, bool centerp) { int len = int(gridref.size()), p = 0; if (len >= 2 && toupper(gridref[0]) == 'I' && toupper(gridref[1]) == 'N') { x = y = Math::NaN(); prec = -2; // For compatibility with MGRS::Reverse. return; } char grid[2 + 2 * maxprec_]; for (int i = 0; i < len; ++i) { if (!isspace(gridref[i])) { if (p >= 2 + 2 * maxprec_) throw GeographicErr("OSGB string " + gridref + " too long"); grid[p++] = gridref[i]; } } len = p; p = 0; if (len < 2) throw GeographicErr("OSGB string " + gridref + " too short"); if (len % 2) throw GeographicErr("OSGB string " + gridref + " has odd number of characters"); int xh = 0, yh = 0; while (p < 2) { int i = Utility::lookup(letters_, grid[p++]); if (i < 0) throw GeographicErr("Illegal prefix character " + gridref); yh = yh * tilegrid_ + tilegrid_ - (i / tilegrid_) - 1; xh = xh * tilegrid_ + (i % tilegrid_); } xh -= tileoffx_; yh -= tileoffy_; int prec1 = (len - p)/2; real unit = tile_, x1 = unit * xh, y1 = unit * yh; for (int i = 0; i < prec1; ++i) { unit /= base_; int ix = Utility::lookup(digits_, grid[p + i]), iy = Utility::lookup(digits_, grid[p + i + prec1]); if (ix < 0 || iy < 0) throw GeographicErr("Encountered a non-digit in " + gridref); x1 += unit * ix; y1 += unit * iy; } if (centerp) { x1 += unit/2; y1 += unit/2; } x = x1; y = y1; prec = prec1; } void OSGB::CheckCoords(real x, real y) { // Limits are all multiples of 100km and are all closed on the lower end // and open on the upper end -- and this is reflected in the error // messages. NaNs are let through. if (x < minx_ || x >= maxx_) throw GeographicErr("Easting " + Utility::str(int(floor(x/1000))) + "km not in OSGB range [" + Utility::str(minx_/1000) + "km, " + Utility::str(maxx_/1000) + "km)"); if (y < miny_ || y >= maxy_) throw GeographicErr("Northing " + Utility::str(int(floor(y/1000))) + "km not in OSGB range [" + Utility::str(miny_/1000) + "km, " + Utility::str(maxy_/1000) + "km)"); } } // namespace geographic_lib
32.313609
77
0.505951
embarktrucks
04ae3908f29be5c0b731c7f52f54c893af83da0e
16,195
cpp
C++
src/formula.cpp
fcimeson/cbTSP
aaf102c7a6a9f3b36a8b5f0c62570c40409ec7c8
[ "Apache-2.0" ]
7
2018-08-11T15:46:14.000Z
2022-01-28T18:39:19.000Z
src/formula.cpp
fcimeson/cbTSP
aaf102c7a6a9f3b36a8b5f0c62570c40409ec7c8
[ "Apache-2.0" ]
null
null
null
src/formula.cpp
fcimeson/cbTSP
aaf102c7a6a9f3b36a8b5f0c62570c40409ec7c8
[ "Apache-2.0" ]
1
2019-01-18T20:38:53.000Z
2019-01-18T20:38:53.000Z
/******************************************************************************** Copyright 2017 Frank Imeson and Stephen L. Smith 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 "formula.hpp" using namespace formula; #define DEBUG /******************************************************************************** * * Functions * ********************************************************************************/ /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula* formula::constraint_implies (const Lit &a, const Lit &b) { Formula* formula = new Formula(F_OR); formula->add(~a); formula->add(b); return formula; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula* formula::constraint_implies (const Lit &a, Formula* b) { Formula* formula = new Formula(F_OR); formula->add(~a); formula->add(b); return formula; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula* formula::constraint_implies (Formula *a, const Lit &b) { Formula* formula = new Formula(F_OR); a->negate(); formula->add(a); formula->add(b); return formula; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula* formula::constraint_implies (Formula *a, Formula* b) { Formula* formula = new Formula(F_OR); formula->add(a->negate()); formula->add(b); return formula; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ int formula::get_solution (const Solver &solver, vec<Lit> &lits, Var max_var) { if (max_var < 0) max_var = solver.model.size()-1; for (unsigned int i=0; i<=max_var; i++) lits.push( mkLit(i, solver.model[i] == l_False) ); return 0; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula* formula::constraint_iff (const Lit &a, const Lit &b) { Formula* formula = new Formula(F_OR); Formula* f0 = new Formula(F_AND); Formula* f1 = new Formula(F_AND); f0->add(a); f0->add(b); f1->add(~a); f1->add(~b); formula->add(f0); formula->add(f1); return formula; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula* formula::constraint_at_least_one_in_a_set (const vector<int> &var_list) { Formula* formula = new Formula(F_OR); for (int i=0; i<var_list.size(); i++) formula->add(mkLit(var_list[i], false)); return formula; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula* formula::constraint_one_in_a_set (const vector<int> &var_list) { Formula* formula = new Formula(F_OR); for (int i=0; i<var_list.size(); i++) { Formula* f0 = new Formula(F_AND); for (int j=0; j<var_list.size(); j++) { if (i == j) f0->add(mkLit(var_list[j], false)); else f0->add(mkLit(var_list[j], true)); } formula->add(f0); } return formula; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula* formula::constraint_at_most_one_in_a_set (const vector<int> &var_list) { Formula* formula = new Formula(F_OR); for (int i=0; i<var_list.size(); i++) { Formula* f0 = new Formula(F_AND); for (int j=0; j<var_list.size(); j++) { if (i == j) f0->add(mkLit(var_list[j], false)); else f0->add(mkLit(var_list[j], true)); } formula->add(f0); } Formula* f0 = new Formula(F_AND); for (int i=0; i<var_list.size(); i++) { f0->add(mkLit(var_list[i], true)); } formula->add(f0); return formula; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ int formula::negate_solution (const vec<Lit> &lits, Solver &solver) { vec<Lit> nlits; for (unsigned int i=0; i<lits.size(); i++) nlits.push( ~lits[i] ); solver.addClause(nlits); return 0; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Lit formula::translate (const int &lit) { return mkLit(abs(lit)-1, (lit<0)); } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ int formula::translate (const Lit &lit) { return sign(lit) ? -var(lit)-1:var(lit)+1; } /************************************************************//** * @brief * @return string representation of connective * @version v0.01b ****************************************************************/ string formula::str (const Con &connective) { switch (connective) { case F_AND: return "^"; case F_OR: return "v"; default: return " "; } } /************************************************************//** * @brief * @return string representation of connective * @version v0.01b ****************************************************************/ string formula::str (const Lit &lit) { stringstream out; if (sign(lit)) out << "-"; else out << " "; out << (var(lit)+1); return out.str(); } /************************************************************//** * @brief * @return string representation of connective * @version v0.01b ****************************************************************/ string formula::str (const vec<Lit> &lits) { string result; for (unsigned int i=0; i<lits.size(); i++) result += str(lits[i]) + " "; return result; } /************************************************************//** * @brief * @return negated connective, -1 on error * @version v0.01b ****************************************************************/ Con formula::negate (const Con &connective) { switch (connective) { case F_AND: return F_OR; case F_OR: return F_AND; default: return -1; } } /************************************************************//** * @brief * @return negated litteral * @version v0.01b ****************************************************************/ Lit formula::negate (const Lit &lit) { return ~lit; } /******************************************************************************** * * Formula Class * ********************************************************************************/ /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula::~Formula () { clear(); } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula::Formula () : connective(F_AND) , max_var(0) {} /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula::Formula (Con _connective) : connective(_connective) , max_var(0) {} /************************************************************//** * @brief Clear all contents of Formula recursively * @version v0.01b ****************************************************************/ int Formula::clear () { try { for (unsigned int i=0; i<formuli.size(); i++) { if (formuli[i] != NULL) { delete formuli[i]; formuli[i] = NULL; } } formuli.clear(); } catch(...) { perror("error Formula::clear(): "); exit(1); } return 0; } /************************************************************//** * @brief Negate entire formula * @return 0 on succession, < 0 on error * @version v0.01b ****************************************************************/ int Formula::negate () { connective = ::negate(connective); if (connective < 0) return connective; for (unsigned int i=0; i<lits.size(); i++) lits[i] = ::negate(lits[i]); for (unsigned int i=0; i<formuli.size(); i++) { int rtn = formuli[i]->negate(); if (rtn < 0) return rtn; } return 0; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ void Formula::track_max (const Var &var) { if (var > max_var) max_var = var; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ int Formula::add (const Lit &lit) { track_max(var(lit)); lits.push(lit); return 0; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ int Formula::add (const int &lit) { return add(translate(lit)); } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ int Formula::add (const vec<Lit> &lits) { for (unsigned int i=0; i<lits.size(); i++) add(lits[i]); return 0; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ int Formula::add (Formula *formula) { track_max(formula->maxVar()); if (formula != NULL) formuli.push(formula); return 0; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Var Formula::newVar () { max_var++; return max_var; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Var Formula::maxVar () { return max_var; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ int Formula::export_cnf (Lit &out, Formula *formula, Solver *solver) { if ( (formula == NULL && solver == NULL) || (formula != NULL && solver != NULL) ) return -1; // setup vars in solver // translation requires a new var to replace nested phrases if (solver != NULL) { while (solver->nVars() < max_var+1) solver->newVar(); out = mkLit( solver->newVar(), false ); } else { while (formula->maxVar() < max_var) formula->newVar(); out = mkLit( formula->newVar(), false ); } vec<Lit> big_clause; switch (connective) { case F_OR: // Variables for (unsigned int i=0; i<lits.size(); i++) { big_clause.push(lits[i]); if (solver != NULL) { solver->addClause(~lits[i], out); } else { Formula *phrase = new Formula(F_OR); phrase->add(~lits[i]); phrase->add(out); formula->add(phrase); } } // Nested formuli for (unsigned int i=0; i<formuli.size(); i++) { Lit cnf_out; if (int err = formuli[i]->export_cnf(cnf_out, formula, solver) < 0) return err; big_clause.push(cnf_out); if (solver != NULL) { solver->addClause(~cnf_out, out); } else { Formula *phrase = new Formula(F_OR); phrase->add(~cnf_out); phrase->add(out); formula->add(phrase); } } big_clause.push(~out); break; case F_AND: // Variables for (unsigned int i=0; i<lits.size(); i++) { big_clause.push(~lits[i]); if (solver != NULL) { solver->addClause(lits[i], ~out); } else { Formula *phrase = new Formula(F_OR); phrase->add(lits[i]); phrase->add(~out); formula->add(phrase); } } // Nested formuli for (unsigned int i=0; i<formuli.size(); i++) { Lit cnf_out; if (int err = formuli[i]->export_cnf(cnf_out, formula, solver) < 0) return err; big_clause.push(~cnf_out); if (solver != NULL) { solver->addClause(cnf_out, ~out); } else { Formula *phrase = new Formula(F_OR); phrase->add(cnf_out); phrase->add(~out); formula->add(phrase); } } big_clause.push(out); break; default: break; } if (solver != NULL) { solver->addClause(big_clause); } else { Formula *phrase = new Formula(F_OR); phrase->add(big_clause); formula->add(phrase); } return 0; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ string Formula::str () { return str(string("")); } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ string Formula::str (string prefix) { string result = prefix; if (formuli.size() == 0) { // result += "( "; for (unsigned int i=0; i<lits.size(); i++) result += ::str(lits[i]) + " " + ::str(connective) + " "; result.resize(result.size()-2); // result += ")\n"; result += "\n"; } else { result += prefix + ::str(connective) + '\n'; for (unsigned int i=0; i<lits.size(); i++) result += prefix + " " + ::str(lits[i]) + '\n'; for (unsigned int i=0; i<formuli.size(); i++) result += formuli[i]->str(prefix+" "); } return result; }
26.946755
91
0.367768
fcimeson
04ae6528676f31336a1509fc10ce4187a0f93f18
4,486
hpp
C++
mtlpp_ue4_ex_03/renderer/mtlpp/depth_stencil.hpp
dtonna/mtlpp_ue4_ex_03
80b945c5b5dbbf6efbe525fb371a2e77657cd595
[ "Unlicense" ]
null
null
null
mtlpp_ue4_ex_03/renderer/mtlpp/depth_stencil.hpp
dtonna/mtlpp_ue4_ex_03
80b945c5b5dbbf6efbe525fb371a2e77657cd595
[ "Unlicense" ]
null
null
null
mtlpp_ue4_ex_03/renderer/mtlpp/depth_stencil.hpp
dtonna/mtlpp_ue4_ex_03
80b945c5b5dbbf6efbe525fb371a2e77657cd595
[ "Unlicense" ]
null
null
null
/* * Copyright 2016-2017 Nikolay Aleksiev. All rights reserved. * License: https://github.com/naleksiev/mtlpp/blob/master/LICENSE */ // Copyright Epic Games, Inc. All Rights Reserved. // Modifications for Unreal Engine #pragma once #include "declare.hpp" #include "imp_DepthStencil.hpp" #include "ns.hpp" #include "device.hpp" MTLPP_BEGIN namespace ue4 { template<> struct ITable<id<MTLDepthStencilState>, void> : public IMPTable<id<MTLDepthStencilState>, void>, public ITableCacheRef { ITable() { } ITable(Class C) : IMPTable<id<MTLDepthStencilState>, void>(C) { } }; template<> inline ITable<MTLStencilDescriptor*, void>* CreateIMPTable(MTLStencilDescriptor* handle) { static ITable<MTLStencilDescriptor*, void> Table(object_getClass(handle)); return &Table; } template<> inline ITable<MTLDepthStencilDescriptor*, void>* CreateIMPTable(MTLDepthStencilDescriptor* handle) { static ITable<MTLDepthStencilDescriptor*, void> Table(object_getClass(handle)); return &Table; } } namespace mtlpp { enum class CompareFunction { Never = 0, Less = 1, Equal = 2, LessEqual = 3, Greater = 4, NotEqual = 5, GreaterEqual = 6, Always = 7, } MTLPP_AVAILABLE(10_11, 8_0); enum class StencilOperation { Keep = 0, Zero = 1, Replace = 2, IncrementClamp = 3, DecrementClamp = 4, Invert = 5, IncrementWrap = 6, DecrementWrap = 7, } MTLPP_AVAILABLE(10_11, 8_0); class MTLPP_EXPORT StencilDescriptor : public ns::Object<MTLStencilDescriptor*> { public: StencilDescriptor(); StencilDescriptor(ns::Ownership const retain) : ns::Object<MTLStencilDescriptor*>(retain) {} StencilDescriptor(MTLStencilDescriptor* handle, ns::Ownership const retain = ns::Ownership::Retain) : ns::Object<MTLStencilDescriptor*>(handle, retain) { } CompareFunction GetStencilCompareFunction() const; StencilOperation GetStencilFailureOperation() const; StencilOperation GetDepthFailureOperation() const; StencilOperation GetDepthStencilPassOperation() const; uint32_t GetReadMask() const; uint32_t GetWriteMask() const; void SetStencilCompareFunction(CompareFunction stencilCompareFunction); void SetStencilFailureOperation(StencilOperation stencilFailureOperation); void SetDepthFailureOperation(StencilOperation depthFailureOperation); void SetDepthStencilPassOperation(StencilOperation depthStencilPassOperation); void SetReadMask(uint32_t readMask); void SetWriteMask(uint32_t writeMask); } MTLPP_AVAILABLE(10_11, 8_0); class MTLPP_EXPORT DepthStencilDescriptor : public ns::Object<MTLDepthStencilDescriptor*> { public: DepthStencilDescriptor(); DepthStencilDescriptor(MTLDepthStencilDescriptor* handle, ns::Ownership const retain = ns::Ownership::Retain) : ns::Object<MTLDepthStencilDescriptor*>(handle, retain) { } CompareFunction GetDepthCompareFunction() const; bool IsDepthWriteEnabled() const; ns::AutoReleased<StencilDescriptor> GetFrontFaceStencil() const; ns::AutoReleased<StencilDescriptor> GetBackFaceStencil() const; ns::AutoReleased<ns::String> GetLabel() const; void SetDepthCompareFunction(CompareFunction depthCompareFunction) const; void SetDepthWriteEnabled(bool depthWriteEnabled) const; void SetFrontFaceStencil(const StencilDescriptor& frontFaceStencil) const; void SetBackFaceStencil(const StencilDescriptor& backFaceStencil) const; void SetLabel(const ns::String& label) const; } MTLPP_AVAILABLE(10_11, 8_0); class MTLPP_EXPORT DepthStencilState : public ns::Object<ns::Protocol<id<MTLDepthStencilState>>::type> { public: DepthStencilState() { } DepthStencilState(ns::Protocol<id<MTLDepthStencilState>>::type handle, ue4::ITableCache* cache = nullptr, ns::Ownership const retain = ns::Ownership::Retain) : ns::Object<ns::Protocol<id<MTLDepthStencilState>>::type>(handle, retain, ue4::ITableCacheRef(cache).GetDepthStencilState(handle)) { } ns::AutoReleased<ns::String> GetLabel() const; ns::AutoReleased<Device> GetDevice() const; } MTLPP_AVAILABLE(10_11, 8_0); } MTLPP_END
34.244275
295
0.689924
dtonna
04b03681ed7b153a4ca4902afba4230763c85552
524
cc
C++
exercises/STRINGS/strings12.cc
mfranzil/Programmazione1UniTN
0aee3ec51d424039afcabfa9de80046c1d5be7d9
[ "MIT" ]
3
2021-11-05T16:25:50.000Z
2022-02-10T14:06:00.000Z
exercises/STRINGS/strings12.cc
mfranzil/Programmazione1UniTN
0aee3ec51d424039afcabfa9de80046c1d5be7d9
[ "MIT" ]
null
null
null
exercises/STRINGS/strings12.cc
mfranzil/Programmazione1UniTN
0aee3ec51d424039afcabfa9de80046c1d5be7d9
[ "MIT" ]
2
2018-10-31T14:53:40.000Z
2020-01-09T22:34:37.000Z
// Example 7.12, page 198 // Schaum's Outline of Programming with C++ by John R. Hubbard // Copyright McGraw-Hill, 1996 using namespace std; #include <iostream> // NOTA: ORMAI DEPRECATO DALLO STANDARD ATTUALE: // EX0712.cc:10: warning: deprecated conversion from string constant to ‘char*’ int main() { char* name[] = { "George Washington", "John Adams", "Thomas Jefferson" }; cout << "The names are:\n"; for (int i = 0; i < 3; i++) cout << "\t" << i << ". [" << name[i] << "]" << endl; return 0; }
26.2
79
0.612595
mfranzil
04b24bfd53799b832594a74becbe2d41bc106104
3,097
cpp
C++
utils.cpp
jaypadath/openpower-pnor-code-mgmt
10e915abf1bd31d8b1dae8d01c731ac8dd76c7c0
[ "Apache-2.0" ]
null
null
null
utils.cpp
jaypadath/openpower-pnor-code-mgmt
10e915abf1bd31d8b1dae8d01c731ac8dd76c7c0
[ "Apache-2.0" ]
2
2019-07-30T15:36:06.000Z
2021-09-28T15:45:27.000Z
utils.cpp
jaypadath/openpower-pnor-code-mgmt
10e915abf1bd31d8b1dae8d01c731ac8dd76c7c0
[ "Apache-2.0" ]
2
2019-07-30T14:06:52.000Z
2019-09-26T15:25:05.000Z
#include "config.h" #include "utils.hpp" #include <phosphor-logging/elog-errors.hpp> #include <phosphor-logging/elog.hpp> #include <phosphor-logging/log.hpp> #include <xyz/openbmc_project/Common/error.hpp> #if OPENSSL_VERSION_NUMBER < 0x10100000L #include <string.h> static void* OPENSSL_zalloc(size_t num) { void* ret = OPENSSL_malloc(num); if (ret != NULL) { memset(ret, 0, num); } return ret; } EVP_MD_CTX* EVP_MD_CTX_new(void) { return (EVP_MD_CTX*)OPENSSL_zalloc(sizeof(EVP_MD_CTX)); } void EVP_MD_CTX_free(EVP_MD_CTX* ctx) { EVP_MD_CTX_cleanup(ctx); OPENSSL_free(ctx); } #endif // OPENSSL_VERSION_NUMBER < 0x10100000L namespace utils { using sdbusplus::exception::SdBusError; using namespace phosphor::logging; constexpr auto HIOMAPD_PATH = "/xyz/openbmc_project/Hiomapd"; constexpr auto HIOMAPD_INTERFACE = "xyz.openbmc_project.Hiomapd.Control"; using InternalFailure = sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure; std::string getService(sdbusplus::bus::bus& bus, const std::string& path, const std::string& intf) { auto mapper = bus.new_method_call(MAPPER_BUSNAME, MAPPER_PATH, MAPPER_INTERFACE, "GetObject"); mapper.append(path, std::vector<std::string>({intf})); try { auto mapperResponseMsg = bus.call(mapper); std::vector<std::pair<std::string, std::vector<std::string>>> mapperResponse; mapperResponseMsg.read(mapperResponse); if (mapperResponse.empty()) { log<level::ERR>("Error reading mapper response"); throw std::runtime_error("Error reading mapper response"); } return mapperResponse[0].first; } catch (const sdbusplus::exception::SdBusError& ex) { log<level::ERR>("Mapper call failed", entry("METHOD=%d", "GetObject"), entry("PATH=%s", path.c_str()), entry("INTERFACE=%s", intf.c_str())); throw std::runtime_error("Mapper call failed"); } } void hiomapdSuspend(sdbusplus::bus::bus& bus) { auto service = getService(bus, HIOMAPD_PATH, HIOMAPD_INTERFACE); auto method = bus.new_method_call(service.c_str(), HIOMAPD_PATH, HIOMAPD_INTERFACE, "Suspend"); try { bus.call_noreply(method); } catch (const SdBusError& e) { log<level::ERR>("Error in mboxd suspend call", entry("ERROR=%s", e.what())); } } void hiomapdResume(sdbusplus::bus::bus& bus) { auto service = getService(bus, HIOMAPD_PATH, HIOMAPD_INTERFACE); auto method = bus.new_method_call(service.c_str(), HIOMAPD_PATH, HIOMAPD_INTERFACE, "Resume"); method.append(true); // Indicate PNOR is modified try { bus.call_noreply(method); } catch (const SdBusError& e) { log<level::ERR>("Error in mboxd suspend call", entry("ERROR=%s", e.what())); } } } // namespace utils
26.470085
78
0.621569
jaypadath
04b35c8cf7b9118dee19bc892bcd69cf302380cd
5,463
cpp
C++
ext/stub/java/text/DateFormat_Field-stub.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/stub/java/text/DateFormat_Field-stub.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/stub/java/text/DateFormat_Field-stub.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar #include <java/text/DateFormat_Field.hpp> extern void unimplemented_(const char16_t* name); java::text::DateFormat_Field::DateFormat_Field(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } java::text::DateFormat_Field::DateFormat_Field(::java::lang::String* name, int32_t calendarField) : DateFormat_Field(*static_cast< ::default_init_tag* >(0)) { ctor(name, calendarField); } java::text::DateFormat_Field*& java::text::DateFormat_Field::AM_PM() { clinit(); return AM_PM_; } java::text::DateFormat_Field* java::text::DateFormat_Field::AM_PM_; java::text::DateFormat_Field*& java::text::DateFormat_Field::DAY_OF_MONTH() { clinit(); return DAY_OF_MONTH_; } java::text::DateFormat_Field* java::text::DateFormat_Field::DAY_OF_MONTH_; java::text::DateFormat_Field*& java::text::DateFormat_Field::DAY_OF_WEEK() { clinit(); return DAY_OF_WEEK_; } java::text::DateFormat_Field* java::text::DateFormat_Field::DAY_OF_WEEK_; java::text::DateFormat_Field*& java::text::DateFormat_Field::DAY_OF_WEEK_IN_MONTH() { clinit(); return DAY_OF_WEEK_IN_MONTH_; } java::text::DateFormat_Field* java::text::DateFormat_Field::DAY_OF_WEEK_IN_MONTH_; java::text::DateFormat_Field*& java::text::DateFormat_Field::DAY_OF_YEAR() { clinit(); return DAY_OF_YEAR_; } java::text::DateFormat_Field* java::text::DateFormat_Field::DAY_OF_YEAR_; java::text::DateFormat_Field*& java::text::DateFormat_Field::ERA() { clinit(); return ERA_; } java::text::DateFormat_Field* java::text::DateFormat_Field::ERA_; java::text::DateFormat_Field*& java::text::DateFormat_Field::HOUR0() { clinit(); return HOUR0_; } java::text::DateFormat_Field* java::text::DateFormat_Field::HOUR0_; java::text::DateFormat_Field*& java::text::DateFormat_Field::HOUR1() { clinit(); return HOUR1_; } java::text::DateFormat_Field* java::text::DateFormat_Field::HOUR1_; java::text::DateFormat_Field*& java::text::DateFormat_Field::HOUR_OF_DAY0() { clinit(); return HOUR_OF_DAY0_; } java::text::DateFormat_Field* java::text::DateFormat_Field::HOUR_OF_DAY0_; java::text::DateFormat_Field*& java::text::DateFormat_Field::HOUR_OF_DAY1() { clinit(); return HOUR_OF_DAY1_; } java::text::DateFormat_Field* java::text::DateFormat_Field::HOUR_OF_DAY1_; java::text::DateFormat_Field*& java::text::DateFormat_Field::MILLISECOND() { clinit(); return MILLISECOND_; } java::text::DateFormat_Field* java::text::DateFormat_Field::MILLISECOND_; java::text::DateFormat_Field*& java::text::DateFormat_Field::MINUTE() { clinit(); return MINUTE_; } java::text::DateFormat_Field* java::text::DateFormat_Field::MINUTE_; java::text::DateFormat_Field*& java::text::DateFormat_Field::MONTH() { clinit(); return MONTH_; } java::text::DateFormat_Field* java::text::DateFormat_Field::MONTH_; java::text::DateFormat_Field*& java::text::DateFormat_Field::SECOND() { clinit(); return SECOND_; } java::text::DateFormat_Field* java::text::DateFormat_Field::SECOND_; java::text::DateFormat_Field*& java::text::DateFormat_Field::TIME_ZONE() { clinit(); return TIME_ZONE_; } java::text::DateFormat_Field* java::text::DateFormat_Field::TIME_ZONE_; java::text::DateFormat_Field*& java::text::DateFormat_Field::WEEK_OF_MONTH() { clinit(); return WEEK_OF_MONTH_; } java::text::DateFormat_Field* java::text::DateFormat_Field::WEEK_OF_MONTH_; java::text::DateFormat_Field*& java::text::DateFormat_Field::WEEK_OF_YEAR() { clinit(); return WEEK_OF_YEAR_; } java::text::DateFormat_Field* java::text::DateFormat_Field::WEEK_OF_YEAR_; java::text::DateFormat_Field*& java::text::DateFormat_Field::YEAR() { clinit(); return YEAR_; } java::text::DateFormat_Field* java::text::DateFormat_Field::YEAR_; java::text::DateFormat_FieldArray*& java::text::DateFormat_Field::calendarToFieldMapping() { clinit(); return calendarToFieldMapping_; } java::text::DateFormat_FieldArray* java::text::DateFormat_Field::calendarToFieldMapping_; java::util::Map*& java::text::DateFormat_Field::instanceMap() { clinit(); return instanceMap_; } java::util::Map* java::text::DateFormat_Field::instanceMap_; constexpr int64_t java::text::DateFormat_Field::serialVersionUID; void ::java::text::DateFormat_Field::ctor(::java::lang::String* name, int32_t calendarField) { /* stub */ /* super::ctor(); */ unimplemented_(u"void ::java::text::DateFormat_Field::ctor(::java::lang::String* name, int32_t calendarField)"); } int32_t java::text::DateFormat_Field::getCalendarField() { /* stub */ return calendarField ; /* getter */ } java::text::DateFormat_Field* java::text::DateFormat_Field::ofCalendarField(int32_t calendarField) { /* stub */ clinit(); unimplemented_(u"java::text::DateFormat_Field* java::text::DateFormat_Field::ofCalendarField(int32_t calendarField)"); return 0; } java::lang::Object* java::text::DateFormat_Field::readResolve() { /* stub */ unimplemented_(u"java::lang::Object* java::text::DateFormat_Field::readResolve()"); return 0; } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* java::text::DateFormat_Field::class_() { static ::java::lang::Class* c = ::class_(u"java.text.DateFormat.Field", 26); return c; } java::lang::Class* java::text::DateFormat_Field::getClass0() { return class_(); }
31.039773
122
0.730551
pebble2015
04b66b86acc2f9cb143b27f52847bc2dee6405d2
12,747
cpp
C++
src/DeviceLogKML.cpp
inertialsense/inertial-sense-sdk
68893b0207d12d21420744706578f90ef215be4a
[ "MIT" ]
4
2021-06-09T16:31:32.000Z
2021-12-01T17:52:06.000Z
src/DeviceLogKML.cpp
inertialsense/inertial-sense-sdk
68893b0207d12d21420744706578f90ef215be4a
[ "MIT" ]
33
2020-08-06T09:09:24.000Z
2022-01-16T05:59:19.000Z
src/DeviceLogKML.cpp
inertialsense/inertial-sense-sdk
68893b0207d12d21420744706578f90ef215be4a
[ "MIT" ]
5
2020-09-04T21:32:37.000Z
2022-02-07T15:25:26.000Z
/* MIT LICENSE Copyright (c) 2014-2021 Inertial Sense, Inc. - http://inertialsense.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <ctime> #include <string> #include <sstream> #include <sys/types.h> #include <sys/stat.h> #include <iomanip> #include <iostream> #include <fstream> #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include "ISPose.h" #include "DeviceLogKML.h" #include "ISLogger.h" #include "ISConstants.h" using namespace std; void cDeviceLogKML::InitDeviceForWriting(int pHandle, std::string timestamp, std::string directory, uint64_t maxDiskSpace, uint32_t maxFileSize) { memset(&m_Log, 0, sizeof(m_Log)); cDeviceLog::InitDeviceForWriting(pHandle, timestamp, directory, maxDiskSpace, maxFileSize); } bool cDeviceLogKML::CloseAllFiles() { cDeviceLog::CloseAllFiles(); for (int kid = 0; kid < cDataKML::MAX_NUM_KID; kid++) { // Close file CloseWriteFile(kid, m_Log[kid]); } return true; } bool cDeviceLogKML::CloseWriteFile(int kid, sKmlLog &log) { // Ensure we have data int64_t dataSize = (int64_t)log.data.size(); if (dataSize <= 0) { return false; } // Ensure directory exists if (m_directory.empty()) { return false; } _MKDIR(m_directory.c_str()); // Create filename log.fileCount++; int serNum = m_devInfo.serialNumber; if (!serNum) { serNum = m_pHandle; } log.fileName = GetNewFileName(serNum, log.fileCount, m_kml.GetDatasetName(kid).c_str()); #define BUF_SIZE 100 char buf[BUF_SIZE]; int styleCnt = 1; string altitudeMode; string iconScale = "0.5"; string labelScale = "0.5"; string iconUrl; if (m_showPointTimestamps) labelScale = "0.5"; else labelScale = "0.01"; // Altitude mode if(m_altClampToGround) altitudeMode = "clampToGround"; else altitudeMode = "absolute"; // Style string styleStr, colorStr; iconUrl = "http://maps.google.com/mapfiles/kml/shapes/shaded_dot.png"; // iconUrl = "http://earth.google.com/images/kml-icons/track-directional/track-none.png"; // colors are ABGR switch (kid) { case cDataKML::KID_INS: iconUrl = "http://earth.google.com/images/kml-icons/track-directional/track-0.png"; colorStr = "ff00ffff"; // yellow break; case cDataKML::KID_GPS: colorStr = "ff0000ff"; // red break; case cDataKML::KID_GPS1: colorStr = "ffff0000"; // blue break; case cDataKML::KID_RTK: colorStr = "ffffff00"; // cyan break; case cDataKML::KID_REF: iconUrl = "http://earth.google.com/images/kml-icons/track-directional/track-0.png"; colorStr = "ffff00ff"; // magenta break; } // Add XML version info and document TiXmlElement *Style, *LineStyle, *IconStyle, *LabelStyle, *Placemark, *Point, *LineString, *heading, *elem, *href; TiXmlDocument tDoc; TiXmlDeclaration* decl = new TiXmlDeclaration("1.0", "UTF-8", ""); tDoc.LinkEndChild(decl); TiXmlElement* kml = new TiXmlElement("kml"); tDoc.LinkEndChild(kml); TiXmlElement* Document = new TiXmlElement("Document"); kml->LinkEndChild(Document); kml->SetAttribute("xmlns", "http://www.opengis.net/kml/2.2"); kml->SetAttribute("xmlns:gx", "http://www.google.com/kml/ext/2.2"); // Show sample (dot) if (m_showPoints) { // Style styleStr = string("stylesel_"); Style = new TiXmlElement("Style"); Style->SetAttribute("id", styleStr); Document->LinkEndChild(Style); // Icon style IconStyle = new TiXmlElement("IconStyle"); Style->LinkEndChild(IconStyle); elem = new TiXmlElement("color"); elem->LinkEndChild(new TiXmlText(colorStr)); IconStyle->LinkEndChild(elem); elem = new TiXmlElement("colorMode"); elem->LinkEndChild(new TiXmlText("normal")); IconStyle->LinkEndChild(elem); elem = new TiXmlElement("scale"); elem->LinkEndChild(new TiXmlText(iconScale)); IconStyle->LinkEndChild(elem); heading = new TiXmlElement("heading"); heading->LinkEndChild(new TiXmlText("0")); IconStyle->LinkEndChild(heading); href = new TiXmlElement("href"); href->LinkEndChild(new TiXmlText(iconUrl)); elem = new TiXmlElement("Icon"); elem->LinkEndChild(href); IconStyle->LinkEndChild(elem); // Label style LabelStyle = new TiXmlElement("LabelStyle"); Style->LinkEndChild(LabelStyle); elem = new TiXmlElement("colorMode"); elem->LinkEndChild(new TiXmlText("normal")); LabelStyle->LinkEndChild(elem); elem = new TiXmlElement("scale"); elem->LinkEndChild(new TiXmlText(labelScale)); LabelStyle->LinkEndChild(elem); double nextTime = log.data[0].time; for (size_t i = 0; i < log.data.size(); i++) { sKmlLogData& item = (log.data[i]); // Log only every iconUpdatePeriodSec if (item.time < nextTime) { continue; } nextTime = item.time - fmod(item.time, m_pointUpdatePeriodSec) + m_pointUpdatePeriodSec; // Placemark Placemark = new TiXmlElement("Placemark"); Document->LinkEndChild(Placemark); // Name elem = new TiXmlElement("name"); ostringstream timeStream; switch (kid) { case cDataKML::KID_GPS: case cDataKML::KID_GPS1: case cDataKML::KID_GPS2: case cDataKML::KID_RTK: timeStream << fixed << setprecision(1) << item.time; break; default: timeStream << fixed << setprecision(3) << item.time; break; } elem->LinkEndChild(new TiXmlText(timeStream.str())); Placemark->LinkEndChild(elem); // styleUrl elem = new TiXmlElement("styleUrl"); if (item.theta[2] != 0.0f) { // Style - to indicate heading string styleCntStr = styleStr + to_string(styleCnt++); TiXmlNode *StyleNode = Style->Clone(); StyleNode->ToElement()->SetAttribute("id", styleCntStr); StyleNode->FirstChildElement("IconStyle")->FirstChildElement("heading")->FirstChild()->ToText()->SetValue(to_string(item.theta[2] * C_RAD2DEG_F)); Document->LinkEndChild(StyleNode); elem->LinkEndChild(new TiXmlText("#" + styleCntStr)); } else { elem->LinkEndChild(new TiXmlText("#" + styleStr)); } Placemark->LinkEndChild(elem); Point = new TiXmlElement("Point"); Placemark->LinkEndChild(Point); elem = new TiXmlElement("coordinates"); #if 1 double lat = _CLAMP(item.lla[0] * DEG2RADMULT, -C_PIDIV2, C_PIDIV2) * RAD2DEGMULT; double lon = _CLAMP(item.lla[1] * DEG2RADMULT, -C_PI, C_PI) * RAD2DEGMULT; double alt = _CLAMP(item.lla[2], -1000, 100000); snprintf(buf, BUF_SIZE, "%.8lf,%.8lf,%.3lf", lon, lat, alt); elem->LinkEndChild(new TiXmlText(buf)); #else ostringstream coordinateStream; // Not getting digits of precision coordinateStream << fixed << setprecision(8) << item->lla[1] << "," // Lat << item->lla[0] << "," // Lon << setprecision(3) << item->lla[2] << " "; // Alt elem->LinkEndChild(new TiXmlText(coordinateStream.str())); #endif Point->LinkEndChild(elem); elem = new TiXmlElement("altitudeMode"); elem->LinkEndChild(new TiXmlText(altitudeMode)); Point->LinkEndChild(elem); } }// if (m_showSample) // Show path (track) if (m_showTracks) { // Track style styleStr = string("stylesel_") + to_string(styleCnt++); Style = new TiXmlElement("Style"); Style->SetAttribute("id", styleStr); Document->LinkEndChild(Style); LineStyle = new TiXmlElement("LineStyle"); Style->LinkEndChild(LineStyle); elem = new TiXmlElement("color"); elem->LinkEndChild(new TiXmlText(colorStr)); LineStyle->LinkEndChild(elem); elem = new TiXmlElement("colorMode"); elem->LinkEndChild(new TiXmlText("normal")); LineStyle->LinkEndChild(elem); elem = new TiXmlElement("width"); elem->LinkEndChild(new TiXmlText("2")); LineStyle->LinkEndChild(elem); // Track Placemark = new TiXmlElement("Placemark"); Document->LinkEndChild(Placemark); elem = new TiXmlElement("name"); elem->LinkEndChild(new TiXmlText("Tracks")); Placemark->LinkEndChild(elem); elem = new TiXmlElement("description"); elem->LinkEndChild(new TiXmlText("SN tracks")); Placemark->LinkEndChild(elem); elem = new TiXmlElement("styleUrl"); elem->LinkEndChild(new TiXmlText("#" + styleStr)); Placemark->LinkEndChild(elem); LineString = new TiXmlElement("LineString"); Placemark->LinkEndChild(LineString); ostringstream coordinateStream; int j = 0; for (size_t i = 0; i < log.data.size(); i++) { sKmlLogData& item = (log.data[i]); double lat = _CLAMP(item.lla[0] * DEG2RADMULT, -C_PIDIV2, C_PIDIV2) * RAD2DEGMULT; double lon = _CLAMP(item.lla[1] * DEG2RADMULT, -C_PI, C_PI) * RAD2DEGMULT; double alt = _CLAMP(item.lla[2], -1000, 100000); if (i >= log.data.size()-2) { j++; } snprintf(buf, BUF_SIZE, "%.8lf,%.8lf,%.3lf ", lon, lat, alt); // if (strcmp("-111.65863637,40.05570543,1418.282 ", buf) == 0) // { // j++; // } // qDebug() << string(buf); // std::cout << "Value of str is : "; coordinateStream << string(buf); } elem = new TiXmlElement("coordinates"); elem->LinkEndChild(new TiXmlText(coordinateStream.str())); LineString->LinkEndChild(elem); elem = new TiXmlElement("extrude"); elem->LinkEndChild(new TiXmlText("1")); LineString->LinkEndChild(elem); elem = new TiXmlElement("altitudeMode"); elem->LinkEndChild(new TiXmlText(altitudeMode)); LineString->LinkEndChild(elem); } // Write XML to file if (!tDoc.SaveFile(log.fileName.c_str())) { return false; } // Remove data log.data.clear(); return true; } bool cDeviceLogKML::OpenWithSystemApp(void) { #if PLATFORM_IS_WINDOWS for (int kid = 0; kid < cDataKML::MAX_NUM_KID; kid++) { sKmlLog &log = m_Log[kid]; if (log.fileName.empty()) { continue; } std::wstring stemp = std::wstring(log.fileName.begin(), log.fileName.end()); LPCWSTR filename = stemp.c_str(); ShellExecuteW(0, 0, filename, 0, 0, SW_SHOW); } #endif return true; } bool cDeviceLogKML::SaveData(p_data_hdr_t *dataHdr, const uint8_t *dataBuf) { cDeviceLog::SaveData(dataHdr, dataBuf); // Save data to file if (!WriteDateToFile(dataHdr, dataBuf)) { return false; } // Convert formats uDatasets& d = (uDatasets&)(*dataBuf); switch (dataHdr->id) { case DID_INS_2: ins_1_t ins1; ins1.week = d.ins2.week; ins1.timeOfWeek = d.ins2.timeOfWeek; ins1.hdwStatus = d.ins2.hdwStatus; ins1.insStatus = d.ins2.insStatus; quat2euler(d.ins2.qn2b, ins1.theta); memcpy(ins1.uvw, d.ins2.uvw, 12); memcpy(ins1.lla, d.ins2.lla, 24); p_data_hdr_t dHdr = { DID_INS_1 , sizeof(ins_1_t), 0 }; // Save data to file if (!WriteDateToFile(&dHdr, (uint8_t*)&ins1)) { return false; } break; } return true; } bool cDeviceLogKML::WriteDateToFile(const p_data_hdr_t *dataHdr, const uint8_t* dataBuf) { int kid = cDataKML::DID_TO_KID(dataHdr->id); // Only use selected data if (kid < 0) { return true; } // Reference current log sKmlLog &log = m_Log[kid]; // Write date to file m_kml.WriteDataToFile(log.data, dataHdr, dataBuf); // File byte size int nBytes = (int)(log.data.size() * cDataKML::BYTES_PER_KID(kid)); log.fileSize = nBytes; m_fileSize = _MAX(m_fileSize, log.fileSize); m_logSize = nBytes; if (log.fileSize >= m_maxFileSize) { // Close existing file if (!CloseWriteFile(kid, log)) { return false; } } return true; } p_data_t* cDeviceLogKML::ReadData() { p_data_t* data = NULL; // Read data from chunk while (!(data = ReadDataFromChunk())) { // Read next chunk from file if (!ReadChunkFromFile()) { return NULL; } } // Read is good cDeviceLog::OnReadData(data); return data; } p_data_t* cDeviceLogKML::ReadDataFromChunk() { return NULL; } bool cDeviceLogKML::ReadChunkFromFile() { return true; } void cDeviceLogKML::SetSerialNumber(uint32_t serialNumber) { m_devInfo.serialNumber = serialNumber; }
25.142012
459
0.683926
inertialsense
04b682e2bee638e6058c378a04e2f6ce49c9266e
6,969
cpp
C++
modules/juce_gui_extra/misc/juce_PushNotifications.cpp
studiobee/JUCE6-Svalbard-Fork
2bcd2101811f6a3a803a7f68d3bac2d0d53f4146
[ "ISC" ]
2,270
2020-04-15T15:14:37.000Z
2022-03-31T19:13:53.000Z
modules/juce_gui_extra/misc/juce_PushNotifications.cpp
studiobee/JUCE6-Svalbard-Fork
2bcd2101811f6a3a803a7f68d3bac2d0d53f4146
[ "ISC" ]
471
2017-04-25T07:57:02.000Z
2020-04-08T21:06:47.000Z
modules/juce_gui_extra/misc/juce_PushNotifications.cpp
studiobee/JUCE6-Svalbard-Fork
2bcd2101811f6a3a803a7f68d3bac2d0d53f4146
[ "ISC" ]
633
2020-04-15T16:45:55.000Z
2022-03-31T13:32:29.000Z
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2020 - Raw Material Software Limited JUCE is an open source library subject to commercial or open-source licensing. By using JUCE, you agree to the terms of both the JUCE 6 End-User License Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020). End User License Agreement: www.juce.com/juce-6-licence Privacy Policy: www.juce.com/juce-privacy-policy Or: You may also use this code under the terms of the GPL v3 (see www.gnu.org/licenses). JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ namespace juce { //============================================================================== #if ! JUCE_ANDROID && ! JUCE_IOS && ! JUCE_MAC bool PushNotifications::Notification::isValid() const noexcept { return true; } #endif PushNotifications::Notification::Notification (const Notification& other) : identifier (other.identifier), title (other.title), body (other.body), subtitle (other.subtitle), groupId (other.groupId), badgeNumber (other.badgeNumber), soundToPlay (other.soundToPlay), properties (other.properties), category (other.category), triggerIntervalSec (other.triggerIntervalSec), repeat (other.repeat), icon (other.icon), channelId (other.channelId), largeIcon (other.largeIcon), tickerText (other.tickerText), actions (other.actions), progress (other.progress), person (other.person), type (other.type), priority (other.priority), lockScreenAppearance (other.lockScreenAppearance), publicVersion (other.publicVersion.get() != nullptr ? new Notification (*other.publicVersion) : nullptr), groupSortKey (other.groupSortKey), groupSummary (other.groupSummary), accentColour (other.accentColour), ledColour (other.ledColour), ledBlinkPattern (other.ledBlinkPattern), vibrationPattern (other.vibrationPattern), shouldAutoCancel (other.shouldAutoCancel), localOnly (other.localOnly), ongoing (other.ongoing), alertOnlyOnce (other.alertOnlyOnce), timestampVisibility (other.timestampVisibility), badgeIconType (other.badgeIconType), groupAlertBehaviour (other.groupAlertBehaviour), timeoutAfterMs (other.timeoutAfterMs) { } //============================================================================== JUCE_IMPLEMENT_SINGLETON (PushNotifications) PushNotifications::PushNotifications() #if JUCE_PUSH_NOTIFICATIONS : pimpl (new Pimpl (*this)) #endif { } PushNotifications::~PushNotifications() { clearSingletonInstance(); } void PushNotifications::addListener (Listener* l) { listeners.add (l); } void PushNotifications::removeListener (Listener* l) { listeners.remove (l); } void PushNotifications::requestPermissionsWithSettings (const PushNotifications::Settings& settings) { #if JUCE_PUSH_NOTIFICATIONS && (JUCE_IOS || JUCE_MAC) pimpl->requestPermissionsWithSettings (settings); #else ignoreUnused (settings); listeners.call ([] (Listener& l) { l.notificationSettingsReceived ({}); }); #endif } void PushNotifications::requestSettingsUsed() { #if JUCE_PUSH_NOTIFICATIONS && (JUCE_IOS || JUCE_MAC) pimpl->requestSettingsUsed(); #else listeners.call ([] (Listener& l) { l.notificationSettingsReceived ({}); }); #endif } bool PushNotifications::areNotificationsEnabled() const { #if JUCE_PUSH_NOTIFICATIONS return pimpl->areNotificationsEnabled(); #else return false; #endif } void PushNotifications::getDeliveredNotifications() const { #if JUCE_PUSH_NOTIFICATIONS pimpl->getDeliveredNotifications(); #endif } void PushNotifications::removeAllDeliveredNotifications() { #if JUCE_PUSH_NOTIFICATIONS pimpl->removeAllDeliveredNotifications(); #endif } String PushNotifications::getDeviceToken() const { #if JUCE_PUSH_NOTIFICATIONS return pimpl->getDeviceToken(); #else return {}; #endif } void PushNotifications::setupChannels (const Array<ChannelGroup>& groups, const Array<Channel>& channels) { #if JUCE_PUSH_NOTIFICATIONS pimpl->setupChannels (groups, channels); #else ignoreUnused (groups, channels); #endif } void PushNotifications::getPendingLocalNotifications() const { #if JUCE_PUSH_NOTIFICATIONS pimpl->getPendingLocalNotifications(); #endif } void PushNotifications::removeAllPendingLocalNotifications() { #if JUCE_PUSH_NOTIFICATIONS pimpl->removeAllPendingLocalNotifications(); #endif } void PushNotifications::subscribeToTopic (const String& topic) { #if JUCE_PUSH_NOTIFICATIONS pimpl->subscribeToTopic (topic); #else ignoreUnused (topic); #endif } void PushNotifications::unsubscribeFromTopic (const String& topic) { #if JUCE_PUSH_NOTIFICATIONS pimpl->unsubscribeFromTopic (topic); #else ignoreUnused (topic); #endif } void PushNotifications::sendLocalNotification (const Notification& n) { #if JUCE_PUSH_NOTIFICATIONS pimpl->sendLocalNotification (n); #else ignoreUnused (n); #endif } void PushNotifications::removeDeliveredNotification (const String& identifier) { #if JUCE_PUSH_NOTIFICATIONS pimpl->removeDeliveredNotification (identifier); #else ignoreUnused (identifier); #endif } void PushNotifications::removePendingLocalNotification (const String& identifier) { #if JUCE_PUSH_NOTIFICATIONS pimpl->removePendingLocalNotification (identifier); #else ignoreUnused (identifier); #endif } void PushNotifications::sendUpstreamMessage (const String& serverSenderId, const String& collapseKey, const String& messageId, const String& messageType, int timeToLive, const StringPairArray& additionalData) { #if JUCE_PUSH_NOTIFICATIONS pimpl->sendUpstreamMessage (serverSenderId, collapseKey, messageId, messageType, timeToLive, additionalData); #else ignoreUnused (serverSenderId, collapseKey, messageId, messageType); ignoreUnused (timeToLive, additionalData); #endif } } // namespace juce
30.3
112
0.638686
studiobee
04b7bba6077c701cfe3ba87b19eb7a5b761f9e5a
1,018
cpp
C++
runtime/src/events/ExplosionEvent.cpp
Timo972/altv-go-module
9762938c019d47b52eceba6761bb6f900ea4f2e8
[ "MIT" ]
null
null
null
runtime/src/events/ExplosionEvent.cpp
Timo972/altv-go-module
9762938c019d47b52eceba6761bb6f900ea4f2e8
[ "MIT" ]
null
null
null
runtime/src/events/ExplosionEvent.cpp
Timo972/altv-go-module
9762938c019d47b52eceba6761bb6f900ea4f2e8
[ "MIT" ]
null
null
null
#include "ExplosionEvent.h" Go::ExplosionEvent::ExplosionEvent(ModuleLibrary *module) : IEvent(module) { } void Go::ExplosionEvent::Call(const alt::CEvent *ev) { static auto call = GET_FUNC(Library, "altExplosionEvent", bool (*)(alt::IPlayer* source, Entity target, Position position, short explosionType, unsigned int explosionFX)); if (call == nullptr) { alt::ICore::Instance().LogError("Couldn't not call ExplosionEvent."); return; } auto event = dynamic_cast<const alt::CExplosionEvent *>(ev); auto target = event->GetTarget(); auto source = event->GetSource().Get(); auto pos = event->GetPosition(); auto expFX = event->GetExplosionFX(); auto expType = event->GetExplosionType(); Entity e = Go::Runtime::GetInstance()->GetEntity(target); Position cPos; cPos.x = pos.x; cPos.y = pos.y; cPos.z = pos.z; auto cancel = call(source, e, cPos, static_cast<short>(expType), expFX); if(!cancel) { event->Cancel(); } }
29.085714
175
0.649312
Timo972
04b8560c82b0f92dd8c621ce7934ca440540a3be
59,762
cpp
C++
Source/VirtualDirectInputDevice.cpp
hamzahamidi/Xidi
d7585ecf23fd17dd5be4e69f63bae08aa0e96988
[ "BSD-3-Clause" ]
1
2021-06-05T00:22:08.000Z
2021-06-05T00:22:08.000Z
Source/VirtualDirectInputDevice.cpp
hamzahamidi/Xidi
d7585ecf23fd17dd5be4e69f63bae08aa0e96988
[ "BSD-3-Clause" ]
null
null
null
Source/VirtualDirectInputDevice.cpp
hamzahamidi/Xidi
d7585ecf23fd17dd5be4e69f63bae08aa0e96988
[ "BSD-3-Clause" ]
null
null
null
/***************************************************************************** * Xidi * DirectInput interface for XInput controllers. ***************************************************************************** * Authored by Samuel Grossman * Copyright (c) 2016-2021 *************************************************************************//** * @file VirtualDirectInputDevice.cpp * Implementation of an IDirectInputDevice interface wrapper around virtual * controllers. *****************************************************************************/ #include "ApiDirectInput.h" #include "ApiGUID.h" #include "ControllerIdentification.h" #include "ControllerTypes.h" #include "DataFormat.h" #include "Message.h" #include "Strings.h" #include "VirtualController.h" #include "VirtualDirectInputDevice.h" #include <atomic> #include <cstdio> #include <cstring> #include <memory> #include <optional> // -------- MACROS --------------------------------------------------------- // /// Logs a DirectInput interface method invocation and returns. #define LOG_INVOCATION_AND_RETURN(result, severity) \ do \ { \ const HRESULT kResult = (result); \ Message::OutputFormatted(severity, L"Invoked %s on Xidi virtual controller %u, result = 0x%08x.", __FUNCTIONW__ L"()", (1 + controller->GetIdentifier()), kResult); \ return kResult; \ } while (false) /// Logs a DirectInput property-related method invocation and returns. #define LOG_PROPERTY_INVOCATION_AND_RETURN(result, severity, rguidprop, propvalfmt, ...) \ do \ { \ const HRESULT kResult = (result); \ Message::OutputFormatted(severity, L"Invoked function %s on Xidi virtual controller %u, result = 0x%08x, property = %s" propvalfmt L".", __FUNCTIONW__ L"()", (1 + controller->GetIdentifier()), kResult, PropertyGuidString(rguidprop), ##__VA_ARGS__); \ return kResult; \ } while (false) /// Logs a DirectInput property-related method without a value and returns. #define LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(result, severity, rguidprop) LOG_PROPERTY_INVOCATION_AND_RETURN(result, severity, rguidprop, L"") /// Logs a DirectInput property-related method where the value is provided in a DIPROPDWORD structure and returns. #define LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(result, severity, rguidprop, ppropval) LOG_PROPERTY_INVOCATION_AND_RETURN(result, severity, rguidprop, L", value = { dwData = %u }", ((LPDIPROPDWORD)ppropval)->dwData) /// Logs a DirectInput property-related method where the value is provided in a DIPROPRANGE structure and returns. #define LOG_PROPERTY_INVOCATION_DIPROPRANGE_AND_RETURN(result, severity, rguidprop, ppropval) LOG_PROPERTY_INVOCATION_AND_RETURN(result, severity, rguidprop, L", value = { lMin = %ld, lMax = %ld }", ((LPDIPROPRANGE)ppropval)->lMin, ((LPDIPROPRANGE)ppropval)->lMax) /// Produces and returns a human-readable string from a given DirectInput property GUID. #define DI_PROPERTY_STRING(rguid, diprop) if (&diprop == &rguid) return _CRT_WIDE(#diprop); namespace Xidi { // -------- INTERNAL FUNCTIONS ----------------------------------------- // /// Converts from axis type enumerator to axis type GUID. /// @param [in] axis Axis type enumerator to convert. /// @return Read-only reference to the corresponding GUID object. static const GUID& AxisTypeGuid(Controller::EAxis axis) { switch (axis) { case Controller::EAxis::X: return GUID_XAxis; case Controller::EAxis::Y: return GUID_YAxis; case Controller::EAxis::Z: return GUID_ZAxis; case Controller::EAxis::RotX: return GUID_RxAxis; case Controller::EAxis::RotY: return GUID_RyAxis; case Controller::EAxis::RotZ: return GUID_RzAxis; default: return GUID_Unknown; } } /// Returns a string representation of the way in which a controller element is identified. /// @param [in] dwHow Value to check. /// @return String representation of the identification method. static const wchar_t* IdentificationMethodString(DWORD dwHow) { switch (dwHow) { case DIPH_DEVICE: return L"DIPH_DEVICE"; case DIPH_BYOFFSET: return L"DIPH_BYOFFSET"; case DIPH_BYUSAGE: return L"DIPH_BYUSAGE"; case DIPH_BYID: return L"DIPH_BYID"; default: return L"(unknown)"; } } /// Returns a human-readable string that represents the specified property GUID. /// @param [in] pguid GUID to check. /// @return String representation of the GUID's semantics. static const wchar_t* PropertyGuidString(REFGUID rguidProp) { switch ((size_t)&rguidProp) { #if DIRECTINPUT_VERSION >= 0x0800 case ((size_t)&DIPROP_KEYNAME): return L"DIPROP_KEYNAME"; case ((size_t)&DIPROP_CPOINTS): return L"DIPROP_CPOINTS"; case ((size_t)&DIPROP_APPDATA): return L"DIPROP_APPDATA"; case ((size_t)&DIPROP_SCANCODE): return L"DIPROP_SCANCODE"; case ((size_t)&DIPROP_VIDPID): return L"DIPROP_VIDPID"; case ((size_t)&DIPROP_USERNAME): return L"DIPROP_USERNAME"; case ((size_t)&DIPROP_TYPENAME): return L"DIPROP_TYPENAME"; #endif case ((size_t)&DIPROP_BUFFERSIZE): return L"DIPROP_BUFFERSIZE"; case ((size_t)&DIPROP_AXISMODE): return L"DIPROP_AXISMODE"; case ((size_t)&DIPROP_GRANULARITY): return L"DIPROP_GRANULARITY"; case ((size_t)&DIPROP_RANGE): return L"DIPROP_RANGE"; case ((size_t)&DIPROP_DEADZONE): return L"DIPROP_DEADZONE"; case ((size_t)&DIPROP_SATURATION): return L"DIPROP_SATURATION"; case ((size_t)&DIPROP_FFGAIN): return L"DIPROP_FFGAIN"; case ((size_t)&DIPROP_FFLOAD): return L"DIPROP_FFLOAD"; case ((size_t)&DIPROP_AUTOCENTER): return L"DIPROP_AUTOCENTER"; case ((size_t)&DIPROP_CALIBRATIONMODE): return L"DIPROP_CALIBRATIONMODE"; case ((size_t)&DIPROP_CALIBRATION): return L"DIPROP_CALIBRATION"; case ((size_t)&DIPROP_GUIDANDPATH): return L"DIPROP_GUIDANDPATH"; case ((size_t)&DIPROP_INSTANCENAME): return L"DIPROP_INSTANCENAME"; case ((size_t)&DIPROP_PRODUCTNAME): return L"DIPROP_PRODUCTNAME"; case ((size_t)&DIPROP_JOYSTICKID): return L"DIPROP_JOYSTICKID"; case ((size_t)&DIPROP_GETPORTDISPLAYNAME): return L"DIPROP_GETPORTDISPLAYNAME"; case ((size_t)&DIPROP_PHYSICALRANGE): return L"DIPROP_PHYSICALRANGE"; case ((size_t)&DIPROP_LOGICALRANGE): return L"DIPROP_LOGICALRANGE"; default: return L"(unknown)"; } } /// Performs property-specific validation of the supplied property header. /// Ensures the header exists and all sizes are correct. /// @param [in] rguidProp GUID of the property for which the header is being validated. /// @param [in] pdiph Pointer to the property header structure to validate. /// @return `true` if the header is valid, `false` otherwise. static bool IsPropertyHeaderValid(REFGUID rguidProp, LPCDIPROPHEADER pdiph) { if (nullptr == pdiph) { Message::OutputFormatted(Message::ESeverity::Warning, L"Rejected null property header for %s.", PropertyGuidString(rguidProp)); return false; } else if ((sizeof(DIPROPHEADER) != pdiph->dwHeaderSize)) { Message::OutputFormatted(Message::ESeverity::Warning, L"Rejected invalid property header for %s: Incorrect size for DIPROPHEADER (expected %u, got %u).", PropertyGuidString(rguidProp), (unsigned int)sizeof(DIPROPHEADER), (unsigned int)pdiph->dwHeaderSize); return false; } else if ((DIPH_DEVICE == pdiph->dwHow) && (0 != pdiph->dwObj)) { Message::OutputFormatted(Message::ESeverity::Warning, L"Rejected invalid property header for %s: Incorrect object identification value used with DIPH_DEVICE (expected %u, got %u).", PropertyGuidString(rguidProp), (unsigned int)0, (unsigned int)pdiph->dwObj); return false; } // Look for reasons why the property header might be invalid and reject it if any are found. switch ((size_t)&rguidProp) { case ((size_t)&DIPROP_AXISMODE): case ((size_t)&DIPROP_DEADZONE): case ((size_t)&DIPROP_GRANULARITY): case ((size_t)&DIPROP_SATURATION): // Axis mode, deadzone, granularity, and saturation all use DIPROPDWORD. if (sizeof(DIPROPDWORD) != pdiph->dwSize) { Message::OutputFormatted(Message::ESeverity::Warning, L"Rejected invalid property header for %s: Incorrect size for DIPROPDWORD (expected %u, got %u).", PropertyGuidString(rguidProp), (unsigned int)sizeof(DIPROPDWORD), (unsigned int)pdiph->dwSize); return false; } break; case ((size_t)&DIPROP_BUFFERSIZE): case ((size_t)&DIPROP_FFGAIN): case ((size_t)&DIPROP_JOYSTICKID): // Buffer size, force feedback gain, and joystick ID all use DIPROPDWORD and are exclusively device-wide properties. if (DIPH_DEVICE != pdiph->dwHow) { Message::OutputFormatted(Message::ESeverity::Warning, L"Rejected invalid property header for %s: Incorrect object identification method for this property (expected %s, got %s).", PropertyGuidString(rguidProp), IdentificationMethodString(DIPH_DEVICE), IdentificationMethodString(pdiph->dwHow)); return false; } else if (sizeof(DIPROPDWORD) != pdiph->dwSize) { Message::OutputFormatted(Message::ESeverity::Warning, L"Rejected invalid property header for %s: Incorrect size for DIPROPDWORD (expected %u, got %u).", PropertyGuidString(rguidProp), (unsigned int)sizeof(DIPROPDWORD), (unsigned int)pdiph->dwSize); return false; } break; case ((size_t)&DIPROP_RANGE): case ((size_t)&DIPROP_LOGICALRANGE): case ((size_t)&DIPROP_PHYSICALRANGE): // Range-related properties use DIPROPRANGE. if (sizeof(DIPROPRANGE) != pdiph->dwSize) { Message::OutputFormatted(Message::ESeverity::Warning, L"Rejected invalid property header for %s: Incorrect size for DIPROPRANGE (expected %u, got %u).", PropertyGuidString(rguidProp), (unsigned int)sizeof(DIPROPRANGE), (unsigned int)pdiph->dwSize); return false; } break; default: // Any property not listed here is not supported by Xidi and therefore not validated by it. Message::OutputFormatted(Message::ESeverity::Warning, L"Skipped property header validation because the property %s is not supported.", PropertyGuidString(rguidProp)); return true; } Message::OutputFormatted(Message::ESeverity::Info, L"Accepted valid property header for %s.", PropertyGuidString(rguidProp)); return true; } /// Dumps the top-level components of a property request. /// @param [in] rguidProp GUID of the property. /// @param [in] pdiph Pointer to the property header. /// @param [in] requestTypeIsSet `true` if the request type is SetProperty, `false` if it is GetProperty. static void DumpPropertyRequest(REFGUID rguidProp, LPCDIPROPHEADER pdiph, bool requestTypeIsSet) { constexpr Message::ESeverity kDumpSeverity = Message::ESeverity::Debug; if (Message::WillOutputMessageOfSeverity(kDumpSeverity)) { Message::Output(kDumpSeverity, L"Begin dump of property request."); Message::Output(kDumpSeverity, L" Metadata:"); Message::OutputFormatted(kDumpSeverity, L" operation = %sProperty", ((true == requestTypeIsSet) ? L"Set" : L"Get")); Message::OutputFormatted(kDumpSeverity, L" rguidProp = %s", PropertyGuidString(rguidProp)); Message::Output(kDumpSeverity, L" Header:"); if (nullptr == pdiph) { Message::Output(kDumpSeverity, L" (missing)"); } else { Message::OutputFormatted(kDumpSeverity, L" dwSize = %u", pdiph->dwSize); Message::OutputFormatted(kDumpSeverity, L" dwHeaderSize = %u", pdiph->dwHeaderSize); Message::OutputFormatted(kDumpSeverity, L" dwObj = %u (0x%08x)", pdiph->dwObj, pdiph->dwObj); Message::OutputFormatted(kDumpSeverity, L" dwHow = %u (%s)", pdiph->dwHow, IdentificationMethodString(pdiph->dwHow)); } Message::Output(kDumpSeverity, L"End dump of property request."); } } /// Fills the specified buffer with a friendly string representation of the specified controller element. /// Default version does nothing. /// @tparam CharType String character type, either `char` or `wchar_t`. /// @param [in] element Controller element for which a string is desired. /// @param [out] buf Buffer to be filled with the string. /// @param [in] bufcount Buffer size in number of characters. template <typename CharType> static void ElementToString(Controller::SElementIdentifier element, CharType* buf, int bufcount) { // Nothing to do here. } /// Fills the specified buffer with a friendly string representation of the specified controller element, specialized for ASCII. /// @param [in] element Controller element for which a string is desired. /// @param [out] buf Buffer to be filled with the string. /// @param [in] bufcount Buffer size in number of characters. template <> static void ElementToString<char>(Controller::SElementIdentifier element, char* buf, int bufcount) { switch (element.type) { case Controller::EElementType::Axis: switch (element.axis) { case Controller::EAxis::X: strncpy_s(buf, bufcount, XIDI_AXIS_NAME_X, _countof(XIDI_AXIS_NAME_X)); break; case Controller::EAxis::Y: strncpy_s(buf, bufcount, XIDI_AXIS_NAME_Y, _countof(XIDI_AXIS_NAME_Y)); break; case Controller::EAxis::Z: strncpy_s(buf, bufcount, XIDI_AXIS_NAME_Z, _countof(XIDI_AXIS_NAME_Z)); break; case Controller::EAxis::RotX: strncpy_s(buf, bufcount, XIDI_AXIS_NAME_RX, _countof(XIDI_AXIS_NAME_RX)); break; case Controller::EAxis::RotY: strncpy_s(buf, bufcount, XIDI_AXIS_NAME_RY, _countof(XIDI_AXIS_NAME_RY)); break; case Controller::EAxis::RotZ: strncpy_s(buf, bufcount, XIDI_AXIS_NAME_RZ, _countof(XIDI_AXIS_NAME_RZ)); break; default: strncpy_s(buf, bufcount, XIDI_AXIS_NAME_UNKNOWN, _countof(XIDI_AXIS_NAME_UNKNOWN)); break; } break; case Controller::EElementType::Button: sprintf_s(buf, bufcount, XIDI_BUTTON_NAME_FORMAT, (1 + (unsigned int)element.button)); break; case Controller::EElementType::Pov: strncpy_s(buf, bufcount, XIDI_POV_NAME, _countof(XIDI_POV_NAME)); break; case Controller::EElementType::WholeController: strncpy_s(buf, bufcount, XIDI_WHOLE_CONTROLLER_NAME, _countof(XIDI_WHOLE_CONTROLLER_NAME)); break; } } /// Fills the specified buffer with a friendly string representation of the specified controller element, specialized for ASCII. /// @param [in] element Controller element for which a string is desired. /// @param [out] buf Buffer to be filled with the string. /// @param [in] bufcount Buffer size in number of characters. template <> static void ElementToString<wchar_t>(Controller::SElementIdentifier element, wchar_t* buf, int bufcount) { switch (element.type) { case Controller::EElementType::Axis: switch (element.axis) { case Controller::EAxis::X: wcsncpy_s(buf, bufcount, _CRT_WIDE(XIDI_AXIS_NAME_X), _countof(_CRT_WIDE(XIDI_AXIS_NAME_X))); break; case Controller::EAxis::Y: wcsncpy_s(buf, bufcount, _CRT_WIDE(XIDI_AXIS_NAME_Y), _countof(_CRT_WIDE(XIDI_AXIS_NAME_Y))); break; case Controller::EAxis::Z: wcsncpy_s(buf, bufcount, _CRT_WIDE(XIDI_AXIS_NAME_Z), _countof(_CRT_WIDE(XIDI_AXIS_NAME_Z))); break; case Controller::EAxis::RotX: wcsncpy_s(buf, bufcount, _CRT_WIDE(XIDI_AXIS_NAME_RX), _countof(_CRT_WIDE(XIDI_AXIS_NAME_RX))); break; case Controller::EAxis::RotY: wcsncpy_s(buf, bufcount, _CRT_WIDE(XIDI_AXIS_NAME_RY), _countof(_CRT_WIDE(XIDI_AXIS_NAME_RY))); break; case Controller::EAxis::RotZ: wcsncpy_s(buf, bufcount, _CRT_WIDE(XIDI_AXIS_NAME_RZ), _countof(_CRT_WIDE(XIDI_AXIS_NAME_RZ))); break; default: wcsncpy_s(buf, bufcount, _CRT_WIDE(XIDI_AXIS_NAME_UNKNOWN), _countof(_CRT_WIDE(XIDI_AXIS_NAME_UNKNOWN))); break; } break; case Controller::EElementType::Button: swprintf_s(buf, bufcount, _CRT_WIDE(XIDI_BUTTON_NAME_FORMAT), (1 + (unsigned int)element.button)); break; case Controller::EElementType::Pov: wcsncpy_s(buf, bufcount, _CRT_WIDE(XIDI_POV_NAME), _countof(_CRT_WIDE(XIDI_POV_NAME))); break; case Controller::EElementType::WholeController: wcsncpy_s(buf, bufcount, _CRT_WIDE(XIDI_WHOLE_CONTROLLER_NAME), _countof(_CRT_WIDE(XIDI_WHOLE_CONTROLLER_NAME))); break; } } /// Computes the offset in a virtual controller's "native" data packet. /// For application information only. Cannot be used to identify objects. /// Application is presented with the image of a native data packet that stores axes first, then buttons (one byte per button), then POV. /// @param [in] controllerElement Virtual controller element for which a native offset is desired. /// @return Native offset value for providing to applications. static TOffset NativeOffsetForElement(Controller::SElementIdentifier controllerElement) { switch (controllerElement.type) { case Controller::EElementType::Axis: return offsetof(Controller::SState, axis[(int)controllerElement.axis]); case Controller::EElementType::Button: return offsetof(Controller::SState, button) + (TOffset)controllerElement.button; case Controller::EElementType::Pov: return offsetof(Controller::SState, button) + (TOffset)Controller::EButton::Count; default: // This should never happen. return DataFormat::kInvalidOffsetValue; } } /// Fills the specified object instance information structure with information about the specified controller element. /// Size member must already be initialized because multiple versions of the structure exist, so it is used to determine which members to fill in. /// @tparam charMode Selects between ASCII ("A" suffix) and Unicode ("W") suffix versions of types and interfaces. /// @param [in] controllerCapabilities Capabilities that describe the layout of the virtual controller. /// @param [in] controllerElement Virtual controller element about which to fill information. /// @param [in] offset Offset to place into the object instance information structure. /// @param objectInfo [out] Structure to be filled with instance information. template <ECharMode charMode> static void FillObjectInstanceInfo(const Controller::SCapabilities controllerCapabilities, Controller::SElementIdentifier controllerElement, TOffset offset, typename DirectInputDeviceType<charMode>::DeviceObjectInstanceType* objectInfo) { objectInfo->dwOfs = offset; ElementToString(controllerElement, objectInfo->tszName, _countof(objectInfo->tszName)); switch (controllerElement.type) { case Controller::EElementType::Axis: objectInfo->guidType = AxisTypeGuid(controllerElement.axis); objectInfo->dwType = DIDFT_ABSAXIS | DIDFT_MAKEINSTANCE((int)controllerCapabilities.FindAxis(controllerElement.axis)); objectInfo->dwFlags = DIDOI_POLLED | DIDOI_ASPECTPOSITION; break; case Controller::EElementType::Button: objectInfo->guidType = GUID_Button; objectInfo->dwType = DIDFT_PSHBUTTON | DIDFT_MAKEINSTANCE((int)controllerElement.button); objectInfo->dwFlags = DIDOI_POLLED; break; case Controller::EElementType::Pov: objectInfo->guidType = GUID_POV; objectInfo->dwType = DIDFT_POV | DIDFT_MAKEINSTANCE(0); objectInfo->dwFlags = DIDOI_POLLED; break; } // DirectInput versions 5 and higher include extra members in this structure, and this is indicated on input using the size member of the structure. if (objectInfo->dwSize > sizeof(DirectInputDeviceType<charMode>::DeviceObjectInstanceCompatType)) { // These fields are zeroed out because Xidi does not currently offer any of the functionality they represent. objectInfo->dwFFMaxForce = 0; objectInfo->dwFFForceResolution = 0; objectInfo->wCollectionNumber = 0; objectInfo->wDesignatorIndex = 0; objectInfo->wUsagePage = 0; objectInfo->wUsage = 0; objectInfo->dwDimension = 0; objectInfo->wExponent = 0; objectInfo->wReportId = 0; } } /// Signals the specified event if its handle is valid. /// @param [in] eventHandle Handle that can be used to identify the desired event object. static inline void SignalEventIfEnabled(HANDLE eventHandle) { if ((NULL != eventHandle) && (INVALID_HANDLE_VALUE != eventHandle)) SetEvent(eventHandle); } // -------- CONSTRUCTION AND DESTRUCTION ------------------------------- // // See "VirtualDirectInputDevice.h" for documentation. template <ECharMode charMode> VirtualDirectInputDevice<charMode>::VirtualDirectInputDevice(std::unique_ptr<Controller::VirtualController>&& controller) : controller(std::move(controller)), dataFormat(), refCount(1), stateChangeEventHandle(NULL) { // Nothing to do here. } // -------- INSTANCE METHODS ------------------------------------------- // // See "VirtualDirectInputDevice.h" for documentation. template <ECharMode charMode> std::optional<Controller::SElementIdentifier> VirtualDirectInputDevice<charMode>::IdentifyElement(DWORD dwObj, DWORD dwHow) const { switch (dwHow) { case DIPH_DEVICE: // Whole device is referenced. // Per DirectInput documentation, the object identifier must be 0. if (0 == dwObj) return Controller::SElementIdentifier({.type = Controller::EElementType::WholeController}); break; case DIPH_BYOFFSET: // Controller element is being identified by offset. // Object identifier is an offset into the application's data format. if (true == IsApplicationDataFormatSet()) return dataFormat->GetElementForOffset(dwObj); break; case DIPH_BYID: // Controller element is being identified by instance identifier. // Object identifier contains type and index, and the latter refers to the controller's reported capabilities. if ((unsigned int)DIDFT_GETINSTANCE(dwObj) >= 0) { const unsigned int kType = (unsigned int)DIDFT_GETTYPE(dwObj); const unsigned int kIndex = (unsigned int)DIDFT_GETINSTANCE(dwObj); switch (kType) { case DIDFT_ABSAXIS: if ((kIndex < (unsigned int)Controller::EAxis::Count) && (kIndex < (unsigned int)controller->GetCapabilities().numAxes)) return Controller::SElementIdentifier({.type = Controller::EElementType::Axis, .axis = controller->GetCapabilities().axisType[kIndex]}); break; case DIDFT_PSHBUTTON: if ((kIndex < (unsigned int)Controller::EButton::Count) && (kIndex < (unsigned int)controller->GetCapabilities().numButtons)) return Controller::SElementIdentifier({.type = Controller::EElementType::Button, .button = (Controller::EButton)kIndex}); break; case DIDFT_POV: if (kIndex == 0) return Controller::SElementIdentifier({.type = Controller::EElementType::Pov}); break; } } break; } return std::nullopt; } // -------- METHODS: IUnknown ------------------------------------------ // // See IUnknown documentation for more information. template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::QueryInterface(REFIID riid, LPVOID* ppvObj) { if (nullptr == ppvObj) return E_POINTER; bool validInterfaceRequested = false; if (ECharMode::W == charMode) { #if DIRECTINPUT_VERSION >= 0x0800 if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IDirectInputDevice8W)) #else if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IDirectInputDevice7W) || IsEqualIID(riid, IID_IDirectInputDevice2W) || IsEqualIID(riid, IID_IDirectInputDeviceW)) #endif validInterfaceRequested = true; } else { #if DIRECTINPUT_VERSION >= 0x0800 if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IDirectInputDevice8A)) #else if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IDirectInputDevice7A) || IsEqualIID(riid, IID_IDirectInputDevice2A) || IsEqualIID(riid, IID_IDirectInputDeviceA)) #endif validInterfaceRequested = true; } if (true == validInterfaceRequested) { AddRef(); *ppvObj = this; return S_OK; } return E_NOINTERFACE; } // --------- template <ECharMode charMode> ULONG VirtualDirectInputDevice<charMode>::AddRef(void) { return ++refCount; } // --------- template <ECharMode charMode> ULONG VirtualDirectInputDevice<charMode>::Release(void) { const unsigned long numRemainingRefs = --refCount; if (0 == numRemainingRefs) delete this; return (ULONG)numRemainingRefs; } // -------- METHODS: IDirectInputDevice COMMON ------------------------- // // See DirectInput documentation for more information. template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::Acquire(void) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; // Controller acquisition is a no-op for Xidi virtual controllers. // However, DirectInput documentation requires that the application data format already be set. if (false == IsApplicationDataFormatSet()) LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::CreateEffect(REFGUID rguid, LPCDIEFFECT lpeff, LPDIRECTINPUTEFFECT* ppdeff, LPUNKNOWN punkOuter) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::EnumCreatedEffectObjects(LPDIENUMCREATEDEFFECTOBJECTSCALLBACK lpCallback, LPVOID pvRef, DWORD fl) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::EnumEffects(DirectInputDeviceType<charMode>::EnumEffectsCallbackType lpCallback, LPVOID pvRef, DWORD dwEffType) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::EnumEffectsInFile(DirectInputDeviceType<charMode>::ConstStringType lptszFileName, LPDIENUMEFFECTSINFILECALLBACK pec, LPVOID pvRef, DWORD dwFlags) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::EnumObjects(DirectInputDeviceType<charMode>::EnumObjectsCallbackType lpCallback, LPVOID pvRef, DWORD dwFlags) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; const bool willEnumerateAxes = ((DIDFT_ALL == dwFlags) || (0 != (dwFlags & DIDFT_ABSAXIS))); const bool willEnumerateButtons = ((DIDFT_ALL == dwFlags) || (0 != (dwFlags & DIDFT_PSHBUTTON))); const bool willEnumeratePov = ((DIDFT_ALL == dwFlags) || (0 != (dwFlags & DIDFT_POV))); if (nullptr == lpCallback) LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); if ((true == willEnumerateAxes) || (true == willEnumerateButtons) || (true == willEnumeratePov)) { std::unique_ptr<DirectInputDeviceType<charMode>::DeviceObjectInstanceType> objectDescriptor = std::make_unique<DirectInputDeviceType<charMode>::DeviceObjectInstanceType>(); const Controller::SCapabilities controllerCapabilities = controller->GetCapabilities(); if (true == willEnumerateAxes) { for (int i = 0; i < controllerCapabilities.numAxes; ++i) { const Controller::EAxis kAxis = controllerCapabilities.axisType[i]; const Controller::SElementIdentifier kAxisIdentifier = {.type = Controller::EElementType::Axis, .axis = kAxis}; const TOffset kAxisOffset = ((true == IsApplicationDataFormatSet()) ? dataFormat->GetOffsetForElement(kAxisIdentifier).value_or(DataFormat::kInvalidOffsetValue) : NativeOffsetForElement(kAxisIdentifier)); *objectDescriptor = {.dwSize = sizeof(*objectDescriptor)}; FillObjectInstanceInfo<charMode>(controllerCapabilities, kAxisIdentifier, kAxisOffset, objectDescriptor.get()); switch (lpCallback(objectDescriptor.get(), pvRef)) { case DIENUM_CONTINUE: break; case DIENUM_STOP: LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); default: LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); } } } if (true == willEnumerateButtons) { for (int i = 0; i < controllerCapabilities.numButtons; ++i) { const Controller::EButton kButton = (Controller::EButton)i; const Controller::SElementIdentifier kButtonIdentifier = {.type = Controller::EElementType::Button, .button = kButton}; const TOffset kButtonOffset = ((true == IsApplicationDataFormatSet()) ? dataFormat->GetOffsetForElement(kButtonIdentifier).value_or(DataFormat::kInvalidOffsetValue) : NativeOffsetForElement(kButtonIdentifier)); *objectDescriptor = {.dwSize = sizeof(*objectDescriptor)}; FillObjectInstanceInfo<charMode>(controllerCapabilities, kButtonIdentifier, kButtonOffset, objectDescriptor.get()); switch (lpCallback(objectDescriptor.get(), pvRef)) { case DIENUM_CONTINUE: break; case DIENUM_STOP: LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); default: LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); } } } if (true == willEnumeratePov) { if (true == controllerCapabilities.hasPov) { const Controller::SElementIdentifier kPovIdentifier = {.type = Controller::EElementType::Pov}; const TOffset kPovOffset = ((true == IsApplicationDataFormatSet()) ? dataFormat->GetOffsetForElement(kPovIdentifier).value_or(DataFormat::kInvalidOffsetValue) : NativeOffsetForElement(kPovIdentifier)); *objectDescriptor = {.dwSize = sizeof(*objectDescriptor)}; FillObjectInstanceInfo<charMode>(controllerCapabilities, kPovIdentifier, kPovOffset, objectDescriptor.get()); switch (lpCallback(objectDescriptor.get(), pvRef)) { case DIENUM_CONTINUE: break; case DIENUM_STOP: LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); default: LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); } } } } LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::Escape(LPDIEFFESCAPE pesc) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::GetCapabilities(LPDIDEVCAPS lpDIDevCaps) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; if (nullptr == lpDIDevCaps) LOG_INVOCATION_AND_RETURN(E_POINTER, kMethodSeverity); switch (lpDIDevCaps->dwSize) { case (sizeof(DIDEVCAPS)): // Force feedback information, only present in the latest version of the structure. lpDIDevCaps->dwFFSamplePeriod = 0; lpDIDevCaps->dwFFMinTimeResolution = 0; lpDIDevCaps->dwFirmwareRevision = 0; lpDIDevCaps->dwHardwareRevision = 0; lpDIDevCaps->dwFFDriverVersion = 0; case (sizeof(DIDEVCAPS_DX3)): // Top-level controller information is common to all virtual controllers. lpDIDevCaps->dwFlags = DIDC_ATTACHED | DIDC_EMULATED | DIDC_POLLEDDEVICE | DIDC_POLLEDDATAFORMAT; lpDIDevCaps->dwDevType = DINPUT_DEVTYPE_XINPUT_GAMEPAD; // Information about controller layout comes from controller capabilities. lpDIDevCaps->dwAxes = controller->GetCapabilities().numAxes; lpDIDevCaps->dwButtons = controller->GetCapabilities().numButtons; lpDIDevCaps->dwPOVs = ((true == controller->GetCapabilities().hasPov) ? 1 : 0); break; default: LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); } LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::GetDeviceData(DWORD cbObjectData, LPDIDEVICEOBJECTDATA rgdod, LPDWORD pdwInOut, DWORD dwFlags) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::SuperDebug; static constexpr Message::ESeverity kMethodSeverityForError = Message::ESeverity::Info; // DIDEVICEOBJECTDATA and DIDEVICEOBJECTDATA_DX3 are defined identically for all DirectInput versions below 8. // There is therefore no need to differentiate, as the distinction between "dinput" and "dinput8" takes care of it. if ((false == IsApplicationDataFormatSet()) || (nullptr == pdwInOut) || (sizeof(DIDEVICEOBJECTDATA) != cbObjectData)) LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverityForError); switch (dwFlags) { case 0: case DIGDD_PEEK: break; default: LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverityForError); } if (false == controller->IsEventBufferEnabled()) LOG_INVOCATION_AND_RETURN(DIERR_NOTBUFFERED, kMethodSeverityForError); auto lock = controller->Lock(); const DWORD kNumEventsAffected = std::min(*pdwInOut, (DWORD)controller->GetEventBufferCount()); const bool kEventBufferOverflowed = controller->IsEventBufferOverflowed(); const bool kShouldPopEvents = (0 == (dwFlags & DIGDD_PEEK)); if (nullptr != rgdod) { for (DWORD i = 0; i < kNumEventsAffected; ++i) { const Controller::StateChangeEventBuffer::SEvent& event = controller->GetEventBufferEvent(i); ZeroMemory(&rgdod[i], sizeof(rgdod[i])); rgdod[i].dwOfs = dataFormat->GetOffsetForElement(event.data.element).value(); // A value should always be present. rgdod[i].dwTimeStamp = event.timestamp; rgdod[i].dwSequence = event.sequence; switch (event.data.element.type) { case Controller::EElementType::Axis: rgdod[i].dwData = (DWORD)DataFormat::DirectInputAxisValue(event.data.value.axis); break; case Controller::EElementType::Button: rgdod[i].dwData = (DWORD)DataFormat::DirectInputButtonValue(event.data.value.button); break; case Controller::EElementType::Pov: rgdod[i].dwData = (DWORD)DataFormat::DirectInputPovValue(event.data.value.povDirection); break; default: LOG_INVOCATION_AND_RETURN(DIERR_GENERIC, kMethodSeverityForError); // This should never happen. break; } } } if (true == kShouldPopEvents) controller->PopEventBufferOldestEvents(kNumEventsAffected); *pdwInOut = kNumEventsAffected; LOG_INVOCATION_AND_RETURN(((true == kEventBufferOverflowed) ? DI_BUFFEROVERFLOW : DI_OK), kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::GetDeviceInfo(DirectInputDeviceType<charMode>::DeviceInstanceType* pdidi) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; if (nullptr == pdidi) LOG_INVOCATION_AND_RETURN(E_POINTER, kMethodSeverity); switch (pdidi->dwSize) { case (sizeof(DirectInputDeviceType<charMode>::DeviceInstanceType)): case (sizeof(DirectInputDeviceType<charMode>::DeviceInstanceCompatType)): break; default: LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); } FillVirtualControllerInfo(*pdidi, controller->GetIdentifier()); LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::GetDeviceState(DWORD cbData, LPVOID lpvData) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::SuperDebug; static constexpr Message::ESeverity kMethodSeverityForError = Message::ESeverity::Info; if ((nullptr == lpvData) || (false == IsApplicationDataFormatSet()) || (cbData < dataFormat->GetPacketSizeBytes())) LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverityForError); bool writeDataPacketResult = false; do { auto lock = controller->Lock(); writeDataPacketResult = dataFormat->WriteDataPacket(lpvData, cbData, controller->GetStateRef()); } while (false); LOG_INVOCATION_AND_RETURN(((true == writeDataPacketResult) ? DI_OK : DIERR_INVALIDPARAM), kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::GetEffectInfo(DirectInputDeviceType<charMode>::EffectInfoType* pdei, REFGUID rguid) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::GetForceFeedbackState(LPDWORD pdwOut) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::GetObjectInfo(DirectInputDeviceType<charMode>::DeviceObjectInstanceType* pdidoi, DWORD dwObj, DWORD dwHow) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; if (nullptr == pdidoi) LOG_INVOCATION_AND_RETURN(E_POINTER, kMethodSeverity); switch (pdidoi->dwSize) { case (sizeof(DirectInputDeviceType<charMode>::DeviceObjectInstanceType)): case (sizeof(DirectInputDeviceType<charMode>::DeviceObjectInstanceCompatType)): break; default: LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); } const std::optional<Controller::SElementIdentifier> maybeElement = IdentifyElement(dwObj, dwHow); if (false == maybeElement.has_value()) LOG_INVOCATION_AND_RETURN(DIERR_OBJECTNOTFOUND, kMethodSeverity); const Controller::SElementIdentifier element = maybeElement.value(); if (Controller::EElementType::WholeController == element.type) LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); FillObjectInstanceInfo<charMode>(controller->GetCapabilities(), element, ((true == IsApplicationDataFormatSet()) ? dataFormat->GetOffsetForElement(element).value_or(DataFormat::kInvalidOffsetValue) : NativeOffsetForElement(element)), pdidoi); LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::GetProperty(REFGUID rguidProp, LPDIPROPHEADER pdiph) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; DumpPropertyRequest(rguidProp, pdiph, false); if (false == IsPropertyHeaderValid(rguidProp, pdiph)) LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp); const std::optional<Controller::SElementIdentifier> maybeElement = IdentifyElement(pdiph->dwObj, pdiph->dwHow); if (false == maybeElement.has_value()) LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_OBJECTNOTFOUND, kMethodSeverity, rguidProp); const Controller::SElementIdentifier element = maybeElement.value(); switch ((size_t)&rguidProp) { case ((size_t)&DIPROP_AXISMODE): if (Controller::EElementType::WholeController != element.type) LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp); ((LPDIPROPDWORD)pdiph)->dwData = DIPROPAXISMODE_ABS; LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DI_OK, kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_BUFFERSIZE): ((LPDIPROPDWORD)pdiph)->dwData = controller->GetEventBufferCapacity(); LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DI_OK, kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_DEADZONE): if (Controller::EElementType::Axis != element.type) LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp); ((LPDIPROPDWORD)pdiph)->dwData = controller->GetAxisDeadzone(element.axis); LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DI_OK, kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_FFGAIN): ((LPDIPROPDWORD)pdiph)->dwData = controller->GetForceFeedbackGain(); LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DI_OK, kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_GRANULARITY): switch (element.type) { case Controller::EElementType::Axis: case Controller::EElementType::WholeController: break; default: LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp); } ((LPDIPROPDWORD)pdiph)->dwData = 1; LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DI_OK, kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_JOYSTICKID): ((LPDIPROPDWORD)pdiph)->dwData = controller->GetIdentifier(); LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DI_OK, kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_LOGICALRANGE): case ((size_t)&DIPROP_PHYSICALRANGE): switch (element.type) { case Controller::EElementType::Axis: case Controller::EElementType::WholeController: break; default: LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp); } ((LPDIPROPRANGE)pdiph)->lMin = Controller::kAnalogValueMin; ((LPDIPROPRANGE)pdiph)->lMax = Controller::kAnalogValueMax; LOG_PROPERTY_INVOCATION_DIPROPRANGE_AND_RETURN(DI_OK, kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_RANGE): do { if (Controller::EElementType::Axis != element.type) LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp); const std::pair kRange = controller->GetAxisRange(element.axis); ((LPDIPROPRANGE)pdiph)->lMin = kRange.first; ((LPDIPROPRANGE)pdiph)->lMax = kRange.second; } while (false); LOG_PROPERTY_INVOCATION_DIPROPRANGE_AND_RETURN(DI_OK, kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_SATURATION): if (Controller::EElementType::Axis != element.type) LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp); ((LPDIPROPDWORD)pdiph)->dwData = controller->GetAxisSaturation(element.axis); LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DI_OK, kMethodSeverity, rguidProp, pdiph); default: LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity, rguidProp); } } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::Initialize(HINSTANCE hinst, DWORD dwVersion, REFGUID rguid) { // Not required for Xidi virtual controllers as they are implemented now. // However, this method is needed for creating IDirectInputDevice objects via COM. static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::Poll(void) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::SuperDebug; // DirectInput documentation requires that the application data format already be set before a device can be polled. if (false == IsApplicationDataFormatSet()) LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); if (true == controller->RefreshState()) SignalEventIfEnabled(stateChangeEventHandle); LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::RunControlPanel(HWND hwndOwner, DWORD dwFlags) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::SendDeviceData(DWORD cbObjectData, LPCDIDEVICEOBJECTDATA rgdod, LPDWORD pdwInOut, DWORD fl) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::SendForceFeedbackCommand(DWORD dwFlags) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::SetCooperativeLevel(HWND hwnd, DWORD dwFlags) { // Presently this is a no-op. static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::SetDataFormat(LPCDIDATAFORMAT lpdf) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; if (nullptr == lpdf) LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); // If this operation fails, then the current data format and event filter remain unaltered. std::unique_ptr<DataFormat> newDataFormat = DataFormat::CreateFromApplicationFormatSpec(*lpdf, controller->GetCapabilities()); if (nullptr == newDataFormat) LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); // Use the event filter to prevent the controller from buffering any events that correspond to elements with no offsets. auto lock = controller->Lock(); controller->EventFilterAddAllElements(); for (int i = 0; i < (int)Controller::EAxis::Count; ++i) { const Controller::SElementIdentifier kElement = {.type = Controller::EElementType::Axis, .axis = (Controller::EAxis)i}; if (false == newDataFormat->HasElement(kElement)) controller->EventFilterRemoveElement(kElement); } for (int i = 0; i < (int)Controller::EButton::Count; ++i) { const Controller::SElementIdentifier kElement = {.type = Controller::EElementType::Button, .button = (Controller::EButton)i}; if (false == newDataFormat->HasElement(kElement)) controller->EventFilterRemoveElement(kElement); } do { const Controller::SElementIdentifier kElement = {.type = Controller::EElementType::Pov}; if (false == newDataFormat->HasElement(kElement)) controller->EventFilterRemoveElement(kElement); } while (false); dataFormat = std::move(newDataFormat); LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::SetEventNotification(HANDLE hEvent) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; stateChangeEventHandle = hEvent; LOG_INVOCATION_AND_RETURN(DI_POLLEDDEVICE, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::SetProperty(REFGUID rguidProp, LPCDIPROPHEADER pdiph) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; DumpPropertyRequest(rguidProp, pdiph, true); if (false == IsPropertyHeaderValid(rguidProp, pdiph)) LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp); const std::optional<Controller::SElementIdentifier> maybeElement = IdentifyElement(pdiph->dwObj, pdiph->dwHow); if (false == maybeElement.has_value()) LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_OBJECTNOTFOUND, kMethodSeverity, rguidProp); const Controller::SElementIdentifier element = maybeElement.value(); switch ((size_t)&rguidProp) { case ((size_t)&DIPROP_AXISMODE): if (DIPROPAXISMODE_ABS == ((LPDIPROPDWORD)pdiph)->dwData) LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DI_PROPNOEFFECT, kMethodSeverity, rguidProp, pdiph); else LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_BUFFERSIZE): LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(((true == controller->SetEventBufferCapacity(((LPDIPROPDWORD)pdiph)->dwData)) ? DI_OK : DIERR_INVALIDPARAM), kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_DEADZONE): switch (element.type) { case Controller::EElementType::Axis: LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(((true == controller->SetAxisDeadzone(element.axis, ((LPDIPROPDWORD)pdiph)->dwData)) ? DI_OK : DIERR_INVALIDPARAM), kMethodSeverity, rguidProp, pdiph); case Controller::EElementType::WholeController: LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(((true == controller->SetAllAxisDeadzone(((LPDIPROPDWORD)pdiph)->dwData)) ? DI_OK : DIERR_INVALIDPARAM), kMethodSeverity, rguidProp, pdiph); default: LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp, pdiph); } case ((size_t)&DIPROP_FFGAIN): LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(((true == controller->SetForceFeedbackGain(((LPDIPROPDWORD)pdiph)->dwData)) ? DI_OK : DIERR_INVALIDPARAM), kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_RANGE): switch (element.type) { case Controller::EElementType::Axis: LOG_PROPERTY_INVOCATION_DIPROPRANGE_AND_RETURN(((true == controller->SetAxisRange(element.axis, ((LPDIPROPRANGE)pdiph)->lMin, ((LPDIPROPRANGE)pdiph)->lMax)) ? DI_OK : DIERR_INVALIDPARAM), kMethodSeverity, rguidProp, pdiph); case Controller::EElementType::WholeController: LOG_PROPERTY_INVOCATION_DIPROPRANGE_AND_RETURN(((true == controller->SetAllAxisRange(((LPDIPROPRANGE)pdiph)->lMin, ((LPDIPROPRANGE)pdiph)->lMax)) ? DI_OK : DIERR_INVALIDPARAM), kMethodSeverity, rguidProp, pdiph); default: LOG_PROPERTY_INVOCATION_DIPROPRANGE_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp, pdiph); } case ((size_t)&DIPROP_SATURATION): switch (element.type) { case Controller::EElementType::Axis: LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(((true == controller->SetAxisSaturation(element.axis, ((LPDIPROPDWORD)pdiph)->dwData)) ? DI_OK : DIERR_INVALIDPARAM), kMethodSeverity, rguidProp, pdiph); case Controller::EElementType::WholeController: LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(((true == controller->SetAllAxisSaturation(((LPDIPROPDWORD)pdiph)->dwData)) ? DI_OK : DIERR_INVALIDPARAM), kMethodSeverity, rguidProp, pdiph); default: LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp, pdiph); } default: LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity, rguidProp); } } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::Unacquire(void) { // Controller acquisition is a no-op for Xidi virtual controllers. static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::WriteEffectToFile(DirectInputDeviceType<charMode>::ConstStringType lptszFileName, DWORD dwEntries, LPDIFILEEFFECT rgDiFileEft, DWORD dwFlags) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } #if DIRECTINPUT_VERSION >= 0x0800 // -------- METHODS: IDirectInputDevice8 ONLY ------------------------------ // // See DirectInput documentation for more information. template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::BuildActionMap(DirectInputDeviceType<charMode>::ActionFormatType* lpdiaf, DirectInputDeviceType<charMode>::ConstStringType lpszUserName, DWORD dwFlags) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::GetImageInfo(DirectInputDeviceType<charMode>::DeviceImageInfoHeaderType* lpdiDevImageInfoHeader) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::SetActionMap(DirectInputDeviceType<charMode>::ActionFormatType* lpdiActionFormat, DirectInputDeviceType<charMode>::ConstStringType lptszUserName, DWORD dwFlags) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } #endif // -------- EXPLICIT TEMPLATE INSTANTIATION ---------------------------- // // Instantiates both the ASCII and Unicode versions of this class. template class VirtualDirectInputDevice<ECharMode::A>; template class VirtualDirectInputDevice<ECharMode::W>; }
47.354992
309
0.652555
hamzahamidi
04b8aa7de0b344b65e179eb0597ff8c745d53000
3,467
cpp
C++
Examples/Cpp/source/Outlook/SetRecurrenceEveryDay.cpp
kashifiqb/Aspose.Email-for-C
96684cb6ed9f4e321a00c74ca219440baaef8ba8
[ "MIT" ]
4
2019-12-01T16:19:12.000Z
2022-03-28T18:51:42.000Z
Examples/Cpp/source/Outlook/SetRecurrenceEveryDay.cpp
kashifiqb/Aspose.Email-for-C
96684cb6ed9f4e321a00c74ca219440baaef8ba8
[ "MIT" ]
1
2022-02-15T01:02:15.000Z
2022-02-15T01:02:15.000Z
Examples/Cpp/source/Outlook/SetRecurrenceEveryDay.cpp
kashifiqb/Aspose.Email-for-C
96684cb6ed9f4e321a00c74ca219440baaef8ba8
[ "MIT" ]
5
2017-09-27T14:43:20.000Z
2021-11-16T06:47:11.000Z
/* This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Email for .NET API reference when the project is build. Please check https://Docs.nuget.org/consume/nuget-faq for more information. If you do not wish to use NuGet, you can manually download Aspose.Email for .NET API from https://www.nuget.org/packages/Aspose.Email/, install it and then add its reference to this project. For any issues, questions or suggestions please feel free to contact us using https://forum.aspose.com/c/email */ #include <system/string.h> #include <system/shared_ptr.h> #include <system/object.h> #include <system/date_time.h> #include <Mapi/TaskSaveFormat.h> #include <Mapi/MapiTaskState.h> #include <Mapi/MapiTask.h> #include <Mapi/MapiCalendarRecurrencePatternType.h> #include <Mapi/MapiCalendarRecurrencePattern.h> #include <Mapi/MapiCalendarRecurrenceEndType.h> #include <Mapi/MapiCalendarDailyRecurrencePattern.h> #include <cstdint> #include <Calendar/Recurrences/DateCollection.h> #include <Calendar/Recurrences/CalendarRecurrence.h> #include "Examples.h" using namespace Aspose::Email; using namespace Aspose::Email::Mapi; using namespace Aspose::Email::Calendar::Recurrences; static uint32_t GetOccurrenceCount(System::DateTime start, System::DateTime endBy, System::String rrule) { System::SharedPtr<CalendarRecurrence> pattern = System::MakeObject<CalendarRecurrence>(System::String::Format(u"DTSTART:{0}\r\nRRULE:{1}", start.ToString(u"yyyyMMdd"), rrule)); System::SharedPtr<DateCollection> dates = pattern->GenerateOccurrences(start, endBy); return (uint32_t)dates->get_Count(); } void SetRecurrenceEveryDay() { System::String dataDir = GetDataDir_Outlook(); System::DateTime StartDate(2015, 7, 16); System::DateTime endByDate(2015, 8, 1); System::DateTime DueDate(2015, 7, 16); System::SharedPtr<MapiTask> task = System::MakeObject<MapiTask>(u"This is test task", u"Sample Body", StartDate, DueDate); task->set_State(Aspose::Email::Mapi::MapiTaskState::NotAssigned); // ExStart:SetRecurrenceEveryDay // Set the Daily recurrence auto record = [&]{ auto tmp_0 = System::MakeObject<MapiCalendarDailyRecurrencePattern>(); tmp_0->set_PatternType(Aspose::Email::Mapi::MapiCalendarRecurrencePatternType::Day); tmp_0->set_Period(1); tmp_0->set_EndType(Aspose::Email::Mapi::MapiCalendarRecurrenceEndType::EndAfterDate); tmp_0->set_OccurrenceCount(GetOccurrenceCount(StartDate, endByDate, u"FREQ=DAILY;INTERVAL=1")); tmp_0->set_EndDate(endByDate); return tmp_0; }(); // ExEnd:SetRecurrenceEveryDay task->set_Recurrence(record); task->Save(dataDir + u"SetRecurrenceEveryDay_out.msg", Aspose::Email::Mapi::TaskSaveFormat::Msg); // ExStart:SetRecurrenceEveryDayInterval // Set the Daily recurrence auto record1 = [&]{ auto tmp_1 = System::MakeObject<MapiCalendarDailyRecurrencePattern>(); tmp_1->set_PatternType(Aspose::Email::Mapi::MapiCalendarRecurrencePatternType::Day); tmp_1->set_Period(2); tmp_1->set_EndType(Aspose::Email::Mapi::MapiCalendarRecurrenceEndType::EndAfterDate); tmp_1->set_OccurrenceCount(GetOccurrenceCount(StartDate, endByDate, u"FREQ=DAILY;INTERVAL=2")); tmp_1->set_EndDate(endByDate); return tmp_1; }(); // ExEnd:SetRecurrenceEveryDayInterval task->set_Recurrence(record); task->Save(dataDir + u"SetRecurrenceEveryDayInterval_out.msg", Aspose::Email::Mapi::TaskSaveFormat::Msg); }
52.530303
433
0.758869
kashifiqb
04bc038e7a46f22a3c8533cca80fe11a4e90bb20
25,705
hpp
C++
Common_3/ThirdParty/OpenSource/entt/entity/snapshot.hpp
pixowl/The-Forge
0df6d608ed7ec556f17b91a749e2f19d75973dc9
[ "Apache-2.0" ]
2
2019-12-05T20:43:33.000Z
2020-12-01T02:57:44.000Z
Common_3/ThirdParty/OpenSource/entt/entity/snapshot.hpp
guillaumeblanc/The-Forge
0df6d608ed7ec556f17b91a749e2f19d75973dc9
[ "Apache-2.0" ]
null
null
null
Common_3/ThirdParty/OpenSource/entt/entity/snapshot.hpp
guillaumeblanc/The-Forge
0df6d608ed7ec556f17b91a749e2f19d75973dc9
[ "Apache-2.0" ]
2
2020-05-10T08:41:12.000Z
2020-05-24T18:58:47.000Z
#ifndef ENTT_ENTITY_SNAPSHOT_HPP #define ENTT_ENTITY_SNAPSHOT_HPP #include "../../TinySTL/array.h" #include <cstddef> #include <utility> #include <cassert> #include <iterator> #include <type_traits> #include "../../TinySTL/unordered_map.h" #include "../config/config.h" #include "entt_traits.hpp" #include "utility.hpp" namespace entt { /** * @brief Forward declaration of the registry class. */ template<typename> class Registry; /** * @brief Utility class to create snapshots from a registry. * * A _snapshot_ can be either a dump of the entire registry or a narrower * selection of components and tags of interest.<br/> * This type can be used in both cases if provided with a correctly configured * output archive. * * @tparam Entity A valid entity type (see entt_traits for more details). */ template<typename Entity> class Snapshot final { /*! @brief A registry is allowed to create snapshots. */ friend class Registry<Entity>; using follow_fn_type = Entity(const Registry<Entity> &, const Entity); Snapshot(const Registry<Entity> &registry, Entity seed, follow_fn_type *follow) ENTT_NOEXCEPT : registry{registry}, seed{seed}, follow{follow} {} template<typename Component, typename Archive, typename It> void get(Archive &archive, size_t sz, It first, It last) const { archive(static_cast<Entity>(sz)); while(first != last) { const auto entity = *(first++); if(registry.template has<Component>(entity)) { archive(entity, registry.template get<Component>(entity)); } } } template<typename... Component, typename Archive, typename It, size_t... Indexes> void component(Archive &archive, It first, It last, std::index_sequence<Indexes...>) const { tinystl::array<size_t, sizeof...(Indexes)> size{}; auto begin = first; while(begin != last) { const auto entity = *(begin++); using accumulator_type = size_t[]; accumulator_type accumulator = { (registry.template has<Component>(entity) ? ++size[Indexes] : size[Indexes])... }; (void)accumulator; } using accumulator_type = int[]; accumulator_type accumulator = { (get<Component>(archive, size[Indexes], first, last), 0)... }; (void)accumulator; } public: /*! @brief Copying a snapshot isn't allowed. */ Snapshot(const Snapshot &) = delete; /*! @brief Default move constructor. */ Snapshot(Snapshot &&) = default; /*! @brief Copying a snapshot isn't allowed. @return This snapshot. */ Snapshot & operator=(const Snapshot &) = delete; /*! @brief Default move assignment operator. @return This snapshot. */ Snapshot & operator=(Snapshot &&) = default; /** * @brief Puts aside all the entities that are still in use. * * Entities are serialized along with their versions. Destroyed entities are * not taken in consideration by this function. * * @tparam Archive Type of output archive. * @param archive A valid reference to an output archive. * @return An object of this type to continue creating the snapshot. */ template<typename Archive> const Snapshot & entities(Archive &archive) const { archive(static_cast<Entity>(registry.alive())); registry.each([&archive](const auto entity) { archive(entity); }); return *this; } /** * @brief Puts aside destroyed entities. * * Entities are serialized along with their versions. Entities that are * still in use are not taken in consideration by this function. * * @tparam Archive Type of output archive. * @param archive A valid reference to an output archive. * @return An object of this type to continue creating the snapshot. */ template<typename Archive> const Snapshot & destroyed(Archive &archive) const { auto size = registry.size() - registry.alive(); archive(static_cast<Entity>(size)); if(size) { auto curr = seed; archive(curr); for(--size; size; --size) { curr = follow(registry, curr); archive(curr); } } return *this; } /** * @brief Puts aside the given component. * * Each instance is serialized together with the entity to which it belongs. * Entities are serialized along with their versions. * * @tparam Component Type of component to serialize. * @tparam Archive Type of output archive. * @param archive A valid reference to an output archive. * @return An object of this type to continue creating the snapshot. */ template<typename Component, typename Archive> const Snapshot & component(Archive &archive) const { const auto sz = registry.template size<Component>(); const auto *entities = registry.template data<Component>(); archive(static_cast<Entity>(sz)); for(std::remove_const_t<decltype(sz)> i{}; i < sz; ++i) { const auto entity = entities[i]; archive(entity, registry.template get<Component>(entity)); }; return *this; } /** * @brief Puts aside the given components. * * Each instance is serialized together with the entity to which it belongs. * Entities are serialized along with their versions. * * @tparam Component Types of components to serialize. * @tparam Archive Type of output archive. * @param archive A valid reference to an output archive. * @return An object of this type to continue creating the snapshot. */ template<typename... Component, typename Archive> std::enable_if_t<(sizeof...(Component) > 1), const Snapshot &> component(Archive &archive) const { using accumulator_type = int[]; accumulator_type accumulator = { 0, (component<Component>(archive), 0)... }; (void)accumulator; return *this; } /** * @brief Puts aside the given components for the entities in a range. * * Each instance is serialized together with the entity to which it belongs. * Entities are serialized along with their versions. * * @tparam Component Types of components to serialize. * @tparam Archive Type of output archive. * @tparam It Type of input iterator. * @param archive A valid reference to an output archive. * @param first An iterator to the first element of the range to serialize. * @param last An iterator past the last element of the range to serialize. * @return An object of this type to continue creating the snapshot. */ template<typename... Component, typename Archive, typename It> const Snapshot & component(Archive &archive, It first, It last) const { component<Component...>(archive, first, last, std::make_index_sequence<sizeof...(Component)>{}); return *this; } /** * @brief Puts aside the given tag. * * Each instance is serialized together with the entity to which it belongs. * Entities are serialized along with their versions. * * @tparam Tag Type of tag to serialize. * @tparam Archive Type of output archive. * @param archive A valid reference to an output archive. * @return An object of this type to continue creating the snapshot. */ template<typename Tag, typename Archive> const Snapshot & tag(Archive &archive) const { const bool has = registry.template has<Tag>(); // numerical length is forced for tags to facilitate loading archive(has ? Entity(1): Entity{}); if(has) { archive(registry.template attachee<Tag>(), registry.template get<Tag>()); } return *this; } /** * @brief Puts aside the given tags. * * Each instance is serialized together with the entity to which it belongs. * Entities are serialized along with their versions. * * @tparam Tag Types of tags to serialize. * @tparam Archive Type of output archive. * @param archive A valid reference to an output archive. * @return An object of this type to continue creating the snapshot. */ template<typename... Tag, typename Archive> std::enable_if_t<(sizeof...(Tag) > 1), const Snapshot &> tag(Archive &archive) const { using accumulator_type = int[]; accumulator_type accumulator = { 0, (tag<Tag>(archive), 0)... }; (void)accumulator; return *this; } private: const Registry<Entity> &registry; const Entity seed; follow_fn_type *follow; }; /** * @brief Utility class to restore a snapshot as a whole. * * A snapshot loader requires that the destination registry be empty and loads * all the data at once while keeping intact the identifiers that the entities * originally had.<br/> * An example of use is the implementation of a save/restore utility. * * @tparam Entity A valid entity type (see entt_traits for more details). */ template<typename Entity> class SnapshotLoader final { /*! @brief A registry is allowed to create snapshot loaders. */ friend class Registry<Entity>; using assure_fn_type = void(Registry<Entity> &, const Entity, const bool); SnapshotLoader(Registry<Entity> &registry, assure_fn_type *assure_fn) ENTT_NOEXCEPT : registry{registry}, assure_fn{assure_fn} { // restore a snapshot as a whole requires a clean registry assert(!registry.capacity()); } template<typename Archive> void assure(Archive &archive, bool destroyed) const { Entity length{}; archive(length); while(length--) { Entity entity{}; archive(entity); assure_fn(registry, entity, destroyed); } } template<typename Type, typename Archive, typename... Args> void assign(Archive &archive, Args... args) const { Entity length{}; archive(length); while(length--) { Entity entity{}; Type instance{}; archive(entity, instance); static constexpr auto destroyed = false; assure_fn(registry, entity, destroyed); registry.template assign<Type>(args..., entity, static_cast<const Type &>(instance)); } } public: /*! @brief Copying a snapshot loader isn't allowed. */ SnapshotLoader(const SnapshotLoader &) = delete; /*! @brief Default move constructor. */ SnapshotLoader(SnapshotLoader &&) = default; /*! @brief Copying a snapshot loader isn't allowed. @return This loader. */ SnapshotLoader & operator=(const SnapshotLoader &) = delete; /*! @brief Default move assignment operator. @return This loader. */ SnapshotLoader & operator=(SnapshotLoader &&) = default; /** * @brief Restores entities that were in use during serialization. * * This function restores the entities that were in use during serialization * and gives them the versions they originally had. * * @tparam Archive Type of input archive. * @param archive A valid reference to an input archive. * @return A valid loader to continue restoring data. */ template<typename Archive> const SnapshotLoader & entities(Archive &archive) const { static constexpr auto destroyed = false; assure(archive, destroyed); return *this; } /** * @brief Restores entities that were destroyed during serialization. * * This function restores the entities that were destroyed during * serialization and gives them the versions they originally had. * * @tparam Archive Type of input archive. * @param archive A valid reference to an input archive. * @return A valid loader to continue restoring data. */ template<typename Archive> const SnapshotLoader & destroyed(Archive &archive) const { static constexpr auto destroyed = true; assure(archive, destroyed); return *this; } /** * @brief Restores components and assigns them to the right entities. * * The template parameter list must be exactly the same used during * serialization. In the event that the entity to which the component is * assigned doesn't exist yet, the loader will take care to create it with * the version it originally had. * * @tparam Component Types of components to restore. * @tparam Archive Type of input archive. * @param archive A valid reference to an input archive. * @return A valid loader to continue restoring data. */ template<typename... Component, typename Archive> const SnapshotLoader & component(Archive &archive) const { using accumulator_type = int[]; accumulator_type accumulator = { 0, (assign<Component>(archive), 0)... }; (void)accumulator; return *this; } /** * @brief Restores tags and assigns them to the right entities. * * The template parameter list must be exactly the same used during * serialization. In the event that the entity to which the tag is assigned * doesn't exist yet, the loader will take care to create it with the * version it originally had. * * @tparam Tag Types of tags to restore. * @tparam Archive Type of input archive. * @param archive A valid reference to an input archive. * @return A valid loader to continue restoring data. */ template<typename... Tag, typename Archive> const SnapshotLoader & tag(Archive &archive) const { using accumulator_type = int[]; accumulator_type accumulator = { 0, (assign<Tag>(archive, tag_t{}), 0)... }; (void)accumulator; return *this; } /** * @brief Destroys those entities that have neither components nor tags. * * In case all the entities were serialized but only part of the components * and tags was saved, it could happen that some of the entities have * neither components nor tags once restored.<br/> * This functions helps to identify and destroy those entities. * * @return A valid loader to continue restoring data. */ const SnapshotLoader & orphans() const { registry.orphans([this](const auto entity) { registry.destroy(entity); }); return *this; } private: Registry<Entity> &registry; assure_fn_type *assure_fn; }; /** * @brief Utility class for _continuous loading_. * * A _continuous loader_ is designed to load data from a source registry to a * (possibly) non-empty destination. The loader can accomodate in a registry * more than one snapshot in a sort of _continuous loading_ that updates the * destination one step at a time.<br/> * Identifiers that entities originally had are not transferred to the target. * Instead, the loader maps remote identifiers to local ones while restoring a * snapshot.<br/> * An example of use is the implementation of a client-server applications with * the requirement of transferring somehow parts of the representation side to * side. * * @tparam Entity A valid entity type (see entt_traits for more details). */ template<typename Entity> class ContinuousLoader final { using traits_type = entt_traits<Entity>; void destroy(Entity entity) { const auto it = remloc.find(entity); if(it == remloc.cend()) { const auto local = registry.create(); remloc.emplace(entity, tinystl::make_pair(local, true)); registry.destroy(local); } } void restore(Entity entity) { const auto it = remloc.find(entity); if(it == remloc.cend()) { const auto local = registry.create(); remloc.emplace(entity, tinystl::make_pair(local, true)); } else { remloc[entity].first = registry.valid(remloc[entity].first) ? remloc[entity].first : registry.create(); // set the dirty flag remloc[entity].second = true; } } template<typename Type, typename Member> std::enable_if_t<std::is_same<Member, Entity>::value> update(Type &instance, Member Type:: *member) { instance.*member = map(instance.*member); } template<typename Type, typename Member> std::enable_if_t<std::is_same<typename std::iterator_traits<typename Member::iterator>::value_type, Entity>::value> update(Type &instance, Member Type:: *member) { for(auto &entity: instance.*member) { entity = map(entity); } } template<typename Other, typename Type, typename Member> std::enable_if_t<!std::is_same<Other, Type>::value> update(Other &, Member Type:: *) {} template<typename Archive> void assure(Archive &archive, void(ContinuousLoader:: *member)(Entity)) { Entity length{}; archive(length); while(length--) { Entity entity{}; archive(entity); (this->*member)(entity); } } template<typename Component> void reset() { for(auto &&ref: remloc) { const auto local = ref.second.first; if(registry.valid(local)) { registry.template reset<Component>(local); } } } template<typename Other, typename Archive, typename Func, typename... Type, typename... Member> void assign(Archive &archive, Func func, Member Type:: *... member) { Entity length{}; archive(length); while(length--) { Entity entity{}; Other instance{}; archive(entity, instance); restore(entity); using accumulator_type = int[]; accumulator_type accumulator = { 0, (update(instance, member), 0)... }; (void)accumulator; func(map(entity), instance); } } public: /*! @brief Underlying entity identifier. */ using entity_type = Entity; /** * @brief Constructs a loader that is bound to a given registry. * @param registry A valid reference to a registry. */ ContinuousLoader(Registry<entity_type> &registry) ENTT_NOEXCEPT : registry{registry} {} /*! @brief Copying a snapshot loader isn't allowed. */ ContinuousLoader(const ContinuousLoader &) = delete; /*! @brief Default move constructor. */ ContinuousLoader(ContinuousLoader &&) = default; /*! @brief Copying a snapshot loader isn't allowed. @return This loader. */ ContinuousLoader & operator=(const ContinuousLoader &) = delete; /*! @brief Default move assignment operator. @return This loader. */ ContinuousLoader & operator=(ContinuousLoader &&) = default; /** * @brief Restores entities that were in use during serialization. * * This function restores the entities that were in use during serialization * and creates local counterparts for them if required. * * @tparam Archive Type of input archive. * @param archive A valid reference to an input archive. * @return A non-const reference to this loader. */ template<typename Archive> ContinuousLoader & entities(Archive &archive) { assure(archive, &ContinuousLoader::restore); return *this; } /** * @brief Restores entities that were destroyed during serialization. * * This function restores the entities that were destroyed during * serialization and creates local counterparts for them if required. * * @tparam Archive Type of input archive. * @param archive A valid reference to an input archive. * @return A non-const reference to this loader. */ template<typename Archive> ContinuousLoader & destroyed(Archive &archive) { assure(archive, &ContinuousLoader::destroy); return *this; } /** * @brief Restores components and assigns them to the right entities. * * The template parameter list must be exactly the same used during * serialization. In the event that the entity to which the component is * assigned doesn't exist yet, the loader will take care to create a local * counterpart for it.<br/> * Members can be either data members of type entity_type or containers of * entities. In both cases, the loader will visit them and update the * entities by replacing each one with its local counterpart. * * @tparam Component Type of component to restore. * @tparam Archive Type of input archive. * @tparam Type Types of components to update with local counterparts. * @tparam Member Types of members to update with their local counterparts. * @param archive A valid reference to an input archive. * @param member Members to update with their local counterparts. * @return A non-const reference to this loader. */ template<typename... Component, typename Archive, typename... Type, typename... Member> ContinuousLoader & component(Archive &archive, Member Type:: *... member) { auto apply = [this](const auto entity, const auto &component) { registry.template accommodate<std::decay_t<decltype(component)>>(entity, component); }; using accumulator_type = int[]; accumulator_type accumulator = { 0, (reset<Component>(), assign<Component>(archive, apply, member...), 0)... }; (void)accumulator; return *this; } /** * @brief Restores tags and assigns them to the right entities. * * The template parameter list must be exactly the same used during * serialization. In the event that the entity to which the tag is assigned * doesn't exist yet, the loader will take care to create a local * counterpart for it.<br/> * Members can be either data members of type entity_type or containers of * entities. In both cases, the loader will visit them and update the * entities by replacing each one with its local counterpart. * * @tparam Tag Type of tag to restore. * @tparam Archive Type of input archive. * @tparam Type Types of components to update with local counterparts. * @tparam Member Types of members to update with their local counterparts. * @param archive A valid reference to an input archive. * @param member Members to update with their local counterparts. * @return A non-const reference to this loader. */ template<typename... Tag, typename Archive, typename... Type, typename... Member> ContinuousLoader & tag(Archive &archive, Member Type:: *... member) { auto apply = [this](const auto entity, const auto &tag) { registry.template assign<std::decay_t<decltype(tag)>>(tag_t{}, entity, tag); }; using accumulator_type = int[]; accumulator_type accumulator = { 0, (registry.template remove<Tag>(), assign<Tag>(archive, apply, member...), 0)... }; (void)accumulator; return *this; } /** * @brief Helps to purge entities that no longer have a conterpart. * * Users should invoke this member function after restoring each snapshot, * unless they know exactly what they are doing. * * @return A non-const reference to this loader. */ ContinuousLoader & shrink() { auto it = remloc.begin(); while(it != remloc.cend()) { const auto local = it->second.first; bool &dirty = it->second.second; if(dirty) { dirty = false; ++it; } else { if(registry.valid(local)) { registry.destroy(local); } it = remloc.erase(it); } } return *this; } /** * @brief Destroys those entities that have neither components nor tags. * * In case all the entities were serialized but only part of the components * and tags was saved, it could happen that some of the entities have * neither components nor tags once restored.<br/> * This functions helps to identify and destroy those entities. * * @return A non-const reference to this loader. */ ContinuousLoader & orphans() { registry.orphans([this](const auto entity) { registry.destroy(entity); }); return *this; } /** * @brief Tests if a loader knows about a given entity. * @param entity An entity identifier. * @return True if `entity` is managed by the loader, false otherwise. */ bool has(entity_type entity) const ENTT_NOEXCEPT { return (remloc.find(entity) != remloc.cend()); } /** * @brief Returns the identifier to which an entity refers. * * @warning * Attempting to use an entity that isn't managed by the loader results in * undefined behavior.<br/> * An assertion will abort the execution at runtime in debug mode if the * loader doesn't knows about the entity. * * @param entity An entity identifier. * @return The identifier to which `entity` refers in the target registry. */ entity_type map(entity_type entity) const ENTT_NOEXCEPT { assert(has(entity)); return remloc.find(entity)->second.first; } private: tinystl::unordered_map<Entity, tinystl::pair<Entity, bool>> remloc; Registry<Entity> &registry; }; } #endif // ENTT_ENTITY_SNAPSHOT_HPP
35.455172
127
0.642482
pixowl
04bc157cb5e67d296fa4450f120cb9db5237b610
4,379
cpp
C++
src/shogun/kernel/ShiftInvariantKernel.cpp
cloner1984/shogun
901c04b2c6550918acf0594ef8afeb5dcd840a7d
[ "BSD-3-Clause" ]
2
2021-08-12T18:11:06.000Z
2021-11-17T10:56:49.000Z
src/shogun/kernel/ShiftInvariantKernel.cpp
cloner1984/shogun
901c04b2c6550918acf0594ef8afeb5dcd840a7d
[ "BSD-3-Clause" ]
null
null
null
src/shogun/kernel/ShiftInvariantKernel.cpp
cloner1984/shogun
901c04b2c6550918acf0594ef8afeb5dcd840a7d
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) The Shogun Machine Learning Toolbox * Written (w) 2016 Soumyajit De * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the Shogun Development Team. */ #include <shogun/lib/common.h> #include <shogun/kernel/ShiftInvariantKernel.h> #include <shogun/distance/CustomDistance.h> using namespace shogun; CShiftInvariantKernel::CShiftInvariantKernel() : CKernel(0) { register_params(); } CShiftInvariantKernel::CShiftInvariantKernel(CFeatures *l, CFeatures *r) : CKernel(l, r, 0) { register_params(); init(l, r); } CShiftInvariantKernel::~CShiftInvariantKernel() { cleanup(); SG_UNREF(m_distance); } bool CShiftInvariantKernel::init(CFeatures* l, CFeatures* r) { REQUIRE(m_distance, "The distance instance cannot be NULL!\n"); CKernel::init(l,r); m_distance->init(l, r); return init_normalizer(); } void CShiftInvariantKernel::precompute_distance() { REQUIRE(m_distance, "The distance instance cannot be NULL!\n"); REQUIRE(m_distance->init(lhs, rhs), "Could not initialize the distance instance!\n"); SGMatrix<float32_t> dist_mat=m_distance->get_distance_matrix<float32_t>(); if (m_precomputed_distance==NULL) { m_precomputed_distance=new CCustomDistance(); SG_REF(m_precomputed_distance); } if (lhs==rhs) m_precomputed_distance->set_triangle_distance_matrix_from_full(dist_mat.data(), dist_mat.num_rows, dist_mat.num_cols); else m_precomputed_distance->set_full_distance_matrix_from_full(dist_mat.data(), dist_mat.num_rows, dist_mat.num_cols); } void CShiftInvariantKernel::cleanup() { SG_UNREF(m_precomputed_distance); m_precomputed_distance=NULL; CKernel::cleanup(); m_distance->cleanup(); } EDistanceType CShiftInvariantKernel::get_distance_type() const { REQUIRE(m_distance, "The distance instance cannot be NULL!\n"); return m_distance->get_distance_type(); } float64_t CShiftInvariantKernel::distance(int32_t a, int32_t b) const { REQUIRE(m_distance, "The distance instance cannot be NULL!\n"); if (m_precomputed_distance!=NULL) return m_precomputed_distance->distance(a, b); else return m_distance->distance(a, b); } void CShiftInvariantKernel::register_params() { SG_ADD((CSGObject**) &m_distance, "m_distance", "Distance to be used."); SG_ADD((CSGObject**) &m_precomputed_distance, "m_precomputed_distance", "Precomputed istance to be used."); m_distance=NULL; m_precomputed_distance=NULL; } void CShiftInvariantKernel::set_precomputed_distance(CCustomDistance* precomputed_distance) { REQUIRE(precomputed_distance, "The precomputed distance instance cannot be NULL!\n"); SG_REF(precomputed_distance); SG_UNREF(m_precomputed_distance); m_precomputed_distance=precomputed_distance; } CCustomDistance* CShiftInvariantKernel::get_precomputed_distance() const { REQUIRE(m_precomputed_distance, "The precomputed distance instance cannot be NULL!\n"); SG_REF(m_precomputed_distance); return m_precomputed_distance; }
34.753968
120
0.781914
cloner1984
04bc831052d4cdf3976f4c818e371795872dbb1e
21,081
hpp
C++
libs/pika/executors/include/pika/executors/dataflow.hpp
pika-org/pika
c80f542b2432a7f108fcfba31a5fe5073ad2b3e1
[ "BSL-1.0" ]
13
2022-01-17T12:01:48.000Z
2022-03-16T10:03:14.000Z
libs/pika/executors/include/pika/executors/dataflow.hpp
pika-org/pika
c80f542b2432a7f108fcfba31a5fe5073ad2b3e1
[ "BSL-1.0" ]
163
2022-01-17T17:36:45.000Z
2022-03-31T17:42:57.000Z
libs/pika/executors/include/pika/executors/dataflow.hpp
pika-org/pika
c80f542b2432a7f108fcfba31a5fe5073ad2b3e1
[ "BSL-1.0" ]
4
2022-01-19T08:44:22.000Z
2022-01-31T23:16:21.000Z
// Copyright (c) 2007-2021 Hartmut Kaiser // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #pragma once #include <pika/config.hpp> #include <pika/allocator_support/internal_allocator.hpp> #include <pika/async_base/dataflow.hpp> #include <pika/async_base/launch_policy.hpp> #include <pika/async_base/traits/is_launch_policy.hpp> #include <pika/coroutines/detail/get_stack_pointer.hpp> #include <pika/datastructures/tuple.hpp> #include <pika/errors/try_catch_exception_ptr.hpp> #include <pika/execution/executors/execution.hpp> #include <pika/execution_base/traits/is_executor.hpp> #include <pika/executors/parallel_executor.hpp> #include <pika/functional/deferred_call.hpp> #include <pika/functional/invoke_fused.hpp> #include <pika/functional/traits/get_function_annotation.hpp> #include <pika/functional/traits/is_action.hpp> #include <pika/futures/detail/future_transforms.hpp> #include <pika/futures/future.hpp> #include <pika/futures/traits/acquire_future.hpp> #include <pika/futures/traits/future_access.hpp> #include <pika/futures/traits/is_future.hpp> #include <pika/modules/memory.hpp> #include <pika/pack_traversal/pack_traversal_async.hpp> #include <pika/threading_base/annotated_function.hpp> #include <pika/threading_base/thread_num_tss.hpp> #include <cstddef> #include <exception> #include <functional> #include <memory> #include <type_traits> #include <utility> /////////////////////////////////////////////////////////////////////////////// // forward declare the type we will get function annotations from namespace pika::detail { template <typename Frame> struct dataflow_finalization; } // namespace pika::lcos::detail namespace pika { namespace traits { #if defined(PIKA_HAVE_THREAD_DESCRIPTION) /////////////////////////////////////////////////////////////////////////// // traits specialization to get annotation from dataflow_finalization template <typename Frame> struct get_function_annotation<pika::detail::dataflow_finalization<Frame>> { using function_type = typename Frame::function_type; // static constexpr char const* call( pika::detail::dataflow_finalization<Frame> const& f) noexcept { char const* annotation = pika::traits::get_function_annotation< typename std::decay<function_type>::type>::call(f.this_->func_); return annotation; } }; #endif }} // namespace pika::traits /////////////////////////////////////////////////////////////////////////////// namespace pika::detail { template <typename Frame> struct dataflow_finalization { // explicit dataflow_finalization(Frame* df) : this_(df) { } using is_void = typename Frame::is_void; // template <typename Futures> void operator()(Futures&& futures) const { return this_->execute(is_void{}, PIKA_FORWARD(Futures, futures)); } // keep the dataflow frame alive with this pointer reference pika::intrusive_ptr<Frame> this_; }; template <typename F, typename Args> struct dataflow_not_callable { static auto error(F f, Args args) { pika::util::invoke_fused(PIKA_MOVE(f), PIKA_MOVE(args)); } using type = decltype(error(std::declval<F>(), std::declval<Args>())); }; /////////////////////////////////////////////////////////////////////// template <bool IsAction, typename Policy, typename F, typename Args, typename Enable = void> struct dataflow_return_impl { using type = typename dataflow_not_callable<F, Args>::type; }; template <typename Policy, typename F, typename Args> struct dataflow_return_impl< /*IsAction=*/false, Policy, F, Args, typename std::enable_if< pika::detail::is_launch_policy<Policy>::value>::type> { using type = pika::future< typename util::detail::invoke_fused_result<F, Args>::type>; }; template <typename Executor, typename F, typename Args> struct dataflow_return_impl_executor; template <typename Executor, typename F, typename... Ts> struct dataflow_return_impl_executor<Executor, F, pika::tuple<Ts...>> { using type = decltype(pika::parallel::execution::async_execute( std::declval<Executor&&>(), std::declval<F>(), std::declval<Ts>()...)); }; template <typename Policy, typename F, typename Args> struct dataflow_return_impl< /*IsAction=*/false, Policy, F, Args, typename std::enable_if<traits::is_one_way_executor<Policy>::value || traits::is_two_way_executor<Policy>::value>::type> : dataflow_return_impl_executor<Policy, F, Args> { }; template <typename Policy, typename F, typename Args> struct dataflow_return : detail::dataflow_return_impl<traits::is_action<F>::value, Policy, F, Args> { }; template <typename Executor, typename Frame, typename Func, typename Futures, typename Enable = void> struct has_dataflow_finalize : std::false_type { }; template <typename Executor, typename Frame, typename Func, typename Futures> struct has_dataflow_finalize<Executor, Frame, Func, Futures, std::void_t<decltype(std::declval<Executor>().dataflow_finalize( std::declval<Frame>(), std::declval<Func>(), std::declval<Futures>()))>> : std::true_type { }; /////////////////////////////////////////////////////////////////////////// template <typename Policy, typename Func, typename Futures> struct dataflow_frame //-V690 : pika::lcos::detail::future_data<typename pika::traits::future_traits< typename detail::dataflow_return<Policy, Func, Futures>::type>::type> { using type = typename detail::dataflow_return<Policy, Func, Futures>::type; using result_type = typename pika::traits::future_traits<type>::type; using base_type = pika::lcos::detail::future_data<result_type>; using is_void = std::is_void<result_type>; using function_type = Func; using dataflow_type = dataflow_frame<Policy, Func, Futures>; friend struct dataflow_finalization<dataflow_type>; friend struct traits::get_function_annotation< dataflow_finalization<dataflow_type>>; private: // workaround gcc regression wrongly instantiating constructors dataflow_frame(); dataflow_frame(dataflow_frame const&); public: using init_no_addref = typename base_type::init_no_addref; /// A struct to construct the dataflow_frame in-place struct construction_data { Policy policy_; Func func_; }; /// Construct the dataflow_frame from the given policy /// and callable object. static construction_data construct_from(Policy policy, Func func) { return construction_data{PIKA_MOVE(policy), PIKA_MOVE(func)}; } explicit dataflow_frame(construction_data data) : base_type(init_no_addref{}) , policy_(PIKA_MOVE(data.policy_)) , func_(PIKA_MOVE(data.func_)) { } private: /////////////////////////////////////////////////////////////////////// /// Passes the futures into the evaluation function and /// sets the result future. template <typename Futures_> PIKA_FORCEINLINE void execute(std::false_type, Futures_&& futures) { pika::detail::try_catch_exception_ptr( [&]() { this->set_data(util::invoke_fused( PIKA_MOVE(func_), PIKA_FORWARD(Futures_, futures))); }, [&](std::exception_ptr ep) { this->set_exception(PIKA_MOVE(ep)); }); } /// Passes the futures into the evaluation function and /// sets the result future. template <typename Futures_> PIKA_FORCEINLINE void execute(std::true_type, Futures_&& futures) { pika::detail::try_catch_exception_ptr( [&]() { util::invoke_fused( PIKA_MOVE(func_), PIKA_FORWARD(Futures_, futures)); this->set_data(util::unused_type()); }, [&](std::exception_ptr ep) { this->set_exception(PIKA_MOVE(ep)); }); } /////////////////////////////////////////////////////////////////////// template <typename Futures_> void finalize(pika::detail::async_policy policy, Futures_&& futures) { detail::dataflow_finalization<dataflow_type> this_f_(this); pika::execution::parallel_policy_executor<launch::async_policy> exec{policy}; exec.post(PIKA_MOVE(this_f_), PIKA_FORWARD(Futures_, futures)); } template <typename Futures_> void finalize(pika::detail::fork_policy policy, Futures_&& futures) { detail::dataflow_finalization<dataflow_type> this_f_(this); pika::execution::parallel_policy_executor<launch::fork_policy> exec{ policy}; exec.post(PIKA_MOVE(this_f_), PIKA_FORWARD(Futures_, futures)); } template <typename Futures_> PIKA_FORCEINLINE void finalize( pika::detail::sync_policy, Futures_&& futures) { // We need to run the completion on a new thread if we are on a // non pika thread. bool recurse_asynchronously = pika::threads::get_self_ptr() == nullptr; #if defined(PIKA_HAVE_THREADS_GET_STACK_POINTER) recurse_asynchronously = !this_thread::has_sufficient_stack_space(); #else struct handle_continuation_recursion_count { handle_continuation_recursion_count() : count_(threads::get_continuation_recursion_count()) { ++count_; } ~handle_continuation_recursion_count() { --count_; } std::size_t& count_; } cnt; recurse_asynchronously = recurse_asynchronously || cnt.count_ > PIKA_CONTINUATION_MAX_RECURSION_DEPTH; #endif if (!recurse_asynchronously) { pika::scoped_annotation annotate(func_); execute(is_void{}, PIKA_FORWARD(Futures_, futures)); } else { finalize(pika::launch::async, PIKA_FORWARD(Futures_, futures)); } } template <typename Futures_> void finalize(launch policy, Futures_&& futures) { if (policy == launch::sync) { finalize(launch::sync, PIKA_FORWARD(Futures_, futures)); } else if (policy == launch::fork) { finalize(launch::fork, PIKA_FORWARD(Futures_, futures)); } else { finalize(launch::async, PIKA_FORWARD(Futures_, futures)); } } // The overload for pika::dataflow taking an executor simply forwards // to the corresponding executor customization point. template <typename Executor, typename Futures_> PIKA_FORCEINLINE typename std::enable_if< (traits::is_one_way_executor<Executor>::value || traits::is_two_way_executor<Executor>::value) && !has_dataflow_finalize<Executor, dataflow_frame, Func, Futures_>::value>::type finalize(Executor&& exec, Futures_&& futures) { detail::dataflow_finalization<dataflow_type> this_f_(this); pika::parallel::execution::post(PIKA_FORWARD(Executor, exec), PIKA_MOVE(this_f_), PIKA_FORWARD(Futures_, futures)); } template <typename Executor, typename Futures_> PIKA_FORCEINLINE typename std::enable_if< (traits::is_one_way_executor<Executor>::value || traits::is_two_way_executor<Executor>::value) && has_dataflow_finalize<Executor, dataflow_frame, Func, Futures_>::value>::type finalize(Executor&& exec, Futures_&& futures) { #if defined(PIKA_CUDA_VERSION) std::forward<Executor>(exec) #else PIKA_FORWARD(Executor, exec) #endif .dataflow_finalize( this, PIKA_MOVE(func_), PIKA_FORWARD(Futures_, futures)); } public: /// Check whether the current future is ready template <typename T> auto operator()(util::async_traverse_visit_tag, T&& current) -> decltype(async_visit_future(PIKA_FORWARD(T, current))) { return async_visit_future(PIKA_FORWARD(T, current)); } /// Detach the current execution context and continue when the /// current future was set to be ready. template <typename T, typename N> auto operator()(util::async_traverse_detach_tag, T&& current, N&& next) -> decltype(async_detach_future( PIKA_FORWARD(T, current), PIKA_FORWARD(N, next))) { return async_detach_future( PIKA_FORWARD(T, current), PIKA_FORWARD(N, next)); } /// Finish the dataflow when the traversal has finished template <typename Futures_> PIKA_FORCEINLINE void operator()( util::async_traverse_complete_tag, Futures_&& futures) { finalize(policy_, PIKA_FORWARD(Futures_, futures)); } private: Policy policy_; Func func_; }; /////////////////////////////////////////////////////////////////////////// template <typename Policy, typename Func, typename... Ts, typename Frame = dataflow_frame<typename std::decay<Policy>::type, typename std::decay<Func>::type, pika::tuple<typename std::decay<Ts>::type...>>> typename Frame::type create_dataflow( Policy&& policy, Func&& func, Ts&&... ts) { // Create the data which is used to construct the dataflow_frame auto data = Frame::construct_from( PIKA_FORWARD(Policy, policy), PIKA_FORWARD(Func, func)); // Construct the dataflow_frame and traverse // the arguments asynchronously pika::intrusive_ptr<Frame> p = util::traverse_pack_async( util::async_traverse_in_place_tag<Frame>{}, PIKA_MOVE(data), PIKA_FORWARD(Ts, ts)...); using traits::future_access; return future_access<typename Frame::type>::create(PIKA_MOVE(p)); } /////////////////////////////////////////////////////////////////////////// template <typename Allocator, typename Policy, typename Func, typename... Ts, typename Frame = dataflow_frame<typename std::decay<Policy>::type, typename std::decay<Func>::type, pika::tuple<typename std::decay<Ts>::type...>>> typename Frame::type create_dataflow_alloc( Allocator const& alloc, Policy&& policy, Func&& func, Ts&&... ts) { // Create the data which is used to construct the dataflow_frame auto data = Frame::construct_from( PIKA_FORWARD(Policy, policy), PIKA_FORWARD(Func, func)); // Construct the dataflow_frame and traverse // the arguments asynchronously pika::intrusive_ptr<Frame> p = util::traverse_pack_async_allocator( alloc, util::async_traverse_in_place_tag<Frame>{}, PIKA_MOVE(data), PIKA_FORWARD(Ts, ts)...); using traits::future_access; return future_access<typename Frame::type>::create(PIKA_MOVE(p)); } /////////////////////////////////////////////////////////////////////////// template <bool IsAction, typename Policy, typename Enable = void> struct dataflow_dispatch_impl; // launch template <typename Policy> struct dataflow_dispatch_impl<false, Policy, typename std::enable_if< pika::detail::is_launch_policy<Policy>::value>::type> { template <typename Allocator, typename Policy_, typename F, typename... Ts> PIKA_FORCEINLINE static decltype(auto) call( Allocator const& alloc, Policy_&& policy, F&& f, Ts&&... ts) { return detail::create_dataflow_alloc(alloc, PIKA_FORWARD(Policy_, policy), PIKA_FORWARD(F, f), traits::acquire_future_disp()(PIKA_FORWARD(Ts, ts))...); } }; template <typename Policy> struct dataflow_dispatch<Policy, typename std::enable_if< pika::detail::is_launch_policy<Policy>::value>::type> { template <typename Allocator, typename F, typename... Ts> PIKA_FORCEINLINE static auto call( Allocator const& alloc, F&& f, Ts&&... ts) -> decltype(dataflow_dispatch_impl<false, Policy>::call( alloc, PIKA_FORWARD(F, f), PIKA_FORWARD(Ts, ts)...)) { return dataflow_dispatch_impl<false, Policy>::call( alloc, PIKA_FORWARD(F, f), PIKA_FORWARD(Ts, ts)...); } template <typename Allocator, typename P, typename F, typename Id, typename... Ts> PIKA_FORCEINLINE static auto call(Allocator const& alloc, P&& p, F&& f, typename std::enable_if< traits::is_action<typename std::decay<F>::type>::value, Id>::type const& id, Ts&&... ts) -> decltype(dataflow_dispatch_impl< traits::is_action<typename std::decay<F>::type>::value, Policy>::call(alloc, PIKA_FORWARD(P, p), PIKA_FORWARD(F, f), id, PIKA_FORWARD(Ts, ts)...)) { return dataflow_dispatch_impl< traits::is_action<typename std::decay<F>::type>::value, Policy>::call(alloc, PIKA_FORWARD(P, p), PIKA_FORWARD(F, f), id, PIKA_FORWARD(Ts, ts)...); } }; // executors template <typename Executor> struct dataflow_dispatch<Executor, typename std::enable_if<traits::is_one_way_executor<Executor>::value || traits::is_two_way_executor<Executor>::value>::type> { template <typename Allocator, typename Executor_, typename F, typename... Ts> PIKA_FORCEINLINE static decltype(auto) call( Allocator const& alloc, Executor_&& exec, F&& f, Ts&&... ts) { return detail::create_dataflow_alloc(alloc, PIKA_FORWARD(Executor_, exec), PIKA_FORWARD(F, f), traits::acquire_future_disp()(PIKA_FORWARD(Ts, ts))...); } }; // any action, plain function, or function object template <typename FD> struct dataflow_dispatch_impl<false, FD, typename std::enable_if<!pika::detail::is_launch_policy<FD>::value && !(traits::is_one_way_executor<FD>::value || traits::is_two_way_executor<FD>::value)>::type> { template <typename Allocator, typename F, typename... Ts, typename Enable = typename std::enable_if< !traits::is_action<typename std::decay<F>::type>::value>::type> PIKA_FORCEINLINE static auto call(Allocator const& alloc, F&& f, Ts&&... ts) -> decltype(dataflow_dispatch<launch>::call(alloc, launch::async, PIKA_FORWARD(F, f), PIKA_FORWARD(Ts, ts)...)) { return dataflow_dispatch<launch>::call(alloc, launch::async, PIKA_FORWARD(F, f), PIKA_FORWARD(Ts, ts)...); } }; template <typename FD> struct dataflow_dispatch<FD, typename std::enable_if<!pika::detail::is_launch_policy<FD>::value && !(traits::is_one_way_executor<FD>::value || traits::is_two_way_executor<FD>::value)>::type> { template <typename Allocator, typename F, typename... Ts> PIKA_FORCEINLINE static auto call( Allocator const& alloc, F&& f, Ts&&... ts) -> decltype(dataflow_dispatch_impl< traits::is_action<typename std::decay<F>::type>::value, launch>::call(alloc, launch::async, PIKA_FORWARD(F, f), PIKA_FORWARD(Ts, ts)...)) { return dataflow_dispatch_impl< traits::is_action<typename std::decay<F>::type>::value, launch>::call(alloc, launch::async, PIKA_FORWARD(F, f), PIKA_FORWARD(Ts, ts)...); } }; } // namespace pika::detail
38.468978
80
0.590342
pika-org