hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
dfccd314035fc846f0521c04ac7b793b04388fec
1,389
hpp
C++
lib/mockturtle/include/mockturtle/networks/sta.hpp
Ace-Ma/LSOracle
6e940906303ef6c2c6b96352f44206567fdd50d3
[ "MIT" ]
null
null
null
lib/mockturtle/include/mockturtle/networks/sta.hpp
Ace-Ma/LSOracle
6e940906303ef6c2c6b96352f44206567fdd50d3
[ "MIT" ]
null
null
null
lib/mockturtle/include/mockturtle/networks/sta.hpp
Ace-Ma/LSOracle
6e940906303ef6c2c6b96352f44206567fdd50d3
[ "MIT" ]
null
null
null
#include <ot/timer/timer.hpp> /* * Interfaces the command line with OpenTimer API */ class STA { private: ot::Timer timer; public: void set_lib_path(const std::string &lib){ this->timer.read_celllib(lib,std::nullopt); } void set_netlist_path(const std::string &netlist){ this->timer.read_verilog(netlist); } void set_sdc_path(const std::string &sdc){ this->timer.read_sdc(sdc); } bool run_slack(){ this->timer.update_timing(); // update timing (O(1) builder) if(auto tns = this->timer.report_tns(); tns) std::cout << "TNS: " << *tns << '\n'; // (O(N) action) if(auto wns = this->timer.report_wns(); wns) std::cout << "WNS: " << *wns << '\n'; // (O(N) action) this->timer.dump_timer(std::cout); // dump the timer details (O(1) accessor) } bool run_report_timing(){ this->timer.update_timing(); // update timing (O(1) builder) std::vector<ot::Path> critical = this->timer.report_timing(1); //if(auto rpt = this->timer.report_timing(1); rpt) std::cout << "Critical Path: " << *rpt << '\n'; // (O(N) action) std::cout << "Critical Path: " << critical[0] << std::endl; this->timer.dump_timer(std::cout); // dump the timer details (O(1) accessor) } };
33.071429
124
0.552196
[ "vector" ]
2545cc12f819ca8b51b9c5a40439cf3fc2ac389d
4,681
cc
C++
device/u2f/u2f_device.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
device/u2f/u2f_device.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
device/u2f/u2f_device.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2017 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 "u2f_device.h" #include "base/bind.h" #include "u2f_apdu_command.h" #include "u2f_apdu_response.h" namespace device { U2fDevice::U2fDevice() : channel_id_(kBroadcastChannel), capabilities_(0) {} U2fDevice::~U2fDevice() {} void U2fDevice::Register(const std::vector<uint8_t>& app_param, const std::vector<uint8_t>& challenge_param, const MessageCallback& callback) { std::unique_ptr<U2fApduCommand> register_cmd = U2fApduCommand::CreateRegister(app_param, challenge_param); if (!register_cmd) { callback.Run(U2fReturnCode::INVALID_PARAMS, std::vector<uint8_t>()); return; } DeviceTransact( std::move(register_cmd), base::Bind(&U2fDevice::OnRegisterComplete, GetWeakPtr(), callback)); } void U2fDevice::Sign(const std::vector<uint8_t>& app_param, const std::vector<uint8_t>& challenge_param, const std::vector<uint8_t>& key_handle, const MessageCallback& callback) { std::unique_ptr<U2fApduCommand> sign_cmd = U2fApduCommand::CreateSign(app_param, challenge_param, key_handle); if (!sign_cmd) { callback.Run(U2fReturnCode::INVALID_PARAMS, std::vector<uint8_t>()); return; } DeviceTransact(std::move(sign_cmd), base::Bind(&U2fDevice::OnSignComplete, GetWeakPtr(), callback)); } void U2fDevice::Version(const VersionCallback& callback) { std::unique_ptr<U2fApduCommand> version_cmd = U2fApduCommand::CreateVersion(); if (!version_cmd) { callback.Run(false, ProtocolVersion::UNKNOWN); return; } DeviceTransact( std::move(version_cmd), base::Bind(&U2fDevice::OnVersionComplete, GetWeakPtr(), callback)); } void U2fDevice::OnRegisterComplete( const MessageCallback& callback, bool success, std::unique_ptr<U2fApduResponse> register_response) { if (!success || !register_response) { callback.Run(U2fReturnCode::FAILURE, std::vector<uint8_t>()); return; } switch (register_response->status()) { case U2fApduResponse::Status::SW_CONDITIONS_NOT_SATISFIED: callback.Run(U2fReturnCode::CONDITIONS_NOT_SATISFIED, std::vector<uint8_t>()); break; case U2fApduResponse::Status::SW_NO_ERROR: callback.Run(U2fReturnCode::SUCCESS, register_response->data()); break; case U2fApduResponse::Status::SW_WRONG_DATA: callback.Run(U2fReturnCode::INVALID_PARAMS, std::vector<uint8_t>()); break; default: callback.Run(U2fReturnCode::FAILURE, std::vector<uint8_t>()); break; } } void U2fDevice::OnSignComplete(const MessageCallback& callback, bool success, std::unique_ptr<U2fApduResponse> sign_response) { if (!success || !sign_response) { callback.Run(U2fReturnCode::FAILURE, std::vector<uint8_t>()); return; } switch (sign_response->status()) { case U2fApduResponse::Status::SW_CONDITIONS_NOT_SATISFIED: callback.Run(U2fReturnCode::CONDITIONS_NOT_SATISFIED, std::vector<uint8_t>()); break; case U2fApduResponse::Status::SW_NO_ERROR: callback.Run(U2fReturnCode::SUCCESS, sign_response->data()); break; case U2fApduResponse::Status::SW_WRONG_DATA: case U2fApduResponse::Status::SW_WRONG_LENGTH: default: callback.Run(U2fReturnCode::INVALID_PARAMS, std::vector<uint8_t>()); break; } } void U2fDevice::OnVersionComplete( const VersionCallback& callback, bool success, std::unique_ptr<U2fApduResponse> version_response) { if (success && version_response && version_response->status() == U2fApduResponse::Status::SW_NO_ERROR && version_response->data() == std::vector<uint8_t>({'U', '2', 'F', '_', 'V', '2'})) { callback.Run(success, ProtocolVersion::U2F_V2); return; } callback.Run(success, ProtocolVersion::UNKNOWN); } void U2fDevice::OnLegacyVersionComplete( const VersionCallback& callback, bool success, std::unique_ptr<U2fApduResponse> legacy_version_response) { if (success && legacy_version_response && legacy_version_response->status() == U2fApduResponse::Status::SW_NO_ERROR && legacy_version_response->data() == std::vector<uint8_t>({'U', '2', 'F', '_', 'V', '2'})) { callback.Run(success, ProtocolVersion::U2F_V2); return; } callback.Run(success, ProtocolVersion::UNKNOWN); } } // namespace device
34.932836
80
0.671865
[ "vector" ]
2549a6466ef17d1a2dcc0ecad4fcad0f1e6c96b7
831
cpp
C++
src/main.cpp
Werfpasta/ClockWorks
708ce5986359bbf2c0419439c4a365dc3169cabd
[ "Zlib" ]
1
2015-01-01T07:10:02.000Z
2015-01-01T07:10:02.000Z
src/main.cpp
Werfpasta/ClockWorks
708ce5986359bbf2c0419439c4a365dc3169cabd
[ "Zlib" ]
null
null
null
src/main.cpp
Werfpasta/ClockWorks
708ce5986359bbf2c0419439c4a365dc3169cabd
[ "Zlib" ]
null
null
null
#pragma warning(disable : 4426) //'constexpr' was ignored (class literal types are not yet supported) #include "clockworks\tinycpp.hpp" #include "clockworks\util\delegate.hpp" #include "clockworks\util\dispatcher.hpp" #include "clockworks\display\window.hpp" #include "clockworks\std\printf.hpp" #include "clockworks\std\pair.hpp" bool MainLoop = true; bool OnClose() { MainLoop = false; return false; } int main(int argc, char **argv) { (void)argc, argv; ClockWorks::std::printf("Welcome to ClockWorks, a (one day) cross-platform, forward-compatable,\n\tOpenGL 2.1 3D game libray.\n\n" "Sorry there isn't much to see!\n"); ClockWorks::Display::Window win; win.OnClose.push_back(ClockWorks::Util::Delegate<bool()>::FromFunction<&OnClose>()); win.Show(); do { win.PumpOSQueue(); } while(MainLoop) ; return 0; }
30.777778
131
0.723225
[ "3d" ]
254ba22563fa92f533e1a178c1494ba3a5f24a30
55,567
cpp
C++
core/server/projectC/commonGame/src/navmesh/NavMesh.cpp
hw233/home3
a15a63694918483b2e4853edab197b5cdddca560
[ "Apache-2.0" ]
8
2020-08-17T09:54:20.000Z
2021-02-08T05:25:02.000Z
core/server/projectC/commonGame/src/navmesh/NavMesh.cpp
shineTeam7/home3
a15a63694918483b2e4853edab197b5cdddca560
[ "Apache-2.0" ]
null
null
null
core/server/projectC/commonGame/src/navmesh/NavMesh.cpp
shineTeam7/home3
a15a63694918483b2e4853edab197b5cdddca560
[ "Apache-2.0" ]
5
2020-07-24T03:07:08.000Z
2021-11-17T14:20:15.000Z
#include "NavMesh.h" #include <DetourAssert.h> #include "utils/FileUtils.h" #include "utils/MathUtils.h" #include <DetourNavMeshQuery.h> #include <assert.h> #include <string.h> #include <float.h> void MeshProcess::process(struct dtNavMeshCreateParams* params, unsigned char* polyAreas, unsigned int* polyFlags) { if (!m_nm->isReading) { TileLayerInfo& tileLayer = m_nm->m_ctx->getTileLayer(params->tileX, params->tileY, params->tileLayer); dtAssert(tileLayer.autoOML == nullptr); tileLayer.autoOML = new bool[params->polyCount]; // Update poly flags from areas. for (int i = 0; i < params->polyCount; ++i) { unsigned char area = polyAreas[i] - RC_WALKABLE_AREA; bool autoOML = area & 0x1; tileLayer.autoOML[i] = autoOML; area >>= 1; dtAssert(area < 32); // store area in flags as walkable mask polyFlags[i] = 1 << area; polyAreas[i] = area; } } else { // Update poly flags from areas. for (int i = 0; i < params->polyCount; ++i) { unsigned int area = polyAreas[i] - RC_WALKABLE_AREA; //bool autoOML = area & 0x1; //tileLayer.autoOML[i] = autoOML; area >>= 1; dtAssert(area < 32); // store area in flags as walkable mask polyFlags[i] = 1 << area; polyAreas[i] = area; } params->offMeshConCount = m_nm->offMeshConCount; params->offMeshConVerts = m_nm->offMeshConVerts; params->offMeshConRad = m_nm->offMeshConRad; params->offMeshConDir = m_nm->offMeshConDir; params->offMeshConAreas = m_nm->offMeshConAreas; params->offMeshConFlags = m_nm->offMeshConFlags; params->offMeshConUserID = m_nm->offMeshConUserID; } } struct TileCacheTileHeader { dtCompressedTileRef tileRef; int dataSize; }; bool BuildContext::checkHeightfieldCollision(const float x, const float ymin, const float ymax, const float z) const { int ix, iz; if (calcTileLoc(x, z, &ix, &iz)) { TileInfo& tile = getTile(ix, iz); rcHeightfield* heightField = tile.rc->solid; if (heightField) { return rcCheckHeightfieldCollision(x, ymin, ymax, z, *heightField); } } return false; } int BuildContext::getNearestHeight(const float x, const float y, const float z, float* h) const { int ix, iz; if (calcTileLoc(x, z, &ix, &iz)) { TileInfo& tile = getTile(ix, iz); rcHeightfield* heightField = tile.rc->solid; if (heightField) return rcGetNearestHeight(x, y, z, *heightField, h); } return false; } void readVec3(BytesReadStream* stream, float* arr) { arr[0] = stream->readFloat(); arr[1] = stream->readFloat(); arr[2] = stream->readFloat(); } void vectorToFloatArr(const Vector3& vec, float* arr) { arr[0] = vec.x; arr[1] = vec.y; arr[2] = vec.z; } void calcTriNormal(const float* v0, const float* v1, const float* v2, float* norm) { float e0[3], e1[3]; rcVsub(e0, v1, v0); rcVsub(e1, v2, v0); rcVcross(norm, e0, e1); rcVnormalize(norm); } //2->3 inline bool checkOverlapRect(const float amin[2], const float amax[2], const float bmin[3], const float bmax[3]) { bool overlap = true; overlap = (amin[0] > bmax[0] || amax[0] < bmin[0]) ? false : overlap; overlap = (amin[1] > bmax[2] || amax[1] < bmin[2]) ? false : overlap; return overlap; } unsigned char countArea(unsigned char srcArea, bool autoOML, float norm, float walkableThr) { int area; if (srcArea == kNotWalkable) { area = RC_FORCE_UNWALKABLE_AREA; } else { area = 0; if (norm > walkableThr) { area = RC_WALKABLE_AREA + ((srcArea << 1) + autoOML); dtAssert(area < RC_FORCE_UNWALKABLE_AREA); } } return area; } rcConfig getRcConfig(const NavMeshConfig& settings, const SceneRecastData& data) { //rcConfig config; //memset(&config, 0, sizeof(config)); //config.cs = settings.cellSize; //config.ch = settings.cellHeight; //config.walkableSlopeAngle = settings.agentMaxSlope; //config.walkableHeight = (int)ceilf(settings.agentHeight / config.ch); //config.walkableClimb = (int)floorf(settings.agentMaxClimb / config.ch); //config.walkableRadius = (int)ceilf(settings.agentRadius / config.cs); //config.maxEdgeLen = (int)(settings.edgeMaxLen / settings.cellSize); //config.maxSimplificationError = settings.edgeMaxError; //config.minRegionArea = (int)rcSqr(settings.regionMinSize); // Note: area = size*size //config.mergeRegionArea = (int)rcSqr(settings.regionMergeSize); // Note: area = size*size //config.maxVertsPerPoly = (int)settings.vertsPerPoly; //config.tileSize = (int)settings.tileSize; //config.borderSize = config.walkableRadius + 3; // Reserve enough padding. //config.width = config.tileSize + config.borderSize * 2; //config.height = config.tileSize + config.borderSize * 2; //config.detailSampleDist = settings.detailSampleDist < 0.9f ? 0 : settings.cellSize * settings.detailSampleDist; //config.detailSampleMaxError = settings.cellHeight * settings.detailSampleMaxError; //float tempFArr[3]; //vectorToFloatArr(data.min, tempFArr); //rcVcopy(config.bmin, tempFArr); //vectorToFloatArr(data.max, tempFArr); //rcVcopy(config.bmax, tempFArr); //return config; rcConfig config; memset(&config, 0, sizeof(config)); float tempFArr[3]; vectorToFloatArr(data.min, tempFArr); rcVcopy(config.bmin, tempFArr); vectorToFloatArr(data.max, tempFArr); rcVcopy(config.bmax, tempFArr); config.bmax[1] += settings.agentHeight + 0.1f; // Make sure the agent can stand at the top. config.cs = fmax(0.01f, settings.cellSize); // Height needs more precision so that walkableClimb is not too prone to rasterization errors. config.ch = config.cs * 0.5f; // Some places inside Recast store height as a byte, make sure the ratio between // the agent height (plus climb) and cell height does not exceed this limit. if ((int)ceilf((settings.agentHeight + settings.agentMaxClimb) / config.ch) > 255) { const float cellHeight = (settings.agentHeight + settings.agentMaxClimb) / 255.0f; config.ch = cellHeight; } // Warn about too large vertical dimension and adjust the cell height to fit the whole world. float worldHeight = config.bmax[1] - config.bmin[1]; int worldHeightVoxels = (int)ceilf(worldHeight / config.ch); if (worldHeightVoxels >= RC_SPAN_MAX_HEIGHT) { config.ch = worldHeight / (float)(RC_SPAN_MAX_HEIGHT); } config.walkableSlopeAngle = MathUtils::clampf(settings.agentMaxSlope, 0.1f, 90.0f); config.walkableHeight = (int)floorf(settings.agentHeight / config.ch); config.walkableClimb = (int)ceilf(settings.agentMaxClimb / config.ch); config.walkableRadius = fmax(0, (int)ceilf(settings.agentRadius / config.cs - config.cs * 0.01f)); config.maxEdgeLen = 0;//(int)(settings.edgeMaxLen / settings.cellSize); config.maxSimplificationError = 1.3f;//settings.edgeMaxError; if (config.walkableClimb >= config.walkableHeight) config.walkableClimb = fmax(0, config.walkableHeight - 1); config.minRegionArea = (int)(settings.minRegionArea / (config.cs * config.cs)); //(int)rcSqr(settings.regionMinSize); // Note: area = size*size config.tileSize = (int)settings.tileSize; config.mergeRegionArea = 400;// (int)rcSqr(settings.regionMergeSize); // Note: area = size*size config.maxVertsPerPoly = kNavMeshVertsPerPoly;//(int)settings.vertsPerPoly; config.detailSampleDist = config.cs * 6.0f; config.detailSampleMaxError = config.ch * 1.0f; //config.borderSize = config.walkableRadius + 3; // Reserve enough padding. /*config.width = config.tileSize + config.borderSize * 2; config.height = config.tileSize + config.borderSize * 2; config.detailSampleDist = settings.detailSampleDist < 0.9f ? 0 : settings.cellSize * settings.detailSampleDist; config.detailSampleMaxError = settings.cellHeight * settings.detailSampleMaxError;*/ rcCalcGridSize(config.bmin, config.bmax, config.cs, &config.width, &config.height); // Adjust for tile border config.borderSize = config.walkableRadius + 3; config.width = config.tileSize + 2 * config.borderSize; config.height = config.tileSize + 2 * config.borderSize; return config; } void rcFilterForceUnwalkableArea(rcContext* ctx, rcHeightfield& solid) { const int w = solid.width; const int h = solid.height; for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { for (rcSpan* s = solid.spans[x + y * w]; s; s = s->next) { if (s->area == RC_FORCE_UNWALKABLE_AREA) { s->area = RC_NULL_AREA; } } } } } void NavMesh::exportNav(const char* configPath, const char* dataPath, const char* savePath) { BytesReadStream* configStream = FileUtils::readFileForBytesReadStream(configPath); BytesReadStream* dataStream = FileUtils::readFileForBytesReadStream(dataPath); if (!configStream || !dataStream) { print("config/data加载失败"); return; } exportNav(configStream, dataStream, savePath); } void NavMesh::exportNav(BytesReadStream* configStream, BytesReadStream* dataStream, string savePath) { NavMeshConfig config; config.read(configStream); SceneRecastData data; data.read(dataStream); clear(); isReading = false; m_talloc = new LinearAllocator(32 * 1024 * 1024); m_tcomp = new FastLZCompressor(); m_tmproc = new MeshProcess(); m_tmproc->m_nm = this; m_ctx = new BuildContext(); m_ctx->m_nm = this; m_tileCache = dtAllocTileCache(); if (!m_tileCache) { m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not allocate tile cache."); clear(); return; } float tempFArr[3]; dtTileCacheParams tcparams; memset(&tcparams, 0, sizeof(tcparams)); vectorToFloatArr(data.min, tempFArr); rcVcopy(tcparams.orig, tempFArr); rcConfig rcConfig = getRcConfig(config, data); m_ctx->config = config; m_ctx->rcConfig = rcConfig; m_ctx->tileSize = data.tileSize; tcparams.cs = rcConfig.cs; tcparams.ch = rcConfig.ch; tcparams.width = (int)config.tileSize; tcparams.height = (int)config.tileSize; tcparams.walkableHeight = config.agentHeight; tcparams.walkableRadius = config.agentRadius; tcparams.walkableClimb = config.agentMaxClimb; tcparams.maxSimplificationError = config.edgeMaxError; tcparams.maxTiles = data.sizeX * data.sizeZ * EXPECTED_LAYERS_PER_TILE; tcparams.maxObstacles = 128; dtStatus status = m_tileCache->init(&tcparams, m_talloc, m_tcomp, m_tmproc); if (dtStatusFailed(status)) { m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not init tile cache."); clear(); return; } m_navMesh = dtAllocNavMesh(); if (!m_navMesh) { m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not allocate navmesh."); clear(); return; } m_navQuery = dtAllocNavMeshQuery(); if (!m_navQuery) { m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not allocate dtAllocNavMeshQuery."); clear(); return; } /*int gw = (int)((data.max.x - data.min.x) / config.cellSize + 0.5f); int gh = (int)((data.max.z - data.min.z) / config.cellSize + 0.5f); const int ts = (int)config.tileSize; const int tw = (gw + ts - 1) / ts; const int th = (gh + ts - 1) / ts;*/ // Max tiles and max polys affect how the tile IDs are caculated. // There are 22 bits available for identifying a tile and a polygon. int tileBits = rcMin((int)dtIlog2(dtNextPow2(data.sizeX * data.sizeZ * EXPECTED_LAYERS_PER_TILE)), 14); if (tileBits > 14) tileBits = 14; int polyBits = 22 - tileBits; int m_maxTiles = 1 << tileBits; int m_maxPolysPerTile = 1 << polyBits; dtNavMeshParams params; memset(&params, 0, sizeof(params)); rcVcopy(params.orig, tcparams.orig); params.tileWidth = config.tileSize * config.cellSize; params.tileHeight = config.tileSize * config.cellSize; params.maxTiles = m_maxTiles; params.maxPolys = m_maxPolysPerTile; status = m_navMesh->init(&params); if (dtStatusFailed(status)) { m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not init navmesh."); clear(); return; } m_navQuery->init(m_navMesh, 4096); // Build initial meshes int64 start = Ctrl::getTimer(); int sizeX = data.sizeX; int sizeZ = data.sizeZ; m_ctx->sizeX = sizeX; m_ctx->sizeZ = sizeZ; int dx; int dy; m_ctx->m_recastTiles = new TileInfo[sizeX * sizeZ]; for (int y = -1; y <= sizeZ; ++y) { for (int x = -1; x <= sizeX; ++x) { dx = x + 1; dy = y + 1; if (m_ctx->inRange(dx, dy)) { TileInfo& tile = m_ctx->getTile(dx, dy); tile.rc = new RasterizationContext(); TileCacheData tiles[MAX_LAYERS]; int nTiles = rasterizeTileLayers(data, dx, dy, rcConfig, tiles, MAX_LAYERS, *tile.rc); //if (nTiles == 0) //{ // /*m_ctx->log(RC_LOG_ERROR, "rasterizeTileLayers Failed."); // clear(); // return;*/ // continue; //} TileInfo& tileInfo = m_ctx->getTile(dx, dy); tileInfo.ntiles = nTiles; for (int i = 0; i < nTiles; ++i) { TileCacheData* tile = &tiles[i]; dtCompressedTileRef tileRef; status = m_tileCache->addTile(tile->data, tile->dataSize, DT_COMPRESSEDTILE_FREE_DATA, &tileRef); if (dtStatusFailed(status)) { dtFree(tile->data); tile->data = 0; m_ctx->log(RC_LOG_ERROR, "addTileFailed."); clear(); return; } status = m_tileCache->buildNavMeshTile(tileRef, m_navMesh); if (dtStatusFailed(status)) { m_ctx->log(RC_LOG_ERROR, "buildTileFailed."); clear(); return; } tileInfo.tileLayers[i].ref = m_navMesh->getTileRefAt(dx, dy, i); } } if (m_ctx->inRange(x, y)) { appendOffMeshLinks(x, y); } dx = x - 1; dy = y - 1; //释放内存 if (m_ctx->inRange(dx, dy)) { m_ctx->clearTile(dx, dy); } } } //for (int y = 0; y < data.sizeZ; ++y) //{ // for (int x = 0; x < data.sizeX; ++x) // { // TileCacheData tiles[MAX_LAYERS]; // int nTiles = rasterizeTileLayers(data, x, y, rcConfig, tiles, MAX_LAYERS); // for (int i = 0; i < nTiles; ++i) // { // TileCacheData* tile = &tiles[i]; // status = m_tileCache->addTile(tile->data, tile->dataSize, DT_COMPRESSEDTILE_FREE_DATA, 0); // if (dtStatusFailed(status)) // { // dtFree(tile->data); // tile->data = 0; // m_ctx->log(RC_LOG_ERROR, "addTileFailed."); // clear(); // return; // } // //list.add(move(*tile)); // list.push_back(move(*tile)); // status = m_tileCache->buildNavMeshTilesAt(x, y, m_navMesh); // if (dtStatusFailed(status)) // { // m_ctx->log(RC_LOG_ERROR, "buildTileFailed."); // clear(); // return; // } // } // } //} int64 end = Ctrl::getTimer(); print("cost time %d", end - start); save(savePath.c_str()); clear(); print("OK"); } //void NavMesh::save(string path) //{ // if (!m_tileCache) // return; // // FILE* fp = fopen(path.c_str(), "wb"); // // if (!fp) // { // Ctrl::errorLog("无法打开目录 %s", path.c_str()); // return; // } // // // Store header. // TileCacheSetHeader header; // header.magic = TILECACHESET_MAGIC; // header.version = TILECACHESET_VERSION; // header.numTiles = 0; // for (int i = 0; i < m_tileCache->getTileCount(); ++i) // { // const dtCompressedTile* tile = m_tileCache->getTile(i); // if (!tile || !tile->header || !tile->dataSize) continue; // header.numTiles++; // } // memcpy(&header.cacheParams, m_tileCache->getParams(), sizeof(dtTileCacheParams)); // memcpy(&header.meshParams, m_navMesh->getParams(), sizeof(dtNavMeshParams)); // fwrite(&header, sizeof(TileCacheSetHeader), 1, fp); // // // Store tiles. // for (int i = 0; i < m_tileCache->getTileCount(); ++i) // { // const dtCompressedTile* tile = m_tileCache->getTile(i); // if (!tile || !tile->header || !tile->dataSize) continue; // // TileCacheTileHeader tileHeader; // tileHeader.tileRef = m_tileCache->getTileRef(tile); // tileHeader.dataSize = tile->dataSize; // fwrite(&tileHeader, sizeof(tileHeader), 1, fp); // // fwrite(tile->data, tile->dataSize, 1, fp); // } // // fclose(fp); //} void NavMesh::save(string path) { if (!m_tileCache) return; BytesWriteStream stream; // Store header. TileCacheSetHeader header; header.magic = TILECACHESET_MAGIC; header.version = TILECACHESET_VERSION; header.numTiles = 0; for (int i = 0; i < m_tileCache->getTileCount(); ++i) { const dtCompressedTile* tile = m_tileCache->getTile(i); if (!tile || !tile->header || !tile->dataSize) continue; header.numTiles++; } memcpy(&header.cacheParams, m_tileCache->getParams(), sizeof(dtTileCacheParams)); memcpy(&header.meshParams, m_navMesh->getParams(), sizeof(dtNavMeshParams)); stream.writeMem(&header, sizeof(TileCacheSetHeader)); //OML int omlLen = m_OffMeshLinks.size(); //ignore big/little Endian stream.writeMem(&omlLen, sizeof(int)); for (AutoOffMeshLinkData v : m_OffMeshLinks) { stream.writeMem(&v, sizeof(AutoOffMeshLinkData)); } // Store tiles. for (int i = 0; i < m_tileCache->getTileCount(); ++i) { const dtCompressedTile* tile = m_tileCache->getTile(i); if (!tile || !tile->header || !tile->dataSize) continue; TileCacheTileHeader tileHeader; tileHeader.tileRef = m_tileCache->getTileRef(tile); tileHeader.dataSize = tile->dataSize; stream.writeMem(&tileHeader, sizeof(tileHeader)); stream.writeMem(tile->data, tile->dataSize); } FileUtils::writeFileForBytesWriteStream(path, stream); } void NavMesh::clear() { isReading = false; if (m_talloc) { delete m_talloc; m_talloc = nullptr; } if (m_tcomp) { delete m_tcomp; m_tcomp = nullptr; } if (m_tmproc) { delete m_tmproc; m_tmproc = nullptr; } if (m_tileCache) { delete m_tileCache; m_tileCache = nullptr; } if (m_ctx) { delete m_ctx; m_ctx = nullptr; } if (m_navMesh) { delete m_navMesh; m_navMesh = nullptr; } if (m_navQuery) { delete m_navQuery; m_navQuery = nullptr; } m_OffMeshLinks.clear(); clearOML(); } void NavMesh::clearOML() { offMeshConCount = 0; if (offMeshConVerts) { delete[] offMeshConVerts; offMeshConVerts = nullptr; } if (offMeshConRad) { delete[] offMeshConRad; offMeshConRad = nullptr; } if (offMeshConFlags) { delete[] offMeshConFlags; offMeshConFlags = nullptr; } if (offMeshConAreas) { delete[] offMeshConAreas; offMeshConAreas = nullptr; } if (offMeshConDir) { delete[] offMeshConDir; offMeshConDir = nullptr; } if (offMeshConUserID) { delete[] offMeshConUserID; offMeshConUserID = nullptr; } } void NavMesh::makeOML() { offMeshConCount = m_OffMeshLinks.size(); offMeshConVerts = new float[offMeshConCount * 6]; offMeshConRad = new float[offMeshConCount]; offMeshConFlags = new unsigned int[offMeshConCount]; offMeshConAreas = new unsigned char[offMeshConCount]; offMeshConDir = new unsigned char[offMeshConCount]; offMeshConUserID = new unsigned int[offMeshConCount]; for (int i = 0; i < offMeshConCount; i++) { AutoOffMeshLinkData v = m_OffMeshLinks[i]; v.m_Start.toArray(&offMeshConVerts[i * 6]); v.m_End.toArray(&offMeshConVerts[i * 6 + 3]); offMeshConRad[i] = v.m_Radius; offMeshConFlags[i] = v.m_LinkType; offMeshConAreas[i] = v.m_Area; offMeshConDir[i] = v.m_LinkDirection; offMeshConUserID[i] = i; } m_OffMeshLinks.clear(); } int NavMesh::rasterizeTileLayers(SceneRecastData& data, const int x, const int y, const rcConfig& cfg, TileCacheData* tiles, const int maxTiles, RasterizationContext& rc) { FastLZCompressor comp; // Tile bounds. const float tcs = cfg.tileSize * cfg.cs; rcConfig tcfg; memcpy(&tcfg, &cfg, sizeof(tcfg)); int tx = x; int ty = y; tcfg.bmin[0] = cfg.bmin[0] + tx * tcs; tcfg.bmin[1] = cfg.bmin[1]; tcfg.bmin[2] = cfg.bmin[2] + ty * tcs; tcfg.bmax[0] = cfg.bmin[0] + (tx + 1) * tcs; tcfg.bmax[1] = cfg.bmax[1]; tcfg.bmax[2] = cfg.bmin[2] + (ty + 1) * tcs; tcfg.bmin[0] -= tcfg.borderSize * tcfg.cs; tcfg.bmin[2] -= tcfg.borderSize * tcfg.cs; tcfg.bmax[0] += tcfg.borderSize * tcfg.cs; tcfg.bmax[2] += tcfg.borderSize * tcfg.cs; // // Step 1. create height field // // Allocate voxel heightfield where we rasterize our input data to. rc.solid = rcAllocHeightfield(); if (!rc.solid) { m_ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'solid'."); return 0; } if (!rcCreateHeightfield(nullptr, *rc.solid, tcfg.width, tcfg.height, tcfg.bmin, tcfg.bmax, tcfg.cs, tcfg.ch)) { m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not create solid heightfield."); return 0; } /*recastTile.m_polyMesh = rcAllocPolyMesh(); if (!recastTile.m_polyMesh) { m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not create solid rcAllocPolyMesh."); return 0; } recastTile.m_detailMesh = rcAllocPolyMeshDetail(); if (!recastTile.m_detailMesh) { m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not create solid rcAllocPolyMeshDetail."); return 0; }*/ /*recastTile.m_heightField = rcAllocHeightfield(); if (!recastTile.m_heightField) { m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not create solid rcAllocHeightfield."); clear(); return 0; }*/ // // Step 2. Rasterize all geometry // const float walkableThr = cosf(tcfg.walkableSlopeAngle / 180.0f * RC_PI); unsigned char area = 0; float norm[3]; float v0[3]; float v1[3]; float v2[3]; float v3[3]; float va0[3]; float va1[3]; float va2[3]; SceneRecastTerrainData* terrain = data.terrain; //first terrain if (terrain) { unsigned char terrainFlag = RC_WALKABLE_AREA;// + 1 int x0 = floor((tcfg.bmin[0] - terrain->origin.x) / terrain->unit.x); int z0 = floor((tcfg.bmin[2] - terrain->origin.z) / terrain->unit.z); int x1 = ceil((tcfg.bmax[0] - terrain->origin.x) / terrain->unit.x); int z1 = ceil((tcfg.bmax[2] - terrain->origin.z) / terrain->unit.z); if (z0 < 0) z0 = 0; if (x0 < 0) x0 = 0; if (x1 >= terrain->resolutionX) x1 = terrain->resolutionX - 1; if (z1 >= terrain->resolutionZ) z1 = terrain->resolutionZ - 1; for (int j = z0; j <= z1; ++j) { for (int i = x0; i <= x1; ++i) { terrain->getVertex(i, j, v0); terrain->getVertex(i, j + 1, v1); terrain->getVertex(i + 1, j, v2); terrain->getVertex(i + 1, j + 1, v3); calcTriNormal(v0, v1, v3, norm); area = 0; if (norm[1] > walkableThr) area = terrainFlag; rcRasterizeTriangle(m_ctx, v0, v1, v3, area, *rc.solid); calcTriNormal(v3, v2, v0, norm); area = 0; if (norm[1] > walkableThr) area = terrainFlag; rcRasterizeTriangle(m_ctx, v3, v2, v0, area, *rc.solid); } } } //then mesh float tbmin[2], tbmax[2]; tbmin[0] = tcfg.bmin[0]; tbmin[1] = tcfg.bmin[2]; tbmax[0] = tcfg.bmax[0]; tbmax[1] = tcfg.bmax[2]; for (int i = 0; i < data.objListSize; i++) { SceneRecastObjData* obj = data.objList[i]; if (checkOverlapRect(tbmin, tbmax, obj->min, obj->max)) { SceneRecastMeshData* meshObj = data.meshList[obj->meshIndex]; int* triangles = meshObj->triangles; Vector3* vertices = meshObj->vertices; int triCount = meshObj->trianglesSize / 3; int jLen = meshObj->trianglesSize; for (int j = 0; j < jLen; j += 3) { vectorToFloatArr(vertices[triangles[j]], va0); vectorToFloatArr(vertices[triangles[j + 1]], va1); vectorToFloatArr(vertices[triangles[j + 2]], va2); obj->transVert(va0, v0); obj->transVert(va1, v1); obj->transVert(va2, v2); calcTriNormal(v0, v1, v2, norm); area = countArea((unsigned char)obj->area, obj->autoOML, norm[1], walkableThr); rcRasterizeTriangle(m_ctx, v0, v1, v2, area, *rc.solid); } } } // // Step 3. Filter walkables surfaces. // rcFilterForceUnwalkableArea(m_ctx, *rc.solid); rcFilterLowHangingWalkableObstacles(m_ctx, tcfg.walkableClimb, *rc.solid); rcFilterLedgeSpans(m_ctx, tcfg.walkableHeight, tcfg.walkableClimb, *rc.solid); rcFilterWalkableLowHeightSpans(m_ctx, tcfg.walkableHeight, *rc.solid); // Skip if tile is empty, i.e. it has no spans allocated /*if (*rc.solid->freelist == NULL) return 0;*/ // // Step 4. Partition walkable surface to simple regions. // rc.chf = rcAllocCompactHeightfield(); if (!rc.chf) { m_ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'chf'."); return 0; } if (!rcBuildCompactHeightfield(m_ctx, tcfg.walkableHeight, tcfg.walkableClimb, *rc.solid, *rc.chf)) { m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not build compact data."); return 0; } // Erode the walkable area by agent radius. if (!rcErodeWalkableArea(m_ctx, tcfg.walkableRadius, *rc.chf)) { m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not erode."); return 0; } // // Step 5. Trace and simplify region contours. // rc.lset = rcAllocHeightfieldLayerSet(); if (!rc.lset) { m_ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'lset'."); return 0; } if (!rcBuildHeightfieldLayers(m_ctx, *rc.chf, tcfg.borderSize, tcfg.walkableHeight, *rc.lset)) { m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not build heighfield layers."); return 0; } rc.ntiles = 0; if (rc.lset->nlayers >= maxTiles) { m_ctx->log(RC_LOG_ERROR, "buildNavigation: layers num above maxTiles."); return 0; } // // Step 6. Build polygons mesh from contours. // int nt = rcMin(rc.lset->nlayers, maxTiles); for (int i = 0; i < nt; ++i) { TileCacheData* tile = &rc.tiles[rc.ntiles++]; const rcHeightfieldLayer* layer = &rc.lset->layers[i]; // Store header dtTileCacheLayerHeader header; header.magic = DT_TILECACHE_MAGIC; header.version = DT_TILECACHE_VERSION; // Tile layer location in the navmesh. header.tx = tx; header.ty = ty; header.tlayer = i; dtVcopy(header.bmin, layer->bmin); dtVcopy(header.bmax, layer->bmax); // Tile info. header.width = (unsigned short)layer->width; header.height = (unsigned short)layer->height; header.minx = (unsigned short)layer->minx; header.maxx = (unsigned short)layer->maxx; header.miny = (unsigned short)layer->miny; header.maxy = (unsigned short)layer->maxy; header.hmin = (unsigned short)layer->hmin; header.hmax = (unsigned short)layer->hmax; dtStatus status = dtBuildTileCacheLayer(&comp, &header, layer->heights, layer->areas, layer->cons, &tile->data, &tile->dataSize); if (dtStatusFailed(status)) { return 0; } } // Transfer ownsership of tile data from build context to the caller. int n = 0; for (int i = 0; i < nt; ++i) { tiles[n++] = rc.tiles[i]; rc.tiles[i].data = 0; rc.tiles[i].dataSize = 0; } return nt; } void NavMesh::appendOffMeshLinks(const int x, const int z) { vector<EdgeSegment> autoLinkEdgeSegments; getMeshEdges(x, z, autoLinkEdgeSegments); if (m_ctx->config.dropHeight > m_ctx->config.agentMaxClimb) { placeDropDownLinks(autoLinkEdgeSegments); } if (m_ctx->config.jumpDistance > m_ctx->config.agentRadius) { placeJumpAcrossLinks(autoLinkEdgeSegments); } } void NavMesh::getMeshEdges(int x, int z, vector<EdgeSegment>& autoLinkEdgeSegments) { autoLinkEdgeSegments.clear(); dtQueryFilter filter; const TileInfo& tileInfo = m_ctx->getTile(x, z); for (int i = 0; i < tileInfo.ntiles; ++i) { const TileLayerInfo& layerInfo = tileInfo.tileLayers[i]; const dtMeshTile* tile = m_navMesh->getTileByRef(layerInfo.ref); if (tile) { const dtPolyRef base = m_navMesh->getPolyRefBase(tile); float segs[kMaxSegsPerPoly * 6]; int polyCount = tile->header->polyCount; for (int ip = 0; ip < polyCount; ++ip) { if (layerInfo.autoOML[ip] == 0) continue; const dtPolyRef pRef = base | (dtPolyRef)ip; int nsegs; m_navQuery->getPolyWallSegments(pRef, &filter, segs, NULL, &nsegs, kMaxSegsPerPoly); float tempV[3]; for (int k = 0; k < nsegs; ++k) { /*const float* start = &segs[6 * k]; const float* end = &segs[6 * k + 3]; dtVsub(tempV, start, end); tempV[1] = 0; dtVnormalize(tempV); const float tx = -tempV[2]; const float tz = tempV[0]; tempV[0] = tx; tempV[1] = 0; tempV[2] = tz;*/ const Vector3 start = Vector3(&segs[6 * k]); const Vector3 end = Vector3(&segs[6 * k + 3]); Vector3 normal = start - end; normal.y = 0; normal = Normalize(normal); normal.Set(normal.z, 0, -normal.x); autoLinkEdgeSegments.emplace_back(); EdgeSegment& segment = autoLinkEdgeSegments.back(); segment.start = start; segment.end = end; segment.normal = normal; } } } else { //print("D1 tile null %d %d %d", x, z, i); //TODO:这里tile会为null } } } void NavMesh::placeDropDownLinks(vector<EdgeSegment>& autoLinkEdgeSegments) { vector<AutoLinkPoints> autoLinkPoints; findValidDropDowns(autoLinkEdgeSegments, autoLinkPoints); m_OffMeshLinks.reserve(m_OffMeshLinks.size() + autoLinkPoints.size()); for (size_t i = 0; i < autoLinkPoints.size(); ++i) { const Vector3& spos = autoLinkPoints[i].start; const Vector3& epos = autoLinkPoints[i].end; addOffMeshConnection(spos, epos, m_ctx->config.agentRadius, false, kJump, kLinkTypeDropDown); } } void NavMesh::findValidDropDowns(vector<EdgeSegment>& autoLinkEdgeSegments, vector<AutoLinkPoints>& autoLinkPoints) { float agentRadius = m_ctx->rcConfig.walkableRadius * m_ctx->rcConfig.cs; float stepSize = agentRadius * 2; float dropDownOffset = m_ctx->config.agentRadius * 2 + m_ctx->rcConfig.cs * 4; // double agent radius + voxel error float minDropHeight = m_ctx->rcConfig.walkableClimb * m_ctx->rcConfig.ch; vector<Vector3> samplePositions; vector<Vector3> startPositions; for (size_t i = 0; i < autoLinkEdgeSegments.size(); i++) { const EdgeSegment& segment = autoLinkEdgeSegments[i]; Vector3 offsetSegmentStart = segment.start + segment.normal * dropDownOffset; Vector3 offsetSegmentEnd = segment.end + segment.normal * dropDownOffset; getSubsampledLocations(segment.start, segment.end, stepSize, startPositions); getSubsampledLocations(offsetSegmentStart, offsetSegmentEnd, stepSize, samplePositions); for (size_t j = 0; j < samplePositions.size(); ++j) { float nearestDistance = verticalNavMeshTest(samplePositions[j], m_ctx->config.dropHeight); if (nearestDistance < m_ctx->config.dropHeight && nearestDistance > minDropHeight) { Vector3 endPosition(samplePositions[j]); endPosition.y -= nearestDistance; if (!dropDownBlocked(startPositions[j], endPosition, m_ctx->rcConfig.cs, m_ctx->rcConfig.ch)) { autoLinkPoints.emplace_back(); AutoLinkPoints& points = autoLinkPoints.back(); points.start = startPositions[j]; points.end = endPosition; } } } } } void NavMesh::getSubsampledLocations(Vector3 segmentStart, Vector3 segmentEnd, float subsampleDistance, vector<Vector3>& locations) { locations.clear(); float segmentLength = Magnitude(segmentStart - segmentEnd); Vector3 segmentMidPoint = (segmentStart + segmentEnd) / 2; Vector3 normal = segmentEnd - segmentStart; normal.y = 0; normal = Normalize(normal); normal.Set(normal.z, 0, -normal.x); locations.push_back(segmentMidPoint); if (segmentLength > subsampleDistance * 2) // construct subsample locations { Vector3 sampleStep = Normalize(segmentStart - segmentEnd) * subsampleDistance; Vector3 pos1 = segmentMidPoint; Vector3 pos2 = segmentMidPoint; float subSampleProgress = subsampleDistance; while (subSampleProgress < segmentLength / 2) { pos1 += sampleStep; pos2 -= sampleStep; locations.push_back(pos1); locations.push_back(pos2); subSampleProgress += subsampleDistance; } } } float NavMesh::verticalNavMeshTest(Vector3 testFrom, float testHeight) { dtQueryFilter filter; float extentSize = testHeight * 0.5f; float extents[3]; extents[0] = 0; extents[1] = extentSize; extents[2] = 0; Vector3 midPoint = testFrom; midPoint.y -= extentSize; dtPolyRef polys[128]; int polyCount = 0; m_navQuery->queryPolygons(midPoint.getPtr(), extents, &filter, polys, &polyCount, 128); // Find higher poly but not higher then max height. float startHeight = testFrom.y; float nearestDistance = FLT_MAX; for (int polyIdx = 0; polyIdx < polyCount; ++polyIdx) { // TODO: Assumes local coords during baking float height; if (dtStatusSucceed(getPolyHeightLocal(polys[polyIdx], testFrom, &height))) { float distance = startHeight - height; if (distance > 0 && distance < nearestDistance) { nearestDistance = distance; } } } return nearestDistance; } bool NavMesh::dropDownBlocked(Vector3 startPos, Vector3 endPos, float cs, float ch) { Vector3 xzStep, perp1Step, perp2Step, centerScanner, perp1Scanner, perp2Scanner; float height = m_ctx->rcConfig.walkableHeight * m_ctx->rcConfig.ch; float linkXZlength, scannedLen, radius, stepSize, verticalOffset; bool overedgeflag = false; float scanHeight; verticalOffset = (m_ctx->rcConfig.walkableClimb + 1) * ch; xzStep = endPos - startPos; xzStep.y = 0; linkXZlength = Magnitude(xzStep); xzStep = Normalize(xzStep); stepSize = cs / 2.0f; xzStep *= stepSize; perp1Step.x = -xzStep.z; perp1Step.y = 0; perp1Step.z = xzStep.x; perp2Step.x = xzStep.z; perp2Step.y = 0; perp2Step.z = -xzStep.x; radius = m_ctx->rcConfig.walkableRadius * cs; scannedLen = 0; centerScanner = startPos; centerScanner.y += verticalOffset; scanHeight = fmax(0.01f, height - verticalOffset); bool blocked = false; while (scannedLen < linkXZlength && !blocked) { if (m_ctx->checkHeightfieldCollision(centerScanner.x, centerScanner.y, centerScanner.y + scanHeight, centerScanner.z)) { blocked = true; break; } float perpScannedLen = stepSize; perp1Scanner = centerScanner + perp1Step; perp2Scanner = centerScanner + perp2Step; while (perpScannedLen < radius) { if (m_ctx->checkHeightfieldCollision(perp1Scanner.x, perp1Scanner.y, perp1Scanner.y + scanHeight, perp1Scanner.z)) { blocked = true; break; } if (m_ctx->checkHeightfieldCollision(perp2Scanner.x, perp2Scanner.y, perp2Scanner.y + scanHeight, perp2Scanner.z)) { blocked = true; break; } perp1Scanner += perp1Step; perp2Scanner += perp2Step; perpScannedLen += stepSize; } scannedLen += stepSize; centerScanner += xzStep; if (!overedgeflag && (linkXZlength - scannedLen) < radius) { overedgeflag = true; centerScanner.y = endPos.y + verticalOffset; perp1Scanner.y = endPos.y + verticalOffset; perp2Scanner.y = endPos.y + verticalOffset; scanHeight += startPos.y - endPos.y; } } return blocked; } void NavMesh::placeJumpAcrossLinks(vector<EdgeSegment>& autoLinkEdgeSegments) { vector<AutoLinkPoints> autoLinkPoints; findValidJumpAcrossLinks(autoLinkEdgeSegments, autoLinkPoints); m_OffMeshLinks.reserve(m_OffMeshLinks.size() + autoLinkPoints.size()); for (size_t i = 0; i < autoLinkPoints.size(); ++i) { const Vector3& spos = autoLinkPoints[i].start; const Vector3& epos = autoLinkPoints[i].end; addOffMeshConnection(spos, epos, m_ctx->config.agentRadius, false, kJump, kLinkTypeJumpAcross); } } void NavMesh::findValidJumpAcrossLinks(vector<EdgeSegment>& autoLinkEdgeSegments, vector<AutoLinkPoints>& autoLinkPoints) { float agentRadius = m_ctx->rcConfig.walkableRadius * m_ctx->rcConfig.cs; float unevenLinkMargin = m_ctx->rcConfig.ch * 2; float testDepth = unevenLinkMargin * 2.1f; float spacing = agentRadius * 2; float minimumJumpDistance = agentRadius * 2; float stepSize = m_ctx->rcConfig.cs; vector<Vector3> samplePositions; vector<Vector3> startPositions; // Clamp the scan distance for auto-link connections. // Since the offmeshlinks are processed as a 3x3 kernel we can use 2x tile diagonal. const float tileSize = m_ctx->rcConfig.tileSize * m_ctx->rcConfig.cs; const float sampleDistance = fmin(m_ctx->config.jumpDistance, 2.83f * tileSize); for (size_t i = 0; i < autoLinkEdgeSegments.size(); ++i) { const EdgeSegment& segment = autoLinkEdgeSegments[i]; Vector3 offsetSegmentStart = segment.start + segment.normal * minimumJumpDistance; offsetSegmentStart.y += unevenLinkMargin; Vector3 offsetSegmentEnd = segment.end + segment.normal * minimumJumpDistance; offsetSegmentEnd.y += unevenLinkMargin; getSubsampledLocations(segment.start, segment.end, spacing, startPositions); getSubsampledLocations(offsetSegmentStart, offsetSegmentEnd, spacing, samplePositions); Vector3 sampleStep = segment.normal * stepSize; for (size_t j = 0; j < samplePositions.size(); ++j) { float sampleProgress = 0; Vector3 samplePoint = samplePositions[j]; while (sampleProgress < sampleDistance) { // Use heightfield first to sample a potential landing spot. float h = 0; if (m_ctx->getNearestHeight(samplePoint.x, samplePoint.y, samplePoint.z, &h)) { float distanceToGround = std::abs(h - samplePoint.y); if (distanceToGround <= testDepth) { // If the landing spot is close to navmesh, accept it. float nearestDistance = verticalNavMeshTest(samplePoint, testDepth); if (nearestDistance <= testDepth) { Vector3 endPosition(samplePoint); endPosition.y -= nearestDistance; bool blocked = jumpAcrossBlocked(startPositions[j], endPosition, m_ctx->rcConfig.cs, m_ctx->rcConfig.ch); if (!blocked) { autoLinkPoints.emplace_back(); AutoLinkPoints& points = autoLinkPoints.back(); points.start = startPositions[j]; points.end = endPosition; } break; } } } sampleProgress += stepSize; samplePoint += sampleStep; } } } } bool NavMesh::jumpAcrossBlocked(Vector3 startPos, Vector3 endPos, float cs, float ch) { Vector3 xzStep, perp1Step, perp2Step, centerScanner, perp1Scanner, perp2Scanner; float height = m_ctx->rcConfig.walkableHeight * m_ctx->rcConfig.ch; float linkXZlength, scannedLen, radius, stepSize, verticalOffset; float scanHeight; float heightDiff = std::abs(startPos.y - endPos.y); verticalOffset = (m_ctx->rcConfig.walkableClimb + 1) * ch + heightDiff; xzStep = endPos - startPos; xzStep.y = 0; linkXZlength = Magnitude(xzStep); xzStep = Normalize(xzStep); stepSize = cs / 2.0f; xzStep *= stepSize; perp1Step.x = xzStep.z; perp1Step.y = 0; perp1Step.z = -xzStep.x; perp2Step.x = -xzStep.z; perp2Step.y = 0; perp2Step.z = xzStep.x; radius = m_ctx->rcConfig.walkableRadius * cs; scannedLen = 0; centerScanner = startPos; centerScanner.y += verticalOffset; scanHeight = fmax(0.01f, height - verticalOffset); bool blocked = false; while (scannedLen < linkXZlength && !blocked) { if (m_ctx->checkHeightfieldCollision(centerScanner.x, centerScanner.y, centerScanner.y + scanHeight, centerScanner.z)) { blocked = true; break; } float perpScannedLen = stepSize; perp1Scanner = centerScanner + perp1Step; perp2Scanner = centerScanner + perp2Step; while (perpScannedLen < radius) { if (m_ctx->checkHeightfieldCollision(perp1Scanner.x, perp1Scanner.y, perp1Scanner.y + scanHeight, perp1Scanner.z)) { blocked = true; break; } if (m_ctx->checkHeightfieldCollision(perp2Scanner.x, perp2Scanner.y, perp2Scanner.y + scanHeight, perp2Scanner.z)) { blocked = true; break; } perp1Scanner += perp1Step; perp2Scanner += perp2Step; perpScannedLen += stepSize; } scannedLen += stepSize; centerScanner += xzStep; } return blocked; } static inline unsigned int getPolyIndex(const dtMeshTile* tile, const dtPoly* poly) { dtAssert(poly); dtAssert(tile); dtAssert(tile->header); const unsigned int ip = (unsigned int)(poly - tile->polys); dtAssert(ip < tile->header->polyCount); return ip; } static bool closestHeightPointTriangle(float* h, const float* p, const float* a, const float* b, const float* c) { float v0[3]; float v1[3]; float v2[3]; dtVsub(v0, c, a); dtVsub(v1, b, a); dtVsub(v2, p, a); const float dot00 = dtVdot2D(v0, v0); const float dot01 = dtVdot2D(v0, v1); const float dot02 = dtVdot2D(v0, v2); const float dot11 = dtVdot2D(v1, v1); const float dot12 = dtVdot2D(v1, v2); // Compute barycentric coordinates const float invDenom = 1.0f / (dot00 * dot11 - dot01 * dot01); const float u = (dot11 * dot02 - dot01 * dot12) * invDenom; const float v = (dot00 * dot12 - dot01 * dot02) * invDenom; // The (sloppy) epsilon is needed to allow to get height of points which // are interpolated along the edges of the triangles. static const float EPS = 1e-4f; // If point lies inside the triangle, return interpolated ycoord. if (u >= -EPS && v >= -EPS && (u + v) <= 1.0f + EPS) { *h = a[1] + v0[1] * u + v1[1] * v; return true; } return false; } static bool projectToPolyDetail(const dtMeshTile* tile, const dtPoly* poly, const Vector3& pos, float* height) { const unsigned int ip = getPolyIndex(tile, poly); const dtPolyDetail* pd = &tile->detailMeshes[ip]; for (int j = 0; j < pd->triCount; ++j) { const unsigned char* t = &tile->detailTris[(pd->triBase + j) * 4]; const float* v[3]; for (int k = 0; k < 3; ++k) { if (t[k] < poly->vertCount) v[k] = &tile->verts[poly->verts[t[k]] * 3]; else v[k] = &tile->detailVerts[(pd->vertBase + (t[k] - poly->vertCount)) * 3]; } float h; if (closestHeightPointTriangle(&h, pos.getPtr(), v[0], v[1], v[2])) { *height = h; return true; } } return false; } float sqrDistancePointSegment2D(float* t, const Vector3& pt, const Vector3& s1, const Vector3& s2) { const float dsx = s2.x - s1.x; const float dsz = s2.z - s1.z; const float dpx = pt.x - s1.x; const float dpz = pt.z - s1.z; const float den = dsx * dsx + dsz * dsz; if (den == 0) { *t = 0; return dpx * dpx + dpz * dpz; } float tt = (dsx * dpx + dsz * dpz) / den; tt = MathUtils::clampf(tt, 0.0f, 1.0f); const float x = tt * dsx - dpx; const float z = tt * dsz - dpz; *t = tt; return x * x + z * z; } // In the plane of projection find the height of the closest point on the edge of the detail triangles static float projectToPolyDetailEdge(const dtMeshTile* tile, const dtPoly* poly, const Vector3& pos) { const unsigned int ip = getPolyIndex(tile, poly); const dtPolyDetail* pd = &tile->detailMeshes[ip]; float dmin = FLT_MAX; float h = FLT_MAX; for (int j = 0; j < pd->triCount; ++j) { const unsigned char* t = &tile->detailTris[(pd->triBase + j) * 4]; Vector3 vec[3]; for (int k = 0; k < 3; ++k) { if (t[k] < poly->vertCount) vec[k] = Vector3(&tile->verts[poly->verts[t[k]] * 3]); else vec[k] = Vector3(&tile->detailVerts[(pd->vertBase + (t[k] - poly->vertCount)) * 3]); } for (int kp = 2, k = 0; k < 3; kp = k++) { float tt; float d = sqrDistancePointSegment2D(&tt, pos, vec[kp], vec[k]); if (d < dmin) { dmin = d; h = MathUtils::lerpf(vec[kp].y, vec[k].y, tt); } } } return h; } dtStatus NavMesh::getPolyHeightLocal(dtPolyRef ref, const Vector3& pos, float* height) { dtAssert(height); const dtMeshTile* tile; const dtPoly* poly; if (dtStatusSucceed(m_navMesh->getTileAndPolyByRef(ref, &tile, &poly))) { if (poly->getType() == dtPolyTypes::DT_POLYTYPE_OFFMESH_CONNECTION) { const dtOffMeshConnection* con = m_navMesh->getOffMeshConnectionByRef(ref); if (con) { const float* v0 = &con->pos[0]; const float* v1 = &con->pos[3]; const float d0 = dtVdist(pos.getPtr(), v0); const float d1 = dtVdist(pos.getPtr(), v1); const float u = d0 / (d0 + d1); *height = MathUtils::lerpf(v0[1], v1[1], u); return DT_SUCCESS; } } else { if (projectToPolyDetail(tile, poly, pos, height)) return DT_SUCCESS; *height = projectToPolyDetailEdge(tile, poly, pos); return DT_SUCCESS; } } return DT_FAILURE | DT_INVALID_PARAM; } void NavMesh::readBytes(char* bytes, int len) { BytesReadStream stream(bytes, len); TileCacheSetHeader header; stream.readMem(&header, sizeof(TileCacheSetHeader)); if (header.magic != TILECACHESET_MAGIC) { Ctrl::errorLog("read magic 出错"); clear(); return; } if (header.version != TILECACHESET_VERSION) { Ctrl::errorLog("read version 出错"); clear(); return; } m_navMesh = dtAllocNavMesh(); if (!m_navMesh) { Ctrl::errorLog("read version 出错"); clear(); return; } dtStatus status = m_navMesh->init(&header.meshParams); if (dtStatusFailed(status)) { Ctrl::errorLog("read version 出错"); clear(); return; } m_tileCache = dtAllocTileCache(); if (!m_tileCache) { Ctrl::errorLog("read version 出错"); clear(); return; } isReading = true; m_talloc = new LinearAllocator(32 * 1024 * 1024); m_tcomp = new FastLZCompressor(); m_tmproc = new MeshProcess(); m_tmproc->m_nm = this; status = m_tileCache->init(&header.cacheParams, m_talloc, m_tcomp, m_tmproc); if (dtStatusFailed(status)) { Ctrl::errorLog("read version 出错"); clear(); return; } m_OffMeshLinks.clear(); int omlLen; stream.readMem(&omlLen, sizeof(int)); //OML for (int i = 0; i < omlLen; ++i) { AutoOffMeshLinkData v; stream.readMem(&v, sizeof(AutoOffMeshLinkData)); m_OffMeshLinks.push_back(v); } makeOML(); // Read tiles. for (int i = 0; i < header.numTiles; ++i) { TileCacheTileHeader tileHeader; stream.readMem(&tileHeader, sizeof(TileCacheTileHeader)); if (!tileHeader.tileRef || !tileHeader.dataSize) break; unsigned char* data = (unsigned char*)dtAlloc(tileHeader.dataSize, DT_ALLOC_PERM); if (!data) break; //memset(data, 0, tileHeader.dataSize); stream.readMem(data, tileHeader.dataSize); dtCompressedTileRef tile = 0; dtStatus addTileStatus = m_tileCache->addTile(data, tileHeader.dataSize, DT_COMPRESSEDTILE_FREE_DATA, &tile); if (dtStatusFailed(addTileStatus)) { dtFree(data); } if (tile) { dtStatus buildStatus = m_tileCache->buildNavMeshTile(tile, m_navMesh); if (dtStatusFailed(buildStatus)) { dtFree(data); } } } m_navQuery = dtAllocNavMeshQuery(); if (!m_navQuery) { m_ctx->log(RC_LOG_ERROR, "buildTiledNavigation: Could not allocate dtAllocNavMeshQuery."); clear(); return; } m_navQuery->init(m_navMesh, 4096); //m_crowd = dtAllocCrowd(); } float magnitude(float x, float y, float z) { return rcSqrt(rcSqr(x) + rcSqr(y) + rcSqr(z)); } float magnitude(const float* start, const float* end) { return rcSqrt(rcSqr(end[0] - start[0]) + rcSqr(end[1] - start[1]) + rcSqr(end[2] - start[2])); } void lerp(float* re, const float* start, const float* end, float t) { re[0] = start[0] + (end[0] - start[0]) * t; re[1] = start[1] + (end[1] - start[1]) * t; re[2] = start[2] + (end[2] - start[2]) * t; } inline bool overlapRange(const float amin, const float amax, const float bmin, const float bmax) { return (amin >= bmax || amax <= bmin) ? false : true; } bool rcCheckHeightfieldCollision(const float x, const float ymin, const float ymax, const float z, const rcHeightfield& hf) { const int w = hf.width; const int h = hf.height; const float cs = hf.cs; const float ch = hf.ch; const float* orig = hf.bmin; const int ix = (int)floorf((x - orig[0]) / cs); const int iz = (int)floorf((z - orig[2]) / cs); if (ix < 0 || iz < 0 || ix >= w || iz >= h) return false; const rcSpan* s = hf.spans[ix + iz * w]; if (!s) return false; while (s) { const float symin = orig[1] + s->smin * ch; const float symax = orig[1] + s->smax * ch; if (overlapRange(ymin, ymax, symin, symax)) { return true; } s = s->next; } return false; } bool rcGetNearestHeight(const float x, const float y, const float z, const rcHeightfield& hf, float* height) { const int w = hf.width; const int h = hf.height; const float cs = hf.cs; const float ch = hf.ch; const float* orig = hf.bmin; const int ix = (int)floorf((x - orig[0]) / cs); const int iz = (int)floorf((z - orig[2]) / cs); if (ix < 0 || iz < 0 || ix >= w || iz >= h) return false; const rcSpan* s = hf.spans[ix + iz * w]; if (!s) return false; float dmin = FLT_MAX; while (s) { const float symax = orig[1] + s->smax * ch; const float d = rcAbs(y - symax); if (symax < y && d < dmin) { dmin = d; *height = symax; } s = s->next; } return dmin < FLT_MAX; } bool NavMesh::samplePosition(NavMeshHit* hit, const float* position, const dtQueryFilter& filter, float maxDistance) { hit->clear(); dtPolyRef ref; float extents[3]; extents[0] = maxDistance; extents[1] = maxDistance; extents[2] = maxDistance; float nearestPt[3]; if (!mapPosition(&ref, nearestPt, position, extents, filter)) { return false; } const float distance = magnitude(nearestPt, position); if (distance > maxDistance) { return false; } unsigned int flag; m_navMesh->getPolyFlags(ref, &flag); hit->setPosition(nearestPt); hit->distance = distance; hit->mask = flag; hit->hit = true; return true; } bool NavMesh::mapPosition(dtPolyRef* nearestRef, float* nearestPt, const float* position, const float* extents, const dtQueryFilter& filter) { if (!m_navQuery) return false; m_navQuery->findNearestPoly(position, extents, &filter, nearestRef, nearestPt); dtPolyRef ref = *nearestRef; return ref != 0; } bool NavMesh::raycast(NavMeshHit* hit, const float* sourcePosition, const float* targetPosition, const dtQueryFilter& filter) { hit->clear(); dtPolyRef ref; float mappedPosition[3]; const dtTileCacheParams* params = m_tileCache->getParams(); float extends[3]; extends[0] = params->walkableRadius; extends[1] = params->walkableHeight; extends[2] = params->walkableRadius; if (!mapPosition(&ref, mappedPosition, sourcePosition, extends, filter)) { return false; } // float* t, float* hitNormal, dtPolyRef* path, int* pathCount, const int maxPath // NavMeshRaycastResult result; float t = 0; float normal[3]; dtStatus status = m_navQuery->raycast(ref, mappedPosition, targetPosition, &filter, &t, normal, NULL, NULL, 0); if (dtStatusFailed(status)) { return false; } if (t > 1.0f) t = 1.0f; float rePos[3]; lerp(rePos, mappedPosition, targetPosition, t); bool blocked = t < 1.0f; // Vector3f pos; // m_NavMeshQuery->ProjectToPoly(&pos, result.lastPoly, lpos); // m_HeightMeshQuery->SetPositionHeight(&pos); hit->setPosition(rePos); hit->setNormal(normal); hit->distance = magnitude(hit->position, sourcePosition); // hit->mask = m_navMesh->getPolyFlags()(result.hitPoly); // hit->mask=0; hit->hit = blocked; return blocked; } bool NavMesh::findPath(NavMeshPath* path, const float* sourcePosition, const float* targetPosition, const dtQueryFilter& filter) { dtPolyRef startRef; dtPolyRef endRef; const dtTileCacheParams* params = m_tileCache->getParams(); float extends[3]; extends[0] = params->walkableRadius; extends[1] = params->walkableHeight; extends[2] = params->walkableRadius; float startPos[3]; if (!mapPosition(&startRef, startPos, sourcePosition, extends, filter)) { return false; } float endPos[3]; if (!mapPosition(&endRef, endPos, targetPosition, extends, filter)) { return false; } dtPolyRef polyRefs[MaxPathNum]; int nPolys; dtStatus re = m_navQuery->findPath(startRef, endRef, startPos, endPos, &filter, polyRefs, &nPolys, MaxPathNum); if (dtStatusFailed(re)) { return false; } if (nPolys > 0) { // In case of partial path, make sure the end point is clamped to the last polygon. float epos[3]; dtVcopy(epos, endPos); if (polyRefs[nPolys - 1] != endRef) m_navQuery->closestPointOnPoly(polyRefs[nPolys - 1], endPos, epos, 0); dtPolyRef straightPathRefs[MaxPathNum]; dtStatus qre = m_navQuery->findStraightPath(startPos, endPos, polyRefs, nPolys, path->path, NULL, straightPathRefs, &path->pointNum, MaxPathNum); if (dtStatusFailed(qre)) { for (size_t i = 0; i < path->pointNum; i++) { path->areas[i] = 0; } return false; } for (size_t i = 0; i < path->pointNum; i++) { if (straightPathRefs[i] == 0) path->areas[i] = 0; else m_navMesh->getPolyArea(straightPathRefs[i], &path->areas[i]); } return true; } return false; } void NavMesh::addOffMeshConnection(const Vector3& start, const Vector3& end, const float radius, bool bidirectional, unsigned char area, OffMeshLinkType linkType) { dtAssert(area < 32); //m_OffMeshLinks.push_back(AutoOffMeshLinkData()); m_OffMeshLinks.emplace_back(); AutoOffMeshLinkData& link = m_OffMeshLinks.back(); link.m_Start = start; link.m_End = end; link.m_Radius = radius; link.m_LinkType = (unsigned short)linkType; link.m_Area = area; link.m_LinkDirection = bidirectional ? kLinkDirectionTwoWay : kLinkDirectionOneWay; } void NavMeshConfig::read(BytesReadStream* stream) { agentHeight = stream->readFloat(); agentRadius = stream->readFloat(); agentMaxClimb = stream->readFloat(); agentMaxSlope = stream->readFloat(); dropHeight = stream->readFloat(); jumpDistance = stream->readFloat(); tileSize = stream->readFloat(); cellSize = stream->readFloat(); minRegionArea = stream->readFloat(); edgeMaxError = stream->readFloat(); } SceneRecastTerrainData::~SceneRecastTerrainData() { if (heightSamples) { delete[] heightSamples; heightSamples = nullptr; } } void SceneRecastTerrainData::read(BytesReadStream* stream) { origin = stream->readVector3(); unit = stream->readVector3(); resolutionX = stream->readInt(); resolutionZ = stream->readInt(); int len = stream->readLen(); heightSamples = new uint16[len]; for (int i = 0; i < len; ++i) { heightSamples[i] = static_cast<uint16>(stream->natureReadShort()); } } void SceneRecastTerrainData::getVertex(int x, int z, float* out) { if (z < 0) z = 0; if (x < 0) x = 0; if (x >= resolutionX) x = resolutionX - 1; if (z >= resolutionZ) z = resolutionZ - 1; out[0] = origin.x + (x * unit.x); out[2] = origin.z + (z * unit.z); uint16 y = heightSamples[x + z * resolutionX]; out[1] = origin.y + y * unit.y; out[1] = 0; } SceneRecastMeshData::~SceneRecastMeshData() { if (triangles) { delete[] triangles; triangles = nullptr; } if (vertices) { delete[] vertices; vertices = nullptr; } } void SceneRecastMeshData::read(BytesReadStream* stream) { int len = trianglesSize = stream->readLen(); triangles = new int[len]; for (int i = 0; i < len; ++i) { triangles[i] = stream->readInt(); } len = verticesSize = stream->readLen(); vertices = new Vector3[len]; for (int i = 0; i < len; ++i) { vertices[i] = stream->readVector3(); } min = stream->readVector3(); max = stream->readVector3(); } void SceneRecastObjData::read(BytesReadStream* stream) { meshIndex = stream->readInt(); readVec3(stream, x); readVec3(stream, y); readVec3(stream, z); readVec3(stream, w); readVec3(stream, min); readVec3(stream, max); area = stream->readInt(); autoOML = stream->readBoolean(); } void SceneRecastObjData::transVert(float* src, float* rtn) { rcVmad(rtn, w, x, src[0]); rcVmad(rtn, rtn, y, src[1]); rcVmad(rtn, rtn, z, src[2]); } SceneRecastData::~SceneRecastData() { if (terrain) { delete terrain; terrain = nullptr; } if (meshList) { int len = meshListSize; for (int i = 0; i < len; ++i) { delete meshList[i]; } delete[] meshList; meshList = nullptr; } } void SceneRecastData::read(BytesReadStream* stream) { originX = stream->readInt(); originZ = stream->readInt(); sizeX = stream->readInt(); sizeZ = stream->readInt(); tileSize = stream->readFloat(); min = stream->readVector3(); max = stream->readVector3(); bool hasTerrain = stream->readBoolean(); if (hasTerrain) { terrain = new SceneRecastTerrainData(); terrain->read(stream); } else { terrain = nullptr; } int len = meshListSize = stream->readLen(); meshList = new SceneRecastMeshData * [len]; for (int i = 0; i < len; ++i) { SceneRecastMeshData* mData = new SceneRecastMeshData(); mData->read(stream); meshList[i] = mData; } len = objListSize = stream->readLen(); objList = new SceneRecastObjData * [len]; for (int i = 0; i < len; ++i) { SceneRecastObjData* oData = new SceneRecastObjData(); oData->read(stream); objList[i] = oData; } } void BuildContext::doLog(const rcLogCategory category, const char* msg, const int len) { Ctrl::print(string(msg, len)); }
24.740427
170
0.681196
[ "mesh", "geometry", "vector", "solid" ]
254bfd970f6218e31159611ed99b376e1b54a554
311
cpp
C++
src/119.pascal_s_triangle_ii/code.cpp
cloudzfy/leetcode
9d32090429ef297e1f62877382bff582d247266a
[ "MIT" ]
1
2016-07-02T17:44:10.000Z
2016-07-02T17:44:10.000Z
src/119.pascal_s_triangle_ii/code.cpp
cloudzfy/leetcode
9d32090429ef297e1f62877382bff582d247266a
[ "MIT" ]
null
null
null
src/119.pascal_s_triangle_ii/code.cpp
cloudzfy/leetcode
9d32090429ef297e1f62877382bff582d247266a
[ "MIT" ]
1
2019-12-21T04:57:15.000Z
2019-12-21T04:57:15.000Z
class Solution { public: vector<int> getRow(int rowIndex) { vector<int> ans; for (int i = 0; i <= rowIndex; i++) { for (int j = ans.size() - 1; j > 0; j--) { ans[j] += ans[j - 1]; } ans.push_back(1); } return ans; } };
22.214286
54
0.398714
[ "vector" ]
254d289b5ce442da1c95f6f2316b59126cdb495b
1,773
hpp
C++
include/spotify/json/detail/bitset.hpp
ivangalkin/spotify-json
68cfafc488ffae851cca3f556b90129cffb26be1
[ "Apache-2.0" ]
11
2020-01-12T19:50:43.000Z
2022-01-27T20:15:24.000Z
include/spotify/json/detail/bitset.hpp
ivangalkin/spotify-json
68cfafc488ffae851cca3f556b90129cffb26be1
[ "Apache-2.0" ]
1
2021-10-31T07:10:47.000Z
2021-10-31T19:28:07.000Z
include/spotify/json/detail/bitset.hpp
ivangalkin/spotify-json
68cfafc488ffae851cca3f556b90129cffb26be1
[ "Apache-2.0" ]
2
2020-10-20T01:32:11.000Z
2021-06-04T10:31:26.000Z
/* * Copyright (c) 2016 Spotify AB * * 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 <array> #include <cstddef> #include <memory> #include <vector> #include <spotify/json/detail/macros.hpp> namespace spotify { namespace json { namespace detail { template <std::size_t inline_size> struct bitset { bitset(const std::size_t size) { if (json_likely(size <= inline_size)) { _array.fill(0x00); } else { _vector.reset(new std::vector<uint8_t>((size + 7) / 8)); } } json_force_inline uint8_t test_and_set(const std::size_t index) { const auto byte = (index / 8); const auto bidx = (index & 7); const auto mask = (1 << bidx); if (json_likely(!_vector)) { const auto byte_before = _array[byte]; _array[byte] = (byte_before | mask); return (byte_before & mask) >> bidx; } else { const auto byte_before = (*_vector)[byte]; (*_vector)[byte] = (byte_before | mask); return (byte_before & mask) >> bidx; } } private: static constexpr auto _num_inline_bytes = ((inline_size + 7) / 8); std::unique_ptr<std::vector<uint8_t>> _vector; std::array<uint8_t, _num_inline_bytes> _array; }; } // namespace detail } // namespace json } // namespace spotify
27.703125
80
0.674563
[ "vector" ]
25526a4f8637e6b754cdba619b36a67ec2263a5b
4,387
cc
C++
src/fdb5/types/TypeParam.cc
dvuckovic/fdb
c529bf5293d1f5e33048b1b12e7fdfbf4d7448b2
[ "Apache-2.0" ]
5
2020-01-03T10:23:05.000Z
2021-10-21T12:52:47.000Z
src/fdb5/types/TypeParam.cc
dvuckovic/fdb
c529bf5293d1f5e33048b1b12e7fdfbf4d7448b2
[ "Apache-2.0" ]
null
null
null
src/fdb5/types/TypeParam.cc
dvuckovic/fdb
c529bf5293d1f5e33048b1b12e7fdfbf4d7448b2
[ "Apache-2.0" ]
1
2021-07-08T16:26:06.000Z
2021-07-08T16:26:06.000Z
/* * (C) Copyright 1996- ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation nor * does it submit to any jurisdiction. */ #include <algorithm> #include "metkit/mars/ParamID.h" #include "metkit/mars/Param.h" #include "fdb5/database/DB.h" #include "fdb5/database/Notifier.h" #include "fdb5/types/TypeParam.h" #include "fdb5/types/TypesFactory.h" using metkit::Param; namespace fdb5 { //---------------------------------------------------------------------------------------------------------------------- TypeParam::TypeParam(const std::string &name, const std::string &type) : Type(name, type) { } TypeParam::~TypeParam() { } void TypeParam::getValues(const metkit::mars::MarsRequest &request, const std::string &keyword, eckit::StringList &values, const Notifier &wind, const DB *db) const { ASSERT(db); eckit::StringSet ax; db->axis(keyword, ax); eckit::StringList us; Type::getValues(request, keyword, us, wind, db); std::vector<Param> user; std::copy(us.begin(), us.end(), std::back_inserter(user)); std::vector<Param> axis; std::copy(ax.begin(), ax.end(), std::back_inserter(axis)); std::sort(axis.begin(), axis.end()); bool windConversion = false; metkit::ParamID::normalise(request, user, axis, windConversion); std::set<Param> axisSet; std::set<long> tables; for (std::vector<Param>::const_iterator i = axis.begin(); i != axis.end(); ++i) { axisSet.insert(*i); tables.insert((*i).table()); tables.insert((*i).value() / 1000); } for (std::vector<Param>::const_iterator i = user.begin(); i != user.end(); ++i) { bool found = false; // User request in axis if (axisSet.find(*i) != axisSet.end()) { values.push_back(*i); continue; } long table = (*i).table(); long value = (*i).value(); // User has specified the table if (table) { // Try 140.xxx Param p(0, table * 1000 + value); if (axisSet.find(p) != axisSet.end()) { values.push_back(p); continue; } // Try xxxx Param q(0, value); if (axisSet.find(q) != axisSet.end()) { values.push_back(q); continue; } } else { // The user did not specify a table, try known tables for (std::set<long>::const_iterator j = tables.begin(); j != tables.end() && !found; ++j) { Param p(0, (*j) * 1000 + value); if (axisSet.find(p) != axisSet.end()) { values.push_back(p); found = true;; } } } if (!found) { values.push_back(*i); } } // Log::info() << "TypeParam before: " << us << std::endl; // Log::info() << " after: " << values << std::endl; // Log::info() << " wind: " << (windConversion ? "true" : "false") << std::endl; // Log::info() << " axis: " << ax << std::endl; if (windConversion) { wind.notifyWind(); } } bool TypeParam::match(const std::string&, const std::string& value1, const std::string& value2) const { if(value1 == value2) { return true; } Param p1(value1); Param p2(value2); if((p1.value() == p2.value()) && (p1.table() == 0 || p2.table() == 0)) { return true; } if(p1.table() * 1000 + p1.value() == p2.value()) { return true; } if(p2.table() * 1000 + p2.value() == p1.value()) { return true; } return false; } void TypeParam::print(std::ostream &out) const { out << "TypeParam[name=" << name_ << "]"; } static TypeBuilder<TypeParam> type("Param"); //---------------------------------------------------------------------------------------------------------------------- } // namespace fdb5
27.248447
120
0.495099
[ "vector" ]
255504982a251679becf8201d842f8d2d1b5d4c2
10,534
cpp
C++
src/trunk/apps/tools/scplot/plotter.cpp
yannikbehr/seiscomp3
ebb44c77092555eef7786493d00ac4efc679055f
[ "Naumen", "Condor-1.1", "MS-PL" ]
94
2015-02-04T13:57:34.000Z
2021-11-01T15:10:06.000Z
src/trunk/apps/tools/scplot/plotter.cpp
yannikbehr/seiscomp3
ebb44c77092555eef7786493d00ac4efc679055f
[ "Naumen", "Condor-1.1", "MS-PL" ]
233
2015-01-28T15:16:46.000Z
2021-08-23T11:31:37.000Z
src/trunk/apps/tools/scplot/plotter.cpp
yannikbehr/seiscomp3
ebb44c77092555eef7786493d00ac4efc679055f
[ "Naumen", "Condor-1.1", "MS-PL" ]
95
2015-02-13T15:53:30.000Z
2021-11-02T14:54:54.000Z
/*************************************************************************** * Copyright (C) by GFZ Potsdam * * * * You can redistribute and/or modify this program under the * * terms of the SeisComP Public License. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * SeisComP Public License for more details. * ***************************************************************************/ #define SEISCOMP_COMPONENT scplot #include "plotter.h" #include <algorithm> #include <iomanip> #include <cstdlib> #include <sstream> #include <locale> #include <seiscomp3/core/strings.h> #include <seiscomp3/logging/log.h> #ifdef WIN32 #undef min #undef max #endif // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Table::Table() : _columns(0), _rows(0) {} // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Table::~Table() {} // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> std::ostream& operator<<(std::ostream& os, const Table& table) { for (size_t i = 0; i < table._table.size(); ++i) { os << std::setw(table._widths[i % table.columns()]) << std::left << table._table[i]; if ((i+1) % table._columns == 0) os << std::endl; else os << " | "; } os.unsetf(os.flags()); return os; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> void Table::readFrom(std::istream& is) { std::string line; while (getline(is, line)) { if (line.empty() || line[0] == '#') continue; std::vector<std::string> tokens; int ret = Seiscomp::Core::split(tokens, line.c_str(), "|"); std::vector<int> widths(ret, 0); for (size_t i = 0; i < tokens.size(); ++i) { // Remove whitespace from the beginning size_t idx = tokens[i].find_first_not_of(" "); if (idx != std::string::npos) tokens[i] = tokens[i].erase(0, idx); // Remove whitespace from the beginning idx = tokens[i].find_first_of(" "); if (idx != std::string::npos) tokens[i] = tokens[i].erase(idx, tokens[i].size()); _table.push_back(tokens[i]); widths[i] = tokens[i].size(); ++_columns; } ++_rows; if (_widths.size() == 0) _widths = widths; else for (size_t i = 0; i < _widths.size(); ++i) _widths[i] = std::max(_widths[i], widths[i]); } _columns /= _rows; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> const std::string& Table::element(int row, int col) const { return _table[col + row * _columns]; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> std::vector<double> Table::numberColumn(int c) const { // Test if elements are numbers //bool isNumber = false; std::vector<double> column; const std::num_get<char, std::istreambuf_iterator<char, std::char_traits<char> > > &ng = std::use_facet<std::num_get<char, std::istreambuf_iterator<char, std::char_traits<char> > > >(std::locale ()); for (size_t r = 0; r < rows(); ++r) { std::istringstream is(element(r, c)); if (is.str() == "NULL") continue; double number = 0; std::istreambuf_iterator<char, std::char_traits<char> > begin (is); std::istreambuf_iterator<char, std::char_traits<char> > end; std::ios::iostate state = std::ios::goodbit; std::istreambuf_iterator<char, std::char_traits<char> > pos = ng.get(begin, end, is, state, number); if ((state & std::istringstream::failbit) != 0 || pos != end) return std::vector<double>(); else column.push_back(number); } return column; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> std::vector<std::string> Table::stringColumn(int c) const { std::vector<std::string> column; for (size_t i = 0; i < rows(); ++i) column.push_back(element(i, c)); return column; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> size_t Table::columns() const { return _columns; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> size_t Table::rows() const { return _rows; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Plotter::Plotter() : _plotter(NULL) { _plotter = gnuplot_init(); } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Plotter::~Plotter() { if (_plotter) gnuplot_close(_plotter); } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> void Plotter::setXLabel(const std::string& xLabel) { if (_plotter) gnuplot_set_xlabel(_plotter, const_cast<char*>(xLabel.c_str())); } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> void Plotter::setYLabel(const std::string& yLabel) { if (_plotter) gnuplot_set_ylabel(_plotter, const_cast<char*>(yLabel.c_str())); } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> void Plotter::setPlottingStyle(PlottingStyle style) { const char* styleString = NULL; switch (style) { case LINES: styleString = "lines"; break; case POINTS: styleString = "points"; break; case LINESPOINTS: styleString = "linespoints"; break; case IMPULSES: styleString = "impulses"; break; case DOTS: styleString = "dots"; break; case STEPS: styleString = "steps"; break; default: break; } if (_plotter && styleString) gnuplot_setstyle(_plotter, styleString); } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> void Plotter::setLowLevelCommand(const std::string& cmd) { if (_plotter) { std::istringstream is(cmd); std::string word; while (is >> word) my_gnuplot_cmd(_plotter, "%s ", word.c_str()); gnuplot_cmd(_plotter, ""); } } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> void Plotter::setOutputDevice(OutputDevice device, const std::string& file) { if (!_plotter) return; bool validDevice = true; switch (device) { case PNG: gnuplot_cmd(_plotter, "set terminal png"); break; case POSTSCRIPT: gnuplot_cmd(_plotter, "set terminal postscript"); break; default: validDevice = false; break; } if (validDevice) gnuplot_cmd(_plotter, const_cast<char*>(std::string("set output " + std::string("\"") + file + std::string("\"")).c_str())); } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> void Plotter::setDefaultOutputDevice() { gnuplot_cmd(_plotter, "set terminal x11") ; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> void Plotter::plot(std::vector<double> x, std::vector<double> y, const std::string& title) { int size = x.size(); double* xArray = new double[size]; double* yArray = new double[size]; std::copy(x.begin(), x.end(), xArray); std::copy(y.begin(), y.end(), yArray); if (_plotter) gnuplot_plot_xy(_plotter, xArray, yArray, size, const_cast<char*>(title.c_str())); delete [] xArray; delete [] yArray; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> void Plotter::plot(std::vector<double> fx, const std::string& title) { int size = fx.size(); double* fxArray = new double[size]; std::copy(fx.begin(), fx.end(), fxArray); if (_plotter) gnuplot_plot_x(_plotter, fxArray, size, const_cast<char*>(title.c_str())); delete [] fxArray; } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> void Plotter::plot(const Table& table, int cx, int cy, const std::string& title) { std::vector<double> cxDoubleVec = table.numberColumn(cx); if (!cxDoubleVec.empty()) { plot(cxDoubleVec, table.numberColumn(cy), title); } else { setLowLevelCommand("set xtics rotate 90"); std::vector<std::string> cxStrVec = table.stringColumn(cx); std::ostringstream os; os << "set xtics ( "; for (size_t i = 0; i < cxStrVec.size(); ++i) os << "\"" << cxStrVec[i] << "\" " << i << ((i < cxStrVec.size() - 1) ? ", " : " )") ; setLowLevelCommand(os.str()); plot(table.numberColumn(cy), title); setLowLevelCommand("unset xtics"); } } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> void Plotter::plot(const Table& table, int c, const std::string& title) { std::vector<double> doubleVec = table.numberColumn(c); if (!doubleVec.empty()) { plot(doubleVec, title); } } // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
25.692683
112
0.410765
[ "vector" ]
256c43b37f51cdbaa11038a904381de94f89adba
2,563
hpp
C++
include/netlist_paths/Waypoints.hpp
heiner-bauer/netlist-paths
7575b87a07d61d03a3900186ae58f790aa5b66d7
[ "Apache-2.0" ]
14
2019-08-13T13:39:01.000Z
2022-02-25T22:33:23.000Z
include/netlist_paths/Waypoints.hpp
heiner-bauer/netlist-paths
7575b87a07d61d03a3900186ae58f790aa5b66d7
[ "Apache-2.0" ]
26
2018-11-20T08:10:00.000Z
2022-03-12T20:02:20.000Z
include/netlist_paths/Waypoints.hpp
heiner-bauer/netlist-paths
7575b87a07d61d03a3900186ae58f790aa5b66d7
[ "Apache-2.0" ]
1
2020-11-30T20:46:55.000Z
2020-11-30T20:46:55.000Z
#ifndef NETLIST_PATHS_WAYPOINTS_HPP #define NETLIST_PATHS_WAYPOINTS_HPP #include "netlist_paths/Exception.hpp" #include "netlist_paths/Vertex.hpp" namespace netlist_paths { /// A class representing a set of waypoints to constrain a search for a path. class Waypoints { std::vector<std::string> waypoints; std::vector<std::string> avoidPoints; bool gotStartPoint; bool gotFinishPoint; public: /// Construct an empty Waypoints object. Waypoints() : gotStartPoint(false), gotFinishPoint(false) {} /// Construct a Waypoints object with patterns matching start and finish /// points. /// /// \param start A pattern specifying a start point. /// \param end A pattern specifying an end point. Waypoints(const std::string start, const std::string end) : gotStartPoint(false), gotFinishPoint(false) { addStartPoint(start); addEndPoint(end); } /// Set a named start point. /// /// \param name A pattern specifying a start point. void addStartPoint(const std::string name) { if (gotStartPoint) { throw Exception("start point already defined"); } gotStartPoint = true; if (waypoints.size() > 0) { waypoints.insert(waypoints.begin(), name); } else { waypoints.push_back(name); } } /// Set a named end point. /// /// \param name A pattern specifying an end point. void addEndPoint(const std::string name) { if (gotFinishPoint) { throw Exception("end point already defined"); } gotFinishPoint = true; if (waypoints.size() > 0) { waypoints.insert(waypoints.end(), name); } else { waypoints.push_back(name); } } /// Add a through point. /// /// \param name A pattern specifying a mid point. void addThroughPoint(const std::string name) { if (waypoints.size() > 0) { waypoints.insert(waypoints.end()-(gotFinishPoint?1:0), name); } else { waypoints.push_back(name); } } /// Add a point to avoid. /// /// \param name A pattern specifying a mid point to avoid. void addAvoidPoint(const std::string name) { avoidPoints.push_back(name); } /// Access the waypoints. /// /// \returns An ordered vector of patterns for each waypoint. const std::vector<std::string> &getWaypoints() const { return waypoints; } /// Access the avoid points. /// /// \returns An ordered vector of patterns for each avoid point. const std::vector<std::string> &getAvoidPoints() const { return avoidPoints; } }; } // End namespace. #endif // NETLIST_PATHS_WAYPOINTS_HPP
26.697917
80
0.665236
[ "object", "vector" ]
25804ae6b2d90cae1eee5fb84995006024c6eff9
558
cpp
C++
main.cpp
KuntimaKiala/Immediate-Mode
07ac525899ac7817350d5c270f5c9fa1df111570
[ "MIT" ]
null
null
null
main.cpp
KuntimaKiala/Immediate-Mode
07ac525899ac7817350d5c270f5c9fa1df111570
[ "MIT" ]
null
null
null
main.cpp
KuntimaKiala/Immediate-Mode
07ac525899ac7817350d5c270f5c9fa1df111570
[ "MIT" ]
null
null
null
/* Author : Kuntima Description : Immediate Mode Date : 17/08/2018 Usage : g++ -std=c++11 main.cpp Display.cpp -o run -lSDL2 -lGL -lGLEW ./run Note : A lot can be changed, this is nothing more than a prototype that I created to train myself, my goal is to do 3D Game. */ #include <iostream> #include <SDL2/SDL.h> #include "Display.h" int main(int argc, char* argv[] ){ /// Create a Display object Display display; /// Callling the function that displays the rotating triangles in the screen display.DisplayWindow() ; return 0; }
23.25
125
0.684588
[ "object", "3d" ]
25835c9aeb655a5d00e56d6cf2d18e282acdf6f1
712
cpp
C++
codeforces/988A.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
codeforces/988A.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
codeforces/988A.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
// A. Diverse Team #include <iostream> #include <map> #include <vector> #include <algorithm> using namespace std; int main(){ int n, k; cin >> n >> k; map<int, int> mp; int tmp; for (int i=0; i<n; ++i){ cin >> tmp; mp.insert(pair<int, int>(tmp, i+1)); } if (mp.size() < k) { cout << "NO\n"; } else { cout << "YES\n"; vector<int> v; for (auto it: mp) { v.push_back(it.second); } sort(v.begin(), v.end()); int count = 1; for (auto it: v){ cout << it << ' '; ++count; if (count > k) break; } cout << endl; } return 0; }
16.55814
44
0.41573
[ "vector" ]
25864bd45ebeb0a94f348898885d7b7a0543392a
6,384
cpp
C++
dlls/avsign.cpp
avwuff/Half-Life-TFC-AVC-Mod
3b6a32b615e42cd541f078065458d47c3d4688ba
[ "MIT" ]
5
2019-05-08T19:25:02.000Z
2021-09-12T00:26:20.000Z
dlls/avsign.cpp
avwuff/Half-Life-TFC-AVC-Mod
3b6a32b615e42cd541f078065458d47c3d4688ba
[ "MIT" ]
1
2018-08-28T13:46:12.000Z
2018-08-28T13:48:40.000Z
dlls/avsign.cpp
avwuff/Half-Life-TFC-AVC-Mod
3b6a32b615e42cd541f078065458d47c3d4688ba
[ "MIT" ]
1
2021-03-08T15:39:39.000Z
2021-03-08T15:39:39.000Z
#include "extdll.h" #include "enginecallback.h" #include "util.h" #include "cbase.h" #include "entity_state.h" #include "soundent.h" #include "studio.h" #include "bot.h" #include "avdll.h" #include "sadll.h" #include "avsign.h" extern GETENTITYAPI other_GetEntityAPI; extern enginefuncs_t g_engfuncs; extern globalvars_t *gpGlobals; extern char *g_argv; extern DLL_FUNCTIONS other_gFunctionTable; extern const Vector g_vecZero; static FILE *fp; // This CPP deals with creating the engineers CAMERA (The THIRD thing they can build) // Basics: We use the TRIPMINE model, and stick it onto the wall just as we would a tripmine! signtext_t texts[1025]; extern bool AdminLoggedIn[33]; bool SignRemove( edict_t *pEntity ) { int radiocount = 0; int i = 1; char *pClassname; edict_t *frontEnt; edict_t *oldSign; for (i; i < 1025; i++) { frontEnt = INDEXENT ( i ); if (frontEnt) { pClassname = (char *)STRING(frontEnt->v.classname); if (FStrEq("building_sign", pClassname)) { if (frontEnt->v.euser4 == pEntity) { radiocount++; oldSign = frontEnt; } } } } if (radiocount >= 1) { // blow up old sign oldSign->v.flags |= FL_KILLME; ClientPrint( VARS(pEntity), HUD_PRINTTALK, "* Sign removed!\n"); } return 1; } bool SignCreate( edict_t *pEntity ) { // Create the sign and stick to the wall entvars_t *pPev = VARS( pEntity ); if (pPev->iuser1 > 0) return 0; // make sure we dont already have a radio int radiocount = 0; int i = 1; char *pClassname; edict_t *frontEnt; edict_t *oldSign; if (strlen((char*) Cmd_Argv(1)) < 1) return 0; if (strlen((char *)Cmd_Args()) > 79) { ClientPrint( pPev, HUD_PRINTTALK, "* Sign text too long!\n"); return 0; } if (strlen((char *)Cmd_Args()) < 2) { ClientPrint( pPev, HUD_PRINTTALK, "* Sign text too short!\n"); return 0; } for (i; i < 1025; i++) { frontEnt = INDEXENT ( i ); if (frontEnt) { pClassname = (char *)STRING(frontEnt->v.classname); if (FStrEq("building_sign", pClassname)) { if (frontEnt->v.euser4 == pEntity) { radiocount++; oldSign = frontEnt; } } } } if (AdminLoggedIn[ENTINDEX(pEntity)] == 0) { if (radiocount >= 1) { // blow up old sign oldSign->v.flags |= FL_KILLME; } } UTIL_MakeVectors( pPev->v_angle + pPev->punchangle ); Vector vecSrc = GetGunPosition( pEntity ); Vector vecAiming = gpGlobals->v_forward; TraceResult tr; UTIL_TraceLine( vecSrc, vecSrc + vecAiming * 128, dont_ignore_monsters, pEntity , &tr ); if (tr.flFraction < 1.0) { if (tr.pHit && !(tr.pHit->v.flags & FL_CONVEYOR) && (FStrEq((char *)STRING(tr.pHit->v.classname), "worldspawn") || FStrEq((char *)STRING(tr.pHit->v.classname), "func_wall") || FStrEq((char *)STRING(tr.pHit->v.classname), "building_dancemachine"))) // Make sure it isnt a conveyor! { Vector angles = UTIL_VecToAngles( tr.vecPlaneNormal ); if (angles.x > 30 || angles.x < -30) { ClientPrint( pPev, HUD_PRINTTALK, "* Can't place signs on floors or cielings!\n"); return 0; } // Create the camera here! Vector vecOri = tr.vecEndPos + tr.vecPlaneNormal * 2; KeyValueData kvd; edict_t *tEntity; tEntity = CREATE_NAMED_ENTITY(MAKE_STRING("info_target")); entvars_t *pRunOnPev; pRunOnPev = VARS(tEntity); char buf[80]; sprintf( buf, "%s", "building_sign"); // Set the KEYVALUES here! kvd.fHandled = FALSE; kvd.szClassName = NULL; kvd.szKeyName = "classname"; kvd.szValue = buf; DispatchKeyValue( tEntity, &kvd ); // place this in front pRunOnPev->origin = vecOri; pRunOnPev->angles = angles; DispatchSpawn( ENT( pRunOnPev ) ); SET_MODEL( ENT( pRunOnPev ) , "models/avnewsign.mdl"); UTIL_SetSize( pRunOnPev, Vector( -6, -6 ,-14), Vector(6, 6, 14)); pRunOnPev->takedamage = DAMAGE_NO; pRunOnPev->euser4 = pEntity; tEntity->v.solid = SOLID_BBOX; // play deploy sound EMIT_SOUND_DYN2( tEntity, CHAN_VOICE, "weapons/mine_deploy.wav", 1.0, ATTN_NORM , 0, 100); pRunOnPev->iuser2 = pRunOnPev->euser4->v.team; // Set the team this radio belongs to pRunOnPev->nextthink = gpGlobals->time + 1; pRunOnPev->fuser4 = gpGlobals->time + 70; pRunOnPev->skin = RANDOM_LONG( 0, 4 ); if (FStrEq(Cmd_Argv(0), "signbusy")) pRunOnPev->skin = 6; if (FStrEq(Cmd_Argv(0), "signavsays")) pRunOnPev->skin = 5; sprintf( texts[ENTINDEX(tEntity)].text , "%s", (char *)Cmd_Args()); SET_ORIGIN( ENT(pRunOnPev) , pRunOnPev->origin ); return 1; } else { ClientPrint( pPev, HUD_PRINTTALK, "* Couldn't place sign here!\n"); return 0; } } else { ClientPrint( pPev, HUD_PRINTTALK, "* Couldn't place sign here!\n"); } return 0; } void SignPrecache() { PRECACHE_MODEL("models/avnewsign.mdl"); } void SignThink ( edict_t *pent ) { // make sure my owner is still alive pent->v.nextthink = gpGlobals->time + 2; /* if (CVAR_GET_FLOAT("deathmatch")) { int hiswon = pfnGetPlayerWONId( pent->v.euser4 ); if (hiswon <= 0) { pent->v.flags |= FL_KILLME; } } */ if (FNullEnt(pent->v.euser4)) pent->v.flags |= FL_KILLME; } void SignTouch ( edict_t *pent , edict_t *pentTouched) { if (FStrEq("player", (char *)STRING(pentTouched->v.classname))) { // player is touching us... make sure we arent stuck in him bool stuck = 0; entvars_t *pev = VARS(pentTouched); entvars_t *sign = VARS(pent); stuck = 1; if ( sign->absmin.x + 1 > pev->absmax.x - 1 || sign->absmin.y + 1 > pev->absmax.y - 1 || sign->absmin.z + 1 > pev->absmax.z - 1 || sign->absmax.x - 1 < pev->absmin.x + 1 || sign->absmax.y - 1 < pev->absmin.y + 1 || sign->absmax.z - 1 < pev->absmin.z + 1 ) stuck = 0; if (stuck) { // player is blocked, remove sign sign->flags |= FL_KILLME; ClientPrint( pev, HUD_PRINTTALK, "* Sign removed because you were stuck in it!\n"); } } /* if (FStrEq("func_ladder", (char *)STRING(pentTouched->v.classname))) { pent->v.flags |= FL_KILLME; } else if (FStrEq("func_door", (char *)STRING(pentTouched->v.classname))) { pent->v.flags |= FL_KILLME; } else if (FStrEq("func_rot_door", (char *)STRING(pentTouched->v.classname))) { pent->v.flags |= FL_KILLME; } else if (FStrEq("func_train", (char *)STRING(pentTouched->v.classname))) { pent->v.flags |= FL_KILLME; } */ }
21.422819
282
0.638941
[ "vector", "model", "solid" ]
259024dcad6929c5743c447dea8859b08116b686
3,089
cc
C++
chrome/browser/sync_file_system/local/syncable_file_operation_runner.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
chrome/browser/sync_file_system/local/syncable_file_operation_runner.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
chrome/browser/sync_file_system/local/syncable_file_operation_runner.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2013 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/sync_file_system/local/syncable_file_operation_runner.h" #include <stddef.h> #include <algorithm> #include "base/callback.h" #include "base/stl_util.h" #include "content/public/browser/browser_thread.h" using storage::FileSystemURL; namespace sync_file_system { // SyncableFileOperationRunner::Task ------------------------------------------- bool SyncableFileOperationRunner::Task::IsRunnable( LocalFileSyncStatus* status) const { for (size_t i = 0; i < target_paths().size(); ++i) { if (!status->IsWritable(target_paths()[i])) return false; } return true; } void SyncableFileOperationRunner::Task::Start(LocalFileSyncStatus* status) { for (size_t i = 0; i < target_paths().size(); ++i) { DCHECK(status->IsWritable(target_paths()[i])); status->StartWriting(target_paths()[i]); } Run(); } // SyncableFileOperationRunner ------------------------------------------------- SyncableFileOperationRunner::SyncableFileOperationRunner( int64_t max_inflight_tasks, LocalFileSyncStatus* sync_status) : sync_status_(sync_status), max_inflight_tasks_(max_inflight_tasks), num_inflight_tasks_(0) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); sync_status_->AddObserver(this); } SyncableFileOperationRunner::~SyncableFileOperationRunner() { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); for (auto& task : pending_tasks_) task->Cancel(); pending_tasks_.clear(); } void SyncableFileOperationRunner::OnSyncEnabled(const FileSystemURL& url) { } void SyncableFileOperationRunner::OnWriteEnabled(const FileSystemURL& url) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); RunNextRunnableTask(); } void SyncableFileOperationRunner::PostOperationTask( std::unique_ptr<Task> task) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); pending_tasks_.push_back(std::move(task)); RunNextRunnableTask(); } void SyncableFileOperationRunner::RunNextRunnableTask() { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); for (auto iter = pending_tasks_.begin(); iter != pending_tasks_.end() && ShouldStartMoreTasks();) { if ((*iter)->IsRunnable(sync_status())) { ++num_inflight_tasks_; DCHECK_GE(num_inflight_tasks_, 1); std::unique_ptr<Task> task = std::move(*iter); pending_tasks_.erase(iter++); task->Start(sync_status()); continue; } ++iter; } } void SyncableFileOperationRunner::OnOperationCompleted( const std::vector<FileSystemURL>& target_paths) { --num_inflight_tasks_; DCHECK_GE(num_inflight_tasks_, 0); for (size_t i = 0; i < target_paths.size(); ++i) { DCHECK(sync_status()->IsWriting(target_paths[i])); sync_status()->EndWriting(target_paths[i]); } RunNextRunnableTask(); } bool SyncableFileOperationRunner::ShouldStartMoreTasks() const { return num_inflight_tasks_ < max_inflight_tasks_; } } // namespace sync_file_system
29.419048
81
0.7135
[ "vector" ]
259deab1e4a130ede1a874158c72dc8f4627922d
991
cpp
C++
ICPC_Mirrors/Nitc_22/gen.cpp
Shahraaz/CP_P_S5
b068ad02d34338337e549d92a14e3b3d9e8df712
[ "MIT" ]
null
null
null
ICPC_Mirrors/Nitc_22/gen.cpp
Shahraaz/CP_P_S5
b068ad02d34338337e549d92a14e3b3d9e8df712
[ "MIT" ]
null
null
null
ICPC_Mirrors/Nitc_22/gen.cpp
Shahraaz/CP_P_S5
b068ad02d34338337e549d92a14e3b3d9e8df712
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #ifdef LOCAL #include "/debug.h" #else #define db(...) #endif #define all(v) v.begin(), v.end() #define pb push_back using ll = long long; const int NAX = 2e5 + 5, MOD = 1000000007; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); void solveCase() { ifstream MyReadFile("/home/shahraaz/Documents/CP/CP_P_S5/ICPC_Mirrors/Nitc_22/in2"); int n = uniform_int_distribution<int>(1, 100)(rng); MyReadFile >> n; cout << n << endl; vector<int> vecc(n); for (size_t i = 0; i < n; i++) vecc[i] = i + 1; shuffle(all(vecc), rng); for (size_t i = 0; i < n; i++) cout << vecc[i] << ' '; cout << '\n'; } int32_t main() { srand(time(NULL)); #ifndef LOCAL // ios_base::sync_with_stdio(0); // cin.tie(0); #endif int t = 1; // cout << t << endl; // int x; // cin >> x; // assert(x == t); for (int i = 1; i <= t; ++i) solveCase(); return 0; }
21.543478
88
0.559031
[ "vector" ]
25a01a370e4d4d5ec0c74846ffad684f2fea7d69
55,863
cxx
C++
inetsrv/query/web/ixsso/ixsso.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetsrv/query/web/ixsso/ixsso.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetsrv/query/web/ixsso/ixsso.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+--------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1996 - 2002. // // File: ixsso.cxx // // Contents: Query SSO class // // History: 25 Oct 1996 Alanw Created // //---------------------------------------------------------------------------- #include "pch.cxx" #pragma hdrstop //----------------------------------------------------------------------------- // Include Files //----------------------------------------------------------------------------- // debugging macros #include "ssodebug.hxx" DECLARE_INFOLEVEL( ixsso ) // class declaration #include "stdcf.hxx" #include "ixsso.hxx" #include <string.hxx> #include <codepage.hxx> #include <initguid.h> #include <adoid.h> // ADO CLSID and IID definitions #include <adoint.h> // ADO interface definition const WCHAR * pwcDefaultDialect = L"2"; extern WCHAR * g_pwszProgIdQuery; #if CIDBG extern ULONG g_ulObjCount; extern LONG g_lQryCount; #endif // CIDBG //----------------------------------------------------------------------------- // // Member: CixssoQuery::CixssoQuery - public // // Synopsis: Constructor of CixssoQuery // // Arguments: [pitlb] - pointer to ITypeLib for ixsso // [pIAdoRecordsetCF] - pointer to the class factory for ADO // recordsets // // History: 06 Nov 1996 Alanw Created // //----------------------------------------------------------------------------- CixssoQuery::CixssoQuery( ITypeLib * pitlb, IClassFactory * pIAdoRecordsetCF, BOOL fAdoV15, const CLSID & ssoClsid) : _pwszRestriction( 0 ), _pwszSort( 0 ), _pwszGroup( 0 ), _pwszColumns( 0 ), _pwszCatalog( 0 ), _pwszDialect( 0 ), _cScopes( 0 ), _apwszScope( 0 ), _aulDepth( 0 ), _fAllowEnumeration( FALSE ), _dwOptimizeFlags( eOptHitCount | eOptRecall ), _maxResults( 0 ), _cFirstRows( 0 ), _iResourceFactor( 0 ), _StartHit( 0 ), _lcid( GetSystemDefaultLCID() ), _ulCodepage( CP_ACP ), _err( IID_IixssoQuery ), _pIAdoRecordsetCF( pIAdoRecordsetCF ), _fAdoV15( fAdoV15 ), _pIRowset( 0 ), _pIRowsetQueryStatus( 0 ), _fSequential( FALSE ), _PropertyList( _ulCodepage ) { _cRef = 1; Win4Assert(g_pTheGlobalIXSSOVariables); SCODE sc; if ( CLSID_CissoQueryEx == ssoClsid ) { _err = IID_IixssoQueryEx; sc = pitlb->GetTypeInfoOfGuid( IID_IixssoQueryEx, &_ptinfo ); } else if ( CLSID_CissoQuery == ssoClsid ) { sc = pitlb->GetTypeInfoOfGuid( IID_IixssoQuery, &_ptinfo ); } else THROW( CException(E_INVALIDARG)); if (FAILED(sc)) { ixssoDebugOut(( DEB_ERROR, "GetTypeInfoOfGuid failed (%x)\n", sc )); Win4Assert(SUCCEEDED(sc)); THROW( CException(sc) ); } #if CIDBG LONG cAdoRecordsetRefs = #endif // CIDBG _pIAdoRecordsetCF->AddRef(); XInterface<IColumnMapper> xColumnMapper; ISimpleCommandCreator *pCmdCreator = 0; pCmdCreator = g_pTheGlobalIXSSOVariables->xCmdCreator.GetPointer(); g_pTheGlobalIXSSOVariables->xColumnMapperCreator->GetColumnMapper( LOCAL_MACHINE, INDEX_SERVER_DEFAULT_CAT, (IColumnMapper **)xColumnMapper.GetQIPointer()); if (0 == pCmdCreator) THROW(CException(REGDB_E_CLASSNOTREG)); _xCmdCreator.Set(pCmdCreator); #if CIDBG LONG cCmdCreatorRefs = #endif // CIDBG pCmdCreator->AddRef(); Win4Assert(xColumnMapper.GetPointer()); _PropertyList.SetDefaultList(xColumnMapper.GetPointer()); INC_OBJECT_COUNT(); ixssoDebugOut((DEB_REFCOUNTS, "[DLL]: Create query: refcounts: glob %d qry %d AdoRSCF %d CmdCtor %d\n", g_ulObjCount, g_lQryCount, cAdoRecordsetRefs, cCmdCreatorRefs )); } CixssoQuery::~CixssoQuery( ) { Reset(); if (_ptinfo) _ptinfo->Release(); #if CIDBG LONG cAdoRecordsetRefs = -2; #endif // CIDBG if (_pIAdoRecordsetCF) #if CIDBG cAdoRecordsetRefs = #endif // CIDBG _pIAdoRecordsetCF->Release(); DEC_OBJECT_COUNT(); #if CIDBG LONG l = InterlockedDecrement( &g_lQryCount ); Win4Assert( l >= 0 ); #endif //CIDBG ixssoDebugOut((DEB_REFCOUNTS, "[DLL]: Delete query: refcounts: glob %d qry %d AdoRSCF %d\n", g_ulObjCount, g_lQryCount, cAdoRecordsetRefs )); } //+--------------------------------------------------------------------------- // // Member: CixssoQuery::Reset - public // // Synopsis: Clear any internal state in the object // // Arguments: - none - // // Notes: Doesn't currently clear lcid or property list. // // History: 05 Mar 1997 Alanw Created // //---------------------------------------------------------------------------- HRESULT CixssoQuery::Reset(void) { _maxResults = 0; _cFirstRows = 0; _cScopes = 0; _fAllowEnumeration = FALSE; _dwOptimizeFlags = eOptHitCount | eOptRecall; if (_pIRowset) { _pIRowset->Release(); _pIRowset = 0; } if (_pIRowsetQueryStatus) { _pIRowsetQueryStatus->Release(); _pIRowsetQueryStatus = 0; } delete _pwszRestriction; _pwszRestriction = 0; delete _pwszSort; _pwszSort = 0; delete _pwszGroup; _pwszGroup = 0; delete _pwszColumns; _pwszColumns = 0; delete _pwszCatalog; _pwszCatalog = 0; delete _pwszDialect; _pwszDialect = 0; // Unneeded since cScopes is set to zero. // _apwszScope.Clear(); _StartHit.Destroy(); return S_OK; } // // ASP Methods // #include <asp/asptlb.h> STDMETHODIMP CixssoQuery::OnStartPage (IUnknown* pUnk) { if ( 0 == pUnk ) return E_INVALIDARG; SCODE sc = S_OK; CTranslateSystemExceptions translate; TRY { // reset the error structure _err.Reset(); SCODE sc; IScriptingContext *piContext = 0; IRequest* piRequest = 0; IRequestDictionary *piRequestDict = 0; ISessionObject* piSession = 0; do { //Get IScriptingContext Interface sc = pUnk->QueryInterface(IID_IScriptingContext, (void**)&piContext); if (FAILED(sc)) break; //Get Request Object Pointer sc = piContext->get_Request(&piRequest); if (FAILED(sc)) break; //Get ServerVariables Pointer sc = piRequest->get_ServerVariables(&piRequestDict); if (FAILED(sc)) break; VARIANT vtOut; VariantInit(&vtOut); // // Get the HTTP_ACCEPT_LANGUAGE Item. Don't need to check the // return code; use a default value for the locale ID // piRequestDict->get_Item(g_vtAcceptLanguageHeader, &vtOut); // //vtOut Contains an IDispatch Pointer. To fetch the value //for HTTP_ACCEPT_LANGUAGE you must get the Default Value for the //Object stored in vtOut using VariantChangeType. // if (V_VT(&vtOut) != VT_BSTR) VariantChangeType(&vtOut, &vtOut, 0, VT_BSTR); if (V_VT(&vtOut) == VT_BSTR) { ixssoDebugOut((DEB_TRACE, "OnStartPage: HTTP_ACCEPT_LANGUAGE = %ws\n", V_BSTR(&vtOut) )); SetLocaleString(V_BSTR(&vtOut)); } else { ixssoDebugOut(( DEB_TRACE, "OnStartPage: HTTP_ACCEPT_LANGAUGE was not set in ServerVariables; using lcid=0x%x\n", GetSystemDefaultLCID() )); put_LocaleID( GetSystemDefaultLCID() ); } VariantClear(&vtOut); _ulCodepage = LocaleToCodepage( _lcid ); //Get Session Object Pointer sc = piContext->get_Session(&piSession); if (FAILED(sc)) { // Don't fail request if sessions are not enabled. This specific // error is given when AspAllowSessionState is zero. if (TYPE_E_ELEMENTNOTFOUND == sc) sc = S_OK; break; } LONG cp = CP_ACP; sc = piSession->get_CodePage( &cp ); if (FAILED(sc)) { // sc = S_OK; break; } if (cp != CP_ACP) _ulCodepage = cp; } while (FALSE); if (piSession) piSession->Release(); if (piRequestDict) piRequestDict->Release(); if (piRequest) piRequest->Release(); if (piContext) piContext->Release(); } CATCH( CException, e ) { sc = e.GetErrorCode(); } END_CATCH return sc; } //----------------------------------------------------------------------------- // CixssoQuery IUnknown Methods //----------------------------------------------------------------------------- STDMETHODIMP CixssoQuery::QueryInterface(REFIID iid, void * * ppv) { *ppv = 0; if (iid == IID_IUnknown || iid == IID_IDispatch) *ppv = (IDispatch *) this; else if (iid == IID_ISupportErrorInfo ) *ppv = (ISupportErrorInfo *) this; else if (iid == IID_IixssoQuery ) *ppv = (IixssoQuery *) this; else if (iid == IID_IixssoQueryPrivate ) *ppv = (IixssoQueryPrivate *) this; else if ( iid == IID_IixssoQueryEx ) *ppv = (IixssoQueryEx *) this; #if 0 else if ( iid == IID_IObjectSafety ) *ppv = (IObjectSafety *) this; #endif else if ( iid == IID_IObjectWithSite ) *ppv = (IObjectWithSite *) this; else return E_NOINTERFACE; AddRef(); return S_OK; } STDMETHODIMP_(ULONG) CixssoQuery::AddRef(void) { return InterlockedIncrement((long *)&_cRef); } STDMETHODIMP_(ULONG) CixssoQuery::Release(void) { ULONG uTmp = InterlockedDecrement((long *)&_cRef); if (uTmp == 0) { delete this; return 0; } return uTmp; } //----------------------------------------------------------------------------- // CixssoQuery IDispatch Methods //----------------------------------------------------------------------------- STDMETHODIMP CixssoQuery::GetTypeInfoCount(UINT * pctinfo) { *pctinfo = 1; return S_OK; } STDMETHODIMP CixssoQuery::GetTypeInfo( UINT itinfo, LCID lcid, ITypeInfo * * pptinfo) { _ptinfo->AddRef(); *pptinfo = _ptinfo; return S_OK; } STDMETHODIMP CixssoQuery::GetIDsOfNames( REFIID riid, OLECHAR * * rgszNames, UINT cNames, LCID lcid, DISPID * rgdispid) { return DispGetIDsOfNames(_ptinfo, rgszNames, cNames, rgdispid); } STDMETHODIMP CixssoQuery::Invoke( DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pParams, VARIANT * pvarResult, EXCEPINFO * pexcepinfo, UINT * puArgErr) { ixssoDebugOut((DEB_IDISPATCH, "Invoking method dispid=%d wFlags=%d\n", dispidMember, wFlags )); _err.Reset(); SCODE sc = DispInvoke( this, _ptinfo, dispidMember, wFlags, pParams, pvarResult, pexcepinfo, puArgErr ); if ( _err.IsError() ) sc = DISP_E_EXCEPTION; return sc; } STDMETHODIMP CixssoQuery::InterfaceSupportsErrorInfo( REFIID riid) { if (IID_IixssoQueryEx == riid || IID_IixssoQuery == riid ) return S_OK; else return S_FALSE; } //----------------------------------------------------------------------------- // CixssoQuery property Methods //----------------------------------------------------------------------------- //+--------------------------------------------------------------------------- // // Member: CixssoQuery::CopyWstrToBstr - private inline // // Synopsis: Copies a Unicode string to a BSTR // // Arguments: [pbstr] - destination BSTR // [pwstr] - string to be copied // // Returns: SCODE - status return // // History: 25 Oct 1996 Alanw Created // //---------------------------------------------------------------------------- inline SCODE CixssoQuery::CopyWstrToBstr( BSTR * pbstr, WCHAR const * pwstr ) { *pbstr = 0; if (pwstr) { *pbstr = SysAllocString( pwstr ); if (0 == *pbstr) return E_OUTOFMEMORY; } return S_OK; } //+--------------------------------------------------------------------------- // // Member: CixssoQuery::CopyBstrToWstr - private inline // // Synopsis: Copies a BSTR to a Unicode string // // Arguments: [bstr] - string to be copied // [rwstr] - destination string // // Returns: SCODE - status return // // History: 25 Oct 1996 Alanw Created // //---------------------------------------------------------------------------- inline SCODE CixssoQuery::CopyBstrToWstr( BSTR bstr, LPWSTR & rwstr ) { SCODE sc = S_OK; if (rwstr) { delete rwstr; rwstr = 0; } if (bstr) { CTranslateSystemExceptions translate; TRY { unsigned cch = SysStringLen( bstr )+1; if (cch > 1) { rwstr = new WCHAR[ cch ]; RtlCopyMemory( rwstr, bstr, cch*sizeof (WCHAR) ); } } CATCH (CException, e) { if (e.GetErrorCode() == STATUS_ACCESS_VIOLATION) sc = E_FAIL; else sc = E_OUTOFMEMORY; SetError( sc, OLESTR("PutProperty") ); } END_CATCH } return sc; } //+--------------------------------------------------------------------------- // // Member: CixssoQuery::CopyBstrToWstr - private inline // // Synopsis: Copies a BSTR to a Unicode string // // Arguments: [bstr] - string to be copied // [apstr] - destination string array // [i] - string array index // // Returns: SCODE - status return // // History: 25 Oct 1996 Alanw Created // //---------------------------------------------------------------------------- inline SCODE CixssoQuery::CopyBstrToWstrArray( BSTR bstr, CDynArray<WCHAR> &apstr, unsigned i ) { SCODE sc = S_OK; if (bstr) { CTranslateSystemExceptions translate; TRY { unsigned cch = SysStringLen( bstr )+1; if (cch > 1) { XArray<WCHAR> wstr( cch ); RtlCopyMemory( wstr.GetPointer(), bstr, cch*sizeof (WCHAR) ); delete apstr.Acquire( i ); apstr.Add( wstr.GetPointer(), i ); wstr.Acquire(); } else apstr.Add( 0, i ); } CATCH (CException, e) { if (e.GetErrorCode() == STATUS_ACCESS_VIOLATION) sc = E_FAIL; else sc = E_OUTOFMEMORY; SetError( sc, OLESTR("CopyBstrToWstrArray") ); } END_CATCH } else apstr.Add( 0, i ); return sc; } inline SCODE CixssoQuery::GetBoolProperty( VARIANT_BOOL * pfVal, BOOL fMemberVal ) { *pfVal = fMemberVal ? VARIANT_TRUE : VARIANT_FALSE; return S_OK; } inline SCODE CixssoQuery::PutBoolProperty( VARIANT_BOOL fInputVal, BOOL & fMemberVal ) { fMemberVal = (fInputVal == VARIANT_TRUE) ? TRUE : FALSE; return S_OK; } //----------------------------------------------------------------------------- // CixssoQuery read-write properties //----------------------------------------------------------------------------- STDMETHODIMP CixssoQuery::get_Query(BSTR * pstr) { _err.Reset(); return CopyWstrToBstr( pstr, _pwszRestriction ); } STDMETHODIMP CixssoQuery::put_Query(BSTR str) { _err.Reset(); return CopyBstrToWstr( str, _pwszRestriction ); } STDMETHODIMP CixssoQuery::get_GroupBy(BSTR * pstr) { _err.Reset(); #if IXSSO_CATEGORIZE == 1 return CopyWstrToBstr( pstr, _pwszGroup ); #else // IXSSO_CATEGORIZE return E_NOTIMPL; #endif // IXSSO_CATEGORIZE } STDMETHODIMP CixssoQuery::put_GroupBy(BSTR str) { _err.Reset(); #if IXSSO_CATEGORIZE == 1 return CopyBstrToWstr( str, _pwszGroup ); #else // IXSSO_CATEGORIZE return E_NOTIMPL; #endif // IXSSO_CATEGORIZE } STDMETHODIMP CixssoQuery::get_Columns(BSTR * pstr) { _err.Reset(); return CopyWstrToBstr( pstr, _pwszColumns ); } STDMETHODIMP CixssoQuery::put_Columns(BSTR str) { _err.Reset(); return CopyBstrToWstr( str, _pwszColumns ); } STDMETHODIMP CixssoQuery::get_LocaleID(LONG * plVal) { _err.Reset(); *plVal = _lcid; return S_OK; } STDMETHODIMP CixssoQuery::put_LocaleID(LONG lVal) { _err.Reset(); _lcid = lVal; return S_OK; } STDMETHODIMP CixssoQuery::get_CodePage(LONG * plVal) { _err.Reset(); *plVal = _ulCodepage; return S_OK; } STDMETHODIMP CixssoQuery::put_CodePage(LONG lVal) { _err.Reset(); if (0 == IsValidCodePage( lVal ) ) { return E_INVALIDARG; } _ulCodepage = lVal; return S_OK; } STDMETHODIMP CixssoQuery::get_SortBy(BSTR * pstr) { _err.Reset(); return CopyWstrToBstr( pstr, _pwszSort ); } STDMETHODIMP CixssoQuery::put_SortBy(BSTR str) { _err.Reset(); return CopyBstrToWstr( str, _pwszSort ); } STDMETHODIMP CixssoQuery::get_CiScope(BSTR * pstr) { _err.Reset(); if (_cScopes > 1) { SetError( E_INVALIDARG, OLESTR("get CiScope") ); return _err.GetError(); } return CopyWstrToBstr( pstr, _apwszScope.Get(0) ); } STDMETHODIMP CixssoQuery::put_CiScope(BSTR str) { _err.Reset(); if (_cScopes > 1) { SetError( E_INVALIDARG, OLESTR("set CiScope") ); return _err.GetError(); } SCODE sc = CopyBstrToWstrArray( str, _apwszScope, 0 ); if (SUCCEEDED(sc)) { _cScopes = (_apwszScope[0] == 0) ? 0 : 1; } return sc; } STDMETHODIMP CixssoQuery::get_CiFlags(BSTR * pstr) { _err.Reset(); if (_cScopes > 1) { SetError( E_INVALIDARG, OLESTR("get CiFlags") ); return _err.GetError(); } ULONG ulDepth = QUERY_DEEP; if (_aulDepth.Count() > 0) ulDepth = _aulDepth[0]; WCHAR * pwszDepth = ulDepth & QUERY_DEEP ? L"DEEP" : L"SHALLOW"; return CopyWstrToBstr( pstr, pwszDepth ); } STDMETHODIMP CixssoQuery::put_CiFlags(BSTR str) { _err.Reset(); SCODE sc = S_OK; if (_cScopes > 1) { SetError( E_INVALIDARG, OLESTR("set CiFlags") ); return _err.GetError(); } CTranslateSystemExceptions translate; TRY { ULONG ulDepth = ParseCiDepthFlag( str ); _aulDepth[0] = ulDepth; } CATCH( CIxssoException, e ) { sc = e.GetErrorCode(); Win4Assert( !SUCCEEDED(sc) ); SetError( sc, OLESTR("set CiFlags"), eIxssoError ); } AND_CATCH( CException, e ) { sc = e.GetErrorCode(); SetError( sc, OLESTR("set CiFlags") ); } END_CATCH return sc; } STDMETHODIMP CixssoQuery::get_Catalog(BSTR * pstr) { _err.Reset(); return CopyWstrToBstr( pstr, _pwszCatalog ); } STDMETHODIMP CixssoQuery::put_Catalog(BSTR str) { _err.Reset(); return CopyBstrToWstr( str, _pwszCatalog ); } STDMETHODIMP CixssoQuery::get_Dialect(BSTR * pstr) { _err.Reset(); return CopyWstrToBstr( pstr, _pwszDialect ? _pwszDialect : pwcDefaultDialect ); } STDMETHODIMP CixssoQuery::put_Dialect(BSTR str) { _err.Reset(); // // Do some validation first // ULONG ulDialect = (ULONG) _wtoi( str ); if ( ulDialect < ISQLANG_V1 || ulDialect > ISQLANG_V2 ) { SetError( E_INVALIDARG, OLESTR("set Dialect") ); return _err.GetError(); } return CopyBstrToWstr( str, _pwszDialect ); } STDMETHODIMP CixssoQuery::get_OptimizeFor(BSTR * pstr) { _err.Reset(); WCHAR * pwszChoice = L"recall"; switch (_dwOptimizeFlags) { case 0: pwszChoice = L"nohitcount"; break; case eOptPerformance: pwszChoice = L"performance,nohitcount"; break; case eOptRecall: pwszChoice = L"recall,nohitcount"; break; case eOptPerformance|eOptHitCount: pwszChoice = L"performance,hitcount"; break; case eOptRecall|eOptHitCount: pwszChoice = L"recall,hitcount"; break; case eOptHitCount: pwszChoice = L"hitcount"; break; default: Win4Assert( !"Invalid value in _dwOptimizeFlags!" ); } return CopyWstrToBstr( pstr, pwszChoice ); } STDMETHODIMP CixssoQuery::put_OptimizeFor(BSTR str) { _err.Reset(); DWORD eChoice; SCODE sc = ParseOptimizeFor( str, eChoice ); if (SUCCEEDED(sc)) { _dwOptimizeFlags = eChoice; return sc; } else { SetError( sc, OLESTR("set OptimizeFor") ); return _err.GetError(); } } STDMETHODIMP CixssoQuery::get_AllowEnumeration(VARIANT_BOOL * pfFlag) { _err.Reset(); return GetBoolProperty( pfFlag, _fAllowEnumeration ); } STDMETHODIMP CixssoQuery::put_AllowEnumeration(VARIANT_BOOL fFlag) { _err.Reset(); return PutBoolProperty( fFlag, _fAllowEnumeration ); } STDMETHODIMP CixssoQuery::get_MaxRecords(LONG * plVal) { _err.Reset(); *plVal = _maxResults; return S_OK; } STDMETHODIMP CixssoQuery::put_MaxRecords(LONG lVal) { _err.Reset(); if (lVal < 0) { SetError( E_INVALIDARG, OLESTR("set MaxRecords") ); return _err.GetError(); } else if (IsQueryActive()) { SetError( MSG_IXSSO_QUERY_ACTIVE, OLESTR("set MaxRecords") ); return _err.GetError(); } _maxResults = lVal; return S_OK; } STDMETHODIMP CixssoQuery::get_FirstRows(LONG * plVal) { _err.Reset(); *plVal = _cFirstRows; return S_OK; } STDMETHODIMP CixssoQuery::put_FirstRows(LONG lVal) { _err.Reset(); if (lVal < 0) { SetError( E_INVALIDARG, OLESTR("set FirstRows") ); return _err.GetError(); } else if (IsQueryActive()) { SetError( MSG_IXSSO_QUERY_ACTIVE, OLESTR("set FirstRows") ); return _err.GetError(); } _cFirstRows = lVal; return S_OK; } STDMETHODIMP CixssoQuery::get_StartHit(VARIANT * pvar) { _err.Reset(); if (_StartHit.Get() != 0) { XGrowable<WCHAR> awchBuf; FormatLongVector( _StartHit.Get(), awchBuf ); VariantInit( pvar ); V_BSTR(pvar) = SysAllocString( awchBuf.Get() ); if ( V_BSTR(pvar) != 0 ) { V_VT(pvar) = VT_BSTR; } else { return E_OUTOFMEMORY; } } else { V_VT(pvar) = VT_EMPTY; } return S_OK; } STDMETHODIMP CixssoQuery::put_StartHit(VARIANT* pvar) { _err.Reset(); // // NOTE: StartHit is not read-only with an active query so it can // be set from the recordset prior to calling QueryToURL. // SCODE sc; SAFEARRAY* psa; XSafeArray xsa; switch( V_VT(pvar) ) { case VT_DISPATCH: // //pvar Contains an IDispatch Pointer. To fetch the value //you must get the Default Value for the //Object stored in pvar using VariantChangeType. // VariantChangeType(pvar, pvar, 0, VT_BSTR); if (V_VT(pvar) != VT_BSTR) { return E_INVALIDARG; } // NOTE: fall through case VT_BSTR: { CDynArrayInPlace<LONG> aStartHit( 0 ); ParseNumberVectorString( V_BSTR(pvar), aStartHit ); unsigned cHits = aStartHit.Count(); psa = SafeArrayCreateVector(VT_I4, 1, cHits); if ( ! psa ) return E_OUTOFMEMORY; xsa.Set(psa); for (unsigned i=1; i<=cHits; i++) { long rgIx[1]; LONG lVal = aStartHit.Get(i-1); rgIx[0] = (long)i; sc = SafeArrayPutElement( xsa.Get(), rgIx, &lVal ); if ( FAILED(sc) ) break; } if ( FAILED(sc) ) return sc; } break; case VT_ARRAY | VT_I4: sc = SafeArrayCopy(V_ARRAY(pvar),&psa); if ( FAILED(sc) ) return sc; xsa.Set(psa); if (SafeArrayGetDim(psa) != 1) return E_INVALIDARG; break; case VT_I4: case VT_I2: psa = SafeArrayCreateVector(VT_I4,1,1); if ( ! psa ) return E_OUTOFMEMORY; xsa.Set(psa); { long rgIx[1]; rgIx[0] = 1; long lVal = (V_VT(pvar) == VT_I4) ? V_I4(pvar) : V_I2(pvar); sc = SafeArrayPutElement( xsa.Get(), rgIx, &lVal ); if ( FAILED( sc ) ) return sc; } break; default: SetError( E_INVALIDARG, OLESTR("set StartHit") ); return _err.GetError(); } _StartHit.Destroy(); _StartHit.Set( xsa.Acquire() ); return S_OK; } STDMETHODIMP CixssoQuery::get_ResourceUseFactor(LONG * plVal) { _err.Reset(); *plVal = _iResourceFactor; return S_OK; } STDMETHODIMP CixssoQuery::put_ResourceUseFactor(LONG lVal) { _err.Reset(); if (IsQueryActive()) { SetError( MSG_IXSSO_QUERY_ACTIVE, OLESTR("set ResourceUseFactor") ); return _err.GetError(); } _iResourceFactor = lVal; return S_OK; } //----------------------------------------------------------------------------- // CixssoQuery read-only properties //----------------------------------------------------------------------------- //+--------------------------------------------------------------------------- // // Member: CixssoQuery::CheckQueryStatusBit - private inline // // Synopsis: Check a specific query status bit, set variant bool accordingly // // Arguments: [pfVal] - VARIANT_BOOL to be set // [dwBit] - bit(s) in query status to be tested // // Returns: SCODE - status return // // History: 03 Jan 1997 Alanw Created // //---------------------------------------------------------------------------- inline SCODE CixssoQuery::CheckQueryStatusBit( VARIANT_BOOL * pfVal, DWORD dwBit ) { SCODE sc = S_OK; CTranslateSystemExceptions translate; TRY { DWORD dwStatus = GetQueryStatus( ); *pfVal = (dwStatus & dwBit) ? VARIANT_TRUE : VARIANT_FALSE; } CATCH( CIxssoException, e ) { sc = e.GetErrorCode(); Win4Assert( !SUCCEEDED(sc) ); SetError( sc, OLESTR("CheckQueryStatus"), eIxssoError ); } AND_CATCH( CException, e ) { sc = e.GetErrorCode(); SetError( sc, OLESTR("CheckQueryStatus") ); } END_CATCH return sc; } STDMETHODIMP CixssoQuery::get_QueryTimedOut(VARIANT_BOOL * pfFlag) { _err.Reset(); return CheckQueryStatusBit( pfFlag, STAT_TIME_LIMIT_EXCEEDED ); } STDMETHODIMP CixssoQuery::get_QueryIncomplete(VARIANT_BOOL * pfFlag) { _err.Reset(); return CheckQueryStatusBit( pfFlag, STAT_CONTENT_QUERY_INCOMPLETE ); } STDMETHODIMP CixssoQuery::get_OutOfDate(VARIANT_BOOL * pfFlag) { _err.Reset(); return CheckQueryStatusBit( pfFlag, (STAT_CONTENT_OUT_OF_DATE | STAT_REFRESH_INCOMPLETE) ); } //----------------------------------------------------------------------------- // CixssoQuery Methods //----------------------------------------------------------------------------- STDMETHODIMP CixssoQuery::AddScopeToQuery( BSTR bstrScope, BSTR bstrDepth) { // // This is an internally used method, so don't need to reset error object here. // if (0 == bstrScope || 0 == SysStringLen(bstrScope) ) { THROW( CException(E_INVALIDARG) ); } SCODE sc = CopyBstrToWstrArray( bstrScope, _apwszScope, _cScopes ); if (FAILED(sc)) { THROW( CException(sc) ); } ULONG ulDepth = ParseCiDepthFlag( bstrDepth ); _aulDepth[_cScopes] = ulDepth; _cScopes++; return S_OK; } STDMETHODIMP CixssoQuery::DefineColumn( BSTR bstrColDefinition) { _err.Reset(); SCODE sc = S_OK; CTranslateSystemExceptions translate; TRY { CQueryScanner scanner( bstrColDefinition, FALSE ); XPtr<CPropEntry> xpropentry; CPropertyList::ParseOneLine( scanner, 0, xpropentry ); if (xpropentry.GetPointer()) sc = _PropertyList.AddEntry( xpropentry, 0 ); } CATCH( CPListException, e ) { sc = e.GetPListError(); Win4Assert( !SUCCEEDED(sc) ); SetError( sc, OLESTR("DefineColumn"), ePlistError ); } AND_CATCH( CException, e ) { sc = e.GetErrorCode(); SetError( sc, OLESTR("DefineColumn") ); } END_CATCH return sc; } //+--------------------------------------------------------------------------- // // Member: CixssoQuery::CreateRecordset - public // // Synopsis: Executes the query and returns a recordset // // Arguments: [bstrSequential] - one of "SEQUENTIAL" or "NONSEQUENTIAL", // selects whether a nonsequential query is used. // [ppDisp] - recordset is returned here. // // History: 06 Nov 1996 Alanw Created // //---------------------------------------------------------------------------- STDMETHODIMP CixssoQuery::CreateRecordset( BSTR bstrSequential, IDispatch * * ppDisp) { _err.Reset(); unsigned eErrorClass = 0; BOOL fSetErrorNeeded = TRUE; if (IsQueryActive()) { SetError( MSG_IXSSO_QUERY_ACTIVE, OLESTR("CreateRecordset") ); return _err.GetError(); } SCODE sc = S_OK; CTranslateSystemExceptions translate; TRY { IsSafeForScripting(); *ppDisp = 0; if ( bstrSequential && 0 == _wcsicmp(bstrSequential, L"SEQUENTIAL") ) _fSequential = TRUE; else if ( bstrSequential && (0 == _wcsicmp(bstrSequential, L"NONSEQUENTIAL") || 0 == _wcsicmp(bstrSequential, L"NON-SEQUENTIAL")) ) _fSequential = FALSE; else { SetError( E_INVALIDARG, OLESTR("CreateRecordset") ); return _err.GetError(); } ExecuteQuery(); Win4Assert( _pIRowset != 0 ); Win4Assert( _pIRowsetQueryStatus != 0 ); // // Create an empty recordset, and put our rowset in it. // IDispatch * pRecordset = 0; sc = _pIAdoRecordsetCF->CreateInstance( 0, IID_IDispatch, (void **)&pRecordset ); ADORecordsetConstruction * pRecordsetConstruction = 0; if ( SUCCEEDED(sc) ) { sc = pRecordset->QueryInterface( IID_IADORecordsetConstruction, (void **)&pRecordsetConstruction ); } if (SUCCEEDED(sc)) { sc = pRecordsetConstruction->put_Rowset( _pIRowset ); pRecordsetConstruction->Release(); } if (SUCCEEDED(sc)) { *ppDisp = pRecordset; } if (FAILED(sc)) { if (pRecordset) pRecordset->Release(); pRecordset = 0; _pIRowset->Release(); _pIRowset = 0; _pIRowsetQueryStatus->Release(); _pIRowsetQueryStatus = 0; } fSetErrorNeeded = FAILED(sc); } CATCH( CPListException, e ) { sc = e.GetPListError(); eErrorClass = ePlistError; Win4Assert( !SUCCEEDED(sc) ); } AND_CATCH( CIxssoException, e ) { sc = e.GetErrorCode(); eErrorClass = eIxssoError; Win4Assert( !SUCCEEDED(sc) ); } AND_CATCH( CParserException, e ) { sc = e.GetParseError(); eErrorClass = eParseError; Win4Assert( !SUCCEEDED(sc) ); } AND_CATCH( CPostedOleDBException, e ) { // // When the execution error was detected, the Ole DB error // info was retrieved and stored in the exception object. // We retrieve that here and compose the error message. // sc = e.GetErrorCode(); Win4Assert( !SUCCEEDED(sc) ); XInterface <IErrorInfo> xErrorInfo(e.AcquireErrorInfo()); if (xErrorInfo.GetPointer()) { BSTR bstrErrorDescription = 0; xErrorInfo->GetDescription(&bstrErrorDescription); if (bstrErrorDescription) { SetError( sc, OLESTR("CreateRecordset"), (WCHAR const *)bstrErrorDescription); SysFreeString(bstrErrorDescription); fSetErrorNeeded = FALSE; } else eErrorClass = eDefaultError; } } AND_CATCH( CException, e ) { sc = e.GetErrorCode(); eErrorClass = eDefaultError; Win4Assert( !SUCCEEDED(sc) ); } END_CATCH if (! SUCCEEDED(sc) && fSetErrorNeeded) SetError( sc, OLESTR("CreateRecordset"), eErrorClass ); return sc; } //+--------------------------------------------------------------------------- // // Member: CixssoQuery::ParseOptimizeFor - private static // // Synopsis: Parse the input string for the OptimizeFor property // // Arguments: [wcsOptString] - input string // [eChoice] - OptimizeFor choice expressed in wcsOptString // // Returns: SCODE - status return // // History: 05 Mar 1997 Alanw Created // //---------------------------------------------------------------------------- SCODE CixssoQuery::ParseOptimizeFor( WCHAR const * wcsOptString, DWORD & eChoice ) { eChoice = eOptHitCount; while (wcsOptString && *wcsOptString) { WCHAR * wcsNext = wcschr( wcsOptString, ',' ); ULONG cch = (wcsNext) ? CiPtrToUlong( wcsNext - wcsOptString ) : wcslen( wcsOptString ); if ( 11 == cch && _wcsnicmp(wcsOptString, L"performance", 11) == 0) { eChoice |= eOptPerformance; } else if ( 6 == cch && _wcsnicmp(wcsOptString, L"recall", 6) == 0) { eChoice |= eOptRecall; } else if ( 8 == cch && _wcsnicmp(wcsOptString, L"hitcount", 8) == 0) { eChoice |= eOptHitCount; } else if ( 10 == cch && _wcsnicmp(wcsOptString, L"nohitcount", 10) == 0) { eChoice &= ~eOptHitCount; } else return E_INVALIDARG; wcsOptString = wcsNext; if (wcsOptString) { wcsOptString++; while (iswspace( *wcsOptString )) wcsOptString++; } } // 'performance' and 'recall' are mutually exclusive. Check if both // were set. if ( (eChoice & (eOptRecall | eOptPerformance)) == (eOptRecall | eOptPerformance) ) return E_INVALIDARG; return S_OK; } //+--------------------------------------------------------------------------- // // Member: CixssoQuery::ParseCiDepthFlag, private // // Synopsis: Parses the flags attribute // // Arguments: [bstrFlags] -- flags // // Returns: ULONG - query scope flags // // History: 96/Jan/03 DwightKr created // //---------------------------------------------------------------------------- ULONG CixssoQuery::ParseCiDepthFlag( BSTR bstrFlags ) { if ( 0 == bstrFlags || 0 == SysStringLen(bstrFlags) ) { return QUERY_DEEP; } ULONG ulFlags; if ( _wcsicmp(bstrFlags, L"SHALLOW") == 0 ) { ulFlags = QUERY_SHALLOW; } else if ( _wcsicmp(bstrFlags, L"DEEP") == 0 ) { ulFlags = QUERY_DEEP; } else { THROW( CIxssoException(MSG_IXSSO_EXPECTING_SHALLOWDEEP, 0) ); } return ulFlags; } //+--------------------------------------------------------------------------- // // Member: CixssoQuery::SetLocaleString - private // // Synopsis: Parse the input string for a recognizable locale name // // Arguments: [bstrLocale] - input string // // Returns: SCODE - status return // // History: 13 Mar 1997 Alanw Created // //---------------------------------------------------------------------------- SCODE CixssoQuery::SetLocaleString(BSTR str) { LCID lcidTemp = GetLCIDFromString( str ); if (lcidTemp == -1) { return E_INVALIDARG; } _lcid = lcidTemp; return S_OK; } //+--------------------------------------------------------------------------- // // Function: ParseNumberVectorString - public // // Synopsis: Parses a string consisting of ',' separated numeric values // into an array. // // Arguments: [pwszValue] - input string // [aNum] - dynamic array where numbers are placed. // // History: 10 Jun 1997 Alanw Created // //---------------------------------------------------------------------------- void ParseNumberVectorString( WCHAR * pwszValue, CDynArrayInPlace<LONG> & aNum ) { while (pwszValue) { LONG lNum = _wtoi( pwszValue ); aNum[aNum.Count()] = lNum; pwszValue = wcschr(pwszValue, L','); if (pwszValue) pwszValue++; } } void FormatLongVector( SAFEARRAY * psa, XGrowable<WCHAR> & awchBuf ) { Win4Assert( SafeArrayGetDim( psa ) == 1 && SafeArrayGetElemsize( psa ) == sizeof (LONG) ); LONG iLBound = 0; LONG iUBound = 0; SCODE sc = SafeArrayGetLBound( psa, 1, &iLBound ); if (SUCCEEDED(sc)) sc = SafeArrayGetUBound( psa, 1, &iUBound ); unsigned cch = 0; for (int i=iLBound; i<= iUBound; i++) { LONG lValue; LONG ix[1]; ix[0] = i; sc = SafeArrayGetElement( psa, ix, &lValue ); awchBuf.SetSize(cch + 20); if (i != iLBound) { awchBuf[cch] = L','; cch++; } _itow( lValue, &awchBuf[cch], 10 ); cch += wcslen( &awchBuf[cch] ); } } // CIXSSOPropertyList methods //+------------------------------------------------------------------------- // // Member: CIXSSOPropertyList::CIXSSOPropertyList, public // // Synopsis: Constructs a property mapper for the ixsso's use. // // Parameters: [pDefaultList] -- The default column mapper. // // History: 26-Aug-97 KrishnaN Created // //-------------------------------------------------------------------------- CIXSSOPropertyList::CIXSSOPropertyList(ULONG ulCodePage) : _cRefs( 1 ), _ulCodePage( ulCodePage ), _xDefaultList(0) { // default list is not known. Use SetDefaultList to set that } // Set the defualt list void CIXSSOPropertyList::SetDefaultList(IColumnMapper *pDefaultList) { Win4Assert(pDefaultList); _xDefaultList.Set(pDefaultList); _xDefaultList->AddRef(); } //+------------------------------------------------------------------------- // // Member: CIXSSOPropertyList::QueryInterface, public // // Arguments: [ifid] -- Interface id // [ppiuk] -- Interface return pointer // // History: 26-Aug-97 KrishnaN Created // //-------------------------------------------------------------------------- STDMETHODIMP CIXSSOPropertyList::QueryInterface( REFIID ifid, void ** ppiuk ) { if (0 == ppiuk) return E_INVALIDARG; if ( IID_IUnknown == ifid ) { AddRef(); *ppiuk = (void *)((IUnknown *)this); return S_OK; } else if (IID_IColumnMapper == ifid ) { AddRef(); *ppiuk = (void *)((IColumnMapper *)this); return S_OK; } else { *ppiuk = 0; return E_NOINTERFACE; } } //+------------------------------------------------------------------------- // // Member: CIXSSOPropertyList::AddRef, public // // Synopsis: Reference the virtual table. // // History: 26-Aug-97 KrishnaN Created // //-------------------------------------------------------------------------- STDMETHODIMP_(ULONG) CIXSSOPropertyList::AddRef(void) { InterlockedIncrement( &_cRefs ); return( _cRefs ); } //+------------------------------------------------------------------------- // // Member: CIXSSOPropertyList::Release, public // // Synopsis: De-Reference the virtual table. // // Effects: If the ref count goes to 0 then the table is deleted. // // History: 26-Aug-97 KrishnaN Created // //-------------------------------------------------------------------------- STDMETHODIMP_(ULONG) CIXSSOPropertyList::Release(void) { unsigned long uTmp = InterlockedDecrement( &_cRefs ); if (0 == uTmp) { delete this; } return(uTmp); } // // IColumnMapper methods // //+------------------------------------------------------------------------- // // Member: CIXSSOPropertyList::GetPropInfoFromName, public // // Synopsis: Get property info. from name. // // Parameters: [wcsPropName] -- Property name to look up. // [ppPropId] -- Ptr to return Id of the property. // [pPropType] -- Ptr to return type of the property. // [puiWidth] -- Ptr to return property width. // // History: 26-Aug-97 KrishnaN Created // //-------------------------------------------------------------------------- SCODE CIXSSOPropertyList::GetPropInfoFromName(const WCHAR *wcsPropName, DBID * *ppPropId, DBTYPE *pPropType, unsigned int *puiWidth) { // // Callers can pass in 0 for pPropType and puiWidth if they // don't care about them. // if (0 == wcsPropName || 0 == ppPropId) return E_INVALIDARG; Win4Assert(_xDefaultList.GetPointer()); // // First check in the default list, then in the override list. // SCODE sc = _xDefaultList->GetPropInfoFromName(wcsPropName, ppPropId, pPropType, puiWidth); if (FAILED(sc) && 0 != _xOverrideList.GetPointer()) { sc = _xOverrideList->GetPropInfoFromName(wcsPropName, ppPropId, pPropType, puiWidth); } return sc; } //+------------------------------------------------------------------------- // // Member: CIXSSOPropertyList::GetPropInfoFromId, public // // Synopsis: Get property info. from dbid. // // Parameters: [pPropId] -- Ptr to prop to look up. // [pwcsName] -- Ptr to return property name. // [pPropType] -- Ptr to return type of the property. // [puiWidth] -- Ptr to return property width. // // History: 26-Aug-97 KrishnaN Created // //-------------------------------------------------------------------------- SCODE CIXSSOPropertyList::GetPropInfoFromId(const DBID *pPropId, WCHAR * *pwcsName, DBTYPE *pPropType, unsigned int *puiWidth) { Win4Assert(!"Not available!"); return E_NOTIMPL; #if 0 // complete, working implementation, but not needed. // // Callers can pass in 0 for pPropType and puiWidth if they // don't care about them. // if (0 == pwcsName || 0 == pPropId) return E_INVALIDARG; // // First check in the default list, then in the override list. // SCODE sc = _xDefaultList->GetPropInfoFromId(pPropId, pwcsName, pPropType, puiWidth); if (FAILED(sc) && 0 != _xOverrideList.GetPointer()) { sc = _xOverrideList->GetPropInfoFromId(pPropId, pwcsName, pPropType, puiWidth); } return sc; #endif // 0 } //+------------------------------------------------------------------------- // // Member: CIXSSOPropertyList::EnumPropInfo, public // // Synopsis: Gets the i-th entry from the list of properties. // // Parameters: [iEntry] -- i-th entry to retrieve (0-based). // [pwcsName] -- Ptr to return property name. // [ppPropId] -- Ptr to return Id of the property. // [pPropType] -- Ptr to return type of the property. // [puiWidth] -- Ptr to return property width. // // History: 26-Aug-97 KrishnaN Created // //-------------------------------------------------------------------------- SCODE CIXSSOPropertyList::EnumPropInfo(ULONG iEntry, const WCHAR * *pwcsName, DBID * *ppPropId, DBTYPE *pPropType, unsigned int *puiWidth) { Win4Assert(!"Not available!"); return E_NOTIMPL; } //+------------------------------------------------------------------------- // // Member: CIXSSOPropertyList::IsMapUpToDate, public // // Synopsis: Indicates if the column map is up to date. // // History: 26-Aug-97 KrishnaN Created // //-------------------------------------------------------------------------- SCODE CIXSSOPropertyList::IsMapUpToDate() { Win4Assert(_xDefaultList.GetPointer()); // return the IsMapUpToDate of the default list. // the override list is always considered to be // upto date. return _xDefaultList->IsMapUpToDate(); } //+--------------------------------------------------------------------------- // // Member: CIXSSOPropertyList::AddEntry, private // // Synopsis: Adds a CPropEntry to the overriding list. Verifies that the name // isn't already in the default list or the overriding list. // // Arguments: [xPropEntry] -- CPropEntry to add. Acquired on success // [iLine] -- line number we're parsing // // Returns: S_OK on success or S_ // // History: 11-Sep-97 KrishnaN Created. // //---------------------------------------------------------------------------- SCODE CIXSSOPropertyList::AddEntry( XPtr<CPropEntry> & xPropEntry, int iLine ) { Win4Assert(_xDefaultList.GetPointer()); SCODE sc = S_OK; // protect _xOverrideList CLock lock(_mtxAdd); // // We do not allow entries in the override list that have the same name // as the default list. // DBID *pPropId; DBTYPE PropType; unsigned uWidth; if ( S_OK == GetPropInfoFromName( xPropEntry->GetName(), &pPropId, &PropType, &uWidth )) { if ( PropType != xPropEntry->GetPropType() || ( uWidth != xPropEntry->GetWidth() && xPropEntry->GetWidth() != PLIST_DEFAULT_WIDTH ) ) { THROW( CPListException( QPLIST_E_DUPLICATE, iLine ) ); } else sc = QPLIST_S_DUPLICATE; } if ( S_OK == sc ) { if (0 == _xOverrideList.GetPointer()) _xOverrideList.Set(new CPropertyList(_ulCodePage)); _xOverrideList->AddEntry( xPropEntry.GetPointer(), iLine); xPropEntry.Acquire(); } return sc; } //AddEntry #if 0 HRESULT CixssoQuery::GetInterfaceSafetyOptions( REFIID riid, DWORD * pdwSupportedOptions, DWORD * pdwEnabledOptions ) { if ( 0 == pdwSupportedOptions || 0 == pdwEnabledOptions ) return E_POINTER; ixssoDebugOut(( DEB_ITRACE, "get safety options called...\n" )); *pdwSupportedOptions = INTERFACESAFE_FOR_UNTRUSTED_CALLER; *pdwEnabledOptions = 0; return S_OK; } //GetInterfaceSafetyOptions HRESULT CixssoQuery::SetInterfaceSafetyOptions( REFIID riid, DWORD dwOptionSetMask, DWORD dwEnabledOptions ) { ixssoDebugOut(( DEB_ITRACE, "set setmask: %#x\n", dwOptionSetMask )); ixssoDebugOut(( DEB_ITRACE, "set enabled: %#x\n", dwEnabledOptions )); _dwSafetyOptions = (dwEnabledOptions & dwOptionSetMask); return S_OK; } //SetInterfaceSafetyOptions #endif //+------------------------------------------------------------------------- // // Member: CixssoQuery::SetSite, public // // Synopsis: Sets the current site (if any). Called by containers of // CixssoQuery like IE. Not called by other containers like // ASP and CScript. // // Arguments: [pSite] -- The container of this query object // // Returns: HRESULT // // History: 09-Nov-00 dlee Created // //-------------------------------------------------------------------------- HRESULT CixssoQuery::SetSite( IUnknown * pSite ) { _xSite.Free(); if ( 0 != pSite ) { pSite->AddRef(); _xSite.Set( pSite ); } ixssoDebugOut(( DEB_ITRACE, "setting site: %#x\n", pSite )); return S_OK; } //SetSite //+------------------------------------------------------------------------- // // Member: CixssoQuery::GetSite, public // // Synopsis: Retrieves the current site (if any) // // Arguments: [riid] -- IID requested // [ppvSite] -- Where the interface pointer is returned // // Returns: HRESULT like a QueryInterface() // // History: 09-Nov-00 dlee Created // //-------------------------------------------------------------------------- HRESULT CixssoQuery::GetSite( REFIID riid, void ** ppvSite ) { ixssoDebugOut(( DEB_ITRACE, "getsite\n" )); if ( 0 == ppvSite ) return E_POINTER; *ppvSite = 0; if ( _xSite.IsNull() ) return E_NOINTERFACE; return _xSite->QueryInterface( riid, ppvSite ); } //GetSite //+------------------------------------------------------------------------- // // Member: CixssoQuery::IsSafeForScripting, private // // Synopsis: Checks if it's ok to execute in the current context. Throws // an exception if it's not safe or on error. It's not safe // to execute script off a remote machine. // // History: 09-Nov-00 dlee Created // //-------------------------------------------------------------------------- void CixssoQuery::IsSafeForScripting() { XInterface<IServiceProvider> xServiceProvider; SCODE sc = GetSite( IID_IServiceProvider, xServiceProvider.GetQIPointer() ); // // When queries are run in IIS the container does not call // SetSite, so there is no site and we'll have E_NOINTERFACE // at this point. Same for cscript.exe queries. // If that ever changes, the check below for file:// URLs will // fail and no IIS queries will ever work. // if ( E_NOINTERFACE == sc ) return; if ( FAILED( sc ) ) THROW( CException( sc ) ); XInterface<IWebBrowser2> xWebBrowser; sc = xServiceProvider->QueryService( SID_SWebBrowserApp, IID_IWebBrowser2, xWebBrowser.GetQIPointer() ); if ( E_NOINTERFACE == sc ) return; if ( FAILED( sc ) ) THROW( CException( sc ) ); BSTR bstrURL; sc = xWebBrowser->get_LocationURL( &bstrURL ); if ( FAILED( sc ) ) THROW( CException( sc ) ); XBStr xURL( bstrURL ); ixssoDebugOut(( DEB_ITRACE, "url: %ws\n", bstrURL )); WCHAR buf[32]; URL_COMPONENTS uc; RtlZeroMemory( &uc, sizeof uc ); uc.dwStructSize = sizeof uc; uc.lpszScheme = buf; uc.dwSchemeLength = sizeof buf / sizeof WCHAR; INTERNET_SCHEME scheme = INTERNET_SCHEME_UNKNOWN; if ( InternetCrackUrl( bstrURL, wcslen( bstrURL ), ICU_DECODE, &uc ) ) scheme = uc.nScheme; // The URL has to be a file:/// URL or we won't allow it. if ( INTERNET_SCHEME_FILE != scheme ) THROW( CException( E_ACCESSDENIED ) ); // OK, now it can't be a UNC path. Look for a drive letter and a colon // file:///c: the length should at least be 10 if ( wcslen( bstrURL ) <= 9 ) THROW( CException( E_ACCESSDENIED ) ); WCHAR const * pwcPath = bstrURL + 8; WCHAR const * pwcColon = wcschr( pwcPath, L':' ); ixssoDebugOut(( DEB_ITRACE, "Path is: %ws\n", pwcPath )); if ( ( 0 == pwcColon ) || ( pwcColon > ( pwcPath + 1 ) ) ) THROW( CException( E_ACCESSDENIED ) ); WCHAR wcDrive = * ( pwcColon - 1 ); ixssoDebugOut(( DEB_ITRACE, "wcDrive is: %wc\n", wcDrive )); wcDrive = towupper( wcDrive ); if ( ( wcDrive < L'A' ) || ( wcDrive > L'Z' ) ) THROW( CException( E_ACCESSDENIED ) ); } //IsSafeForScripting
26.177601
119
0.499042
[ "object" ]
25a66c90f6c237e811d71b2f3290e068adb1976b
3,845
cpp
C++
private/windows/shell/encrypt/addsheet.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/windows/shell/encrypt/addsheet.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/windows/shell/encrypt/addsheet.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
// AddSheet.cpp : implementation file // #include "stdafx.h" #include "EFSADU.h" #include "AddSheet.h" #include "userlist.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CAddSheet IMPLEMENT_DYNAMIC(CAddSheet, CPropertySheet) CAddSheet::CAddSheet(UINT nIDCaption, CWnd* pParentWnd, UINT iSelectPage) :CPropertySheet(nIDCaption, pParentWnd, iSelectPage) { EnableAutomation(); AddControlPages(); m_cfDsObjectNames = RegisterClipboardFormat(CFSTR_DSOBJECTNAMES); } CAddSheet::CAddSheet(LPCTSTR pszCaption, CWnd* pParentWnd, UINT iSelectPage) :CPropertySheet(pszCaption, pParentWnd, iSelectPage), m_SheetTitle(pszCaption) { EnableAutomation(); AddControlPages(); m_cfDsObjectNames = RegisterClipboardFormat(CFSTR_DSOBJECTNAMES); } CAddSheet::~CAddSheet() { } void CAddSheet::OnFinalRelease() { // When the last reference for an automation object is released // OnFinalRelease is called. The base class will automatically // deletes the object. Add additional cleanup required for your // object before calling the base class. CPropertySheet::OnFinalRelease(); } // // This routine adds the tab to the sheet // void CAddSheet::AddControlPages() { AddPage(&m_WelcomePage); AddPage(&m_LocatePage); AddPage(&m_CompletePage); } BEGIN_MESSAGE_MAP(CAddSheet, CPropertySheet) //{{AFX_MSG_MAP(CAddSheet) // NOTE - the ClassWizard will add and remove mapping macros here. //}}AFX_MSG_MAP END_MESSAGE_MAP() BEGIN_DISPATCH_MAP(CAddSheet, CPropertySheet) //{{AFX_DISPATCH_MAP(CAddSheet) // NOTE - the ClassWizard will add and remove mapping macros here. //}}AFX_DISPATCH_MAP END_DISPATCH_MAP() // Note: we add support for IID_IAddSheet to support typesafe binding // from VBA. This IID must match the GUID that is attached to the // dispinterface in the .ODL file. // {AD17A13F-5492-11D1-BB63-00A0C906345D} static const IID IID_IAddSheet = { 0xad17a13f, 0x5492, 0x11d1, { 0xbb, 0x63, 0x0, 0xa0, 0xc9, 0x6, 0x34, 0x5d } }; BEGIN_INTERFACE_MAP(CAddSheet, CPropertySheet) INTERFACE_PART(CAddSheet, IID_IAddSheet, Dispatch) END_INTERFACE_MAP() ///////////////////////////////////////////////////////////////////////////// // CAddSheet message handlers BOOL CAddSheet::OnInitDialog() { BOOL bResult = CPropertySheet::OnInitDialog(); SetTitle(m_SheetTitle); return bResult; } UINT CAddSheet::GetDataFormat() { return m_cfDsObjectNames; } DWORD CAddSheet::Add( LPTSTR UserName, LPTSTR DnName, PVOID UserCert, PSID UserSid /*= NULL */, DWORD Flag /*= USERINFILE*/, PVOID Context /*= NULL*/ ) { return m_Users.Add( UserName, DnName, UserCert, UserSid, Flag, Context ); } DWORD CAddSheet::Remove( LPCTSTR UserName, LPCTSTR UserCertName ) { return m_Users.Remove( UserName, UserCertName ); } PVOID CAddSheet::StartEnum() { return m_Users.StartEnum(); } PVOID CAddSheet::GetNextUser( PVOID Token, CString &UserName, CString &CertName ) { return m_Users.GetNextUser( Token, UserName, CertName ); } void CAddSheet::ClearUserList(void) { m_Users.Clear(); } DWORD CAddSheet::AddNewUsers(void) { USERLIST *Parent = (USERLIST *)GetParent(); return Parent->AddNewUsers(m_Users); }
22.617647
82
0.610143
[ "object" ]
25b715add368b085e7d70214811ba48bf96869ea
7,493
cpp
C++
examples/cpp/rvtester.cpp
ijnek/RoboViz
11649ba555cee3dfada0ec071cf36ed99b4f9cad
[ "Apache-2.0" ]
48
2015-06-15T20:42:08.000Z
2022-01-27T08:43:19.000Z
examples/cpp/rvtester.cpp
igorasilveira/RoboViz
d45d8294999c70d8a1e45da10b2c86431b5ad0ec
[ "Apache-2.0" ]
80
2015-06-06T13:02:31.000Z
2022-02-17T03:30:20.000Z
examples/cpp/rvtester.cpp
igorasilveira/RoboViz
d45d8294999c70d8a1e45da10b2c86431b5ad0ec
[ "Apache-2.0" ]
24
2015-06-20T10:53:49.000Z
2021-12-06T10:26:04.000Z
/* * Copyright (C) 2011 Justin Stoecker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * This source file uses some basic datagram socket communication code from * Brian "Beej Jorgensen" Hall's Guide to Network Programming: * http://beej.us/guide/bgnet/output/html/multipage/clientserver.html#datagram */ #include "rvdraw.h" #include <arpa/inet.h> #include <errno.h> #include <math.h> #include <netdb.h> #include <netinet/in.h> #include <sstream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> using namespace std; #define ROBOVIS_HOST "localhost" #define ROBOVIS_PORT "32769" #define TEST_DURATION 10000 int sockfd; struct addrinfo *p; double angle = 0.0; void swapBuffers(const string *setName) { int bufSize = -1; unsigned char *buf = newBufferSwap(setName, &bufSize); sendto(sockfd, buf, bufSize, 0, p->ai_addr, p->ai_addrlen); delete[] buf; } void drawLine(float x1, float y1, float z1, float x2, float y2, float z2, float thickness, float r, float g, float b, const string *setName) { float pa[3] = {x1, y1, z1}; float pb[3] = {x2, y2, z2}; float color[3] = {r, g, b}; int bufSize = -1; unsigned char *buf = newLine(pa, pb, thickness, color, setName, &bufSize); sendto(sockfd, buf, bufSize, 0, p->ai_addr, p->ai_addrlen); delete[] buf; } void drawCircle(float x, float y, float radius, float thickness, float r, float g, float b, const string *setName) { float center[2] = {x, y}; float color[3] = {r, g, b}; int bufSize = -1; unsigned char *buf = newCircle(center, 2.0f, 2.5f, color, setName, &bufSize); sendto(sockfd, buf, bufSize, 0, p->ai_addr, p->ai_addrlen); delete[] buf; } void drawSphere(float x, float y, float z, float radius, float r, float g, float b, const string *setName) { float center[3] = {x, y, z}; float color[3] = {r, g, b}; int bufSize = -1; unsigned char *buf = newSphere(center, radius, color, setName, &bufSize); sendto(sockfd, buf, bufSize, 0, p->ai_addr, p->ai_addrlen); delete[] buf; } void drawPoint(float x, float y, float z, float size, float r, float g, float b, const string *setName) { float center[3] = {x, y, z}; float color[3] = {r, g, b}; int bufSize = -1; unsigned char *buf = newPoint(center, size, color, setName, &bufSize); sendto(sockfd, buf, bufSize, 0, p->ai_addr, p->ai_addrlen); delete[] buf; } void drawPolygon(const float *v, int numVerts, float r, float g, float b, float a, const string *setName) { float color[4] = {r, g, b, a}; int bufSize = -1; unsigned char *buf = newPolygon(v, numVerts, color, setName, &bufSize); sendto(sockfd, buf, bufSize, 0, p->ai_addr, p->ai_addrlen); delete[] buf; } void drawAnnotation(const string *text, float x, float y, float z, float r, float g, float b, const string *setName) { float color[3] = {r, g, b}; float pos[3] = {x, y, z}; int bufSize = -1; unsigned char *buf = newAnnotation(text, pos, color, setName, &bufSize); sendto(sockfd, buf, bufSize, 0, p->ai_addr, p->ai_addrlen); delete[] buf; } void drawAgentAnnotation(const string *text, bool leftTeam, int agentNum, float r, float g, float b) { float color[3] = {r, g, b}; int bufSize = -1; unsigned char *buf = newAgentAnnotation(text, leftTeam, agentNum, color, &bufSize); sendto(sockfd, buf, bufSize, 0, p->ai_addr, p->ai_addrlen); delete[] buf; } void selectAgent(bool leftTeam, int agentNum) { int bufSize = -1; unsigned char *buf = newSelectAgent(leftTeam, agentNum, &bufSize); sendto(sockfd, buf, bufSize, 0, p->ai_addr, p->ai_addrlen); delete[] buf; } float maxf(float a, float b) { return a > b ? a : b; } void renderAnimatedShapes() { angle += 0.05; string n1("animated.points"); for (int i = 0; i < 60; i++) { float p = i / 60.0f; float height = maxf(0, sin(angle + p * 18)); drawPoint(-9 + 18 * p, p * 12 - 6, height, 5, 0, 0, 0, &n1); } float bx = cos(angle) * 2; float by = sin(angle) * 2; float bz = cos(angle) + 1.5f; string n2("animated.spinner"); drawLine(0, 0, 0, bx, by, bz, 5, 1, 1, 0, &n2); drawLine(bx, by, bz, bx, by, 0, 5, 1, 1, 0, &n2); drawLine(0, 0, 0, bx, by, 0, 5, 1, 1, 0, &n2); string n3("animated.annotation"); char tbuf[4]; int result = snprintf(tbuf, 4, "%.1f", bz); string aText(tbuf); drawAnnotation(&aText, bx, by, bz, 0, 1, 0, &n3); string staticSets("animated"); swapBuffers(&staticSets); } void renderStaticShapes() { // draw 3D coordinate axes string n1("static.axes"); drawLine(0, 0, 0, 3, 0, 0, 3, 1, 0, 0, &n1); drawLine(0, 0, 0, 0, 3, 0, 3, 0, 1, 0, &n1); drawLine(0, 0, 0, 0, 0, 3, 3, 0, 0, 1, &n1); // draw 1 meter lines on field string n2("static.lines.field"); drawLine(-9, -6, 0, 9, -6, 0, 1, 0.6f, 0.9f, 0.6f, &n2); drawLine(-9, 6, 0, 9, 6, 0, 1, 0.6f, 0.9f, 0.6f, &n2); for (int i = 0; i <= 18; i++) drawLine(-9 + i, -6, 0, -9 + i, 6, 0, 1, 0.6f, 0.9f, 0.6f, &n2); // draw some circles string n3("static.circles"); drawCircle(-5, 0, 3, 2, 0, 0, 1, &n3); drawCircle(5, 0, 3, 2, 0, 0, 1, &n3); // draw some spheres string n4("static.spheres"); drawSphere(-5, 0, 2, 0.5f, 1, 0, 0.5f, &n4); drawSphere(5, 0, 2, 0.5f, 1, 0, 0.5f, &n4); // draw a polygon string n5("static.polygons"); float v[] = {0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 3, 0, -2, -2, 0}; drawPolygon(v, 4, 1, 1, 1, 0.5f, &n5); string staticSets("static"); swapBuffers(&staticSets); } void annotateAgents() { // Annotate left team agents for (int i = 1; i <= 11; i++) { ostringstream stream; stream << "L" << i; const string annotation = stream.str(); drawAgentAnnotation(&annotation, true, i, 0, 0, 1); } // Annotate right team agents for (int i = 1; i <= 11; i++) { ostringstream stream; stream << "R" << i; const string annotation = stream.str(); drawAgentAnnotation(&annotation, false, i, 1, 0, 0); } } void selectAgents() { // Select left team agents for (int i = 1; i <= 11; i++) { selectAgent(true, i); usleep(500000); } // Select right team agents for (int i = 1; i <= 11; i++) { selectAgent(false, i); usleep(500000); } } void runTest() { renderStaticShapes(); for (int i = 0; i < TEST_DURATION / 17; i++) { renderAnimatedShapes(); usleep(16000); } annotateAgents(); selectAgents(); } int main(int argc, char *argv[]) { struct addrinfo hints, *servinfo; int rv; int numbytes; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; if ((rv = getaddrinfo(ROBOVIS_HOST, ROBOVIS_PORT, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } // loop through all the results and make a socket for (p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("socket"); continue; } break; } if (p == NULL) { fprintf(stderr, "failed to bind socket\n"); return 2; } runTest(); freeaddrinfo(servinfo); close(sockfd); return 0; }
25.573379
117
0.642199
[ "3d" ]
25bed2826fc8bed75b7d1d481112a8f1b4b5b635
5,238
hpp
C++
source/proxyd/statemachine.hpp
mgrech/vitamine
d2fab653a0146b0ad9eb40d62213c968af2a100b
[ "Apache-2.0" ]
null
null
null
source/proxyd/statemachine.hpp
mgrech/vitamine
d2fab653a0146b0ad9eb40d62213c968af2a100b
[ "Apache-2.0" ]
null
null
null
source/proxyd/statemachine.hpp
mgrech/vitamine
d2fab653a0146b0ad9eb40d62213c968af2a100b
[ "Apache-2.0" ]
null
null
null
#pragma once #include <atomic> #include <memory> #include <string> #include <boost/container/flat_set.hpp> #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_io.hpp> #include <common/buffer.hpp> #include <common/clock.hpp> #include <common/coord.hpp> #include <common/span.hpp> #include <common/types.hpp> #include <common/vector.hpp> #include <common/net/connection.hpp> #include <proxyd/chat.hpp> #include <proxyd/deserialize.hpp> #include <proxyd/framing.hpp> #include <proxyd/globalstate.hpp> #include <proxyd/packetreader.hpp> #include <proxyd/packets.hpp> #include <proxyd/playertracker.hpp> #include <proxyd/serialize.hpp> #include <proxyd/types.hpp> namespace vitamine::proxyd { enum struct ClientPhase { INITIAL, LOGIN, PLAY_INIT, PLAY, STATUS, }; struct ClientSettings { std::string locale; UInt8 viewDistance; ChatMode chatMode; bool chatColorsEnabled; UInt8 displayedSkinParts; MainHand mainHand; }; struct PlayerState { std::string clientBrand; std::string username; boost::uuids::uuid uuid = {}; EntityId entityId; GameMode gameMode = GameMode::CREATIVE; ClientSettings clientSettings; EntityCoord position = {0, 64, 0}; Float32 yaw = 0, pitch = 0; UInt8 heldItemSlot = 0; Int32 nextTeleportId = 0; boost::container::flat_set<Int32> outstandingTeleportIds; UInt8 openWindow = 0; UInt8 abilityFlags = 0x0f; Float32 walkingSpeed = 1.0; Float32 flyingSpeed = 1.0; bool sprinting = false; bool crouching = false; Int32 startTeleport() { auto id = nextTeleportId++; outstandingTeleportIds.insert(id); return id; } bool confirmTeleport(Int32 id) { auto it = outstandingTeleportIds.find(id); if(it == outstandingTeleportIds.end()) return false; outstandingTeleportIds.erase(it); return true; } }; class StateMachine { GlobalState* _globalState; std::shared_ptr<IConnection> _connection; PacketReader _reader; std::atomic<ClientPhase> _phase = ClientPhase::INITIAL; std::atomic<Int64> _lastPacketTime; std::atomic<Int64> _lastKeepAliveSentTime; PlayerState _playerState; void disconnect() { _connection->disconnect(); } void disconnect(std::string const& message) { auto reason = chat::plainText(message); if(_phase == ClientPhase::PLAY) { PacketDisconnect packet; packet.reason = spanFromStdString(reason); sendPacket(packet); } else { PacketDisconnectLogin packet; packet.reason = spanFromStdString(reason); sendPacket(packet); } disconnect(); } void sendPacket(Buffer const& buffer) { _connection->send(buffer); } template <typename Packet> void sendPacket(Packet const& packet) { sendPacket(serializePacket(packet)); } void broadcastGloballyUnsafe(Buffer const& buffer, bool includeSelf) { for(auto& player : _globalState->players) if(includeSelf || player != this) player->_connection->send(buffer); } template <typename Packet> void broadcastGloballyUnsafe(Packet const& packet, bool includeSelf) { auto buffer = serializePacket(packet); broadcastGloballyUnsafe(buffer, includeSelf); } void broadcastLocallyUnsafe(Buffer const& buffer, bool includeSelf) { auto coord = coord_cast<ChunkCoord>(_playerState.position); for(auto& player : _globalState->playerTracker.subscribers(coord)) if(includeSelf || player != this) player->_connection->send(buffer); } template <typename Packet> void broadcastLocallyUnsafe(Packet const& packet, bool includeSelf) { auto buffer = serializePacket(packet); broadcastLocallyUnsafe(buffer, includeSelf); } void broadcastLocally(Buffer const& buffer, bool includeSelf) { auto lock = _globalState->playerTracker.lock(); broadcastLocallyUnsafe(buffer, includeSelf); } template <typename Packet> void broadcastLocally(Packet const& packet, bool includeSelf) { auto buffer = serializePacket(packet); broadcastLocally(buffer, includeSelf); } void sendChunk(ChunkCoord coord); void onPacket(PacketFrame frame); void onClientSettingsChange(PacketClientSettings const& packet); Buffer createMovePacket(EntityCoord oldPosition, bool rotate); static Buffer createSpawnPacket(PlayerState const& state); static Buffer createDespawnPacket(PlayerState const& state); void sendMetadataUpdate(); void onMove(EntityCoord oldPosition, bool rotate); void onChunkTransition(ChunkCoord from, ChunkCoord to, EntityCoord oldPosition, bool rotate); Chunk* getOrCreateChunk(ChunkCoord coord); public: StateMachine(StateMachine const&) = delete; StateMachine& operator=(StateMachine const&) = delete; StateMachine(StateMachine&&) = delete; StateMachine& operator=(StateMachine&&) = delete; StateMachine(GlobalState* globalState, std::shared_ptr<IConnection> const& connection) : _globalState(globalState), _connection(connection) , _reader([this](auto frame){ onPacket(frame); }, [connection]{ connection->disconnect(); }) , _lastPacketTime(_globalState->clock.now()), _lastKeepAliveSentTime(0) {} ~StateMachine(); void onTick(); void onBytesReceived(Span<UInt8 const> data) { _reader.onBytesReceived(data); } }; }
22.577586
95
0.727186
[ "vector" ]
25c56805dd44fb0ad550be0cc1319d962e26fc64
4,766
cpp
C++
ScriptHookDotNet/SkinTemplate.cpp
HazardX/gta4_scripthookdotnet
927b2830952664b63415234541a6c83592e53679
[ "MIT" ]
3
2021-11-14T20:59:58.000Z
2021-12-16T16:41:31.000Z
ScriptHookDotNet/SkinTemplate.cpp
HazardX/gta4_scripthookdotnet
927b2830952664b63415234541a6c83592e53679
[ "MIT" ]
2
2021-11-29T14:41:23.000Z
2021-11-30T13:13:51.000Z
ScriptHookDotNet/SkinTemplate.cpp
HazardX/gta4_scripthookdotnet
927b2830952664b63415234541a6c83592e53679
[ "MIT" ]
3
2021-11-21T12:41:55.000Z
2021-12-22T16:17:52.000Z
/* * Copyright (c) 2009-2011 Hazard (hazard_x@gmx.net / twitter.com/HazardX) * * 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 "stdafx.h" #include "SkinTemplate.h" #include "Ped.h" #include "Player.h" #include "vPedSkin.h" #pragma managed namespace GTA{ SkinTemplate::SkinTemplate() { Initialize(); } SkinTemplate::SkinTemplate(value::PedSkin^ skin) { Initialize(); FromPedSkin(skin); } void SkinTemplate::Initialize() { pModel = GTA::Model::Null; PropIndices = gcnew array<int>(PROP_COUNT); ComponentModel = gcnew array<int>(COMPONENT_COUNT); ComponentTexture = gcnew array<int>(COMPONENT_COUNT); } GTA::Model SkinTemplate::Model::get(){ return pModel; } void SkinTemplate::Model::set(GTA::Model value){ pModel = value; } void SkinTemplate::FromPedSkin(value::PedSkin^ sk) { if isNULL(sk) return; OBJECT_NON_EXISTING_CHECK(sk->ped); int i; pModel = sk->Model; for (i=0; i<PROP_COUNT; i++) { PropIndices[i] = sk->GetPropIndex((PedProp)i); //Scripting::GetCharPropIndex2(ped->Handle, i, &value); } for (i=0; i<COMPONENT_COUNT; i++) { //ComponentModel[i] = sk->GetComponentModel((PedComponent)i); //ComponentTexture[i] = sk->GetComponentTexture((PedComponent)i); //ComponentModel[i] = sk->Component((PedComponent)i)->ModelIndex; //ComponentTexture[i] = sk->Component((PedComponent)i)->TextureIndex; ComponentModel[i] = Scripting::GetCharDrawableVariation(sk->ped->Handle, (Scripting::ePedComponent)i); ComponentTexture[i] = Scripting::GetCharTextureVariation(sk->ped->Handle, (Scripting::ePedComponent)i); } } void SkinTemplate::ApplyToPed(Ped^ ped) { if isNULL(ped) return; OBJECT_NON_EXISTING_CHECK(ped); value::PedSkin^ sk = ped->Skin; int i; //ped->Model = pModel; for (i=0; i<PROP_COUNT; i++) { sk->SetPropIndex((PedProp)i, PropIndices[i]); } for (i=0; i<COMPONENT_COUNT; i++) { //sk->SetComponent((PedComponent)i, ComponentModel[i], ComponentTexture[i]); //sk->Component((PedComponent)i)->Change(ComponentModel[i], ComponentTexture[i]); Scripting::SetCharComponentVariation(ped->Handle, (Scripting::ePedComponent)i, (u32)ComponentModel[i], (u32)ComponentTexture[i]); } //ped->SetDefaultVoice(); } void SkinTemplate::ApplyToPlayer(Player^ player) { player->Model = pModel; ApplyToPed(player->Character); } String^ SkinTemplate::ToString() { System::Text::StringBuilder^ sb = gcnew System::Text::StringBuilder(); sb->Append(pModel.ToString()); sb->Append(";"); for (int i = 0; i < PROP_COUNT; i++) { if (i > 0) sb->Append("_"); sb->Append(Helper::ToShortestHex(PropIndices[i])); } sb->Append(";"); for (int i = 0; i < COMPONENT_COUNT; i++) { if (i > 0) sb->Append("_"); sb->Append(Helper::ToShortestHex(ComponentModel[i])); } sb->Append(";"); for (int i = 0; i < COMPONENT_COUNT; i++) { if (i > 0) sb->Append("_"); sb->Append(Helper::ToShortestHex(ComponentTexture[i])); } return sb->ToString(); } SkinTemplate^ SkinTemplate::FromString(String^ input) { array<String^>^ segs = input->Split(';'); if (segs->Length < 4) return nullptr; SkinTemplate^ res = gcnew SkinTemplate(); res->Model = GTA::Model::FromString(segs[0]); array<String^>^ vals = segs[1]->Split('_'); for (int i = 0; i < System::Math::Min(vals->Length,PROP_COUNT); i++) { res->PropIndices[i] = Helper::HexToInteger(vals[i]); } vals = segs[2]->Split('_'); for (int i = 0; i < System::Math::Min(vals->Length,COMPONENT_COUNT); i++) { res->ComponentModel[i] = Helper::HexToInteger(vals[i]); } vals = segs[3]->Split('_'); for (int i = 0; i < System::Math::Min(vals->Length,COMPONENT_COUNT); i++) { res->ComponentTexture[i] = Helper::HexToInteger(vals[i]); } return res; } }
33.801418
132
0.690306
[ "model" ]
25c707c981483bca7b0550a1be033af093ab66f1
5,043
cpp
C++
Action/Action.cpp
Ricecrackie/Fantasy-Battle
058dc323101d405e222e9c8f135500044ce6e180
[ "Apache-2.0" ]
null
null
null
Action/Action.cpp
Ricecrackie/Fantasy-Battle
058dc323101d405e222e9c8f135500044ce6e180
[ "Apache-2.0" ]
null
null
null
Action/Action.cpp
Ricecrackie/Fantasy-Battle
058dc323101d405e222e9c8f135500044ce6e180
[ "Apache-2.0" ]
null
null
null
#include "Action.h" #include "../Skill/Regular_attack.h" #include "../Skill/Defence.h" #include "../Skill/Blessing.h" #include "../Skill/Blood_sucking.h" #include "../Skill/Cursing.h" #include "../Skill/Greater_defence.h" #include "../Skill/Greater_strengthen.h" #include "../Skill/Sharp_attack.h" #include "../Skill/Strengthen.h" #include "../Skill/Ultimate_strike.h" #include "../Item/HPpotion.h" #include "../Item/MPpotion.h" int use_item_APcost = 2; // call constructor to create an Action Object (depending on the action is skill or item) Action::Action(Character* doer, Character* receiver, Skill* skill) : doer(doer), receiver(receiver), skill(skill), item(nullptr), action_type(type::USE_A_SKILL) {} Action::Action(Character* doer, Character* receiver, Item* item) : doer(doer), receiver(receiver), skill(nullptr), action_type(type::USE_AN_ITEM) { switch(item->get_item_type()) { case Item::item_type::HP_POTION: this->item = new HPpotion; break; case Item::item_type::MP_POTION: this->item = new MPpotion; break; } } Action::Action(Character* doer) : doer(doer), receiver(nullptr), skill(nullptr), item(nullptr), action_type(type::FLEE) {} // returns the AP cost of the action int Action::get_action_APcost() { if (skill != nullptr) return skill->get_AP_cost(); if (item != nullptr) return use_item_APcost; else return 0; } // returns the MP cost of the action int Action::get_action_MPcost() { if (skill != nullptr) return skill->get_MP_cost(); if (item != nullptr) return 0; else return 0; } // returns the pointers or type called by the code Skill* Action::get_skill() {return skill;} Item* Action::get_item() {return item;} Action::type Action::get_type() {return action_type;} // destricutor to delete the contents pointed by the item pointer Action::~Action() { if (item != nullptr) { delete item; } } // return the name of the action std::string Action::get_action_name() { if (skill != nullptr) {return "use "+skill->get_name()+" on "+receiver->get_name();} if (item != nullptr) {return "use a "+item->get_item_name()+" on "+receiver->get_name();} if (skill == nullptr && item == nullptr) {return "flee";} return ""; } // operator overloading to return if true or false bool Action::operator==(Action& action) { return (this->skill == action.skill && this->item == action.item && this->action_type == action.action_type && this->doer == action.doer && this->receiver == action.receiver); } // call constructor to create an Action Object Action::Action(Action& action) { this->doer = action.doer; this->receiver = action.receiver; this->skill = action.get_skill(); /*switch(action.get_skill()->get_skill_type()) { case Skill::skill_type::REGULAR_ATTACK: this->skill = new Regular_attack; break; case Skill::skill_type::DEFENCE: this->skill = new Defence(receiver); break; case Skill::skill_type::STRENGTHEN: this->skill = new Strengthen(receiver); break; case Skill::skill_type::SHARP_ATTACK: this->skill = new Sharp_attack; break; case Skill::skill_type::BLESSING: this->skill = new Blessing(receiver); break; case Skill::skill_type::CURSING: this->skill = new Cursing(receiver); break; case Skill::skill_type::ULTIMATE_STRIKE: this->skill = new Ultimate_strike; break; case Skill::skill_type::BLOOD_SUCKING: this->skill = new Blood_sucking; break; case Skill::skill_type::GREATER_DEFENCE: this->skill = new Greater_defence(receiver); break; case Skill::skill_type::GREATER_STRENGTHEN: this->skill = new Greater_strengthen(receiver); break; }*/ } // executes the code for doer effect void Action::doer_effect(double power_up) { if (skill != nullptr) { skill->doer_effect(doer, power_up); attribute_outofbound_check(); return;} } // checks if the attribute (e.g. HP and MP) is out of bound void Action::attribute_outofbound_check() { if (doer->HP > doer->get_HP_max()) {doer->HP = doer->get_HP_max();} if (doer->MP > doer->get_MP_max()) {doer->MP = doer->get_MP_max();} if (doer->HP < 0) {doer->HP = 0;} if (doer->MP < 0) {doer->MP = 0;} if (receiver->HP > receiver->get_HP_max()) {receiver->HP = receiver->get_HP_max();} if (receiver->MP > receiver->get_MP_max()) {receiver->MP = receiver->get_MP_max();} if (receiver->HP < 0) {receiver->HP = 0;} if (receiver->MP < 0) {receiver->MP = 0;} } // executes the code for the receiver effect void Action::receiver_effect(double power_up) { if (skill != nullptr) {skill->receiver_effect(receiver, doer, power_up);} if (item != nullptr) {item->receiver_effect(*receiver, power_up);} attribute_outofbound_check(); return; }
36.810219
163
0.640492
[ "object" ]
25c766c576ee817da58036030801c01f29a4e18d
6,653
cpp
C++
Tools/TexturePacker/src/TexturePacker.cpp
palikar/DirectXer
c21b87eed220fc54d97d5363e8a33bd0944a2596
[ "MIT" ]
null
null
null
Tools/TexturePacker/src/TexturePacker.cpp
palikar/DirectXer
c21b87eed220fc54d97d5363e8a33bd0944a2596
[ "MIT" ]
null
null
null
Tools/TexturePacker/src/TexturePacker.cpp
palikar/DirectXer
c21b87eed220fc54d97d5363e8a33bd0944a2596
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <unordered_map> #include <vector> #include <string> #include <cstdint> #include <fstream> #include <GraphicsCommon.hpp> #include <Types.hpp> #include <Utils.hpp> #include <Assets.hpp> #include <fmt/format.h> #include <filesystem> #include <stb_image.h> #include <stb_image_resize.h> #include <stb_rect_pack.h> #include <cmath> #include "TexturePacker.hpp" static inline ImageToPack images[] = { {"images/evil_ship_1.png", 64, 64, "I_EVIL_SHIP_1"}, {"images/evil_ship_2.png", 64, 64, "I_EVIL_SHIP_2"}, {"images/evil_ship_3.png", 64, 64, "I_EVIL_SHIP_3"}, {"images/ship_bullet.png", 32, 64, "I_BULLET"}, {"images/explosion.png", 0, 0, "I_EXPLOSION"}, {"images/heart.png", 32, 32, "I_HEART"}, {"images/SpaceGameAssets/Ship_Parts/Ship_Main_Icon.png", 64, 64, "I_MAIN_SHIP"}, {"images/SpaceGameAssets/Main_UI/Health_Bar_Table.png", 0, 0, "I_HEALTH"}, }; static void ParseCommandLineArguments(int argc, char *argv[], TexturePacker::CommandLineArguments& arguments) { for (size_t i = 0; i < argc; ++i) { std::string current{argv[i]}; if(current == "-r") { arguments.Root = argv[++i]; } else if (current == "-o") { arguments.Output = argv[++i]; } else if (current == "-s") { arguments.Size = std::stoi(argv[++i]); } else if (current == "-m") { arguments.MaxAtlases = std::stoi(argv[++i]); } } } static void PutPixels(std::vector<unsigned char>& atlasBytes, stbrp_rect rect, unsigned char* data, size_t atlasSize) { for (size_t i = 0; i < rect.h; ++i) { for (size_t j = 0; j < rect.w; ++j) { atlasBytes[((i + rect.y) * atlasSize + (j + rect.x))*4 + 0] = data[(i*rect.w + j)*4 + 0]; atlasBytes[((i + rect.y) * atlasSize + (j + rect.x))*4 + 1] = data[(i*rect.w + j)*4 + 1]; atlasBytes[((i + rect.y) * atlasSize + (j + rect.x))*4 + 2] = data[(i*rect.w + j)*4 + 2]; atlasBytes[((i + rect.y) * atlasSize + (j + rect.x))*4 + 3] = data[(i*rect.w + j)*4 + 3]; } } } TexturePackerOutput PackTextures(TexturePacker::CommandLineArguments arguments, ImageToPack* imagesToPack, size_t imagesCount) { AtlasFileHeader header{0}; header.NumAtlases = 1; header.NumImages = (uint16)imagesCount; uint16 atlasSize = arguments.Size; uint16 maxAtlases = arguments.MaxAtlases; std::vector<AtlasImage> images; images.reserve(50); std::vector<AtlasEntry> atlases; images.reserve(3); std::vector<std::vector<unsigned char>> atlasesBytes(1); atlasesBytes.back().resize(atlasSize * atlasSize * 4); AtlasEntry atlasEntry; atlasEntry.Width = atlasSize; atlasEntry.Height = atlasSize; atlasEntry.Format = TF_RGBA; atlasEntry.Offset = sizeof(AtlasFileHeader) + sizeof(ImageEntry)*header.NumImages + sizeof(AtlasEntry); atlases.push_back(atlasEntry); std::vector<stbrp_context> RectContexts; RectContexts.resize(maxAtlases); stbrp_init_target(&RectContexts[0], atlasSize, atlasSize, (stbrp_node*)malloc(sizeof(stbrp_node)*atlasSize), atlasSize); fmt::print("Packing [{}] images\n", imagesCount); for (size_t i = 0; i < imagesCount; ++i) { auto& entry = imagesToPack[i]; entry.Path = fmt::format("{}/{}", arguments.Root, entry.Path); int width, height, channels; unsigned char* data = stbi_load(entry.Path.c_str(), &width, &height, &channels, 4); if(!data) { fmt::print("Cannot open image file: [{}]\n", entry.Path); return {}; } unsigned char* resized = data; if (entry.Width != 0 && (width != entry.Width || height != entry.Height)) { auto res = stbir_resize_uint8(data, width, height, 0, resized, entry.Width, entry.Height, 0, 4); width = entry.Width; height = entry.Height; } stbrp_rect rect; rect.w = (stbrp_coord)width; rect.h = (stbrp_coord)height; AtlasImage image; strcpy_s(image.Name, entry.Id.c_str()); image.Id = 0; for (size_t j = 0; j < maxAtlases; ++j) { if (j >= atlasesBytes.size()) { uint16 atlasWidth = std::max(atlasSize, (uint16)(width + 16)); uint16 atlasHeight = std::max(atlasSize, (uint16)(height + 16)); fmt::print("Generating a new atlas [{}] with size [{}x{}]!\n", j, atlasWidth, atlasHeight); stbrp_init_target(&RectContexts[j], atlasWidth, atlasHeight, (stbrp_node*)malloc(sizeof(stbrp_node)* atlasWidth), atlasSize); atlasesBytes.push_back({}); atlasesBytes.back().resize(atlasWidth * atlasHeight * 4); atlasEntry.Offset += atlasHeight * atlasWidth * 4; atlasEntry.Width = atlasWidth; atlasEntry.Height = atlasHeight; atlases.push_back(atlasEntry); std::for_each(atlases.begin(), atlases.end(), [](auto& atlas){ atlas.Offset += sizeof(AtlasEntry); }); header.NumAtlases += 1; } stbrp_pack_rects(&RectContexts[j], &rect, 1); image.Atlas = (uint32)j; if (rect.was_packed != 0) break; } if (rect.was_packed == 0) { fmt::print("Cannot pack image : [{}]. Maybe increase the maximum number of atlases\n", entry.Path); return {}; }; fmt::print("Packing image with size [{}x{}] in atlas [{}] : [{}]\n", width, height, image.Atlas, entry.Path); image.X = rect.x / (float)atlases[image.Atlas].Width; image.Y = rect.y / (float)atlases[image.Atlas].Height; image.Width = rect.w / (float)atlases[image.Atlas].Width; image.Height = rect.h / (float)atlases[image.Atlas].Height; image.AtlasWidth = (float)atlases[image.Atlas].Width; image.AtlasHeight = (float)atlases[image.Atlas].Height; images.push_back(image); PutPixels(atlasesBytes[image.Atlas], rect, resized, atlases[image.Atlas].Width); stbi_image_free(data); } TexturePackerOutput res; res.Success = true; res.Header = header; res.Images = std::move(images); res.Atlases = std::move(atlases); res.AtlasesBytes = std::move(atlasesBytes); return res; } #ifdef TEXTURE_PACKER_COMPILE_APPLICATION int main(int argc, char *argv[]) { TexturePacker::CommandLineArguments arguments{}; ParseCommandLineArguments(argc, argv, arguments); TexturePackerOutput res = PackTextures(arguments, images, size(images)); std::string atlasFileName = fmt::format("{}.datlas", arguments.Output); std::ofstream outfile(atlasFileName, std::ios::out | std::ios::binary); if (!outfile.is_open()) { fmt::print("Cannot open output file: [{}]\n", atlasFileName); return 1; } fmt::print("Generating output file [{}]\n", atlasFileName); outfile.write((char*)&res.Header, sizeof(AtlasFileHeader)); outfile.write((char*)res.Atlases.data(), res.Atlases.size() * sizeof(AtlasEntry)); outfile.write((char*)res.Images.data(), res.Images.size() * sizeof(ImageEntry)); for (auto& bytes : res.AtlasesBytes) { outfile.write((char*)bytes.data(), bytes.size() * sizeof(char)); } return 0; } #endif
31.680952
129
0.675635
[ "vector" ]
5ad5d9f279b7ccec093b02102b1253c3920bfd66
1,109
cpp
C++
Codeforces/FormingTeams.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
1
2018-08-28T19:58:40.000Z
2018-08-28T19:58:40.000Z
Codeforces/FormingTeams.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
2
2017-04-16T00:48:05.000Z
2017-08-03T20:12:26.000Z
Codeforces/FormingTeams.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
4
2016-03-04T19:42:00.000Z
2018-01-08T11:42:00.000Z
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <utility> #include <functional> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <assert.h> #include <limits.h> #define REP(i, n) for(i = 0; i < n; i++) typedef long long ll; using namespace std; int a, b, n, m, ans = 0, adj[110][110], vis[110], mt[110]; bool dfs(int x) { if(vis[x]) return false; vis[x] = true; for(int i = 1; i <= n; i++) if(adj[x][i] == 1) { if(mt[i] == -1 || dfs(mt[i])) { mt[i] = x; return true; } } return false; } int main(void) { scanf("%d%d", &n, &m); for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) { adj[i][j] = 1; } } for(int i = 0; i < m; i++) { scanf("%d%d", &a, &b); adj[a][b] = adj[b][a] = 0; } memset(mt, -1, sizeof(mt)); for(int i = 1; i <= n; i++) { memset(vis, 0, sizeof(vis)); dfs(i); } printf("%d\n", ans); return 0; }
20.924528
59
0.444545
[ "vector" ]
5ad63b3bcabd589432967c1030d581646bb9a37e
1,929
hh
C++
lrauv_ignition_plugins/src/ReferenceAxis.hh
osrf/lrauv
2efa79e10682def98f8277fe313ffd1488708b1e
[ "Apache-2.0" ]
24
2021-11-03T18:45:41.000Z
2022-03-28T17:53:29.000Z
lrauv_ignition_plugins/src/ReferenceAxis.hh
osrf/lrauv
2efa79e10682def98f8277fe313ffd1488708b1e
[ "Apache-2.0" ]
105
2021-11-04T03:15:55.000Z
2022-03-30T20:48:01.000Z
lrauv_ignition_plugins/src/ReferenceAxis.hh
osrf/lrauv
2efa79e10682def98f8277fe313ffd1488708b1e
[ "Apache-2.0" ]
1
2022-03-18T14:16:47.000Z
2022-03-18T14:16:47.000Z
/* * Copyright (C) 2021 Open Source Robotics Foundation * * 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. * */ /* * Development of this module has been funded by the Monterey Bay Aquarium * Research Institute (MBARI) and the David and Lucile Packard Foundation */ #ifndef TETHYS_REFERENCEAXIS_HH_ #define TETHYS_REFERENCEAXIS_HH_ #include <memory> #include "ignition/msgs/pointcloud_packed.pb.h" #include <ignition/gui/Plugin.hh> namespace tethys { class ReferenceAxisPrivate; /// \brief This plugin adds a few reference frames to the 3D scene: /// /// * ENU: floating op the user camera's top-left corner /// * NED: floating op the user camera's top-right corner /// * FSK: attached to all models specified in `<fsk>` /// /// For each frame, red-green-blue axes are spawned. When using Ogre 1, a /// floating text with the frame name is also spawned. class ReferenceAxis : public ignition::gui::Plugin { Q_OBJECT /// \brief Constructor public: ReferenceAxis(); /// \brief Destructor public: ~ReferenceAxis() override; // Documentation inherited public: void LoadConfig(const tinyxml2::XMLElement *_pluginElem) override; // Documentation inherited public: bool eventFilter(QObject *_obj, QEvent *_event) override; /// \internal /// \brief Pointer to private data private: std::unique_ptr<ReferenceAxisPrivate> dataPtr; }; } #endif
29.227273
78
0.717989
[ "3d" ]
5adaa746e608018218acf4c48633ae7138ac3975
15,199
cpp
C++
collector/lib/NetworkStatusNotifier.cpp
kudz00/collector
73a5366e4d95bc33e85ed0d7578c74f0a2e8a0aa
[ "Apache-2.0" ]
1
2022-03-31T15:25:16.000Z
2022-03-31T15:25:16.000Z
collector/lib/NetworkStatusNotifier.cpp
kudz00/collector
73a5366e4d95bc33e85ed0d7578c74f0a2e8a0aa
[ "Apache-2.0" ]
4
2022-03-31T16:16:00.000Z
2022-03-31T23:24:33.000Z
collector/lib/NetworkStatusNotifier.cpp
stackrox/collector
4c3913176eb62636e32a8a56f889e611c638de73
[ "Apache-2.0" ]
null
null
null
/** collector A full notice with attributions is provided along with this source code. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. */ #include "NetworkStatusNotifier.h" #include <google/protobuf/util/time_util.h> #include "CollectorStats.h" #include "DuplexGRPC.h" #include "GRPCUtil.h" #include "Profiler.h" #include "ProtoUtil.h" #include "TimeUtil.h" #include "Utility.h" namespace collector { namespace { storage::L4Protocol TranslateL4Protocol(L4Proto proto) { switch (proto) { case L4Proto::TCP: return storage::L4_PROTOCOL_TCP; case L4Proto::UDP: return storage::L4_PROTOCOL_UDP; case L4Proto::ICMP: return storage::L4_PROTOCOL_ICMP; default: return storage::L4_PROTOCOL_UNKNOWN; } } sensor::SocketFamily TranslateAddressFamily(Address::Family family) { switch (family) { case Address::Family::IPV4: return sensor::SOCKET_FAMILY_IPV4; case Address::Family::IPV6: return sensor::SOCKET_FAMILY_IPV6; default: return sensor::SOCKET_FAMILY_UNKNOWN; } } } // namespace constexpr char NetworkStatusNotifier::kHostnameMetadataKey[]; constexpr char NetworkStatusNotifier::kCapsMetadataKey[]; constexpr char NetworkStatusNotifier::kSupportedCaps[]; std::vector<IPNet> readNetworks(const string& networks, Address::Family family) { int tuple_size = Address::Length(family) + 1; int num_nets = networks.size() / tuple_size; std::vector<IPNet> ip_nets; ip_nets.reserve(num_nets); for (int i = 0; i < num_nets; i++) { // Bytes are received in big-endian order. std::array<uint64_t, Address::kU64MaxLen> ip = {}; std::memcpy(&ip, &networks.c_str()[tuple_size * i], Address::Length(family)); IPNet net(Address(family, ip), static_cast<int>(networks.c_str()[tuple_size * i + tuple_size - 1])); ip_nets.push_back(net); } return ip_nets; } std::unique_ptr<grpc::ClientContext> NetworkStatusNotifier::CreateClientContext() const { auto ctx = MakeUnique<grpc::ClientContext>(); ctx->AddMetadata(kHostnameMetadataKey, hostname_); ctx->AddMetadata(kCapsMetadataKey, kSupportedCaps); return ctx; } void NetworkStatusNotifier::OnRecvControlMessage(const sensor::NetworkFlowsControlMessage* msg) { if (!msg) { return; } if (msg->has_ip_networks()) { ReceivePublicIPs(msg->public_ip_addresses()); } if (msg->has_ip_networks()) { ReceiveIPNetworks(msg->ip_networks()); } } void NetworkStatusNotifier::ReceivePublicIPs(const sensor::IPAddressList& public_ips) { UnorderedSet<Address> known_public_ips; for (const uint32_t public_ip : public_ips.ipv4_addresses()) { Address addr(htonl(public_ip)); known_public_ips.insert(addr); known_public_ips.insert(addr.ToV6()); } auto ipv6_size = public_ips.ipv6_addresses_size(); if (ipv6_size % 2 != 0) { CLOG(WARNING) << "IPv6 address field has odd length " << ipv6_size << ". Ignoring IPv6 addresses..."; } else { for (int i = 0; i < ipv6_size; i += 2) { known_public_ips.emplace(htonll(public_ips.ipv6_addresses(i)), htonll(public_ips.ipv6_addresses(i + 1))); } } conn_tracker_->UpdateKnownPublicIPs(std::move(known_public_ips)); } void NetworkStatusNotifier::ReceiveIPNetworks(const sensor::IPNetworkList& networks) { UnorderedMap<Address::Family, std::vector<IPNet>> known_ip_networks; auto ipv4_networks_size = networks.ipv4_networks().size(); if (ipv4_networks_size % 5 != 0) { CLOG(WARNING) << "IPv4 network field has incorrect length " << ipv4_networks_size << ". Ignoring IPv4 networks..."; } else { std::vector<IPNet> ipv4_networks = readNetworks(networks.ipv4_networks(), Address::Family::IPV4); known_ip_networks[Address::Family::IPV4] = ipv4_networks; } auto ipv6_networks_size = networks.ipv6_networks().size(); if (ipv6_networks_size % 17 != 0) { CLOG(WARNING) << "IPv6 network field has incorrect length " << ipv6_networks_size << ". Ignoring IPv6 networks..."; } else { std::vector<IPNet> ipv6_networks = readNetworks(networks.ipv6_networks(), Address::Family::IPV6); known_ip_networks[Address::Family::IPV6] = ipv6_networks; } conn_tracker_->UpdateKnownIPNetworks(std::move(known_ip_networks)); } void NetworkStatusNotifier::Run() { Profiler::RegisterCPUThread(); auto next_attempt = std::chrono::system_clock::now(); while (thread_.PauseUntil(next_attempt)) { WITH_LOCK(context_mutex_) { context_ = CreateClientContext(); } if (!WaitForChannelReady(channel_, [this] { return thread_.should_stop(); })) { break; } std::function<void(const sensor::NetworkFlowsControlMessage*)> read_cb = [this](const sensor::NetworkFlowsControlMessage* msg) { OnRecvControlMessage(msg); }; auto client_writer = DuplexClient::CreateWithReadCallback( &sensor::NetworkConnectionInfoService::Stub::AsyncPushNetworkConnectionInfo, channel_, context_.get(), std::move(read_cb)); if (enable_afterglow_) { RunSingleAfterglow(client_writer.get()); } else { RunSingle(client_writer.get()); } if (thread_.should_stop()) { return; } auto status = client_writer->Finish(std::chrono::seconds(5)); if (status.ok()) { CLOG(ERROR) << "Error streaming network connection info: server hung up unexpectedly"; } else { CLOG(ERROR) << "Error streaming network connection info: " << status.error_message(); } next_attempt = std::chrono::system_clock::now() + std::chrono::seconds(10); } CLOG(INFO) << "Stopped network status notifier."; } void NetworkStatusNotifier::Start() { thread_.Start([this] { Run(); }); CLOG(INFO) << "Started network status notifier."; } void NetworkStatusNotifier::Stop() { WITH_LOCK(context_mutex_) { if (context_) context_->TryCancel(); } thread_.Stop(); } void NetworkStatusNotifier::WaitUntilWriterStarted(DuplexClientWriter<sensor::NetworkConnectionInfoMessage>* writer, int wait_time_seconds) { if (!writer->WaitUntilStarted(std::chrono::seconds(wait_time_seconds))) { CLOG(ERROR) << "Failed to establish network connection info stream."; return; } CLOG(INFO) << "Established network connection info stream."; } bool NetworkStatusNotifier::UpdateAllConnsAndEndpoints() { if (turn_off_scraping_) { return true; } int64_t ts = NowMicros(); std::vector<Connection> all_conns; std::vector<ContainerEndpoint> all_listen_endpoints; WITH_TIMER(CollectorStats::net_scrape_read) { bool success = conn_scraper_.Scrape(&all_conns, scrape_listen_endpoints_ ? &all_listen_endpoints : nullptr); if (!success) { CLOG(ERROR) << "Failed to scrape connections and no pending connections to send"; return false; } } WITH_TIMER(CollectorStats::net_scrape_update) { conn_tracker_->Update(all_conns, all_listen_endpoints, ts); } return true; } void NetworkStatusNotifier::RunSingle(DuplexClientWriter<sensor::NetworkConnectionInfoMessage>* writer) { WaitUntilWriterStarted(writer, 10); ConnMap old_conn_state; ContainerEndpointMap old_cep_state; auto next_scrape = std::chrono::system_clock::now(); while (writer->Sleep(next_scrape)) { next_scrape = std::chrono::system_clock::now() + std::chrono::seconds(scrape_interval_); if (!UpdateAllConnsAndEndpoints()) { continue; } const sensor::NetworkConnectionInfoMessage* msg; ConnMap new_conn_state; ContainerEndpointMap new_cep_state; WITH_TIMER(CollectorStats::net_fetch_state) { new_conn_state = conn_tracker_->FetchConnState(true, true); ConnectionTracker::ComputeDelta(new_conn_state, &old_conn_state); new_cep_state = conn_tracker_->FetchEndpointState(true, true); ConnectionTracker::ComputeDelta(new_cep_state, &old_cep_state); } WITH_TIMER(CollectorStats::net_create_message) { msg = CreateInfoMessage(old_conn_state, old_cep_state); old_conn_state = std::move(new_conn_state); old_cep_state = std::move(new_cep_state); } if (!msg) { continue; } WITH_TIMER(CollectorStats::net_write_message) { if (!writer->Write(*msg, next_scrape)) { CLOG(ERROR) << "Failed to write network connection info"; return; } } } } void NetworkStatusNotifier::RunSingleAfterglow(DuplexClientWriter<sensor::NetworkConnectionInfoMessage>* writer) { WaitUntilWriterStarted(writer, 10); ConnMap old_conn_state; ContainerEndpointMap old_cep_state; auto next_scrape = std::chrono::system_clock::now(); int64_t time_at_last_scrape = NowMicros(); while (writer->Sleep(next_scrape)) { next_scrape = std::chrono::system_clock::now() + std::chrono::seconds(scrape_interval_); if (!UpdateAllConnsAndEndpoints()) { continue; } int64_t time_micros = NowMicros(); const sensor::NetworkConnectionInfoMessage* msg; ContainerEndpointMap new_cep_state, delta_cep; ConnMap new_conn_state, delta_conn; WITH_TIMER(CollectorStats::net_fetch_state) { new_conn_state = conn_tracker_->FetchConnState(true, true); ConnectionTracker::ComputeDeltaAfterglow(new_conn_state, old_conn_state, delta_conn, time_micros, time_at_last_scrape, afterglow_period_micros_); new_cep_state = conn_tracker_->FetchEndpointState(true, true); ConnectionTracker::ComputeDeltaAfterglow(new_cep_state, old_cep_state, delta_cep, time_micros, time_at_last_scrape, afterglow_period_micros_); } WITH_TIMER(CollectorStats::net_create_message) { // Report the deltas msg = CreateInfoMessage(delta_conn, delta_cep); // Add new connections to the old_state and remove inactive connections that are older than the afterglow period. ConnectionTracker::UpdateOldState(&old_conn_state, new_conn_state, time_micros, afterglow_period_micros_); ConnectionTracker::UpdateOldState(&old_cep_state, new_cep_state, time_micros, afterglow_period_micros_); time_at_last_scrape = time_micros; } if (!msg) { continue; } WITH_TIMER(CollectorStats::net_write_message) { if (!writer->Write(*msg, next_scrape)) { CLOG(ERROR) << "Failed to write network connection info"; return; } } } } sensor::NetworkConnectionInfoMessage* NetworkStatusNotifier::CreateInfoMessage(const ConnMap& conn_delta, const ContainerEndpointMap& endpoint_delta) { if (conn_delta.empty() && endpoint_delta.empty()) return nullptr; Reset(); auto* msg = AllocateRoot(); auto* info = msg->mutable_info(); AddConnections(info->mutable_updated_connections(), conn_delta); COUNTER_ADD(CollectorStats::net_conn_deltas, conn_delta.size()); AddContainerEndpoints(info->mutable_updated_endpoints(), endpoint_delta); COUNTER_ADD(CollectorStats::net_cep_deltas, endpoint_delta.size()); *info->mutable_time() = CurrentTimeProto(); return msg; } void NetworkStatusNotifier::AddConnections(::google::protobuf::RepeatedPtrField<sensor::NetworkConnection>* updates, const ConnMap& delta) { for (const auto& delta_entry : delta) { auto* conn_proto = ConnToProto(delta_entry.first); if (!delta_entry.second.IsActive()) { *conn_proto->mutable_close_timestamp() = google::protobuf::util::TimeUtil::MicrosecondsToTimestamp( delta_entry.second.LastActiveTime()); } updates->AddAllocated(conn_proto); } } void NetworkStatusNotifier::AddContainerEndpoints(::google::protobuf::RepeatedPtrField<sensor::NetworkEndpoint>* updates, const ContainerEndpointMap& delta) { for (const auto& delta_entry : delta) { auto* endpoint_proto = ContainerEndpointToProto(delta_entry.first); if (!delta_entry.second.IsActive()) { *endpoint_proto->mutable_close_timestamp() = google::protobuf::util::TimeUtil::MicrosecondsToTimestamp( delta_entry.second.LastActiveTime()); } updates->AddAllocated(endpoint_proto); } } sensor::NetworkConnection* NetworkStatusNotifier::ConnToProto(const Connection& conn) { auto* conn_proto = Allocate<sensor::NetworkConnection>(); conn_proto->set_container_id(conn.container()); conn_proto->set_role(conn.is_server() ? sensor::ROLE_SERVER : sensor::ROLE_CLIENT); conn_proto->set_protocol(TranslateL4Protocol(conn.l4proto())); conn_proto->set_socket_family(TranslateAddressFamily(conn.local().address().family())); conn_proto->set_allocated_local_address(EndpointToProto(conn.local())); conn_proto->set_allocated_remote_address(EndpointToProto(conn.remote())); return conn_proto; } sensor::NetworkEndpoint* NetworkStatusNotifier::ContainerEndpointToProto(const ContainerEndpoint& cep) { auto* endpoint_proto = Allocate<sensor::NetworkEndpoint>(); endpoint_proto->set_container_id(cep.container()); endpoint_proto->set_protocol(TranslateL4Protocol(cep.l4proto())); endpoint_proto->set_socket_family(TranslateAddressFamily(cep.endpoint().address().family())); endpoint_proto->set_allocated_listen_address(EndpointToProto(cep.endpoint())); return endpoint_proto; } sensor::NetworkAddress* NetworkStatusNotifier::EndpointToProto(const collector::Endpoint& endpoint) { if (endpoint.IsNull()) { return nullptr; } // Note: We are sending the address data and network data as separate fields for // backward compatibility, although, network field can handle both. // Sensor tries to match address to known cluster entities. If that fails, it tries // to match the network to known external networks, auto* addr_proto = Allocate<sensor::NetworkAddress>(); auto addr_length = endpoint.address().length(); if (endpoint.network().IsAddress()) { addr_proto->set_address_data(endpoint.address().data(), addr_length); } if (endpoint.network().bits() > 0) { std::array<uint8_t, Address::kMaxLen + 1> buff; std::memcpy(buff.data(), endpoint.network().address().data(), addr_length); buff[addr_length] = endpoint.network().bits(); addr_proto->set_ip_network(buff.data(), addr_length + 1); } addr_proto->set_port(endpoint.port()); return addr_proto; } } // namespace collector
37.161369
233
0.733206
[ "vector" ]
5addad4cc48bf3e7f7339835b7d3cd86546c1df9
17,288
hh
C++
src/ob/fft.hh
octobanana/octavia
1c45addc4f8341bb7a8b445773efd3c8d2d10e90
[ "MIT" ]
11
2020-09-10T16:31:29.000Z
2022-01-14T12:17:08.000Z
src/ob/fft.hh
octobanana/octavia
1c45addc4f8341bb7a8b445773efd3c8d2d10e90
[ "MIT" ]
3
2020-09-14T15:18:39.000Z
2021-09-01T04:43:39.000Z
src/ob/fft.hh
octobanana/octavia
1c45addc4f8341bb7a8b445773efd3c8d2d10e90
[ "MIT" ]
1
2022-02-06T22:23:35.000Z
2022-02-06T22:23:35.000Z
/* 88888888 888888888888 88888888888888 8888888888888888 888888888888888888 888888 8888 888888 88888 88 88888 888888 8888 888888 88888888888888888888 88888888888888888888 8888888888888888888888 8888888888888888888888888888 88888888888888888888888888888888 88888888888888888888 888888888888888888888888 888888 8888888888 888888 888 8888 8888 888 888 888 OCTOBANANA Licensed under the MIT License Copyright (c) 2020 Brett Robinson <https://octobanana.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. */ /* This file is part of KISS FFT - https://github.com/mborgerding/kissfft Copyright (c) 2003-2010, Mark Borgerding. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef OB_FFT_HH #define OB_FFT_HH #include <cmath> #include <cstddef> #include <complex> #include <utility> #include <vector> namespace OB { template<typename Type, bool Inverse> class FFT_Basic final { public: using value_type = Type; using complex_type = std::complex<value_type>; FFT_Basic() = default; FFT_Basic(FFT_Basic&&) = default; FFT_Basic(FFT_Basic const&) = default; ~FFT_Basic() = default; FFT_Basic& operator=(FFT_Basic&&) = default; FFT_Basic& operator=(FFT_Basic const&) = default; void operator()(std::vector<complex_type> const& fft_in, std::vector<complex_type>& fft_out) { init(fft_in.size()); fft_out.resize(fft_in.size()); transform(&fft_in[0], &fft_out[0]); } void operator()(std::vector<value_type> const& fft_in, std::vector<complex_type>& fft_out) { init(fft_in.size()); fft_out.resize(fft_in.size()); transform(&fft_in[0], &fft_out[0]); } private: void init(std::size_t const nfft) { if (_nfft == nfft) { return; } _nfft = nfft; // fill twiddle factors _twiddles.resize(_nfft); if constexpr (Inverse) { value_type const phinc {static_cast<value_type>(2) * std::acos(static_cast<value_type>(-1)) / static_cast<value_type>(_nfft)}; for (std::size_t i = 0; i < _nfft; ++i) { _twiddles[i] = std::exp(complex_type(0, i * phinc)); } } else { value_type const phinc {static_cast<value_type>(-2) * std::acos(static_cast<value_type>(-1)) / static_cast<value_type>(_nfft)}; for (std::size_t i = 0; i < _nfft; ++i) { _twiddles[i] = std::exp(complex_type(0, i * phinc)); } } _stage_radix.clear(); _stage_remainder.clear(); std::size_t n {_nfft}; std::size_t p {4}; do { while (n % p) { switch (p) { case 4: p = 2; break; case 2: p = 3; break; default: p += 2; break; } if (p * p > n) { // no more factors p = n; } } n /= p; _stage_radix.emplace_back(p); _stage_remainder.emplace_back(n); } while (n > 1); } /// Calculates the complex Discrete Fourier Transform. /// /// The size of the passed arrays must be passed in the constructor. /// The sum of the squares of the absolute values in the @c dst /// array will be @c N times the sum of the squares of the absolute /// values in the @c src array, where @c N is the size of the array. /// In other words, the l_2 norm of the resulting array will be /// @c sqrt(N) times as big as the l_2 norm of the input array. /// This is also the case when the inverse flag is set in the /// constructor. Hence when applying the same transform twice, but with /// the inverse flag changed the second time, then the result will /// be equal to the original input times @c N. void transform(complex_type const* fft_in, complex_type* fft_out, std::size_t const stage = 0, std::size_t const fstride = 1, std::size_t const in_stride = 1) { std::size_t const p {_stage_radix[stage]}; std::size_t const m {_stage_remainder[stage]}; complex_type* const fout_beg {fft_out}; complex_type* const fout_end {fft_out + p * m}; if (m == 1) { do { *fft_out = *fft_in; fft_in += fstride * in_stride; } while (++fft_out != fout_end); } else { do { // recursive call: // DFT of size m*p performed by doing // p instances of smaller DFTs of size m, // each one takes a decimated version of the input transform(fft_in, fft_out, stage + 1, fstride * p, in_stride); fft_in += fstride * in_stride; } while ((fft_out += m) != fout_end); } fft_out = fout_beg; // recombine the p smaller DFTs switch (p) { case 2: kf_bfly2(fft_out, fstride, m); break; case 3: kf_bfly3(fft_out, fstride, m); break; case 4: kf_bfly4(fft_out, fstride, m); break; case 5: kf_bfly5(fft_out, fstride, m); break; default: kf_bfly_generic(fft_out, fstride, m, p); break; } } /// Calculates the Discrete Fourier Transform (DFT) of a real input /// of size @c 2*N. /// /// The 0-th and N-th value of the DFT are real numbers. These are /// stored in @c dst[0].real() and @c dst[0].imag() respectively. /// The remaining DFT values up to the index N-1 are stored in /// @c dst[1] to @c dst[N-1]. /// The other half of the DFT values can be calculated from the /// symmetry relation /// @code /// DFT(src)[2*N-k] == conj( DFT(src)[k] ); /// @endcode /// The same scaling factors as in @c transform() apply. /// /// @note For this to work, the types @c value_type and @c complex_type /// must fulfill the following requirements: /// /// For any object @c z of type @c complex_type, /// @c reinterpret_cast<value_type(&)[2]>(z)[0] is the real part of @c z and /// @c reinterpret_cast<value_type(&)[2]>(z)[1] is the imaginary part of @c z. /// For any pointer to an element of an array of @c complex_type named @c p /// and any valid array index @c i, @c reinterpret_cast<T*>(p)[2*i] /// is the real part of the complex number @c p[i], and /// @c reinterpret_cast<T*>(p)[2*i+1] is the imaginary part of the /// complex number @c p[i]. /// /// Since C++11, these requirements are guaranteed to be satisfied for /// @c value_types being @c float, @c double or @c long @c double /// together with @c complex_type being @c std::complex<value_type>. void transform(value_type const* const src, complex_type* const dst) { if (_nfft == 0) { return; } // perform complex FFT transform(reinterpret_cast<complex_type const*>(src), dst); // post processing for k = 0 and k = N dst[0] = complex_type(dst[0].real() + dst[0].imag(), dst[0].real() - dst[0].imag()); // post processing for all the other k = 1, 2, ..., N-1 if constexpr (Inverse) { value_type const pi {std::acos(static_cast<value_type>(-1))}; value_type const half_phi_inc {pi / _nfft}; complex_type const twiddle_mul {std::exp(complex_type(0, half_phi_inc))}; for (std::size_t k = 1; 2 * k < _nfft; ++k) { complex_type const w = static_cast<value_type>(0.5) * complex_type( dst[k].real() + dst[_nfft - k].real(), dst[k].imag() - dst[_nfft - k].imag()); const complex_type z = static_cast<value_type>(0.5) * complex_type( dst[k].imag() + dst[_nfft - k].imag(), -dst[k].real() + dst[_nfft - k].real()); const complex_type twiddle = k % 2 == 0 ? _twiddles[k / 2] : _twiddles[k / 2] * twiddle_mul; dst[k] = w + twiddle * z; dst[_nfft - k] = std::conj(w - twiddle * z); } if (_nfft % 2 == 0) { dst[_nfft / 2] = std::conj(dst[_nfft / 2]); } } else { value_type const pi {std::acos(static_cast<value_type>(-1))}; value_type const half_phi_inc {-pi / _nfft}; complex_type const twiddle_mul {std::exp(complex_type(0, half_phi_inc))}; for (std::size_t k = 1; 2 * k < _nfft; ++k) { complex_type const w = static_cast<value_type>(0.5) * complex_type( dst[k].real() + dst[_nfft - k].real(), dst[k].imag() - dst[_nfft - k].imag()); const complex_type z = static_cast<value_type>(0.5) * complex_type( dst[k].imag() + dst[_nfft - k].imag(), -dst[k].real() + dst[_nfft - k].real()); const complex_type twiddle = k % 2 == 0 ? _twiddles[k / 2] : _twiddles[k / 2] * twiddle_mul; dst[k] = w + twiddle * z; dst[_nfft - k] = std::conj(w - twiddle * z); } if (_nfft % 2 == 0) { dst[_nfft / 2] = std::conj(dst[_nfft / 2]); } } } void kf_bfly2(complex_type* fout, std::size_t const fstride, std::size_t const m) const { for (std::size_t k = 0; k < m; ++k) { complex_type const t {fout[m + k] * _twiddles[k * fstride]}; fout[m + k] = fout[k] - t; fout[k] += t; } } void kf_bfly3(complex_type* fout, std::size_t const fstride, std::size_t const m) const { std::size_t k {m}; std::size_t const m2 {2 * m}; complex_type const* tw1 {&_twiddles[0]}; complex_type const* tw2 {&_twiddles[0]}; complex_type const epi3 {_twiddles[fstride * m]}; complex_type scratch[5]; do{ scratch[1] = fout[m] * *tw1; scratch[2] = fout[m2] * *tw2; scratch[3] = scratch[1] + scratch[2]; scratch[0] = scratch[1] - scratch[2]; tw1 += fstride; tw2 += fstride * 2; fout[m] = fout[0] - scratch[3] * static_cast<value_type>(0.5); scratch[0] *= epi3.imag(); fout[0] += scratch[3]; fout[m2] = complex_type(fout[m].real() + scratch[0].imag() , fout[m].imag() - scratch[0].real()); fout[m] += complex_type(-scratch[0].imag(), scratch[0].real()); ++fout; } while (--k); } void kf_bfly4(complex_type* const fout, std::size_t const fstride, std::size_t const m) const { complex_type scratch[7]; if constexpr (Inverse) { for (std::size_t k = 0; k < m; ++k) { scratch[0] = fout[k + m] * _twiddles[k * fstride]; scratch[1] = fout[k + 2 * m] * _twiddles[k * fstride * 2]; scratch[2] = fout[k + 3 * m] * _twiddles[k * fstride * 3]; scratch[5] = fout[k] - scratch[1]; fout[k] += scratch[1]; scratch[3] = scratch[0] + scratch[2]; scratch[4] = scratch[0] - scratch[2]; scratch[4] = complex_type(scratch[4].imag() * -1, -scratch[4].real() * -1); fout[k + 2 * m] = fout[k] - scratch[3]; fout[k] += scratch[3]; fout[k + m] = scratch[5] + scratch[4]; fout[k + 3 * m] = scratch[5] - scratch[4]; } } else { for (std::size_t k = 0; k < m; ++k) { scratch[0] = fout[k + m] * _twiddles[k * fstride]; scratch[1] = fout[k + 2 * m] * _twiddles[k * fstride * 2]; scratch[2] = fout[k + 3 * m] * _twiddles[k * fstride * 3]; scratch[5] = fout[k] - scratch[1]; fout[k] += scratch[1]; scratch[3] = scratch[0] + scratch[2]; scratch[4] = scratch[0] - scratch[2]; scratch[4] = complex_type(scratch[4].imag(), -scratch[4].real()); fout[k + 2 * m] = fout[k] - scratch[3]; fout[k] += scratch[3]; fout[k + m] = scratch[5] + scratch[4]; fout[k + 3 * m] = scratch[5] - scratch[4]; } } } void kf_bfly5(complex_type* const fout, std::size_t const fstride, std::size_t const m) const { complex_type* fout0 {fout}; complex_type* fout1 {fout0 + m}; complex_type* fout2 {fout0 + m + 2}; complex_type* fout3 {fout0 + m + 3}; complex_type* fout4 {fout0 + m + 4}; complex_type scratch[13]; complex_type const ya {_twiddles[fstride * m]}; complex_type const yb {_twiddles[fstride * 2 * m]}; for (std::size_t u = 0; u < m; ++u) { scratch[0] = *fout0; scratch[1] = *fout1 * _twiddles[u * fstride]; scratch[2] = *fout2 * _twiddles[2 * u * fstride]; scratch[3] = *fout3 * _twiddles[3 * u * fstride]; scratch[4] = *fout4 * _twiddles[4 * u * fstride]; scratch[7] = scratch[1] + scratch[4]; scratch[10] = scratch[1] - scratch[4]; scratch[8] = scratch[2] + scratch[3]; scratch[9] = scratch[2] - scratch[3]; *fout0 += scratch[7]; *fout0 += scratch[8]; scratch[5] = scratch[0] + complex_type( scratch[7].real() * ya.real() + scratch[8].real() * yb.real(), scratch[7].imag() * ya.real() + scratch[8].imag() * yb.real()); scratch[6] = complex_type( scratch[10].imag() * ya.imag() + scratch[9].imag() * yb.imag(), -scratch[10].real() * ya.imag() - scratch[9].real() * yb.imag()); *fout1 = scratch[5] - scratch[6]; *fout4 = scratch[5] + scratch[6]; scratch[11] = scratch[0] + complex_type( scratch[7].real() * yb.real() + scratch[8].real() * ya.real(), scratch[7].imag() * yb.real() + scratch[8].imag() * ya.real()); scratch[12] = complex_type( -scratch[10].imag() * yb.imag() + scratch[9].imag() * ya.imag(), scratch[10].real() * yb.imag() - scratch[9].real() * ya.imag()); *fout2 = scratch[11] + scratch[12]; *fout3 = scratch[11] - scratch[12]; ++fout0; ++fout1; ++fout2; ++fout3; ++fout4; } } // perform the butterfly for one stage of a mixed radix FFT void kf_bfly_generic(complex_type* const fout, std::size_t const fstride, std::size_t const m, std::size_t const p) { complex_type const* twiddles {&_twiddles[0]}; if (p > _scratchbuf.size()) { _scratchbuf.resize(p); } for (std::size_t u = 0; u < m; ++u) { std::size_t k {u}; for (std::size_t q1 = 0; q1 < p; ++q1) { _scratchbuf[q1] = fout[k]; k += m; } k = u; for(std::size_t q1 = 0; q1 < p; ++q1) { std::size_t twidx {0}; fout[k] = _scratchbuf[0]; for (std::size_t q = 1; q < p; ++q) { twidx += fstride * k; if (twidx >= _nfft) { twidx -= _nfft; } fout[k] += _scratchbuf[q] * twiddles[twidx]; } k += m; } } } std::size_t _nfft {0}; std::vector<complex_type> _twiddles; std::vector<std::size_t> _stage_radix; std::vector<std::size_t> _stage_remainder; std::vector<complex_type> _scratchbuf; }; // class FFT_Basic template<typename T> using FFT = FFT_Basic<T, false>; template<typename T> using FFTI = FFT_Basic<T, true>; } // namespace OB #endif // OB_FFT_HH
36.627119
162
0.595558
[ "object", "vector", "transform" ]
5adff043d744c1ba3a8863d3074ddd7ba144a428
1,794
hpp
C++
gh/log_sink.hpp
coryan/gee-h
306ddb047b60e9bffdcee22f73960d984fb4dc44
[ "Apache-2.0" ]
2
2017-11-19T15:19:55.000Z
2019-12-19T09:14:00.000Z
gh/log_sink.hpp
coryan/gee-h
306ddb047b60e9bffdcee22f73960d984fb4dc44
[ "Apache-2.0" ]
6
2017-08-06T22:18:59.000Z
2018-05-24T18:54:32.000Z
gh/log_sink.hpp
coryan/gee-h
306ddb047b60e9bffdcee22f73960d984fb4dc44
[ "Apache-2.0" ]
2
2019-12-19T09:14:02.000Z
2020-10-26T10:05:05.000Z
#ifndef gh_log_sink_hpp #define gh_log_sink_hpp #include <gh/log_severity.hpp> #include <memory> #include <string> #include <utility> namespace gh { /** * A destination for logging messages. * * Applications can configure the destination for logging messages by setting one more more instances of gh::log_sink * in the global logger. */ class log_sink { public: virtual ~log_sink() {} /** * Log the given message to the sink. * * @param sev the severity of the message. * @param message the message value. */ virtual void log(severity sev, std::string&& message) = 0; }; /** * An adaptor that converts any Functor into a @c gh::log_sink. * * Often it is easier for the application developer to declare a long sink in-situ using a lambda or another functor * type. This class makes it easy to adapt such objects to the @c gh::log_sink interface. * * @tparam Functor the type of the functor to adapt. */ template<typename Functor> class log_to_functor : public log_sink { public: log_to_functor(Functor &&f) : functor(f) { } log_to_functor(Functor const& f) : log_to_functor(std::move(f)) { } /// Forward logging to the functor. virtual void log(severity sev, std::string&& message) override { functor(sev, std::move(message)); } private: Functor functor; }; /** * Create a @c gh::log_sink shared pointer from a functor. * * @tparam Functor the type of the functor object @a f. * @param f the functor object to forward calls to. * @return a log_sink that forwards log() calls to the given functor @a f. */ template<typename Functor> std::shared_ptr<log_sink> make_log_sink(Functor&& f) { return std::shared_ptr<log_sink>(new log_to_functor<Functor>(std::move(f))); } } // namespace gh #endif // gh_log_sink_hpp
24.575342
117
0.701784
[ "object" ]
5aeddf05317acc76002cdb8f6a4970d1a7eff714
6,974
cpp
C++
HarmonyEditor/src/Windows/CommonWindows.cpp
Nick-Fanelli/HarmonyEngine
383ec0253665a69b961371ada03edafef4ecdd2a
[ "MIT" ]
1
2021-01-09T23:26:06.000Z
2021-01-09T23:26:06.000Z
HarmonyEditor/src/Windows/CommonWindows.cpp
Nick-Fanelli/HarmonyEngine
383ec0253665a69b961371ada03edafef4ecdd2a
[ "MIT" ]
1
2021-08-15T18:58:07.000Z
2021-08-15T18:58:07.000Z
HarmonyEditor/src/Windows/CommonWindows.cpp
Nick-Fanelli/HarmonyEngine
383ec0253665a69b961371ada03edafef4ecdd2a
[ "MIT" ]
null
null
null
#include "CommonWindows.h" #include <Core/Input.h> using namespace HarmonyEditor; void CommonWindows::OnImGuiRender() { ConfirmationWindow::OnImGuiRender(); NewComponentWindow::OnImGuiRender(); } // Confirmation Window const char* ConfirmationWindow::s_PopupWindowTitle = "Confirmation Window"; bool ConfirmationWindow::s_ShouldOpen = false; bool ConfirmationWindow::s_UseVoidFunctionPtr = false; std::string ConfirmationWindow::s_PopupMessage; std::function<void(bool)> ConfirmationWindow::s_FunctionPtr; std::function<void()> ConfirmationWindow::s_VoidFunctionPtr; void ConfirmationWindow::Confirm(const std::string& message, std::function<void(bool)> functionPtr) { s_PopupMessage = message; s_FunctionPtr = functionPtr; s_UseVoidFunctionPtr = false; s_ShouldOpen = true; } void ConfirmationWindow::Confirm(const std::string& message, std::function<void()> functionPtr) { s_PopupMessage = message; s_VoidFunctionPtr = functionPtr; s_UseVoidFunctionPtr = true; s_ShouldOpen = true; } void ConfirmationWindow::OnImGuiRender() { static constexpr auto flags = ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse; if(s_ShouldOpen) { ImGui::OpenPopup(s_PopupWindowTitle); ImGui::SetNextWindowSize({ 300.0f, 125.0f }, ImGuiCond_Appearing); s_ShouldOpen = false; } if(ImGui::BeginPopupModal(s_PopupWindowTitle, NULL, flags)) { ImGui::TextWrapped("%s", s_PopupMessage.c_str()); ImGui::SetCursorPosY(ImGui::GetWindowHeight() - 35.0f); // 10px padding if(ImGui::Button("Cancel", { 75.0f, 25.0f })) { ImGui::CloseCurrentPopup(); if(!s_UseVoidFunctionPtr) s_FunctionPtr(false); } ImGui::SameLine(); if(ImGui::Button("Confirm", { 75.0f, 25.0f })) { ImGui::CloseCurrentPopup(); if(s_UseVoidFunctionPtr) s_VoidFunctionPtr(); else s_FunctionPtr(true); } ImGui::EndPopup(); } } // New Component Windows bool NewComponentWindow::s_IsVisable = false; Entity NewComponentWindow::s_CurrentEntity = {}; static const char* s_SelectedComponentID = nullptr; static bool s_ShouldApplyComponent = false; void NewComponentWindow::OpenNewComponentPopup(Entity& entity) { if(!entity) return; s_SelectedComponentID = nullptr; s_ShouldApplyComponent = false; s_CurrentEntity = entity; s_IsVisable = true; } void NewComponentWindow::CloseNewComponentPopup() { s_IsVisable = false; } template<typename ComponentType> static void DrawComponent(const char* componentName, Entity& entity, ImGuiTextFilter& filter) { static constexpr auto treeNodeFlags = ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen; if(!entity.ContainsComponent<ComponentType>() && filter.PassFilter(componentName)) { ImGui::TreeNodeEx(componentName, treeNodeFlags | ((s_SelectedComponentID == componentName) ? ImGuiTreeNodeFlags_Selected : 0)); if(s_ShouldApplyComponent && s_SelectedComponentID == componentName) { entity.AddComponent<ComponentType>(); NewComponentWindow::CloseNewComponentPopup(); } if(ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) { entity.AddComponent<ComponentType>(); NewComponentWindow::CloseNewComponentPopup(); } if(ImGui::IsItemClicked(ImGuiMouseButton_Left)) { s_SelectedComponentID = componentName; } } } void NewComponentWindow::OnImGuiRender() { // ImGui::ShowDemoWindow(); if(s_IsVisable) { static constexpr auto flags = ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoCollapse; ImGui::SetNextWindowSize({800.0f, 550.0f}, ImGuiCond_Appearing); ImGui::SetNextWindowPos({ ImGui::GetMainViewport()->GetCenter().x - 400.0f, ImGui::GetMainViewport()->GetCenter().y - 275.0f }, ImGuiCond_Appearing); ImGui::Begin("New Component", &s_IsVisable, flags); ImGui::BeginChild("##Component List", { ImGui::GetWindowWidth() / 2.0f, ImGui::GetContentRegionAvail().y }, false, flags); { static ImGuiTextFilter filter; // Draw Search Bar ImGui::Text("Search"); ImGui::SameLine(); filter.Draw("", ImGui::GetContentRegionAvailWidth()); DrawComponent<TransformComponent>("Transform", s_CurrentEntity, filter); DrawComponent<OrthographicCameraComponent>("Orthographic Camera", s_CurrentEntity, filter); DrawComponent<QuadRendererComponent>("Quad Renderer", s_CurrentEntity, filter); DrawComponent<SpriteRendererComponent>("Sprite Renderer", s_CurrentEntity, filter); DrawComponent<LuaScriptComponent>("Lua Script", s_CurrentEntity, filter); DrawComponent<PointLightComponent>("Point Light", s_CurrentEntity, filter); } ImGui::EndChild(); ImGui::SameLine(); ImGui::SeparatorEx(ImGuiSeparatorFlags_Vertical); ImGui::SameLine(); ImGui::BeginChild("Description View", ImGui::GetContentRegionAvail(), false, flags | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse); { float lineHeight = GImGui->Font->FontSize + GImGui->Style.FramePadding.y * 2.0f; ImGui::BeginChild("##Description", { ImGui::GetContentRegionAvailWidth(), ImGui::GetContentRegionAvail().y - lineHeight - 5.0f }, false, flags); if(!s_SelectedComponentID) // TODO: Implement somthing where it shows documentation for how components work ImGui::Text("%s", "Select A Component for Documentation"); else // Pull the specific component documentation from some wiki ImGui::Text("%s", "Component Documentation Comming Soon!"); ImGui::EndChild(); static const auto adjustment = ImGui::CalcTextSize("Add Component").x + 15.0f; ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetContentRegionAvailWidth() - adjustment); if(s_SelectedComponentID == nullptr) ImGui::PushStyleVar(ImGuiStyleVar_Alpha, 0.5f); s_ShouldApplyComponent |= ImGui::ButtonEx("Add Component", {}, (s_SelectedComponentID == nullptr ? ImGuiItemFlags_Disabled : 0)); if(Input::IsKeyDown(HARMONY_KEY_ENTER)) s_ShouldApplyComponent = true; if(s_SelectedComponentID == nullptr) { s_ShouldApplyComponent = false; ImGui::PopStyleVar(); } } ImGui::EndChild(); ImGui::End(); } }
35.764103
162
0.675509
[ "transform" ]
5aff80c43f1f87500af94dcd0067b0285463d4ac
3,970
cpp
C++
src/vbte/graphics/vertex_layout.cpp
Berling/bachelor_arbeit
c788227721a132560943c6991f5e3a25c47217cf
[ "MIT" ]
null
null
null
src/vbte/graphics/vertex_layout.cpp
Berling/bachelor_arbeit
c788227721a132560943c6991f5e3a25c47217cf
[ "MIT" ]
null
null
null
src/vbte/graphics/vertex_layout.cpp
Berling/bachelor_arbeit
c788227721a132560943c6991f5e3a25c47217cf
[ "MIT" ]
null
null
null
#include <vbte/graphics/vertex_layout.hpp> namespace vbte { namespace graphics { void vertex_layout::emplace_back(const std::string& name, uint32_t size, GLenum type, bool normalized, size_t stride, intptr_t offset, int index, int divisor) { auto attribute = vertex_attribute{name, size, type, normalized, stride, offset, index, 0, 1, divisor}; vertex_attributes_.emplace_back(attribute); } void vertex_layout::emplace_back(const std::string& name, uint32_t size, GLenum type, bool normalized, size_t stride, intptr_t offset, intptr_t attribute_size, int factor, int index, int divisor) { auto attribute = vertex_attribute{name, size, type, normalized, stride, intptr_t(offset), index, attribute_size / factor, factor, divisor}; vertex_attributes_.emplace_back(attribute); } void vertex_layout::emplace_back(const std::string& varying_name) { transform_feedback_varyings_.emplace_back(varying_name); } void vertex_layout::setup_layout(const vertex_array& vertex_array, const std::unique_ptr<vertex_buffer>* buffers) noexcept { vertex_array.bind(); auto i = uint32_t(0); for (auto& attribute : vertex_attributes_) { for (auto j = 0; j < attribute.factor; ++j) { buffers[attribute.index]->bind(); if (attribute.type == GL_INT) { vertex_array.bind_vertex_attributei(*(buffers[attribute.index]), i, attribute.size, attribute.type, attribute.stride, attribute.offset + j * attribute.component_offset); } else { vertex_array.bind_vertex_attribute(*(buffers[attribute.index]), i, attribute.size, attribute.type, attribute.normalized, attribute.stride, attribute.offset + j * attribute.component_offset); } glVertexAttribDivisor(i, attribute.divisor); ++i; } } } void vertex_layout::setup_layout(const vertex_array& vertex_array, const vertex_buffer* buffers) noexcept { vertex_array.bind(); auto i = uint32_t(0); for (auto& attribute : vertex_attributes_) { buffers[attribute.index].bind(); for (auto j = 0; j < attribute.factor; ++j) { if (attribute.type == GL_INT) { vertex_array.bind_vertex_attributei(buffers[attribute.index], i, attribute.size, attribute.type, attribute.stride, attribute.offset + j * attribute.component_offset); } else { vertex_array.bind_vertex_attribute(buffers[attribute.index], i, attribute.size, attribute.type, attribute.normalized, attribute.stride, attribute.offset + j * attribute.component_offset); } glVertexAttribDivisor(i, attribute.divisor); ++i; } } } void vertex_layout::setup_layout(const vertex_array& vertex_array, const vertex_buffer** buffers) noexcept { vertex_array.bind(); auto i = uint32_t(0); for (auto& attribute : vertex_attributes_) { buffers[attribute.index]->bind(); for (auto j = 0; j < attribute.factor; ++j) { if (attribute.type == GL_INT) { vertex_array.bind_vertex_attributei(*buffers[attribute.index], i, attribute.size, attribute.type, attribute.stride, attribute.offset + j * attribute.component_offset); } else { vertex_array.bind_vertex_attribute(*buffers[attribute.index], i, attribute.size, attribute.type, attribute.normalized, attribute.stride, attribute.offset + j * attribute.component_offset); } glVertexAttribDivisor(i, attribute.divisor); ++i; } } } void vertex_layout::setup_program(program& program, const std::string& fragcolor_name) noexcept { auto i = uint32_t(0); for (auto& attribute : vertex_attributes_) { program.bind_attribute_location(attribute.name, i); i += attribute.factor; } program.bind_frag_data_location(fragcolor_name, 0); if (transform_feedback_varyings_.size() != 0) { std::vector<const char*> varyings; for (auto& v : transform_feedback_varyings_) { varyings.emplace_back(v.c_str()); } glTransformFeedbackVaryings(program.id_, varyings.size(), varyings.data(), GL_INTERLEAVED_ATTRIBS); } } } }
44.606742
199
0.721662
[ "vector" ]
850039e0e9535f54d545db47a63b292dbf4026cf
7,308
cc
C++
agp-7.1.0-alpha01/tools/base/deploy/installer/dump.cc
jomof/CppBuildCacheWorkInProgress
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
[ "Apache-2.0" ]
null
null
null
agp-7.1.0-alpha01/tools/base/deploy/installer/dump.cc
jomof/CppBuildCacheWorkInProgress
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
[ "Apache-2.0" ]
null
null
null
agp-7.1.0-alpha01/tools/base/deploy/installer/dump.cc
jomof/CppBuildCacheWorkInProgress
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "tools/base/deploy/installer/dump.h" #include <iostream> #include <dirent.h> #include <libgen.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> #include "tools/base/deploy/common/event.h" #include "tools/base/deploy/common/io.h" #include "tools/base/deploy/common/log.h" #include "tools/base/deploy/common/utils.h" #include "tools/base/deploy/installer/apk_archive.h" #include "tools/base/deploy/installer/command_cmd.h" #include "tools/base/deploy/installer/executor/executor.h" #include "tools/base/deploy/installer/executor/runas_executor.h" #include "tools/base/deploy/proto/deploy.pb.h" namespace deploy { void DumpCommand::ParseParameters(const proto::InstallerRequest& request) { if (!request.has_dump_request()) { return; } proto::DumpRequest dumpRequest = request.dump_request(); for (size_t i = 0; i < dumpRequest.package_names_size(); i++) { const std::string& package_name = dumpRequest.package_names(i); package_names_.emplace_back(package_name); } ready_to_run_ = true; } void DumpCommand::Run(proto::InstallerResponse* response) { Phase p("Command Dump"); auto dump_response = response->mutable_dump_response(); for (const std::string& package_name : package_names_) { proto::PackageDump* package_dump = dump_response->add_packages(); package_dump->set_name(package_name); GetProcessIds(package_name, package_dump); // TODO: Since dump performs multiple operations, this should not // terminate the command. Processing should continue here. if (!GetApks(package_name, package_dump)) { dump_response->set_status(proto::DumpResponse::ERROR_PACKAGE_NOT_FOUND); dump_response->set_failed_package(package_name); return; } } dump_response->set_status(proto::DumpResponse::OK); } bool DumpCommand::GetApks(const std::string& package_name, proto::PackageDump* package_dump) { // Retrieve apks for this package. std::vector<std::string> apks_path; std::string error_message; CmdCommand cmd(workspace_); if (!cmd.GetApks(package_name, &apks_path, &error_message)) { ErrEvent("Could not find apks for this package: " + package_name); ErrEvent("Error: " + error_message); return false; } if (apks_path.size() == 0) { ErrEvent("Could not find apks for package: " + package_name); return false; } // Extract all apks. for (std::string& apk_path : apks_path) { Phase p2("processing APK"); ApkArchive archive(apk_path); Dump dump = archive.ExtractMetadata(); proto::ApkDump* apk_dump = package_dump->add_apks(); apk_dump->set_absolute_path(apk_path); if (dump.cd != nullptr || dump.signature != nullptr) { std::string apk_file_name = std::string(strrchr(apk_path.c_str(), '/') + 1); apk_dump->set_name(apk_file_name); } if (dump.cd != nullptr) { apk_dump->set_allocated_cd(dump.cd.release()); } if (dump.signature != nullptr) { apk_dump->set_allocated_signature(dump.signature.release()); } } return true; } bool DumpCommand::GetProcessIds(const std::string& package_name, proto::PackageDump* package_dump) { Phase p("get process ids"); std::string output; std::string error; RunasExecutor run_as(package_name); if (!run_as.Run("id", {"-u"}, &output, &error)) { ErrEvent("Could not get package user id: " + error); return false; } int package_uid = strtol(output.c_str(), nullptr, 10); if (package_uid < 0) { ErrEvent("Could not parse package user id: " + output); return false; } DIR* proc_dir = IO::opendir("/proc"); if (proc_dir == nullptr) { ErrEvent("Could not open system '/proc' directory"); return false; } int zygote_pid = 0; int zygote64_pid = 0; std::vector<ProcStats> stats_list; // Search the /proc directory for processes with a uid equal to the package // uid, as well as for the zygote and zygote64 processes. dirent* proc_entry; while ((proc_entry = readdir(proc_dir)) != nullptr) { // Skip entries that aren't integers. int pid = strtol(proc_entry->d_name, nullptr, 10); if (pid <= 0) { continue; } // Try to parse this process. If we fail, just continue to the next one. // Default constructor handles proper intialization of the stats struct. ProcStats stats; if (!ParseProc(proc_entry, &stats)) { continue; } // We obtain the zygote pids to allow us to filter out any non-ART // processes, as well as to determine whether each process is 32 or 64 // bit. if (strcmp(stats.name, "zygote") == 0) { zygote_pid = stats.pid; } else if (strcmp(stats.name, "zygote64") == 0) { zygote64_pid = stats.pid; } else if (stats.uid == package_uid) { stats_list.emplace_back(stats); } } closedir(proc_dir); // If we haven't found any zygote processes, we can't tell what is an ART // process and what isn't, so we should exit early. if (zygote_pid == 0 && zygote64_pid == 0) { ErrEvent("Could not find a zygote process"); return false; } for (auto& stats : stats_list) { // We assume an app can't mix 32-bit and 64-bit ART processes, so we just // set this to the last architecture of the last zygote child we find. if (stats.ppid == zygote_pid) { package_dump->set_arch(proto::ARCH_32_BIT); } else if (stats.ppid == zygote64_pid) { package_dump->set_arch(proto::ARCH_64_BIT); } else { continue; } package_dump->add_processes(stats.pid); } return true; } bool DumpCommand::ParseProc(dirent* proc_entry, ProcStats* stats) { const std::string proc_path = "/proc/"_s + proc_entry->d_name; struct stat proc_dir_stat; if (IO::stat(proc_path, &proc_dir_stat) < 0) { return false; } stats->uid = proc_dir_stat.st_uid; std::string cmdline_path = proc_path + "/cmdline"; FILE* proc_cmdline = IO::fopen(cmdline_path, "r"); if (proc_cmdline == nullptr) { return false; } // Read up to 15 characters + the null terminator. Processes may have an // empty command line, so we don't need to check that this succeeds. fscanf(proc_cmdline, "%15s", stats->name); fclose(proc_cmdline); std::string stat_path = proc_path + "/stat"; FILE* proc_stat = IO::fopen(stat_path, "r"); if (proc_stat == nullptr) { return false; } // The format of this string is well-specified by man proc(5). int parsed = fscanf(proc_stat, "%d %*s %*c %d", &stats->pid, &stats->ppid); fclose(proc_stat); if (parsed != 2) { return false; } return true; } } // namespace deploy
30.705882
78
0.678024
[ "vector" ]
85051d73db97f2d038286690f9281743c66cf497
19,155
cc
C++
alljoyn_core/src/PermissionConfigurator.cc
liuxiang88/core-alljoyn
549c966482d9b89da84aa528117584e7049916cb
[ "Apache-2.0" ]
33
2018-01-12T00:37:43.000Z
2022-03-24T02:31:36.000Z
alljoyn_core/src/PermissionConfigurator.cc
liuxiang88/core-alljoyn
549c966482d9b89da84aa528117584e7049916cb
[ "Apache-2.0" ]
1
2020-01-05T05:51:27.000Z
2020-01-05T05:51:27.000Z
alljoyn_core/src/PermissionConfigurator.cc
liuxiang88/core-alljoyn
549c966482d9b89da84aa528117584e7049916cb
[ "Apache-2.0" ]
30
2017-12-13T23:24:00.000Z
2022-01-25T02:11:19.000Z
/** * @file * This file defines the implementation of the Permission Configurator to allow app to setup some permission templates. */ /****************************************************************************** * Copyright (c) Open Connectivity Foundation (OCF), AllJoyn Open Source * Project (AJOSP) Contributors and others. * * SPDX-License-Identifier: Apache-2.0 * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution, and is available at * http://www.apache.org/licenses/LICENSE-2.0 * * Copyright (c) Open Connectivity Foundation and Contributors to AllSeen * Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for * any purpose with or without fee is hereby granted, provided that the * above copyright notice and this permission notice appear in all * copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. ******************************************************************************/ #include <qcc/CryptoECC.h> #include <qcc/KeyInfoECC.h> #include <qcc/StringUtil.h> #include <alljoyn/PermissionConfigurator.h> #include <alljoyn/SecurityApplicationProxy.h> #include "PermissionMgmtObj.h" #include "BusInternal.h" #include "CredentialAccessor.h" #include "KeyInfoHelper.h" #include "XmlManifestConverter.h" #include "XmlManifestTemplateConverter.h" #define QCC_MODULE "PERMISSION_MGMT" using namespace std; using namespace qcc; namespace ajn { /* Keep this definition in sync with the doc comment for this constant in PermissionConfigurator.h. */ const uint16_t PermissionConfigurator::CLAIM_CAPABILITIES_DEFAULT = (CAPABLE_ECDHE_NULL | CAPABLE_ECDHE_PSK | CAPABLE_ECDHE_SPEKE); /** * Class for internal state of a PermissionConfigurator object. */ class PermissionConfigurator::Internal { public: /** * Constructor. */ Internal(BusAttachment& bus) : m_bus(bus) { } /* Reference to the relevant bus attachment */ BusAttachment& m_bus; private: /** * Assignment operator is private. */ Internal& operator=(const Internal& other); /** * Copy constructor is private. */ Internal(const Internal& other); }; PermissionConfigurator::PermissionConfigurator(BusAttachment& bus) : m_internal(new PermissionConfigurator::Internal(bus)) { } PermissionConfigurator::~PermissionConfigurator() { delete m_internal; m_internal = nullptr; } QStatus PermissionConfigurator::GetManifestTemplateAsXml(string& manifestTemplateXml) { PermissionMgmtObj* permissionMgmtObj = m_internal->m_bus.GetInternal().GetPermissionManager().GetPermissionMgmtObj(); if (!permissionMgmtObj || !permissionMgmtObj->IsReady()) { QCC_DbgPrintf(("PermissionConfigurator::SetPermissionManifestTemplate does not have PermissionMgmtObj initialized")); return ER_FEATURE_NOT_AVAILABLE; } vector<PermissionPolicy::Rule> manifestTemplate; QStatus status = permissionMgmtObj->GetManifestTemplate(manifestTemplate); if (ER_OK != status) { return status; } return XmlManifestTemplateConverter::GetInstance()->RulesToXml(manifestTemplate.data(), manifestTemplate.size(), manifestTemplateXml); } QStatus PermissionConfigurator::SetPermissionManifestTemplate(PermissionPolicy::Rule* rules, size_t count) { PermissionMgmtObj* permissionMgmtObj = m_internal->m_bus.GetInternal().GetPermissionManager().GetPermissionMgmtObj(); if (!permissionMgmtObj || !permissionMgmtObj->IsReady()) { QCC_DbgPrintf(("PermissionConfigurator::SetPermissionManifestTemplate does not have PermissionMgmtObj initialized")); return ER_FEATURE_NOT_AVAILABLE; } return permissionMgmtObj->SetManifestTemplate(rules, count); } QStatus PermissionConfigurator::SetManifestTemplateFromXml(AJ_PCSTR manifestXml) { QStatus status; std::vector<PermissionPolicy::Rule> rules; status = XmlManifestTemplateConverter::GetInstance()->XmlToRules(manifestXml, rules); if (ER_OK == status) { status = SetPermissionManifestTemplate(rules.data(), rules.size()); } return status; } QStatus PermissionConfigurator::GetApplicationState(ApplicationState& applicationState) const { PermissionMgmtObj* permissionMgmtObj = m_internal->m_bus.GetInternal().GetPermissionManager().GetPermissionMgmtObj(); if (!permissionMgmtObj || !permissionMgmtObj->IsReady()) { return ER_FEATURE_NOT_AVAILABLE; } applicationState = permissionMgmtObj->GetApplicationState(); return ER_OK; } QStatus PermissionConfigurator::SetApplicationState(ApplicationState newState) { PermissionMgmtObj* permissionMgmtObj = m_internal->m_bus.GetInternal().GetPermissionManager().GetPermissionMgmtObj(); if (!permissionMgmtObj || !permissionMgmtObj->IsReady()) { return ER_FEATURE_NOT_AVAILABLE; } return permissionMgmtObj->SetApplicationState(newState); } QStatus PermissionConfigurator::Reset() { PermissionMgmtObj* permissionMgmtObj = m_internal->m_bus.GetInternal().GetPermissionManager().GetPermissionMgmtObj(); if (!permissionMgmtObj || !permissionMgmtObj->IsReady()) { return ER_FEATURE_NOT_AVAILABLE; } return permissionMgmtObj->Reset(false); } QStatus PermissionConfigurator::GetSigningPublicKey(KeyInfoECC& keyInfo) { if (keyInfo.GetCurve() != Crypto_ECC::ECC_NIST_P256) { return ER_NOT_IMPLEMENTED; /* currently only support NIST P256 curve */ } CredentialAccessor ca(m_internal->m_bus); ECCPublicKey publicKey; QStatus status = ca.GetDSAPublicKey(publicKey); if (status != ER_OK) { return status; } KeyInfoNISTP256* pKeyInfo = (KeyInfoNISTP256*) &keyInfo; pKeyInfo->SetPublicKey(&publicKey); KeyInfoHelper::GenerateKeyId(*pKeyInfo); return ER_OK; } QStatus PermissionConfigurator::SignCertificate(CertificateX509& cert) { CredentialAccessor ca(m_internal->m_bus); ECCPrivateKey privateKey; QStatus status = ca.GetDSAPrivateKey(privateKey); if (status != ER_OK) { return status; } ECCPublicKey publicKey; status = ca.GetDSAPublicKey(publicKey); if (status != ER_OK) { return status; } return cert.SignAndGenerateAuthorityKeyId(&privateKey, &publicKey); } QStatus PermissionConfigurator::SignManifest(const std::vector<uint8_t>& subjectThumbprint, Manifest& manifest) { QCC_DbgTrace(("%s", __FUNCTION__)); CredentialAccessor ca(m_internal->m_bus); ECCPrivateKey privateKey; QStatus status = ca.GetDSAPrivateKey(privateKey); if (status != ER_OK) { QCC_LogError(status, ("Could not GetDSAPrivateKey")); return status; } status = manifest->Sign(subjectThumbprint, &privateKey); return status; } QStatus PermissionConfigurator::ComputeThumbprintAndSignManifest(const qcc::CertificateX509& subjectCertificate, Manifest& manifest) { QCC_DbgTrace(("%s", __FUNCTION__)); CredentialAccessor ca(m_internal->m_bus); ECCPrivateKey privateKey; QStatus status = ca.GetDSAPrivateKey(privateKey); if (status != ER_OK) { QCC_LogError(status, ("Could not GetDSAPrivateKey")); return status; } status = manifest->ComputeThumbprintAndSign(subjectCertificate, &privateKey); return status; } QStatus PermissionConfigurator::ComputeThumbprintAndSignManifestXml(const qcc::CertificateX509& subjectCertificate, std::string& manifestXml) { QCC_DbgTrace(("%s", __FUNCTION__)); Manifest manifest; const size_t manifestSize = 1; std::vector<PermissionPolicy::Rule> rules; QStatus status = XmlManifestTemplateConverter::GetInstance()->XmlToRules(manifestXml.c_str(), rules); if (status != ER_OK) { QCC_LogError(status, ("Could not convert string to manifest")); return status; } status = manifest->SetRules(&rules[0], manifestSize); if (status != ER_OK) { QCC_LogError(status, ("could not set rules on manifest")); return status; } status = ComputeThumbprintAndSignManifest(subjectCertificate, manifest); if (status != ER_OK) { QCC_LogError(status, ("error computing thumbprint and/or signing")); return status; } return XmlManifestConverter::ManifestToXml(manifest, manifestXml); } QStatus PermissionConfigurator::GetConnectedPeerPublicKey(const GUID128& guid, qcc::ECCPublicKey* publicKey) { PermissionMgmtObj* permissionMgmtObj = m_internal->m_bus.GetInternal().GetPermissionManager().GetPermissionMgmtObj(); if (!permissionMgmtObj || !permissionMgmtObj->IsReady()) { return ER_FEATURE_NOT_AVAILABLE; } return permissionMgmtObj->GetConnectedPeerPublicKey(guid, publicKey); } QStatus PermissionConfigurator::SetClaimCapabilities(PermissionConfigurator::ClaimCapabilities claimCapabilities) { PermissionMgmtObj* permissionMgmtObj = m_internal->m_bus.GetInternal().GetPermissionManager().GetPermissionMgmtObj(); if (!permissionMgmtObj || !permissionMgmtObj->IsReady()) { return ER_FEATURE_NOT_AVAILABLE; } return permissionMgmtObj->SetClaimCapabilities(claimCapabilities); } QStatus PermissionConfigurator::SetClaimCapabilityAdditionalInfo(PermissionConfigurator::ClaimCapabilityAdditionalInfo additionalInfo) { PermissionMgmtObj* permissionMgmtObj = m_internal->m_bus.GetInternal().GetPermissionManager().GetPermissionMgmtObj(); if (!permissionMgmtObj || !permissionMgmtObj->IsReady()) { return ER_FEATURE_NOT_AVAILABLE; } return permissionMgmtObj->SetClaimCapabilityAdditionalInfo(additionalInfo); } QStatus PermissionConfigurator::GetClaimCapabilities(PermissionConfigurator::ClaimCapabilities& claimCapabilities) const { PermissionMgmtObj* permissionMgmtObj = m_internal->m_bus.GetInternal().GetPermissionManager().GetPermissionMgmtObj(); if (!permissionMgmtObj || !permissionMgmtObj->IsReady()) { return ER_FEATURE_NOT_AVAILABLE; } return permissionMgmtObj->GetClaimCapabilities(claimCapabilities); } QStatus PermissionConfigurator::GetClaimCapabilityAdditionalInfo(PermissionConfigurator::ClaimCapabilityAdditionalInfo& additionalInfo) const { PermissionMgmtObj* permissionMgmtObj = m_internal->m_bus.GetInternal().GetPermissionManager().GetPermissionMgmtObj(); if (!permissionMgmtObj || !permissionMgmtObj->IsReady()) { return ER_FEATURE_NOT_AVAILABLE; } return permissionMgmtObj->GetClaimCapabilityAdditionalInfo(additionalInfo); } QStatus PermissionConfigurator::Claim( const KeyInfoNISTP256& certificateAuthority, const qcc::GUID128& adminGroupGuid, const KeyInfoNISTP256& adminGroupAuthority, const qcc::CertificateX509* identityCertChain, size_t identityCertChainCount, AJ_PCSTR* manifestsXmls, size_t manifestsCount) { PermissionMgmtObj* permissionMgmtObj = m_internal->m_bus.GetInternal().GetPermissionManager().GetPermissionMgmtObj(); if (!permissionMgmtObj || !permissionMgmtObj->IsReady()) { return ER_FEATURE_NOT_AVAILABLE; } std::vector<Manifest> manifests; QStatus status = XmlManifestConverter::XmlArrayToManifests(manifestsXmls, manifestsCount, manifests); if (ER_OK == status) { PermissionMgmtObj::TrustAnchor caTrustAnchor(PermissionMgmtObj::TRUST_ANCHOR_CA, certificateAuthority); PermissionMgmtObj::TrustAnchor adminGroupAnchor(PermissionMgmtObj::TRUST_ANCHOR_SG_AUTHORITY, adminGroupAuthority); adminGroupAnchor.securityGroupId = adminGroupGuid; return permissionMgmtObj->Claim( caTrustAnchor, adminGroupAnchor, identityCertChain, identityCertChainCount, manifests.data(), manifests.size(), false); } else { return status; } } QStatus PermissionConfigurator::UpdateIdentity( const qcc::CertificateX509* certs, size_t certCount, AJ_PCSTR* manifestsXmls, size_t manifestsCount) { PermissionMgmtObj* permissionMgmtObj = m_internal->m_bus.GetInternal().GetPermissionManager().GetPermissionMgmtObj(); if (!permissionMgmtObj || !permissionMgmtObj->IsReady()) { return ER_FEATURE_NOT_AVAILABLE; } std::vector<Manifest> manifests; QStatus status = XmlManifestConverter::XmlArrayToManifests(manifestsXmls, manifestsCount, manifests); if (ER_OK == status) { return permissionMgmtObj->UpdateIdentity(certs, certCount, manifests.data(), manifests.size()); } else { return status; } } QStatus PermissionConfigurator::GetIdentity(std::vector<qcc::CertificateX509>& certChain) { PermissionMgmtObj* permissionMgmtObj = m_internal->m_bus.GetInternal().GetPermissionManager().GetPermissionMgmtObj(); if (!permissionMgmtObj || !permissionMgmtObj->IsReady()) { return ER_FEATURE_NOT_AVAILABLE; } return permissionMgmtObj->GetIdentity(certChain); } QStatus PermissionConfigurator::GetManifests(std::vector<Manifest>& manifests) { PermissionMgmtObj* permissionMgmtObj = m_internal->m_bus.GetInternal().GetPermissionManager().GetPermissionMgmtObj(); if (!permissionMgmtObj || !permissionMgmtObj->IsReady()) { return ER_FEATURE_NOT_AVAILABLE; } return permissionMgmtObj->RetrieveManifests(manifests); } QStatus PermissionConfigurator::GetIdentityCertificateId(qcc::String& serial, qcc::KeyInfoNISTP256& issuerKeyInfo) { PermissionMgmtObj* permissionMgmtObj = m_internal->m_bus.GetInternal().GetPermissionManager().GetPermissionMgmtObj(); if (!permissionMgmtObj || !permissionMgmtObj->IsReady()) { return ER_FEATURE_NOT_AVAILABLE; } return permissionMgmtObj->RetrieveIdentityCertificateId(serial, issuerKeyInfo); } QStatus PermissionConfigurator::UpdatePolicy(const PermissionPolicy& policy) { PermissionMgmtObj* permissionMgmtObj = m_internal->m_bus.GetInternal().GetPermissionManager().GetPermissionMgmtObj(); if (!permissionMgmtObj || !permissionMgmtObj->IsReady()) { return ER_FEATURE_NOT_AVAILABLE; } return permissionMgmtObj->InstallPolicy(policy); } QStatus PermissionConfigurator::GetPolicy(PermissionPolicy& policy) { PermissionMgmtObj* permissionMgmtObj = m_internal->m_bus.GetInternal().GetPermissionManager().GetPermissionMgmtObj(); if (!permissionMgmtObj || !permissionMgmtObj->IsReady()) { return ER_FEATURE_NOT_AVAILABLE; } return permissionMgmtObj->RetrievePolicy(policy, false); } QStatus PermissionConfigurator::GetDefaultPolicy(PermissionPolicy& policy) { PermissionMgmtObj* permissionMgmtObj = m_internal->m_bus.GetInternal().GetPermissionManager().GetPermissionMgmtObj(); if (!permissionMgmtObj || !permissionMgmtObj->IsReady()) { return ER_FEATURE_NOT_AVAILABLE; } return permissionMgmtObj->RetrievePolicy(policy, true); } QStatus PermissionConfigurator::ResetPolicy() { PermissionMgmtObj* permissionMgmtObj = m_internal->m_bus.GetInternal().GetPermissionManager().GetPermissionMgmtObj(); if (!permissionMgmtObj || !permissionMgmtObj->IsReady()) { return ER_FEATURE_NOT_AVAILABLE; } return permissionMgmtObj->ResetPolicy(); } QStatus PermissionConfigurator::GetMembershipSummaries(std::vector<String>& serials, std::vector<KeyInfoNISTP256>& keyInfos) { PermissionMgmtObj* permissionMgmtObj = m_internal->m_bus.GetInternal().GetPermissionManager().GetPermissionMgmtObj(); if (!permissionMgmtObj || !permissionMgmtObj->IsReady()) { serials.clear(); keyInfos.clear(); return ER_FEATURE_NOT_AVAILABLE; } MsgArg arg; QStatus status = permissionMgmtObj->GetMembershipSummaries(arg); if (ER_OK != status) { serials.clear(); keyInfos.clear(); return status; } size_t count = arg.v_array.GetNumElements(); serials.resize(count); keyInfos.resize(count); status = SecurityApplicationProxy::MsgArgToCertificateIds(arg, serials.data(), keyInfos.data(), count); if (ER_OK != status) { serials.clear(); keyInfos.clear(); } return status; } QStatus PermissionConfigurator::InstallMembership(const qcc::CertificateX509* certChain, size_t certCount) { PermissionMgmtObj* permissionMgmtObj = m_internal->m_bus.GetInternal().GetPermissionManager().GetPermissionMgmtObj(); if (!permissionMgmtObj || !permissionMgmtObj->IsReady()) { return ER_FEATURE_NOT_AVAILABLE; } return permissionMgmtObj->StoreMembership(certChain, certCount); } QStatus PermissionConfigurator::RemoveMembership(const qcc::String& serial, const qcc::ECCPublicKey* issuerPubKey, const qcc::String& issuerAki) { PermissionMgmtObj* permissionMgmtObj = m_internal->m_bus.GetInternal().GetPermissionManager().GetPermissionMgmtObj(); if (!permissionMgmtObj || !permissionMgmtObj->IsReady()) { return ER_FEATURE_NOT_AVAILABLE; } return permissionMgmtObj->RemoveMembership(serial, issuerPubKey, issuerAki); } QStatus PermissionConfigurator::RemoveMembership(const qcc::String& serial, const qcc::KeyInfoNISTP256& issuerKeyInfo) { String issuerAki((const char*)issuerKeyInfo.GetKeyId(), issuerKeyInfo.GetKeyIdLen()); return RemoveMembership(serial, issuerKeyInfo.GetPublicKey(), issuerAki); } QStatus PermissionConfigurator::StartManagement() { PermissionMgmtObj* permissionMgmtObj = m_internal->m_bus.GetInternal().GetPermissionManager().GetPermissionMgmtObj(); if (!permissionMgmtObj || !permissionMgmtObj->IsReady()) { return ER_FEATURE_NOT_AVAILABLE; } return permissionMgmtObj->StartManagement(); } QStatus PermissionConfigurator::EndManagement() { PermissionMgmtObj* permissionMgmtObj = m_internal->m_bus.GetInternal().GetPermissionManager().GetPermissionMgmtObj(); if (!permissionMgmtObj || !permissionMgmtObj->IsReady()) { return ER_FEATURE_NOT_AVAILABLE; } return permissionMgmtObj->EndManagement(); } QStatus PermissionConfigurator::InstallManifests(AJ_PCSTR* manifestsXmls, size_t manifestsCount, bool append) { PermissionMgmtObj* permissionMgmtObj = m_internal->m_bus.GetInternal().GetPermissionManager().GetPermissionMgmtObj(); if (!permissionMgmtObj || !permissionMgmtObj->IsReady()) { return ER_FEATURE_NOT_AVAILABLE; } std::vector<Manifest> manifests; QStatus status = XmlManifestConverter::XmlArrayToManifests(manifestsXmls, manifestsCount, manifests); if (ER_OK == status) { return permissionMgmtObj->StoreManifests(manifests.size(), manifests.data(), append); } else { return status; } } }
37.194175
144
0.739546
[ "object", "vector" ]
8505a34802e884469eca3027554b2a8442533967
1,944
cpp
C++
android-31/android/telephony/mbms/GroupCall.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/android/telephony/mbms/GroupCall.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/android/telephony/mbms/GroupCall.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "./GroupCall.hpp" namespace android::telephony::mbms { // Fields jint GroupCall::REASON_BY_USER_REQUEST() { return getStaticField<jint>( "android.telephony.mbms.GroupCall", "REASON_BY_USER_REQUEST" ); } jint GroupCall::REASON_FREQUENCY_CONFLICT() { return getStaticField<jint>( "android.telephony.mbms.GroupCall", "REASON_FREQUENCY_CONFLICT" ); } jint GroupCall::REASON_LEFT_MBMS_BROADCAST_AREA() { return getStaticField<jint>( "android.telephony.mbms.GroupCall", "REASON_LEFT_MBMS_BROADCAST_AREA" ); } jint GroupCall::REASON_NONE() { return getStaticField<jint>( "android.telephony.mbms.GroupCall", "REASON_NONE" ); } jint GroupCall::REASON_NOT_CONNECTED_TO_HOMECARRIER_LTE() { return getStaticField<jint>( "android.telephony.mbms.GroupCall", "REASON_NOT_CONNECTED_TO_HOMECARRIER_LTE" ); } jint GroupCall::REASON_OUT_OF_MEMORY() { return getStaticField<jint>( "android.telephony.mbms.GroupCall", "REASON_OUT_OF_MEMORY" ); } jint GroupCall::STATE_STALLED() { return getStaticField<jint>( "android.telephony.mbms.GroupCall", "STATE_STALLED" ); } jint GroupCall::STATE_STARTED() { return getStaticField<jint>( "android.telephony.mbms.GroupCall", "STATE_STARTED" ); } jint GroupCall::STATE_STOPPED() { return getStaticField<jint>( "android.telephony.mbms.GroupCall", "STATE_STOPPED" ); } // QJniObject forward GroupCall::GroupCall(QJniObject obj) : JObject(obj) {} // Constructors // Methods void GroupCall::close() const { callMethod<void>( "close", "()V" ); } jlong GroupCall::getTmgi() const { return callMethod<jlong>( "getTmgi", "()J" ); } void GroupCall::updateGroupCall(JObject arg0, JObject arg1) const { callMethod<void>( "updateGroupCall", "(Ljava/util/List;Ljava/util/List;)V", arg0.object(), arg1.object() ); } } // namespace android::telephony::mbms
19.247525
66
0.698045
[ "object" ]
850754a2a167f131596f5519f52cffca8a308000
663
cpp
C++
LAB2/Stack_Array_Implementation.cpp
agarwalanant/DS_Assignment
2fc9258edfa522397d6068efac797ce3a8f2d174
[ "MIT" ]
null
null
null
LAB2/Stack_Array_Implementation.cpp
agarwalanant/DS_Assignment
2fc9258edfa522397d6068efac797ce3a8f2d174
[ "MIT" ]
null
null
null
LAB2/Stack_Array_Implementation.cpp
agarwalanant/DS_Assignment
2fc9258edfa522397d6068efac797ce3a8f2d174
[ "MIT" ]
null
null
null
// // Created by Anant Agarwal on 8/9/18. // #include "iostream" #include "vector" using namespace std; class stack { public: vector<char> vec; char pop() { char data = vec.at(vec.size()-1); vec.pop_back(); //print(); return data; } void push(char val) { vec.push_back(val); print(); } void print(){ for (int i = 0; i < vec.size(); ++i) { cout<<vec.at(i)<<" "; } cout<<""<<endl; } public:stack() { vector<char> vec; } }; int main() { stack s1; s1.push('a'); s1.push('4'); cout<<s1.pop(); return 0; }
12.054545
46
0.455505
[ "vector" ]
8507657e2b24dee5b2c03e980e108cc9525a93f5
2,559
cpp
C++
Codes/jxdeng3264/701-800/707.Design-Linked-List/Solution.cpp
liuxiaohui1221/algorithm
d80e64185ceb4798ac5389bfbd226dc1d406f6b5
[ "Apache-2.0" ]
256
2017-10-25T13:02:15.000Z
2022-02-25T13:47:59.000Z
Codes/jxdeng3264/701-800/707.Design-Linked-List/Solution.cpp
liuxiaohui1221/algorithm
d80e64185ceb4798ac5389bfbd226dc1d406f6b5
[ "Apache-2.0" ]
56
2017-10-27T01:34:20.000Z
2022-03-01T00:20:55.000Z
Codes/jxdeng3264/701-800/707.Design-Linked-List/Solution.cpp
liuxiaohui1221/algorithm
d80e64185ceb4798ac5389bfbd226dc1d406f6b5
[ "Apache-2.0" ]
83
2017-10-25T12:51:53.000Z
2022-02-15T08:27:03.000Z
class MyLinkedList { public: /** Initialize your data structure here. */ MyLinkedList() { // m_head = new ListNode(0); m_size = 0; m_tail = &m_head; m_tail->next = NULL; } /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */ int get(int index) { if (index >= m_size) return -1; int sp = -1; ListNode *p = &m_head; while (p) { p = p->next; sp++; if (sp==index) break; } return p->val; } /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */ void addAtHead(int val) { ListNode *n = new ListNode(val); n->next = m_head.next; m_head.next = n; m_size++; if (m_size==1) m_tail = m_head.next; } /** Append a node of value val to the last element of the linked list. */ void addAtTail(int val) { ListNode *n = new ListNode(val); m_tail->next = n; m_tail = n; m_size++; } /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */ void addAtIndex(int index, int val) { if (index == m_size) { addAtTail(val); } else { int sp = -1; ListNode *p = &m_head; while (p) { sp++; if (sp == index) { ListNode *n = new ListNode(val); n->next = p->next; p->next = n; m_size++; return ; } p = p->next; } } } /** Delete the index-th node in the linked list, if the index is valid. */ void deleteAtIndex(int index) { if (index >= m_size) return ; int sp = -1; ListNode *p = &m_head; while (p) { sp++; if (sp==index) { ListNode *d = p->next; p->next = p->next->next; delete d; if (index == m_size-1) { m_tail = p; } m_size--; } p = p->next; } } typedef struct ListNode { int val; ListNode *next; ListNode():val(0), next(NULL){} ListNode(int v):val(v), next(NULL){} }ListNode; ListNode m_head; ListNode *m_tail; int m_size = 0; }; /** * Your MyLinkedList object will be instantiated and called as such: * MyLinkedList obj = new MyLinkedList(); * int param_1 = obj.get(index); * obj.addAtHead(val); * obj.addAtTail(val); * obj.addAtIndex(index,val); * obj.deleteAtIndex(index); */
21.686441
246
0.5678
[ "object" ]
850874adee720f13b3b3193d3107530773755241
11,039
cpp
C++
Import/Detector.cpp
renesugar/FileConvert
1f304e126d7e5029c42d5f8943a9e725ef798035
[ "Apache-2.0" ]
21
2017-09-24T14:03:39.000Z
2021-05-21T02:01:16.000Z
Import/Detector.cpp
renesugar/FileConvert
1f304e126d7e5029c42d5f8943a9e725ef798035
[ "Apache-2.0" ]
null
null
null
Import/Detector.cpp
renesugar/FileConvert
1f304e126d7e5029c42d5f8943a9e725ef798035
[ "Apache-2.0" ]
1
2017-09-25T13:34:16.000Z
2017-09-25T13:34:16.000Z
/* * Copyright 2017 MapD Technologies, 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. */ /* * @file Detector.cpp * @author Wei Hong <wei@mapd.com> * @brief Functions for Importer class */ #include "Detector.h" #include <unistd.h> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <boost/filesystem.hpp> #include <glog/logging.h> #include <string> #include <algorithm> #include <iostream> #include <fstream> #include <iomanip> #include <cstdio> #include <cstdlib> #include <stdexcept> #include <list> #include <vector> #include <unordered_map> #include <unordered_set> #include "../QueryEngine/SqlTypesLayout.h" #include "../Shared/mapdpath.h" #include "../Shared/measure.h" #include "DelimitedSupport.h" #include "gen-cpp/MapD.h" namespace Importer_NS { void Detector::init() { detect_row_delimiter(); split_raw_data(); find_best_sqltypes_and_headers(); } void Detector::read_file() { if (!boost::filesystem::exists(file_path)) { LOG(ERROR) << "File does not exist: " << file_path; return; } std::ifstream infile(file_path.string()); std::string line; auto end_time = std::chrono::steady_clock::now() + timeout; try { while (std::getline(infile, line, copy_params.line_delim)) { raw_data += line; raw_data += copy_params.line_delim; if (std::chrono::steady_clock::now() > end_time) { break; } } } catch (std::exception& e) { } infile.close(); } void Detector::detect_row_delimiter() { if (copy_params.delimiter == '\0') { copy_params.delimiter = ','; if (boost::filesystem::extension(file_path) == ".tsv") { copy_params.delimiter = '\t'; } } } void Detector::split_raw_data() { const char* buf = raw_data.c_str(); const char* buf_end = buf + raw_data.size(); bool try_single_thread = false; for (const char* p = buf; p < buf_end; p++) { std::vector<std::string> row; p = get_row(p, buf_end, buf_end, copy_params, true, nullptr, row, try_single_thread); raw_rows.push_back(row); if (try_single_thread) { break; } } if (try_single_thread) { copy_params.threads = 1; raw_rows.clear(); for (const char* p = buf; p < buf_end; p++) { std::vector<std::string> row; p = get_row(p, buf_end, buf_end, copy_params, true, nullptr, row, try_single_thread); raw_rows.push_back(row); } } } template <class T> bool try_cast(const std::string& str) { try { boost::lexical_cast<T>(str); } catch (const boost::bad_lexical_cast& e) { return false; } return true; } inline char* try_strptimes(const char* str, const std::vector<std::string>& formats) { std::tm tm_struct; char* buf; for (auto format : formats) { buf = strptime(str, format.c_str(), &tm_struct); if (buf) { return buf; } } return nullptr; } // TODO(renesugar): Add a specialization for bool to use boost::lexical_cast? // try_cast<bool> is commented out below. /* Example: (would need to check for "t", "f", "true", "false") namespace boost { template<> bool lexical_cast<bool, std::string>(const std::string& arg) { std::istringstream ss(arg); bool b; ss >> std::boolalpha >> b; return b; } template<> std::string lexical_cast<std::string, bool>(const bool& b) { std::ostringstream ss; ss << std::boolalpha << b; return ss.str(); } } */ SQLTypes Detector::detect_sqltype(const std::string& str) { SQLTypes type = kTEXT; if (try_cast<double>(str)) { type = kDOUBLE; // if (try_cast<bool>(str)) { // type = kBOOLEAN; // } else if (try_cast<int16_t>(str)) { type = kSMALLINT; } else if (try_cast<int32_t>(str)) { type = kINT; } else if (try_cast<int64_t>(str)) { type = kBIGINT; } else if (try_cast<float>(str)) { type = kFLOAT; } } // see StringToDatum in Shared/Datum.cpp if (type == kTEXT) { char* buf; buf = try_strptimes(str.c_str(), {"%Y-%m-%d", "%m/%d/%Y", "%d-%b-%y", "%d/%b/%Y"}); if (buf) { type = kDATE; if (*buf == 'T' || *buf == ' ' || *buf == ':') { buf++; } } buf = try_strptimes(buf == nullptr ? str.c_str() : buf, {"%T %z", "%T", "%H%M%S", "%R"}); if (buf) { if (type == kDATE) { type = kTIMESTAMP; } else { type = kTIME; } } } return type; } std::vector<SQLTypes> Detector::detect_column_types(const std::vector<std::string>& row) { std::vector<SQLTypes> types(row.size()); for (size_t i = 0; i < row.size(); i++) { types[i] = detect_sqltype(row[i]); } return types; } bool Detector::more_restrictive_sqltype(const SQLTypes a, const SQLTypes b) { static std::array<int, kSQLTYPE_LAST> typeorder; typeorder[kCHAR] = 0; typeorder[kBOOLEAN] = 2; typeorder[kSMALLINT] = 3; typeorder[kINT] = 4; typeorder[kBIGINT] = 5; typeorder[kFLOAT] = 6; typeorder[kDOUBLE] = 7; typeorder[kTIMESTAMP] = 8; typeorder[kTIME] = 9; typeorder[kDATE] = 10; typeorder[kTEXT] = 11; // note: b < a instead of a < b because the map is ordered most to least restrictive return typeorder[b] < typeorder[a]; } void Detector::find_best_sqltypes_and_headers() { best_sqltypes = find_best_sqltypes(raw_rows.begin() + 1, raw_rows.end(), copy_params); best_encodings = find_best_encodings(raw_rows.begin() + 1, raw_rows.end(), best_sqltypes); std::vector<SQLTypes> head_types = detect_column_types(raw_rows.at(0)); has_headers = detect_headers(head_types, best_sqltypes); copy_params.has_header = has_headers; } void Detector::find_best_sqltypes() { best_sqltypes = find_best_sqltypes(raw_rows.begin(), raw_rows.end(), copy_params); } std::vector<SQLTypes> Detector::find_best_sqltypes( const std::vector<std::vector<std::string>>& raw_rows, const CopyParams& copy_params) { return find_best_sqltypes(raw_rows.begin(), raw_rows.end(), copy_params); } std::vector<SQLTypes> Detector::find_best_sqltypes( const std::vector<std::vector<std::string>>::const_iterator& row_begin, const std::vector<std::vector<std::string>>::const_iterator& row_end, const CopyParams& copy_params) { if (raw_rows.size() < 1) { throw std::runtime_error("No rows found in: " + boost::filesystem::basename(file_path)); } auto end_time = std::chrono::steady_clock::now() + timeout; size_t num_cols = raw_rows.front().size(); std::vector<SQLTypes> best_types(num_cols, kCHAR); std::vector<size_t> non_null_col_counts(num_cols, 0); for (auto row = row_begin; row != row_end; row++) { while (best_types.size() < row->size() || non_null_col_counts.size() < row->size()) { best_types.push_back(kCHAR); non_null_col_counts.push_back(0); } for (size_t col_idx = 0; col_idx < row->size(); col_idx++) { // do not count nulls if (row->at(col_idx) == "" || !row->at(col_idx).compare(copy_params.null_str)) continue; SQLTypes t = detect_sqltype(row->at(col_idx)); non_null_col_counts[col_idx]++; if (!more_restrictive_sqltype(best_types[col_idx], t)) { best_types[col_idx] = t; } } if (std::chrono::steady_clock::now() > end_time) { break; } } for (size_t col_idx = 0; col_idx < num_cols; col_idx++) { // if we don't have any non-null values for this column make it text to be // safe b/c that is least restrictive type if (non_null_col_counts[col_idx] == 0) best_types[col_idx] = kTEXT; } return best_types; } std::vector<EncodingType> Detector::find_best_encodings( const std::vector<std::vector<std::string>>::const_iterator& row_begin, const std::vector<std::vector<std::string>>::const_iterator& row_end, const std::vector<SQLTypes>& best_types) { if (raw_rows.size() < 1) { throw std::runtime_error("No rows found in: " + boost::filesystem::basename(file_path)); } size_t num_cols = best_types.size(); std::vector<EncodingType> best_encodes(num_cols, kENCODING_NONE); std::vector<size_t> num_rows_per_col(num_cols, 1); std::vector<std::unordered_set<std::string>> count_set(num_cols); for (auto row = row_begin; row != row_end; row++) { for (size_t col_idx = 0; col_idx < row->size(); col_idx++) { if (IS_STRING(best_types[col_idx])) { count_set[col_idx].insert(row->at(col_idx)); num_rows_per_col[col_idx]++; } } } for (size_t col_idx = 0; col_idx < num_cols; col_idx++) { if (IS_STRING(best_types[col_idx])) { float uniqueRatio = static_cast<float>(count_set[col_idx].size()) / num_rows_per_col[col_idx]; if (uniqueRatio < 0.75) { best_encodes[col_idx] = kENCODING_DICT; } } } return best_encodes; } void Detector::detect_headers() { has_headers = detect_headers(raw_rows); } bool Detector::detect_headers(const std::vector<std::vector<std::string>>& raw_rows) { if (raw_rows.size() < 3) { return false; } std::vector<SQLTypes> head_types = detect_column_types(raw_rows.at(0)); std::vector<SQLTypes> tail_types = find_best_sqltypes(raw_rows.begin() + 1, raw_rows.end(), copy_params); return detect_headers(head_types, tail_types); } // detect_headers returns true if: // - all elements of the first argument are kTEXT // - there is at least one instance where tail_types is more restrictive than head_types (ie, not kTEXT) bool Detector::detect_headers( const std::vector<SQLTypes>& head_types, const std::vector<SQLTypes>& tail_types) { if (head_types.size() != tail_types.size()) { return false; } bool has_headers = false; for (size_t col_idx = 0; col_idx < tail_types.size(); col_idx++) { if (head_types[col_idx] != kTEXT) { return false; } has_headers = has_headers || tail_types[col_idx] != kTEXT; } return has_headers; } std::vector<std::vector<std::string>> Detector::get_sample_rows(size_t n) { n = std::min(n, raw_rows.size()); size_t offset = (has_headers && raw_rows.size() > 1) ? 1 : 0; std::vector<std::vector<std::string>> sample_rows(raw_rows.begin() + offset, raw_rows.begin() + n); return sample_rows; } std::vector<std::string> Detector::get_headers() { std::vector<std::string> headers(best_sqltypes.size()); for (size_t i = 0; i < best_sqltypes.size(); i++) { headers[i] = has_headers ? raw_rows[0][i] : "column_" + std::to_string(i + 1); } return headers; } } // namespace Importer_NS
30.663889
107
0.648519
[ "vector" ]
850bf745c495e6cae3ece20cfa4abe1b114f0c93
3,147
cpp
C++
cpp-101/week8/tranche2.cpp
mcrts-learning/mcrts-cpp
5de2ce243d554c7a259e860d08e677059537084b
[ "Unlicense" ]
null
null
null
cpp-101/week8/tranche2.cpp
mcrts-learning/mcrts-cpp
5de2ce243d554c7a259e860d08e677059537084b
[ "Unlicense" ]
null
null
null
cpp-101/week8/tranche2.cpp
mcrts-learning/mcrts-cpp
5de2ce243d554c7a259e860d08e677059537084b
[ "Unlicense" ]
null
null
null
#include <iostream> #include <vector> #include <memory> using namespace std; typedef size_t Position; typedef vector<int> Sequence; struct SousSequence { Sequence& sequence; Position debut; Position fin; int somme; }; int evaluate(Sequence const& sequence, size_t debut, size_t fin) { int somme(0); for (size_t i(debut); i <= fin; i++) { somme += sequence[i]; } return somme; } SousSequence greedy (Sequence& sequence) { int best_somme(sequence[0]); size_t best_debut(0); size_t best_fin(0); for (size_t debut(0); debut < sequence.size(); debut++) { for (size_t fin(debut); fin < sequence.size(); fin++) { int somme = evaluate(sequence, debut, fin); if (somme > best_somme) { best_somme = somme; best_debut = debut; best_fin = fin; } } } return SousSequence({sequence, best_debut, best_fin, best_somme}); } SousSequence greedy2 (Sequence& sequence) { int best_somme(sequence[0]); size_t best_debut(0); size_t best_fin(0); for (size_t debut(0); debut < sequence.size(); debut++) { int somme(0); for (size_t fin(debut); fin < sequence.size(); fin++) { somme += sequence[fin]; if (somme > best_somme) { best_somme = somme; best_debut = debut; best_fin = fin; } } } return SousSequence({sequence, best_debut, best_fin, best_somme}); } SousSequence linear (Sequence& sequence) { int best_somme(sequence[0]); size_t debut(0); size_t best_fin(0); int somme(0); for (size_t fin(0); fin < sequence.size(); fin++) { somme += sequence[fin]; if (somme > best_somme) { best_somme = somme; best_fin = fin; } if (somme <= 0) { debut = fin + 1; somme = 0; } } return SousSequence({sequence, debut, best_fin, best_somme}); } void affiche(Sequence const& sequence) { cout << "<Sequence {"; for (size_t i(0); i < sequence.size() - 1; i++) { cout << sequence[i] << ", "; } cout << sequence.back() << "}>" << endl; } void affiche(SousSequence const& sous_sequence) { cout << "<SousSequence debut=" << sous_sequence.debut << " fin=" << sous_sequence.fin << " somme=" << sous_sequence.somme << ">" << endl; cout << "<Sequence {"; for (size_t i(sous_sequence.debut); i < sous_sequence.fin; i++) { cout << sous_sequence.sequence[i] << ", "; } cout << sous_sequence.sequence[sous_sequence.fin] << "}>" << endl; } int main() { vector<Sequence> sequences({ {11, 13, -4, 3, -26, 7, -13, 25, -2, 17, 5, -8, 1}, {-3, -4, -1, -2, -3}, {-1, -4, -3, -2, -3}, {3, -1, -1, -1, 5}, {3, 4, 1, 2, -3}, {3, 4, 1, 2, 3}, {-5, -4, 1, 1, 1}, }); for (auto sequence : sequences) { affiche(sequence); SousSequence res(linear(sequence)); affiche(res); cout << endl; } return 0; }
26.008264
70
0.527804
[ "vector" ]
850d28b2a1e9444326de1f29234cf8f34773b4ff
424
cpp
C++
src/main.cpp
handsomefox/cpp-data-structures
61cdeb7824ad62278a8c9631f24e50841b16f47e
[ "MIT" ]
1
2021-04-01T13:32:55.000Z
2021-04-01T13:32:55.000Z
src/main.cpp
handsomefox/cpp-data-structures
61cdeb7824ad62278a8c9631f24e50841b16f47e
[ "MIT" ]
null
null
null
src/main.cpp
handsomefox/cpp-data-structures
61cdeb7824ad62278a8c9631f24e50841b16f47e
[ "MIT" ]
null
null
null
#include "pch.h" #include "Array.h" #include "String.h" #include "Vector.h" int main() { for (cpp::Array<int, 5> arr{ 1,2,3,4,5 }; const auto & element : arr) std::cout << element << ' '; for (const cpp::Vector vec{ 1,2,3,4,5,6 }; const auto & element : vec) std::cout << element << ' '; const cpp::String str = "Hello world!"; std::cout << '\n'; for (const auto c : str) std::cout << c << ' '; return 0; }
19.272727
71
0.566038
[ "vector" ]
850e13fae7b914bcf966da155c1743f3892ed057
1,597
cpp
C++
BZOJ/2746/code.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
BZOJ/2746/code.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
BZOJ/2746/code.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<vector> #define pb push_back #define rg register #define rep(i,x,y) for(rg int i=(x);i<=(y);++i) #define per(i,x,y) for(rg int i=(x);i>=(y);--i) using namespace std; const int N=1e6+10,alp=26,mo=1e9+7; inline bool vaild(char c){return c>='a'&&c<='z';} inline char gc(){char c=getchar();while(!vaild(c))c=getchar();return c;} int n; vector<int> pos[N]; struct Trie{ int tot,son[N][alp],fail[N],pa[N][20],dep[N],val[N]; Trie(){tot=1;} int ins(int k,int c){ if(son[k][c])return son[k][c]; val[++tot]=(val[k]*26ll+c)%mo; return son[k][c]=tot; } int q[N],ql,qr; void buildAC(){ ql=qr=0; dep[1]=1; fail[1]=1; rep(i,0,alp-1)if(son[1][i]){ fail[son[1][i]]=1; dep[son[1][i]]=2; q[qr++]=son[1][i]; }else son[1][i]=1; while(ql!=qr){ int k=q[ql++]; rep(i,0,alp-1)if(son[k][i]){ fail[son[k][i]]=son[fail[k]][i]; dep[son[k][i]]=dep[fail[son[k][i]]]+1; q[qr++]=son[k][i]; }else son[k][i]=son[fail[k]][i]; } rep(i,1,tot)pa[i][0]=fail[i]; rep(i,1,19)rep(j,1,tot)pa[j][i]=pa[pa[j][i-1]][i-1]; } int lca(int a,int b){ if(dep[a]<dep[b])swap(a,b); per(i,19,0)if(dep[pa[a][i]]>=dep[b])a=pa[a][i]; if(a==b)return a; per(i,19,0)if(pa[a][i]!=pa[b][i])a=pa[a][i],b=pa[b][i]; return pa[a][0]; } }T; int main(){ scanf("%d",&n); rep(i,1,n){ char c=gc(); pos[i].pb(1); while(vaild(c))pos[i].pb(T.ins(pos[i].back(),c-'a')),c=getchar(); } T.buildAC(); int m;scanf("%d",&m); while(m--){ int i,j,k,l;scanf("%d%d%d%d",&i,&j,&k,&l); printf("%d\n",T.val[T.lca(pos[i][j],pos[k][l])]); } return 0; }
24.19697
72
0.539136
[ "vector" ]
850f127ff403bc67d71cb4d2322c29b63208d5a4
13,762
cpp
C++
FinalArrorDection/main.cpp
Jiaoboy96/Robomaster
3896320a28884016edbba492b81d514650c81d81
[ "MulanPSL-1.0" ]
1
2021-01-12T05:26:19.000Z
2021-01-12T05:26:19.000Z
FinalArrorDection/main.cpp
Jiaoboy96/Robomaster
3896320a28884016edbba492b81d514650c81d81
[ "MulanPSL-1.0" ]
null
null
null
FinalArrorDection/main.cpp
Jiaoboy96/Robomaster
3896320a28884016edbba492b81d514650c81d81
[ "MulanPSL-1.0" ]
null
null
null
/*###################&&&&&&&&&&&&&&&&############################# # 据xml文件调参 # Y-89,N-78 r-114,b-98 ###################@@@@@@@@@@@@@@@@#############################*/ #include "ArrorRecognition.h" //程序1---装甲识别 #include "BigPinwheel.h" //程序2---大风车 #include "ArrorAttitudeAlgorithm.h" //姿态解算 #include "Graph.h" //打印波形 #include <iomanip> #include <thread> #include <mutex> #define SEND_SHOW String videoPath0 = "./video/17Arror1.mp4"; String videoPath1 = "./video/19(1280x720)0.avi"; String videoPath2 = "./video/19(1280x960)01.mp4"; String videoPath3 = "./video/rBigPinwheel0.avi"; String videoPath4 = "./video/number31.avi"; String videoPath5 = "./video/video13(800)6000.avi"; String videoPath6 = "./video/bisai5(728).avi"; String videoPath7 = "./video/bisai0(800).avi"; String pinwheelPath0 = "./video/bBigPinwheel0.avi"; String pinwheelPath1 = "./video/rBigPinwheel0.avi"; String pinwheelPath2 = "./video/bBigPinwheel1.mov"; String pinwheelPath3 = "./video/rBigPinwheel1.mov"; VideoCapture cap(videoPath6); VideoCapture cap0(pinwheelPath3); // 能量机关视频 int ExposureValue = 1; void disposeImg0(VideoCapture cap); static mutex g_mutex; static char ReceiveData = 'z';//"1"+"2" uchar MlFlag = 'N'; Ptr<SVM> SvmLoad ; FileStorage fsRead; bool WriteFlag = false; Mat WriterImg; void main() { printf("正在加载xml...\n"); SvmLoad = StatModel::load<SVM>("./xml/svm.xml"); fsRead.open("./xml/debugging.xml", FileStorage::READ, "utf-8"); printf("加载完成...\n"); fsRead["ExposureValue"] >> ExposureValue; printf("ExposureValue=%dus 0 \n", ExposureValue); thread deal0(disposeImg0,cap); //此线程进行持续的数据处理 waitKey(50); #ifdef ImgWriter thread write(writerWriter); #endif while (1) { uchar key = getchar(); switch (key) { case 'b':cout << "\tExiting..." << endl; exit(0); break; case 'z':ReceiveData = 'z'; break; case 'n':ReceiveData = 'n'; break; default: break; } } } void disposeImg0(VideoCapture cap) { //$$$初始化调参参数 //坐标系初始化 Graph coord(800,600); //两函数共用区 int finalNum = 0; double yaw = 0; double pitch = 0; double dist = 0; vector <RotatedRect> finalArror; ArrorAttitudeAlgorithm targetArror; //自瞄初始参数 Mat mainSrc; Mat mainGrayBinary; Mat srcMask; vector<RotatedRect> arrorRect; ArrorRecognition targetCar; /*感兴趣搜索*/ g_mutex.lock(); cap >> mainSrc; g_mutex.unlock(); Point2f roiPoint[4]; uint roiWidth = mainSrc.cols; uint roiHeight = mainSrc.rows; roiPoint[1].x = 0; roiPoint[1].y = 0; Rect srcRoi = Rect(roiPoint[1].x, roiPoint[1].y, roiWidth, roiHeight); uint roiCounter = 0; //大风车初始化参数 BigPinwheel targetPinWheel; Mat pinWheelSrc; Mat pinWheelGrayBinary; //读取xml参数 /*自瞄参数*/ fsRead["MlFlag"] >> MlFlag; fsRead["ImgWriter"] >> targetCar.ImgWriter; fsRead["fileHeaderNum"] >> targetCar.fileHeaderNum; fsRead["mainColor"] >> targetCar.mainColor; if (targetCar.mainColor == 'b') { printf("蓝场\n"); fsRead["bMainColorThre"] >> targetCar.mainColorThre; fsRead["bMainGrayThre"] >> targetCar.mainGrayThre; fsRead["bFocalLenth"] >> targetArror.focalLenth; } else if (targetCar.mainColor == 'r') { printf("红场\n"); fsRead["rMainColorThre"] >> targetCar.mainColorThre; fsRead["rMainGrayThre"] >> targetCar.mainGrayThre; fsRead["rFocalLenth"] >> targetArror.focalLenth; } fsRead["actualDist"] >> targetArror.actualDist; fsRead["ledMinArea"] >> targetCar.ledMinArea; fsRead["ledMaxArea"] >> targetCar.ledMaxArea; fsRead["ledMinAngle"] >> targetCar.ledMinAngle; fsRead["ledMaxAngle"] >> targetCar.ledMaxAngle; fsRead["ledWitdhHeightRatio"] >> targetCar.ledWitdhHeightRatio; fsRead["arrorMinDiffX"] >> targetCar.arrorMinDiffX; fsRead["arrorMaxDiffX"] >> targetCar.arrorMaxDiffX; fsRead["arrorMaxDiffY"] >> targetCar.arrorMaxDiffY; fsRead["arrorMinAngle"] >> targetCar.arrorMinAngle; fsRead["arrorMaxAngle"] >> targetCar.arrorMaxAngle; /* cout << "自瞄参数:\n"; cout << "ImgWriter=" << targetCar.ImgWriter << "\t\t\t" <<"fileHeaderNum="<<targetCar.fileHeaderNum<<"\t\t\t" << "mainColor=" << targetCar.mainColor << "\t\t\t" << endl << "mainColorThre=" << targetCar.mainColorThre << "\t\t" << "mainGrayThre=" << targetCar.mainGrayThre << "\t\t" << "neighborGrayThre=" << targetCar.neighborGrayThre << "\t\t\t" << endl << "actualDist=" << targetArror.actualDist << "\t\t\t" << "focalLenth=" << targetArror.focalLenth << "\t\t\t" << "ledMinArea=" << targetCar.ledMinArea << "\t\t\t" << endl << "ledMaxArea=" << targetCar.ledMaxArea << "\t\t\t" << targetCar.ledMinAngle << "\t\t\t" << "ledMaxAngle=" << targetCar.ledMaxAngle << "\t\t\t" << endl << "ledWitdhHeightRatio=" << targetCar.ledWitdhHeightRatio << "\t" << "arrorMinDiffX=" << targetCar.arrorMinDiffX << "\t" << "arrorMaxDiffX=" << targetCar.arrorMaxDiffX << "\t" << endl << "arrorMaxDiffY=" << targetCar.arrorMaxDiffY << "\t\t" << "arrorMinAngle=" << targetCar.arrorMinAngle << "\t\t" << "arrorMaxAngle=" << targetCar.arrorMaxAngle << "\t\t" << endl; //*/ /*大风车参数*/ fsRead["pinWheelGrayThre"] >> targetPinWheel.pinWheelGrayThre; fsRead["flabellumMinArea"] >> targetPinWheel.flabellumMinArea; fsRead["centerRadiusMin"] >> targetPinWheel.centerRadiusMin; fsRead["centerRadiusMax"] >> targetPinWheel.centerRadiusMax; fsRead["centerAreaMin"] >> targetPinWheel.centerAreaMin; fsRead["centerLengthWidthRatioMin"] >> targetPinWheel.centerLengthWidthRatioMin; fsRead["antiAngleDividend"] >> targetPinWheel.antiAngleDividend; fsRead["obeyAngleDividend"] >> targetPinWheel.obeyAngleDividend; /* cout << "大风车参数:\n"; cout << "pinWheelGrayThre=" << targetPinWheel.pinWheelGrayThre << "\t\t\t" << "flabellumMinArea=" << targetPinWheel.flabellumMinArea << "\t\t\t" << "centerRadiusMin=" << targetPinWheel.centerRadiusMin << "\t\t\t" << endl << "centerRadiusMax=" << targetPinWheel.centerRadiusMax << "\t\t\t" << "centerAreaMin=" << targetPinWheel.centerAreaMin << "\t\t\t" << "centerLengthWidthRatioMin=" << targetPinWheel.centerLengthWidthRatioMin << "\t\t\t" << endl << "antiAngleDividend=" << targetPinWheel.antiAngleDividend << "\t\t\t" << "obeyAngleDividend=" << targetPinWheel.obeyAngleDividend << "\t\t\t" << endl; //*/ #ifdef PinWheelTrackbar namedWindow("PinWheelTrackbarDebugging", CV_WINDOW_NORMAL); #endif // PinWheelTrackbar #ifdef MainTrackbar namedWindow("Debugging", CV_WINDOW_NORMAL); #endif while (1) { printf("大风车\n"); finalArror.clear(); targetPinWheel.clear(); while (1) { #ifdef PinWheelTrackbar createTrackbar("pinWheelGrayThre", "PinWheelTrackbarDebugging", &targetPinWheel.pinWheelGrayThre, 255, 0); createTrackbar("半径下限", "PinWheelTrackbarDebugging", &targetPinWheel.centerRadiusMin, 255, 0); createTrackbar("半径上限", "PinWheelTrackbarDebugging", &targetPinWheel.centerRadiusMax, 255, 0); createTrackbar("中心最小面积", "PinWheelTrackbarDebugging", &targetPinWheel.centerAreaMin, 300, 0); createTrackbar("逆预测", "PinWheelTrackbarDebugging", &targetPinWheel.antiAngleDividend, 50, 0); createTrackbar("顺预测", "PinWheelTrackbarDebugging", &targetPinWheel.obeyAngleDividend, 50, 0); uchar key = uchar(waitKey(1)); switch (key) { case 'q': targetPinWheel.pinWheelGrayThre++; break; case 'w': targetPinWheel.pinWheelGrayThre--; break; case 'a': targetPinWheel.centerRadiusMin++; break; case 's': targetPinWheel.centerRadiusMin--; break; case 'z': targetPinWheel.centerRadiusMax++; break; case 'x': targetPinWheel.centerRadiusMax--; break; case 'e': targetPinWheel.centerAreaMin++; break; case 'r': targetPinWheel.centerAreaMin--; break; case 'd': targetPinWheel.antiAngleDividend++; break; case 'f': targetPinWheel.antiAngleDividend--; break; case 'c': targetPinWheel.obeyAngleDividend++; break; case 'v': targetPinWheel.obeyAngleDividend--; break; case 'p': case 'P':waitKey(0); break; case 27: printf("\tExiting...\n"); exit(0); default: break; } #endif if (ReceiveData == 'z') break; cap0 >> pinWheelSrc; if (pinWheelSrc.empty()) { printf("0\n"); continue; } resize(pinWheelSrc, pinWheelSrc, Size(pinWheelSrc.cols / 2, pinWheelSrc.rows / 2.0)); /*@@@PinwheelStep0二值化*/ //***灰度参数准备*** Mat pinWheelGray; cvtColor(pinWheelSrc, pinWheelGray, COLOR_BGR2GRAY); //***开始二值化*** threshold(pinWheelGray, pinWheelGrayBinary, targetPinWheel.pinWheelGrayThre, 255, CV_THRESH_BINARY); dilate(pinWheelGrayBinary, pinWheelGrayBinary, Mat(), Point(-1, -1), 3); //图像膨胀 erode(pinWheelGrayBinary, pinWheelGrayBinary, Mat(), Point(-1, -1), 3); #ifdef MainPinWheelGrayBinary imshow("pinWheelGrayBinary", pinWheelGrayBinary); waitKey(1); #endif // MainPinWheelGrayBinary /*@@@PinwheelStep2找扇叶*/ targetPinWheel.getCotyledonArror(pinWheelSrc, pinWheelGrayBinary, finalArror); /*@@@开始预测*/ targetPinWheel.predictFinalArror(pinWheelSrc, finalArror); /*开始发送*/ if (!finalArror.empty()) { targetArror.angleSover(pinWheelSrc, finalArror[0], yaw, pitch); printf("\t[Yaw=%f\tPich=%f\t]\n", yaw, pitch); } else { yaw = 0; pitch = 0; printf("\t[Yaw=%f\tPich=%f\t]\n", yaw, pitch); } finalArror.clear(); coord.coordinateSystem(yaw, pitch); } printf("自瞄\n"); finalArror.clear(); while (1) { if (ReceiveData == 'n') break; #ifdef MainTrackbar createTrackbar("mainColorThre", "Debugging", &targetCar.mainColorThre, 255, 0); createTrackbar("mainGrayThre", "Debugging", &targetCar.mainGrayThre, 255, 0); createTrackbar("neighborGrayThre", "Debugging", &targetCar.neighborGrayThre, 255, 0); createTrackbar("ExposureValue", "Debugging", &ExposureValue, 200, 0); //srcRoi = Rect(0, 0, mainSrc.cols, mainSrc.rows); #endif g_mutex.lock(); cap >> mainSrc; g_mutex.unlock(); if (mainSrc.empty()) { printf("0\n"); continue; } #ifdef ImgClone imshow("mainSrc", mainSrc); waitKey(1); #endif //@@@Step0,准备ROI跟(踪颜色空间、灰度)二值图 //***颜色空间参数准备*** srcMask = mainSrc(srcRoi).clone(); Mat mainColorBinary(srcMask.size(), CV_8UC1, Scalar(0)); //***灰度参数准备*** Mat mainGray; cvtColor(srcMask, mainGray, COLOR_BGR2GRAY); //***开始二值化*** threshold(mainGray, mainGrayBinary, targetCar.mainGrayThre, 255, CV_THRESH_BINARY); dilate(mainGrayBinary, mainGrayBinary, Mat(), Point(-1, -1), 2); //图像膨胀、 targetCar.getColorBinary(srcMask, mainColorBinary, targetCar.mainColor, targetCar.mainColorThre); //@@@Step1。开始颜色空间二值图和灰度二值图的轮廓查找,并进行中心灯条拟合+两两灯条拟合 Mat mainMergeBinary(srcMask.size(), CV_8UC1, Scalar(0)); targetCar.mergeGrayColor(mainColorBinary, mainGrayBinary, mainMergeBinary); #ifdef MainGrayBinary imshow("mainGrayBinary", mainGrayBinary); #endif #ifdef MainColorBinary imshow("mainColorBinary", mainColorBinary); #endif // MainColorBinary #ifdef MainMergeBinary imshow("mainMergeBinary", mainMergeBinary); #endif targetCar.detectionContour(mainSrc, mainMergeBinary, arrorRect, srcRoi); //@@@Step2开始进行最终装甲板的确定 if (MlFlag == 'Y') { /*if (srcRoi.width == mainSrc.cols&&srcRoi.height == mainSrc.rows) {*/ printf("机器学习\n"); targetCar.finalMachineLearn(mainSrc, mainMergeBinary, arrorRect, finalArror, finalNum, SvmLoad); /*} else { printf("非机器学习\n"); targetCar.nonML(mainSrc, arrorRect, finalArror); }*/ } else { targetCar.mlNumNonMl(mainSrc, mainMergeBinary, arrorRect, finalArror, finalNum, SvmLoad); } #ifdef MainTrackbar uchar Key = uchar(waitKey(1)); switch (Key) { case 'q': targetCar.mainColorThre++; break; case 'w': targetCar.mainColorThre--; break; case 'e': targetCar.mainGrayThre++; break; case 'r': targetCar.mainGrayThre--; break; case 'a': targetCar.neighborGrayThre++; break; case 's': targetCar.neighborGrayThre--; break; case 'p': case 'P':waitKey(0); break; case 27: printf("\tExiting...\n"); exit(0); default: break; } if (!finalArror.empty()) { dist = targetArror.angleSover(mainSrc, finalArror[0], yaw, pitch); #ifdef SEND_SHOW printf("\t[Yaw=%f\tPich=%f\tdist=%f\tarrorNum=%d]\n", yaw, pitch, dist, finalNum); #endif // SEND_SHOW } else { #ifdef SEND_SHOW yaw = 0; pitch = 0; printf("\t[Yaw=9999\tPich=9999\tdist=9999\tarrorNum=9999]\n"); #endif // SEND_SHOW } #else //@@@Step2,开始角度解算,发送数据 if (!finalArror.empty()) { dist = targetArror.angleSover(mainSrc, finalArror[0], yaw, pitch); printf("\t[Yaw=%f,Pich=%f,dist=%f,arrorNum=%d]\n", yaw, pitch, dist, finalNum); //@@@开始感兴趣跟踪 finalArror[0].points(roiPoint); roiPoint[1].x -= finalArror[0].size.width*0.5; roiPoint[1].y -= finalArror[0].size.height * 0.5; roiWidth = finalArror[0].size.width * 2; roiHeight = finalArror[0].size.height * 2; if (roiPoint[1].x <= 0 || roiPoint[1].x >= mainSrc.cols || roiPoint[1].y <= 0 || roiPoint[1].y >= mainSrc.rows || roiPoint[1].x + roiWidth >= mainSrc.cols || roiPoint[1].y + roiHeight >= mainSrc.rows) { roiPoint[1].x = 0; roiPoint[1].y = 0; roiWidth = mainSrc.cols; roiHeight = mainSrc.rows; } srcRoi = Rect(roiPoint[1].x, roiPoint[1].y, roiWidth, roiHeight); #ifdef MainSrcMask line(mainSrc, roiPoint[1], roiPoint[1], Scalar(0, 255, 0), 4); rectangle(mainSrc, srcRoi, Scalar(0, 255, 0), 2, 8); imshow("mainSrc", mainSrc); #endif } else { yaw = 0; pitch = 0; #ifdef SEND_SHOW printf("\t[Yaw=9999\tPich=9999\tdist=9999\tarrorNum=9999]\n"); #endif // SEND_SHOW #ifdef LINUX sendDataId0(9999, 9999, 9999, 9999); #endif //@@@开始感兴趣计数 srcRoi = Rect(0, 0, mainSrc.cols, mainSrc.rows); } #endif coord.coordinateSystem(yaw, pitch); arrorRect.clear(); finalArror.clear(); } } }
30.582222
204
0.669961
[ "vector" ]
851f916f1b09de63dba321d7aff962c46b3fec26
3,255
cpp
C++
5. Virtual Functions/1.Basic/2.Pointers.cpp
Imran4424/C-Plus-Plus-Object-Oriented
a9c16ce6506b4cc0f3ec82fdf2e750bec50aab79
[ "MIT" ]
3
2019-11-06T15:43:06.000Z
2020-06-05T10:47:28.000Z
5. Virtual Functions/1.Basic/2.Pointers.cpp
Imran4424/C-Plus-Plus-Object-Oriented
a9c16ce6506b4cc0f3ec82fdf2e750bec50aab79
[ "MIT" ]
null
null
null
5. Virtual Functions/1.Basic/2.Pointers.cpp
Imran4424/C-Plus-Plus-Object-Oriented
a9c16ce6506b4cc0f3ec82fdf2e750bec50aab79
[ "MIT" ]
1
2019-09-06T03:37:08.000Z
2019-09-06T03:37:08.000Z
/* Write a program to demonstrate use of pointers */ #include <iostream> #include <string> using namespace std; class Engineer { public: string profession; public: Engineer() { profession = ""; } public: Engineer(string profession) { this -> profession = profession; } public: string GetJob() { return "do nothing"; } public: string GetProfession() { return profession; } }; class Computer: public Engineer { public: Computer(): Engineer() { } public: Computer(string profession): Engineer(profession) { } public: string GetJob() { return "Develop Software"; } }; class Civil: public Engineer { public: Civil(): Engineer() { } public: Civil(string profession): Engineer(profession) { } public: string GetJob() { return "Buid Building"; } }; class Mechanical: public Engineer { public: Mechanical(): Engineer() { } public: Mechanical(string profession): Engineer(profession) { } public: string GetJob() { return "Work with Machinery"; } }; void Report(Engineer *eng) { cout << eng -> GetProfession() << " Engineers " << eng -> GetJob() << endl; } int main(int argc, char const *argv[]) { Computer dipu("CSE"); Civil sadman("Civil"); Mechanical jannat("Mechanical"); /* Engineer *ptr = &CSE; Report(ptr); ptr = &sadman; Report(ptr); ptr = &jannat; Report(ptr); */ Report(&dipu); Report(&sadman); Report(&jannat); return 0; } /* Now, let's do the same work in other way Instead of declaring dervied class pointer, now we will declare base class pointer and we will try to access all derived class public members Here in this code we delared a function called report, which take base pointer of base class as parameters and trying to call the base function GetProfession and overridden function void Report(Engineer *eng) { cout << eng -> GetProfession() << " Engineers " << eng -> GetJob() << endl; } expected output: CSE Engineers Develop Software Civil Engineers Buid Building Mechanical Engineers Work with Machinery given output: CSE Engineers do nothing Civil Engineers do nothing Mechanical Engineers do nothing Now question is why? Because base pointer can only see the base class members, it can not see derived and derived overridden members(hidden to base class pointer) which is why base pointer is calling base class GetJob() function rather than derived GetJob() function This is when virtual functions come to rescue for this kind of situation We will talk about that more deeply in the later codes Now, one can ask why we need to use pointer to make things complex we can simply use derived class object. Let's say we have 50 or more derived classes and we want to display all of their member variables, then we need to declare one display function for each class which is really time consuming and declaring 50 or more functions will make it lot more harder and painful So want a easy solution Use base pointer to pointer derived class objects, and with one function you can show the all derived class objects members variables. but normally base pointer will not work as we see earlier, so we have to use virtual function and that we gonna learn in next codes */
17.5
95
0.713671
[ "object" ]
852104efc0342556a37d76d0cc0559a3134429a2
3,346
cc
C++
modules/dreamview/backend/websocket.cc
Orientlee/apollo
710c3714b8be10ba3410e2c30b4b6758f6d99918
[ "Apache-2.0" ]
1
2017-07-19T07:17:29.000Z
2017-07-19T07:17:29.000Z
modules/dreamview/backend/websocket.cc
wzh212/apollo
0a87c670a9adea5e61b89458c082ddfb39218952
[ "Apache-2.0" ]
1
2022-02-10T18:36:05.000Z
2022-02-10T18:36:05.000Z
modules/dreamview/backend/websocket.cc
wzh212/apollo
0a87c670a9adea5e61b89458c082ddfb39218952
[ "Apache-2.0" ]
1
2017-10-04T12:27:24.000Z
2017-10-04T12:27:24.000Z
/* Copyright 2017 The Apollo 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 "modules/dreamview/backend/websocket.h" #include <sstream> #include <vector> #include "glog/logging.h" namespace apollo { namespace dreamview { void WebSocketHandler::handleReadyState(CivetServer *server, Connection *conn) { { std::unique_lock<std::mutex> lock(mutex_); connections_.insert(conn); } LOG(INFO) << "Accepted connection. Total connections: " << connections_.size(); } void WebSocketHandler::handleClose(CivetServer *server, const Connection *conn) { { std::unique_lock<std::mutex> lock(mutex_); // Remove from the store of currently open connections. connections_.erase(const_cast<Connection *>(conn)); } LOG(INFO) << "Connection closed. Total connections: " << connections_.size(); } bool WebSocketHandler::SendData(const std::string &data) { std::vector<Connection *> connections_to_send; { std::unique_lock<std::mutex> lock(mutex_); if (connections_.empty()) { return true; } for (Connection *conn : connections_) { connections_to_send.push_back(conn); } } bool all_success = true; for (Connection *conn : connections_to_send) { if (!SendData(data, conn)) { all_success = false; } } return all_success; } bool WebSocketHandler::SendData(const std::string &data, Connection *conn) { int ret = mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, data.c_str(), data.size()); if (ret != static_cast<int>(data.size())) { // Determine error message based on return value. std::string msg; if (ret == 0) { msg = "Connection Closed"; } else if (ret < 0) { msg = "Send Error"; } else { std::ostringstream os; os << "Expect to send " << data.size() << " bytes. But sent " << ret << " bytes"; msg = os.str(); } LOG(WARNING) << "Failed to send data via websocket connection. Reason: " << msg; return false; } return true; } bool WebSocketHandler::handleData(CivetServer *server, Connection *conn, int bits, char *data, size_t data_len) { // Ignore connection close request. if ((bits & 0x0F) == WEBSOCKET_OPCODE_CONNECTION_CLOSE) { return false; } auto json = Json::parse(std::string(data, data_len)); auto type = json["type"]; if (message_handlers_.find(type) == message_handlers_.end()) { LOG(ERROR) << "No message handler found for message type " << type << ". The message will be discarded!"; return true; } message_handlers_[type](json, conn); return true; } } // namespace dreamview } // namespace apollo
30.144144
80
0.638972
[ "vector" ]
8524d5ea6d62401ae1a549a8e4f233f485549320
1,394
cpp
C++
books/tech/cpp/std-17/m_bancila-modern_cpp_programming_cookbook/ch_01-core_lang/08-range-based_for_loops.cpp
ordinary-developer/education
1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58
[ "MIT" ]
null
null
null
books/tech/cpp/std-17/m_bancila-modern_cpp_programming_cookbook/ch_01-core_lang/08-range-based_for_loops.cpp
ordinary-developer/education
1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58
[ "MIT" ]
null
null
null
books/tech/cpp/std-17/m_bancila-modern_cpp_programming_cookbook/ch_01-core_lang/08-range-based_for_loops.cpp
ordinary-developer/education
1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58
[ "MIT" ]
null
null
null
// region [gettying ready] #include <vector> #include <map> std::vector<int> getRates() { return std::vector<int>{ 1, 1, 2, 3, 5, 8, 13 }; } std::multimap<int, bool> getRates2() { return std::multimap<int, bool> { { 1, true }, { 1, true }, { 2, false }, { 3, true }, { 5, true }, { 8, false }, { 13, true } }; } // endregion [getting ready] // region [how to do it] #include <iostream> namespace example_01 { void run() { auto rates = getRates(); for (int rate : rates) std::cout << rate << std::endl; for (int & rate : rates) rate *= 2; } } // example_01 #include <iostream> namespace example_02 { void run() { for (auto&& rate : getRates()) std::cout << rate << std::endl; auto rates = getRates(); for (auto & rate : rates) rate *= 2; for (auto const& rate : rates) std::cout << rate << std::endl; } } // example_02 #include <iostream> namespace example_03 { void run() { for (auto&& [rate, flag] : getRates2()) std::cout << rate << "-" << flag << std::endl; } } // example_03 // endregion [how to do it] #include <iostream> int main() { getRates(); getRates2(); example_01::run(); example_02::run(); example_03::run(); std::cout << "DONE" << std::endl; return 0; }
19.09589
54
0.514347
[ "vector" ]
852cc9cfc8ed86be7e1a84176adb3489357ef347
1,298
hpp
C++
agency/cuda/execution/execution_policy/concurrent_grid_execution_policy.hpp
nerikhman/agency
966ac59101f2fc3561a86b11874fbe8de361d0e4
[ "BSD-3-Clause" ]
129
2016-08-18T23:24:15.000Z
2022-03-25T12:06:05.000Z
agency/cuda/execution/execution_policy/concurrent_grid_execution_policy.hpp
nerikhman/agency
966ac59101f2fc3561a86b11874fbe8de361d0e4
[ "BSD-3-Clause" ]
86
2016-08-19T03:43:33.000Z
2020-07-20T14:27:41.000Z
agency/cuda/execution/execution_policy/concurrent_grid_execution_policy.hpp
nerikhman/agency
966ac59101f2fc3561a86b11874fbe8de361d0e4
[ "BSD-3-Clause" ]
23
2016-08-18T23:52:13.000Z
2022-02-28T16:28:20.000Z
#pragma once #include <agency/detail/config.hpp> #include <agency/execution/execution_policy/basic_execution_policy.hpp> #include <agency/cuda/execution/executor/concurrent_grid_executor.hpp> #include <agency/cuda/execution/executor/scoped_executor.hpp> #include <agency/cuda/device.hpp> namespace agency { namespace cuda { // XXX consider making this a global object like the other execution policies inline auto con_grid(size_t num_blocks, size_t num_threads) -> decltype( con(num_blocks, con(num_threads)) ) { return con(num_blocks, con(num_threads)); }; // XXX consider making this a unique type instead of an alias using con_grid_agent = concurrent_group<concurrent_agent>; // this overload is called on e.g. con(con).on(device(0)) // XXX this function needs to account for the dimensionality of ParallelPolicy's agents template<class ConcurrentGridPolicy, __AGENCY_REQUIRES( agency::detail::policy_is_scoped_concurrent_concurrent<ConcurrentGridPolicy>::value )> __AGENCY_ANNOTATION basic_execution_policy<cuda::con_grid_agent, cuda::concurrent_grid_executor> replace_executor(const ConcurrentGridPolicy& policy, device_id device) { cuda::concurrent_grid_executor exec(device); return policy.on(exec); } } // end cuda } // end agency
27.041667
94
0.775039
[ "object" ]
852e90a5fd2f67749f1c8c3e0d229a4e2c9725fb
347
cpp
C++
AtCoder/Mynavi Programming Contest 2021(AtCoder Beginner Contest 201)/A.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
3
2020-11-01T06:31:30.000Z
2022-02-21T20:37:51.000Z
AtCoder/Mynavi Programming Contest 2021(AtCoder Beginner Contest 201)/A.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
null
null
null
AtCoder/Mynavi Programming Contest 2021(AtCoder Beginner Contest 201)/A.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
1
2021-05-05T18:56:31.000Z
2021-05-05T18:56:31.000Z
//https://atcoder.jp/contests/abc201/tasks/abc201_a #include <bits/stdc++.h> using namespace std; int main () { ios_base::sync_with_stdio (0); cin.tie (0); cout.tie (0); vector<int> V(3); for (int i = 0; i < 3; ++i) { cin >> V[i]; } sort(V.begin(), V.end()); cout << (V[2] - V[1] == V[1] - V[0] ? "Yes" : "No"); }
24.785714
61
0.512968
[ "vector" ]
8536c63f89089001afd9bffa47c5a38866da6261
164,330
cpp
C++
code/src/AmrIce.cpp
cemacrr/bisicles_gia
ee3a4c96ca492568900c31501935288c00f583f3
[ "BSD-3-Clause-LBNL" ]
null
null
null
code/src/AmrIce.cpp
cemacrr/bisicles_gia
ee3a4c96ca492568900c31501935288c00f583f3
[ "BSD-3-Clause-LBNL" ]
null
null
null
code/src/AmrIce.cpp
cemacrr/bisicles_gia
ee3a4c96ca492568900c31501935288c00f583f3
[ "BSD-3-Clause-LBNL" ]
null
null
null
#ifdef CH_LANG_CC /* * _______ __ * / ___/ / ___ __ _ / / ___ * / /__/ _ \/ _ \/ V \/ _ \/ _ \ * \___/_//_/\___/_/_/_/_.__/\___/ * Please refer to Copyright.txt, in Chombo's root directory. */ #endif #include <iostream> #include <fstream> #include <string> #include <cstdio> #include <cmath> using std::ifstream; using std::ios; using std::cout; using std::cin; using std::cerr; using std::endl; using std::string; #include "BISICLES_VERSION.H" #include "Box.H" #include "Vector.H" #include "DisjointBoxLayout.H" #include "ParmParse.H" #include "LayoutIterator.H" #include "BoxIterator.H" #include "parstream.H" #include "CoarseAverage.H" #include "CoarseAverageFace.H" #include "FineInterp.H" #include "AMRIO.H" #include "BRMeshRefine.H" #include "LoadBalance.H" #include "MayDay.H" #include "AmrIce.H" #include "computeNorm.H" #include "PatchGodunov.H" #include "AdvectPhysics.H" #include "PiecewiseLinearFillPatch.H" #include "CellToEdge.H" #include "EdgeToCell.H" #include "DerivativesF_F.H" #include "DivergenceF_F.H" #include "computeSum.H" #include "CONSTANTS.H" #include "IceConstants.H" #include "ExtrapBCF_F.H" #include "amrIceF_F.H" #include "BisiclesF_F.H" #include "IceThermodynamics.H" #include "JFNKSolver.H" #include "InverseVerticallyIntegratedVelocitySolver.H" #include "PetscIceSolver.H" #include "RelaxSolver.H" #ifdef CH_USE_FAS #include "FASIceSolver.H" #endif #include "KnownVelocitySolver.H" #include "VCAMRPoissonOp2.H" #include "AMRPoissonOpF_F.H" #include "CH_HDF5.H" #include "IceUtility.H" #include "LevelMappedDerivatives.H" #ifdef HAVE_PYTHON #include "PythonInterface.H" #endif #include "BuelerGIA.H" #include "NamespaceHeader.H" // small parameter defining when times are equal #define TIME_EPS 1.0e-12 int AmrIce::s_verbosity = 1; /// fill flattened Fortran array of data with ice thickness void AmrIce::getIceThickness(Real* a_data_ptr, int* a_dim_info, Real* a_dew, Real* a_dns) const { // dimInfo is (SPACEDIM, nz, nx, ny) // assumption is that data_ptr is indexed using fortran // ordering from (1:dimInfo[1])1,dimInfo[2]) // we want to use c ordering IntVect hiVect(D_DECL(a_dim_info[2]-1,a_dim_info[3]-1, a_dim_info[1]-1)); Box fabBox(IntVect::Zero, hiVect); FArrayBox exportHfab(fabBox, 1, a_data_ptr); // now pack this into a LevelData -- this will need to be expanded in MPI Vector<Box> exportBoxes(1,fabBox); Vector<int> procAssign(1,0); // ignore periodicity, since we don't have ghost cells DisjointBoxLayout exportGrids(exportBoxes, procAssign); LevelData<FArrayBox> exportLDF(exportGrids, 1); // this isn't correct in 3d... CH_assert(SpaceDim != 3); RealVect exportDx = RealVect(D_DECL(*a_dew, *a_dns, 1)); // assume that dx = dy, at least for now CH_assert (exportDx[0] == exportDx[1]); // start at level 0, then work our way up to finest level, // over-writing as we go. An optimzation would be to check // to see if finer levels cover the entire domain... for (int lev=0; lev<= m_finest_level; lev++) { const LevelSigmaCS& levelCS = *(m_vect_coordSys[lev]); const DisjointBoxLayout& levelGrids = m_amrGrids[lev]; const LevelData<FArrayBox>& levelThickness = levelCS.getH(); // refinement ratio Real refRatio = exportDx[0]/m_amrDx[lev]; Real tolerance = 1.0e-6; if (refRatio > 1.0 + tolerance) { // current level finer than export level -- average solution // onto output int nRef = (int)(refRatio + tolerance); CoarseAverage averager(levelGrids,exportGrids, 1, nRef); averager.averageToCoarse(exportLDF, levelThickness); } else if (refRatio < 1.0-tolerance) { // current level coarser than export level -- interpolate solution int nRef = (int)(1.0/refRatio + tolerance); // FineInterp needs a problem domain ProblemDomain exportDomain(m_amrDomains[lev]); exportDomain.refine(nRef); FineInterp interpolator(exportGrids, 1, nRef, exportDomain); interpolator.interpToFine(exportLDF, levelThickness); } else { // same resolution -- just do a copyTo levelThickness.copyTo(exportLDF); } } // end loop over levels // now copy to input fab DataIterator exportDit = exportLDF.dataIterator(); for (exportDit.begin(); exportDit.ok(); ++exportDit) { // in parallel, this should only be on proc 0 exportHfab.copy(exportLDF[exportDit]); } } bool AmrIce::isDefined() const { return m_is_defined; } AmrIce::AmrIce() : m_velSolver(NULL), m_constitutiveRelation(NULL), m_rateFactor(NULL), m_basalFrictionRelation(NULL), m_basalRateFactor(NULL), m_thicknessPhysPtr(NULL), m_thicknessIBCPtr(NULL), m_surfaceFluxPtr(NULL), m_basalFluxPtr(NULL), m_surfaceHeatBoundaryDataPtr(NULL), m_basalHeatBoundaryDataPtr(NULL), m_topographyFluxPtr(NULL), m_basalFrictionPtr(NULL), m_calvingModelPtr(NULL) { setDefaults(); } void AmrIce::setDefaults() { m_sigmaSet = false; // set some bogus values as defaults m_is_defined = false; m_max_level = -1; m_finest_level = -1; m_finest_timestep_level = -1; m_tag_cap = 100; m_block_factor = -1; m_fill_ratio = -1; m_do_restart = false; m_restart_step = -1; // m_constitutiveRelation = NULL; m_solverType = JFNK; // at the moment, 1 is the only one which works m_temporalAccuracy = 1; m_num_thickness_ghost = 4; // default is -1, which means use the solver's own defaults m_maxSolverIterations = -1; m_velocity_solver_tolerance = 1e-10; //by default, solve the full velocity problem on every timestep m_velocity_solve_interval = 1; //m_velSolver = NULL; m_domainSize = -1*RealVect::Unit; //m_beta_type = constantBeta; m_betaVal = 1000.0; m_betaEps = 0.0; m_basalSlope = RealVect::Zero; m_interpolate_zb = true; m_regrid_thickness_interpolation_method = 0; // set the rest of these to reasonable defaults m_nesting_radius = 1; #ifdef CH_USE_PETSC m_nesting_radius = 3; #endif m_tagOnGradVel = false; m_tagging_val = 0.1; m_tagOnLapVel = false; m_tagOnGroundedLapVel = false; m_laplacian_tagging_val = 1.0; m_laplacian_tagging_max_basal_friction_coef = 1.2345678e+300; m_tagOnEpsSqr = false; m_epsSqr_tagVal =0.1; m_tagOnVelRHS = false; m_velRHS_tagVal = 1.0; m_tagOndivHgradVel = false; m_divHGradVel_tagVal = 1.0; m_tagGroundingLine = false; m_tagVelDx = false; m_velDx_tagVal = 0.0; m_velDx_tagVal_finestLevelGrounded = -1; m_velDx_tagVal_finestLevelFloating = -1; m_tagMargin = false; m_margin_tagVal_finestLevel = -1; m_tagAllIce = false; m_tagEntireDomain = false; m_groundingLineTaggingMinVel = 200.0; m_groundingLineTaggingMaxBasalFrictionCoef = 1.2345678e+300; m_tag_thin_cavity = false; m_tag_thin_cavity_thickness = TINY_THICKNESS; #ifdef HAVE_PYTHON m_tagPython = false; m_tagPythonModule = NULL; m_tagPythonFunction = NULL; #endif m_tags_grow = 1; m_tags_grow_dir = IntVect::Zero; m_cfl = 0.25; m_max_dt_grow = 1.5; m_dt = 1.0e20; m_stable_dt = m_dt; m_velocity_exit = HUGE_VEL; m_max_box_size = 64; m_max_base_grid_size = -1; m_isothermal = true; m_waterDepth = 0.0; m_surfaceBoundaryHeatDataDirichlett = true; m_surfaceBoundaryHeatDataTemperature = true; m_iceDensity = ICE_DENSITY; m_seaWaterDensity = SEA_WATER_DENSITY; m_mantleDensity = 3313.0; m_gravity = GRAVITY; m_seconds_per_unit_time = SECONDS_PER_TROPICAL_YEAR; m_report_discharge = false; m_report_time_interval = 0.01; m_eliminate_remote_ice = false; m_eliminate_remote_ice_max_iter = 10; m_eliminate_remote_ice_tol = 1.0; m_eliminate_remote_ice_after_regrid = false; m_diffusionTreatment = NONE; m_additionalDiffusivity = 0.0; m_additionalVelocity = false; m_timeStepTicks = false; m_fixed_dt = 0.0; m_velocitySolveInitialResidualNorm = -1.0; m_doInitialVelSolve = true; m_doInitialVelGuess = false; m_initialGuessType = SlidingLaw; m_initialGuessConstMu = 1.0e+7; // a number that seems plausible, only needed // if m_initialGuessType = ConstMu m_initialGuessSolverType = JFNK; m_initialGuessConstVel = RealVect::Zero; // only needed if m_initialGuessType = ConstMu *and* the basal traction relation is nonlinear m_reset_floating_friction_to_zero = true; // set basal friction to zero where ice is floating m_basalLengthScale = 0.0; // don't mess about with the basal friction / rhs by default m_evolve_thickness = true; m_evolve_velocity = true; m_evolve_topography_fix_surface = false; m_grounded_ice_stable = false; m_floating_ice_stable = false; m_floating_ice_basal_flux_is_dhdt = false; m_floating_ice_basal_flux_is_min_dhdt = false; m_grounded_ice_basal_flux_is_dhdt = false; m_frac_sources = false; m_groundingLineProximityScale = 1.0e+4; m_groundingLineProximityCalcType = 0 ; // default to the old (odd) behaviour //cache validity flags m_A_valid = false; m_groundingLineProximity_valid = false; m_viscousTensor_valid = false; zeroFlux* cfptr = new zeroFlux; m_basalFluxPtr = cfptr; m_offsetTime = 0.0; } AmrIce::~AmrIce() { if (s_verbosity > 4) { pout() << "AmrIce::~AmrIce()" << endl; } // clean up memory for (int lev=0; lev<m_velocity.size(); lev++) { if (m_velocity[lev] != NULL) { delete m_velocity[lev]; m_velocity[lev] = NULL; } } // clean up ice fraction for (int lev=0; lev<m_iceFrac.size(); lev++) { if (m_iceFrac[lev] != NULL) { delete m_iceFrac[lev]; m_iceFrac[lev] = NULL; } } // clean up velocityRHS storage if appropriate for (int lev=0; lev<m_velRHS.size(); lev++) { if (m_velRHS[lev] != NULL) { delete m_velRHS[lev]; m_velRHS[lev] = NULL; } } // clean up basal C storage if appropriate for (int lev=0; lev < m_velBasalC.size(); lev++) { if (m_velBasalC[lev] != NULL) { delete m_velBasalC[lev]; m_velBasalC[lev] = NULL; } } // clean up cell centered mu coefficient storage if appropriate for (int lev=0; lev < m_cellMuCoef.size(); lev++) { if (m_cellMuCoef[lev] != NULL) { delete m_cellMuCoef[lev]; m_cellMuCoef[lev] = NULL; } } // clean up face advection velocity storage if appropriate for (int lev=0; lev < m_faceVelAdvection.size(); lev++) { if (m_faceVelAdvection[lev] != NULL) { delete m_faceVelAdvection[lev]; m_faceVelAdvection[lev] = NULL; } } // clean up face total velocity storage if appropriate for (int lev=0; lev < m_faceVelTotal.size(); lev++) { if (m_faceVelTotal[lev] != NULL) { delete m_faceVelTotal[lev]; m_faceVelTotal[lev] = NULL; } } for (int lev=0; lev < m_diffusivity.size(); lev++) { if (m_diffusivity[lev] != NULL) { delete m_diffusivity[lev]; m_diffusivity[lev] = NULL; } } // clean up surface thickness storage if appropriate for (int lev=0; lev < m_surfaceThicknessSource.size(); lev++) { if (m_surfaceThicknessSource[lev] != NULL) { delete m_surfaceThicknessSource[lev]; m_surfaceThicknessSource[lev] = NULL; } if (m_basalThicknessSource[lev] != NULL) { delete m_basalThicknessSource[lev]; m_basalThicknessSource[lev] = NULL; } if (m_volumeThicknessSource[lev] != NULL) { delete m_volumeThicknessSource[lev]; m_volumeThicknessSource[lev] = NULL; } if (m_calvedIceThickness[lev] != NULL) { delete m_calvedIceThickness[lev]; m_calvedIceThickness[lev] = NULL; } if (m_removedIceThickness[lev] != NULL) { delete m_removedIceThickness[lev]; m_removedIceThickness[lev] = NULL; } if (m_addedIceThickness[lev] != NULL) { delete m_addedIceThickness[lev]; m_addedIceThickness[lev] = NULL; } } for (int lev=0; lev < m_divThicknessFlux.size(); lev++) { if (m_divThicknessFlux[lev] != NULL) { delete m_divThicknessFlux[lev]; m_divThicknessFlux[lev] = NULL; } } #if BISICLES_Z == BISICLES_LAYERED for (int lev=0; lev < m_layerSFaceXYVel.size(); lev++) { if (m_layerSFaceXYVel[lev] != NULL) { delete m_layerSFaceXYVel[lev]; m_layerSFaceXYVel[lev] = NULL; } } for (int lev=0; lev < m_layerSFaceSVel.size(); lev++) { if (m_layerSFaceSVel[lev] != NULL) { delete m_layerSFaceSVel[lev]; m_layerSFaceSVel[lev] = NULL; } } for (int lev=0; lev < m_layerXYFaceXYVel.size(); lev++) { if (m_layerXYFaceXYVel[lev] != NULL) { delete m_layerXYFaceXYVel[lev]; m_layerXYFaceXYVel[lev] = NULL; } } #endif // clean up internalEnergy storage if appropriate for (int lev=0; lev < m_internalEnergy.size(); lev++) { if (m_internalEnergy[lev] != NULL) { delete m_internalEnergy[lev]; m_internalEnergy[lev] = NULL; } } // clean up internalEnergy storage if appropriate for (int lev=0; lev < m_temperature.size(); lev++) { if (m_temperature[lev] != NULL) { delete m_temperature[lev]; m_temperature[lev] = NULL; } } for (int lev=0; lev < m_A.size(); lev++) { if (m_A[lev] != NULL) { delete m_A[lev]; m_A[lev] = NULL; } } #if BISICLES_Z == BISICLES_LAYERED for (int lev=0; lev < m_sA.size(); lev++) { if (m_sA[lev] != NULL) { delete m_sA[lev]; m_sA[lev] = NULL; } } for (int lev=0; lev < m_tillWaterDepth.size(); lev++) { if (m_tillWaterDepth[lev] != NULL) { delete m_tillWaterDepth[lev]; m_tillWaterDepth[lev] = NULL; } } for (int lev=0; lev < m_sInternalEnergy.size(); lev++) { if (m_sInternalEnergy[lev] != NULL) { delete m_sInternalEnergy[lev]; m_sInternalEnergy[lev] = NULL; } } for (int lev=0; lev < m_sTemperature.size(); lev++) { if (m_sTemperature[lev] != NULL) { delete m_sTemperature[lev]; m_sTemperature[lev] = NULL; } } for (int lev=0; lev < m_sHeatFlux.size(); lev++) { if (m_sHeatFlux[lev] != NULL) { delete m_sHeatFlux[lev]; m_sHeatFlux[lev] = NULL; } } for (int lev=0; lev < m_bInternalEnergy.size(); lev++) { if (m_bInternalEnergy[lev] != NULL) { delete m_bInternalEnergy[lev]; m_bInternalEnergy[lev] = NULL; } } for (int lev=0; lev < m_bTemperature.size(); lev++) { if (m_bTemperature[lev] != NULL) { delete m_bTemperature[lev]; m_bTemperature[lev] = NULL; } } for (int lev=0; lev < m_bHeatFlux.size(); lev++) { if (m_bHeatFlux[lev] != NULL) { delete m_bHeatFlux[lev]; m_bHeatFlux[lev] = NULL; } } for (int lev=0; lev < m_bA.size(); lev++) { if (m_bA[lev] != NULL) { delete m_bA[lev]; m_bA[lev] = NULL; } } #endif for (int lev = 0; lev < m_old_thickness.size(); lev++) { if (m_old_thickness[lev] != NULL) { delete m_old_thickness[lev]; m_old_thickness[lev] = NULL; } } for (int lev = 0; lev < m_groundingLineProximity.size(); lev++) { if (m_groundingLineProximity[lev] != NULL) { delete m_groundingLineProximity[lev]; m_groundingLineProximity[lev] = NULL; } } for (int lev = 0; lev < m_dragCoef.size(); lev++) { if (m_dragCoef[lev] != NULL) { delete m_dragCoef[lev]; m_dragCoef[lev] = NULL; } } for (int lev = 0; lev < m_viscosityCoefCell.size(); lev++) { if (m_viscosityCoefCell[lev] != NULL) { delete m_viscosityCoefCell[lev]; m_viscosityCoefCell[lev] = NULL; } } for (int lev = 0; lev < m_viscousTensorCell.size(); lev++) { if (m_viscousTensorCell[lev] != NULL) { delete m_viscousTensorCell[lev]; m_viscousTensorCell[lev] = NULL; } } for (int lev = 0; lev < m_viscousTensorFace.size(); lev++) { if (m_viscousTensorFace[lev] != NULL) { delete m_viscousTensorFace[lev]; m_viscousTensorFace[lev] = NULL; } } for (int lev = 0; lev < m_deltaTopography.size(); lev++) { if (m_deltaTopography[lev] != NULL) { delete m_deltaTopography[lev]; m_deltaTopography[lev] = NULL; } } if (m_velSolver != NULL) { // code crashes here. comment out until I figure out the problem... delete m_velSolver; m_velSolver = NULL; } if (m_constitutiveRelation != NULL) { delete m_constitutiveRelation; m_constitutiveRelation = NULL; } if (m_rateFactor != NULL) { delete m_rateFactor; m_rateFactor = NULL; } if (m_basalFrictionRelation != NULL) { delete m_basalFrictionRelation; m_basalFrictionRelation = NULL; } if (m_basalRateFactor != NULL) { delete m_basalRateFactor; m_basalRateFactor = NULL; } for (int lev=0; lev<m_thicknessPatchGodVect.size(); lev++) { if (m_thicknessPatchGodVect[lev] != NULL) { delete m_thicknessPatchGodVect[lev]; m_thicknessPatchGodVect[lev] = NULL; } } if (m_thicknessPhysPtr != NULL) { delete m_thicknessPhysPtr; m_thicknessPhysPtr = NULL; } if (m_thicknessIBCPtr != NULL) { delete m_thicknessIBCPtr; m_thicknessIBCPtr = NULL; } if (m_internalEnergyIBCPtr != NULL) { delete m_internalEnergyIBCPtr; m_internalEnergyIBCPtr = NULL; } if (m_muCoefficientPtr != NULL) { delete m_muCoefficientPtr; m_muCoefficientPtr = NULL; } if (m_surfaceFluxPtr != NULL) { delete m_surfaceFluxPtr; m_surfaceFluxPtr = NULL; } if (m_basalFluxPtr != NULL) { delete m_basalFluxPtr; m_basalFluxPtr = NULL; } if (m_calvingModelPtr != NULL) { delete m_calvingModelPtr; m_calvingModelPtr = NULL; } if (m_basalFrictionPtr != NULL) { delete m_basalFrictionPtr; m_basalFrictionPtr = NULL; } if (m_surfaceHeatBoundaryDataPtr != NULL) { delete m_surfaceHeatBoundaryDataPtr; m_surfaceHeatBoundaryDataPtr = NULL; } if (m_basalHeatBoundaryDataPtr != NULL) { delete m_basalHeatBoundaryDataPtr; m_basalHeatBoundaryDataPtr = NULL; } #ifdef HAVE_PYTHON if (m_tagPythonFunction != NULL) { Py_DECREF(m_tagPythonFunction); } if (m_tagPythonModule != NULL) { Py_DECREF(m_tagPythonModule); } #endif // that should be it! } void AmrIce::initialize() { CH_TIME("AmrIce::initialize"); if (s_verbosity > 3) { pout() << "AmrIce::initialize" << endl; } // set time to be 0 -- do this now in case it needs to be changed later m_time = 0.0; m_cur_step = 0; // first, read in info from parmParse file ParmParse ppCon("constants"); ppCon.query("ice_density",m_iceDensity); ppCon.query("sea_water_density",m_seaWaterDensity); ppCon.query("gravity",m_gravity); ppCon.query("seconds_per_unit_time",m_seconds_per_unit_time); IceThermodynamics::setConstants(m_iceDensity,m_seaWaterDensity,m_gravity,m_seconds_per_unit_time); ParmParse ppAmr("amr"); Vector<int> ancells(3); // allows for domains with lower indices which are not positive Vector<int> domLoIndex(SpaceDim,0); // slc : SpaceDim == 2 implies poor-mans multidim mode, in which we still // care about the number of vertical layers. Vector<Real> domsize(SpaceDim); // assumption is that domains are not periodic bool is_periodic[SpaceDim]; for (int dir=0; dir<SpaceDim; dir++) is_periodic[dir] = false; Vector<int> is_periodic_int(SpaceDim, 0); ppAmr.get("maxLevel", m_max_level); ppAmr.query("tagCap",m_tag_cap); ppAmr.getarr("num_cells", ancells, 0, ancells.size()); // this one doesn't have a vertical dimension ppAmr.queryarr("domainLoIndex", domLoIndex, 0, SpaceDim); # if 0 // this is now handled in main and passed in using the // setDomainSize function if (ppAmr.contains("domain_size")) { ppAmr.getarr("domain_size", domsize, 0, SpaceDim); m_domainSize = RealVect(D_DECL(domsize[0], domsize[1], domsize[2])); } #endif ppAmr.getarr("is_periodic", is_periodic_int, 0, SpaceDim); for (int dir=0; dir<SpaceDim; dir++) { is_periodic[dir] = (is_periodic_int[dir] == 1); } ppAmr.query("velocity_exit", m_velocity_exit); ppAmr.query("cfl", m_cfl); m_initial_cfl = m_cfl; ppAmr.query("initial_cfl", m_initial_cfl); ppAmr.query("max_dt_grow_factor", m_max_dt_grow); ppAmr.query("time_step_ticks", m_timeStepTicks); // max_dt_grow must be at least two in this case - or it will never grow if (m_timeStepTicks) m_max_dt_grow = std::max(m_max_dt_grow, two); ppAmr.query("fixed_dt", m_fixed_dt); ppAmr.query("offsetTime", m_offsetTime); ppAmr.query("isothermal",m_isothermal); setOutputOptions(ppAmr); ppAmr.query("evolve_thickness", m_evolve_thickness); ppAmr.query("evolve_topography_fix_surface", m_evolve_topography_fix_surface); ppAmr.query("evolve_velocity", m_evolve_velocity); ppAmr.query("velocity_solve_interval", m_velocity_solve_interval); ppAmr.query("grounded_ice_stable", m_grounded_ice_stable); ppAmr.query("floating_ice_stable", m_floating_ice_stable); ppAmr.query("floating_ice_basal_flux_is_dhdt", m_floating_ice_basal_flux_is_dhdt); ppAmr.query("floating_ice_basal_flux_is_min_dhdt", m_floating_ice_basal_flux_is_min_dhdt); CH_assert( ! (m_floating_ice_basal_flux_is_dhdt && m_floating_ice_basal_flux_is_min_dhdt) ); CH_assert( ! (m_floating_ice_basal_flux_is_dhdt && m_floating_ice_stable) ); CH_assert( ! (m_floating_ice_stable && m_floating_ice_basal_flux_is_min_dhdt) ); ppAmr.query("grounded_ice_basal_flux_is_dhdt",m_grounded_ice_basal_flux_is_dhdt); ppAmr.query("mask_sources", m_frac_sources); ppAmr.query("grounding_line_proximity_scale",m_groundingLineProximityScale); ppAmr.query("grounding_line_proximity_calc_type", m_groundingLineProximityCalcType); bool tempBool = m_write_dHDt; ppAmr.query("write_dHDt", tempBool); m_write_dHDt = (tempBool == 1); ppAmr.query("write_mask", m_write_mask); ppAmr.query("write_solver_rhs", m_write_solver_rhs); if (m_max_level > 0) { //m_refinement_ratios.resize(m_max_level+1,-1); ppAmr.getarr("ref_ratio", m_refinement_ratios, 0, m_max_level); } else { m_refinement_ratios.resize(1); m_refinement_ratios[0] = -1; } ppAmr.query("verbosity", s_verbosity); ppAmr.get("regrid_interval", m_regrid_interval); m_n_regrids = 0; ppAmr.query("interpolate_zb", m_interpolate_zb); ppAmr.query("regrid_thickness_interpolation_method", m_regrid_thickness_interpolation_method); ppAmr.get("blockFactor", m_block_factor); ppAmr.get("fill_ratio", m_fill_ratio); ppAmr.query("nestingRadius", m_nesting_radius); #ifdef CH_USE_PETSC // petsc solvers require nesting radius >= 3 if (m_nesting_radius < 3) { MayDay::Warning("PETSC solvers require nesting radius >= 3 -- resetting to 3"); m_nesting_radius = 3; } #endif bool isThereATaggingCriterion = false; ppAmr.query("tag_on_grad_velocity", m_tagOnGradVel); isThereATaggingCriterion |= m_tagOnGradVel; ppAmr.query("tagging_val", m_tagging_val); ppAmr.query("tag_on_laplacian_velocity", m_tagOnLapVel); isThereATaggingCriterion |= m_tagOnLapVel; ppAmr.query("tag_on_grounded_laplacian_velocity", m_tagOnGroundedLapVel); isThereATaggingCriterion |= m_tagOnGroundedLapVel; // if we set either of these to be true, require that we also provide the threshold if (m_tagOnLapVel | m_tagOnGroundedLapVel) { ppAmr.get("lap_vel_tagging_val", m_laplacian_tagging_val); ppAmr.query("lap_vel_tagging_max_basal_friction_coef", m_laplacian_tagging_max_basal_friction_coef); } ppAmr.query("tag_on_strain_rate_invariant",m_tagOnEpsSqr); isThereATaggingCriterion |= m_tagOnEpsSqr; // if we set this to be true, require that we also provide the threshold if (m_tagOnEpsSqr) { ppAmr.get("strain_rate_invariant_tagging_val", m_epsSqr_tagVal); } ppAmr.query("tag_on_velocity_rhs",m_tagOnVelRHS); isThereATaggingCriterion |= m_tagOnVelRHS; // if we set this to be true, require that we also provide the threshold if (m_tagOnVelRHS) { ppAmr.get("velocity_rhs_tagging_val", m_velRHS_tagVal); } ppAmr.query("tag_grounding_line", m_tagGroundingLine); isThereATaggingCriterion |= m_tagGroundingLine; // if we set this to be true, require that we also provide the threshold if (m_tagGroundingLine) { ppAmr.get("grounding_line_tagging_min_vel",m_groundingLineTaggingMinVel); ppAmr.query("grounding_line_tagging_max_basal_friction_coef", m_groundingLineTaggingMaxBasalFrictionCoef); } ppAmr.query("tag_vel_dx", m_tagVelDx); isThereATaggingCriterion |= m_tagVelDx; // if we set this to be true, require that we also provide the threshold if (m_tagVelDx) { ppAmr.get("vel_dx_tagging_val",m_velDx_tagVal); ppAmr.query("vel_dx_finest_level_grounded",m_velDx_tagVal_finestLevelGrounded); m_velDx_tagVal_finestLevelFloating = m_velDx_tagVal_finestLevelGrounded; ppAmr.query("vel_dx_finest_level_floating",m_velDx_tagVal_finestLevelFloating); } ppAmr.query("tag_thin_cavity", m_tag_thin_cavity); ppAmr.query("tag_thin_cavity_thickness", m_tag_thin_cavity_thickness); #ifdef HAVE_PYTHON ppAmr.query("tag_python", m_tagPython); isThereATaggingCriterion |= m_tagPython; if (m_tagPython) { std::string s; ppAmr.get("tag_python_module", s); PythonInterface::InitializePythonModule (&m_tagPythonModule, s); ppAmr.get("tag_python_function",s); PythonInterface::InitializePythonFunction (&m_tagPythonFunction, m_tagPythonModule , s); } #endif ppAmr.query("tag_ice_margin", m_tagMargin); isThereATaggingCriterion |= m_tagMargin; // if we set this to be true, require finest level to tag if (m_tagMargin) { m_margin_tagVal_finestLevel = m_max_level+1; ppAmr.query("margin_finest_level",m_margin_tagVal_finestLevel); } ppAmr.query("tag_all_ice", m_tagAllIce); isThereATaggingCriterion |= m_tagAllIce; ppAmr.query("tag_entire_domain", m_tagEntireDomain); isThereATaggingCriterion |= m_tagEntireDomain; ppAmr.query("tag_on_div_H_grad_vel",m_tagOndivHgradVel); isThereATaggingCriterion |= m_tagOndivHgradVel; // if we set this to be true, require that we also provide the threshold if (m_tagOndivHgradVel) { ppAmr.get("div_H_grad_vel_tagging_val", m_divHGradVel_tagVal); } // here is a good place to set default to grad(vel) //if ((!m_tagOnGradVel) && (!m_tagOnLapVel) && (!m_tagOnEpsSqr)) if (!isThereATaggingCriterion) { m_tagOnGradVel = true; } ppAmr.query("tags_grow", m_tags_grow); { Vector<int> tgd(SpaceDim,0); ppAmr.queryarr("tags_grow_dir", tgd, 0, tgd.size()); for (int dir =0; dir < SpaceDim; dir++) { m_tags_grow_dir[dir] = tgd[dir]; } } ppAmr.query("max_box_size", m_max_box_size); if (ppAmr.contains("max_base_grid_size") ) { ppAmr.get("max_base_grid_size", m_max_base_grid_size); } else { m_max_base_grid_size = m_max_box_size; } ppAmr.query("report_discharge", m_report_discharge); ppAmr.query("report_time_interval", m_report_time_interval); ppAmr.query("eliminate_remote_ice", m_eliminate_remote_ice); ppAmr.query("eliminate_remote_ice_max_iter", m_eliminate_remote_ice_max_iter); ppAmr.query("eliminate_remote_ice_tol", m_eliminate_remote_ice_tol); ppAmr.query("eliminate_remote_ice_after_regrid", m_eliminate_remote_ice_after_regrid); // get temporal accuracy ppAmr.query("temporal_accuracy", m_temporalAccuracy); // number of ghost cells depends on what scheme we're using if (m_temporalAccuracy < 3) { m_num_thickness_ghost = 4; } else { m_num_thickness_ghost = 1; } // get solver type ppAmr.query("velocity_solver_type", m_solverType); ppAmr.query("max_solver_iterations",m_maxSolverIterations); ppAmr.query("velocity_solver_tolerance", m_velocity_solver_tolerance); ppAmr.query("do_initial_velocity_solve", m_doInitialVelSolve); ppAmr.query("do_initial_velocity_guess", m_doInitialVelGuess); ppAmr.query("initial_velocity_guess_type", m_initialGuessType); ppAmr.query("initial_velocity_guess_const_mu", m_initialGuessConstMu); ppAmr.query("initial_velocity_guess_solver_type", m_initialGuessSolverType); { Vector<Real> t(SpaceDim,0.0); ppAmr.queryarr("initial_velocity_guess_const_vel", t, 0, SpaceDim); m_initialGuessConstVel = RealVect(D_DECL(t[0], t[1], t[2])); } ppAmr.query("additional_velocity",m_additionalVelocity); //thickness diffusion options std::string diffusionTreatment = "none"; ppAmr.query("diffusion_treatment", diffusionTreatment); if (diffusionTreatment == "implicit") { m_diffusionTreatment = IMPLICIT; } else if (diffusionTreatment == "explicit") m_diffusionTreatment = EXPLICIT; ppAmr.query("additional_diffusivity",m_additionalDiffusivity); //option to advance thickness/internalEnergy only on coarser levels ppAmr.query("finest_timestep_level",m_finest_timestep_level); ppAmr.query("reset_floating_friction", m_reset_floating_friction_to_zero); ppAmr.query("basal_length_scale", m_basalLengthScale); // now set up problem domains { IntVect loVect = IntVect(D_DECL(domLoIndex[0], domLoIndex[1], domLoIndex[3])); IntVect hiVect(D_DECL(domLoIndex[0]+ancells[0]-1, domLoIndex[1]+ancells[1]-1, domLoIndex[2]+ancells[2]-1)); #if BISICLES_Z == BISICLES_LAYERED { int nLayers = ancells[2]; Vector<Real> faceSigma(nLayers+1); Real dsigma = 1.0 / Real(nLayers); for (unsigned int l = 0; l < faceSigma.size(); ++l) faceSigma[l] = dsigma * (Real(l)); { ParmParse ppGeo("geometry"); ppGeo.queryarr("sigma",faceSigma,0,faceSigma.size()); } ppAmr.queryarr("sigma",faceSigma,0,faceSigma.size()); setLayers(faceSigma); } #endif ProblemDomain baseDomain(loVect, hiVect); // now set periodicity for (int dir=0; dir<SpaceDim; dir++) baseDomain.setPeriodic(dir, is_periodic[dir]); // now set up vector of domains m_amrDomains.resize(m_max_level+1); m_amrDx.resize(m_max_level+1); m_amrDomains[0] = baseDomain; m_amrDx[0] = m_domainSize[0]/baseDomain.domainBox().size(0); for (int lev=1; lev<= m_max_level; lev++) { m_amrDomains[lev] = refine(m_amrDomains[lev-1], m_refinement_ratios[lev-1]); m_amrDx[lev] = m_amrDx[lev-1]/m_refinement_ratios[lev-1]; } } // leaving problem domain setup scope std::string tagSubsetBoxesFile = ""; m_vectTagSubset.resize(m_max_level); ppAmr.query("tagSubsetBoxesFile",tagSubsetBoxesFile); if (tagSubsetBoxesFile != "") { if (procID() == uniqueProc(SerialTask::compute)) { ifstream is(tagSubsetBoxesFile.c_str(), ios::in); int lineno = 1; if (is.fail()) { pout() << "Can't open " << tagSubsetBoxesFile << std::endl; MayDay::Error("Cannot open refine boxes file"); } for (int lev = 0; lev < m_max_level; lev++) { // allowable tokens to identify levels in tag subset file const char level[6] = "level"; const char domain[7] = "domain"; char s[6]; is >> s; if (std::string(level) == std::string(s)) { int inlev; is >> inlev; if (inlev != lev) { pout() << "expected ' " << lev << "' at line " << lineno << std::endl; MayDay::Error("bad input file"); } } else if (std::string(domain) == std::string(s)) { // basic idea here is that we read in domain box // (domains must be ordered from coarse->fine) // until we get to a domain box which matches ours. // This lets us make a single list of subset regions // which we can use for any coarsening/refining of the domain const Box& levelDomainBox = m_amrDomains[lev].domainBox(); bool stillLooking = true; while (stillLooking) { Box domainBox; is >> domainBox; if (domainBox == levelDomainBox) { pout() << "Found a domain matching level " << lev << endl; stillLooking = false; } else // move on until we find our level { // read in info for the level we're ignoring //advance to next line while (is.get() != '\n'); lineno++; int nboxes; is >> nboxes; if (nboxes > 0) { for (int i = 0; i < nboxes; ++i) { Box box; is >> box; while (is.get() != '\n'); lineno++; } } is >> s; if (std::string(domain) != std::string(s)) { pout() << "expected '" << domain << "' at line " << lineno << ", got " << s << std::endl; MayDay::Error("bad input file"); } } } } else { pout() << "expected '" << level << "' or '" << domain << "' at line " << lineno << ", got " << s << std::endl; MayDay::Error("bad input file"); } //advance to next line while (is.get() != '\n'); lineno++; int nboxes; is >> nboxes; if (nboxes > 0) { for (int i = 0; i < nboxes; ++i) { Box box; is >> box; while (is.get() != '\n'); lineno++; m_vectTagSubset[lev] |= box; pout() << " level " << lev << " refine box : " << box << std::endl; } } //advance to next line while (is.get() != '\n'); lineno++; if (lev > 0) { //add lower level's subset to this subset IntVectSet crseSet (m_vectTagSubset[lev-1]); if (!crseSet.isEmpty()) { crseSet.refine(m_refinement_ratios[lev-1]); // crseSet.nestingRegion(m_block_factor,m_amrDomains[lev]); if (m_vectTagSubset[lev].isEmpty()) { m_vectTagSubset[lev] = crseSet; } else { m_vectTagSubset[lev] &= crseSet; } } } } // end loop over levels } // end if serial compute for (int lev = 0; lev < m_max_level; lev++) broadcast(m_vectTagSubset[lev], uniqueProc(SerialTask::compute)); } /// PatchGodunov used for thickness advection if (m_temporalAccuracy < 3) { // get PatchGodunov options -- first set reasonable defaults. // can over-ride from ParmParse ParmParse pph ("amr.thickness_advection"); int normalPredOrder = 2; pph.query("normal_pred_order",normalPredOrder); bool useFourthOrderSlopes = true; pph.query("fourth_order_slopes",useFourthOrderSlopes); bool usePrimLimiting = true; bool useCharLimiting = false; bool useFlattening = false; Real artificialViscosity = 0.0; pph.query("artificial_viscosity",artificialViscosity); bool useArtificialViscosity = artificialViscosity > TINY_NORM; // define AdvectionPhysics ptr // (does this need to be a special Ice-advection pointer due // to H factors? m_thicknessPhysPtr = new AdvectPhysics; m_thicknessPhysPtr->setPhysIBC(m_thicknessIBCPtr); m_thicknessPatchGodVect.resize(m_max_level+1, NULL); for (int lev=0; lev<=m_max_level; lev++) { m_thicknessPatchGodVect[lev] = new PatchGodunov; m_thicknessPatchGodVect[lev]->define(m_amrDomains[lev], m_amrDx[lev], m_thicknessPhysPtr, normalPredOrder, useFourthOrderSlopes, usePrimLimiting, useCharLimiting, useFlattening, useArtificialViscosity, artificialViscosity); } //m_internalEnergyIBCPtr = new IceInternalEnergyIBC; } // end if temporal accuracy < 3 // check to see if we're using predefined grids bool usePredefinedGrids = false; std::string gridFile; if (ppAmr.contains("gridsFile")) { usePredefinedGrids = true; ppAmr.get("gridsFile",gridFile); } ParmParse geomPP("geometry"); if (geomPP.contains("basalSlope") ) { Vector<Real> basalSlope(SpaceDim, 0.0); geomPP.getarr("basalSlope", basalSlope, 0, SpaceDim); D_TERM( m_basalSlope[0] = basalSlope[0];, m_basalSlope[1] = basalSlope[1];, m_basalSlope[2] = basalSlope[2];); } // check to see if we're restarting from a checkpoint file if (!ppAmr.contains("restart_file")) { // if we're not restarting // now set up data holders m_old_thickness.resize(m_max_level+1, NULL); m_velocity.resize(m_max_level+1, NULL); m_iceFrac.resize(m_max_level+1, NULL); m_faceVelAdvection.resize(m_max_level+1, NULL); m_faceVelTotal.resize(m_max_level+1, NULL); m_diffusivity.resize(m_max_level+1); m_velBasalC.resize(m_max_level+1,NULL); m_cellMuCoef.resize(m_max_level+1,NULL); m_velRHS.resize(m_max_level+1, NULL); m_surfaceThicknessSource.resize(m_max_level+1, NULL); m_basalThicknessSource.resize(m_max_level+1, NULL); m_volumeThicknessSource.resize(m_max_level+1, NULL); m_calvedIceThickness.resize(m_max_level+1, NULL); m_removedIceThickness.resize(m_max_level+1, NULL); m_addedIceThickness.resize(m_max_level+1, NULL); m_divThicknessFlux.resize(m_max_level+1, NULL); m_internalEnergy.resize(m_max_level+1, NULL); m_tillWaterDepth.resize(m_max_level+1, NULL); m_deltaTopography.resize(m_max_level+1, NULL); #if BISICLES_Z == BISICLES_LAYERED m_layerXYFaceXYVel.resize(m_max_level+1, NULL); m_layerSFaceXYVel.resize(m_max_level+1, NULL); m_layerSFaceSVel.resize(m_max_level+1, NULL); m_sInternalEnergy.resize(m_max_level+1, NULL); m_bInternalEnergy.resize(m_max_level+1, NULL); m_sHeatFlux.resize(m_max_level+1, NULL); m_bHeatFlux.resize(m_max_level+1, NULL); #endif // allocate storage for m_old_thickness, m_velocity, etc for (int lev=0; lev<m_velocity.size(); lev++) { m_old_thickness[lev] = new LevelData<FArrayBox>; m_velocity[lev] = new LevelData<FArrayBox>; m_iceFrac[lev] = new LevelData<FArrayBox>; m_faceVelAdvection[lev] = new LevelData<FluxBox>; m_faceVelTotal[lev] = new LevelData<FluxBox>; m_velBasalC[lev] = new LevelData<FArrayBox>; m_cellMuCoef[lev] = new LevelData<FArrayBox>; m_velRHS[lev] = new LevelData<FArrayBox>; m_diffusivity[lev] = new LevelData<FluxBox>; m_internalEnergy[lev] = new LevelData<FArrayBox>; m_tillWaterDepth[lev] = new LevelData<FArrayBox>; m_deltaTopography[lev] = new LevelData<FArrayBox>; #if BISICLES_Z == BISICLES_LAYERED m_sInternalEnergy[lev] = new LevelData<FArrayBox>; m_bInternalEnergy[lev] = new LevelData<FArrayBox>; m_sHeatFlux[lev] = new LevelData<FArrayBox>; m_bHeatFlux[lev] = new LevelData<FArrayBox>; m_layerXYFaceXYVel[lev] = new LevelData<FluxBox>; m_layerSFaceXYVel[lev] = new LevelData<FArrayBox>; m_layerSFaceSVel[lev] = new LevelData<FArrayBox>; #endif } int finest_level = -1; if (usePredefinedGrids) { setupFixedGrids(gridFile); } else { // now create grids initGrids(finest_level); } } else { // we're restarting from a checkpoint file string restart_file; ppAmr.get("restart_file", restart_file); m_do_restart = true; #ifdef CH_USE_HDF5 restart(restart_file); #else MayDay::Error("restart_file specified but hdf5 support not built"); #endif // hdf5 } // last thing to do is to set this to true from here on out... m_doInitialVelSolve = true; // set up counter of number of cells m_num_cells.resize(m_max_level+1, 0); for (int lev=0; lev<=m_finest_level; lev++) { const DisjointBoxLayout& levelGrids = m_amrGrids[lev]; LayoutIterator lit = levelGrids.layoutIterator(); for (lit.begin(); lit.ok(); ++lit) { const Box& thisBox = levelGrids.get(lit()); m_num_cells[lev] += thisBox.numPts(); } } // finally, set up covered_level flags m_covered_level.resize(m_max_level+1, 0); // note that finest level can't be covered. for (int lev=m_finest_level-1; lev>=0; lev--) { // if the next finer level is covered, then this one is too. if (m_covered_level[lev+1] == 1) { m_covered_level[lev] = 1; } else { // see if the grids finer than this level completely cover it IntVectSet fineUncovered(m_amrDomains[lev+1].domainBox()); const DisjointBoxLayout& fineGrids = m_amrGrids[lev+1]; LayoutIterator lit = fineGrids.layoutIterator(); for (lit.begin(); lit.ok(); ++lit) { const Box& thisBox = fineGrids.get(lit()); fineUncovered.minus_box(thisBox); } if (fineUncovered.isEmpty()) { m_covered_level[lev] = 1; } } } // end loop over levels to determine covered levels m_cf_domain_diagnostic_data.initDiagnostics (*this, m_vect_coordSys, m_amrGrids, m_refinement_ratios, m_amrDx[0], time() , m_finest_level); } /// set BC for thickness advection void AmrIce::setThicknessBC( IceThicknessIBC* a_thicknessIBC) { m_thicknessIBCPtr = a_thicknessIBC->new_thicknessIBC(); } /// set BC for internalEnergy advection void AmrIce::setInternalEnergyBC( IceInternalEnergyIBC* a_internalEnergyIBC) { m_internalEnergyIBCPtr = a_internalEnergyIBC->new_internalEnergyIBC(); } void AmrIce::defineSolver() { if (m_solverType == Picard) { MayDay::Error("PicardSolver is deprecated (for now)"); } else if (m_solverType == JFNK) { // for now, at least, just delete any existing solvers // and rebuild them from scratch JFNKSolver* jfnkSolver; RealVect dxCrse = m_amrDx[0]*RealVect::Unit; int numLevels = m_finest_level +1; // make sure that the IBC has the correct grid hierarchy info m_thicknessIBCPtr->setGridHierarchy(m_vect_coordSys, m_amrDomains); if (m_velSolver != NULL) { // assume that any extant solver is also a JFNKSolver jfnkSolver = dynamic_cast<JFNKSolver*>(m_velSolver); CH_assert(jfnkSolver != NULL); } else { jfnkSolver = new JFNKSolver(); } jfnkSolver->define(m_amrDomains[0], m_constitutiveRelation, m_basalFrictionRelation, m_amrGrids, m_refinement_ratios, dxCrse, m_thicknessIBCPtr, numLevels); m_velSolver = jfnkSolver; } else if (m_solverType == KnownVelocity) { if (m_velSolver != NULL) { delete m_velSolver; m_velSolver = NULL; } m_velSolver = new KnownVelocitySolver; RealVect dxCrse = m_amrDx[0]*RealVect::Unit; int numLevels = m_finest_level +1; m_velSolver->define(m_amrDomains[0], m_constitutiveRelation, m_basalFrictionRelation, m_amrGrids, m_refinement_ratios, dxCrse, m_thicknessIBCPtr, numLevels); } #ifdef CH_USE_PETSC else if (m_solverType == PetscNLSolver) { // for now, at least, just delete any existing solvers // and rebuild them from scratch if (m_velSolver != NULL) { delete m_velSolver; m_velSolver = NULL; } m_velSolver = new PetscIceSolver; RealVect dxCrse = m_amrDx[0]*RealVect::Unit; int numLevels = m_finest_level +1; // make sure that the IBC has the correct grid hierarchy info m_thicknessIBCPtr->setGridHierarchy(m_vect_coordSys, m_amrDomains); m_velSolver->define(m_amrDomains[0], m_constitutiveRelation, m_basalFrictionRelation, m_amrGrids, m_refinement_ratios, dxCrse, m_thicknessIBCPtr, numLevels); m_velSolver->setVerbosity(s_verbosity); m_velSolver->setTolerance(m_velocity_solver_tolerance); if (m_maxSolverIterations > 0) { m_velSolver->setMaxIterations(m_maxSolverIterations); } } #endif #ifdef CH_USE_FAS else if (m_solverType == FASMGAMR) { // for now, at least, just delete any existing solvers // and rebuild them from scratch if (m_velSolver != NULL) { delete m_velSolver; m_velSolver = NULL; } FASIceSolver *solver = new FASIceSolver; m_velSolver = solver; solver->setParameters( "FASSolver" ); RealVect dxCrse = m_amrDx[0]*RealVect::Unit; int numLevels = m_finest_level + 1; // make sure that the IBC has the correct grid hierarchy info m_thicknessIBCPtr->setGridHierarchy( m_vect_coordSys, m_amrDomains ); solver->define( m_amrDomains[0], m_constitutiveRelation, m_basalFrictionRelation, m_amrGrids, m_refinement_ratios, dxCrse, m_thicknessIBCPtr, numLevels ); solver->setTolerance( m_velocity_solver_tolerance ); if (m_maxSolverIterations > 0) { solver->setMaxIterations( m_maxSolverIterations ); } } #endif #ifdef HAVE_PYTHON else if (m_solverType == Python) { // for now, at least, just delete any existing solvers // and rebuild them from scratch if (m_velSolver != NULL) { delete m_velSolver; m_velSolver = NULL; } m_velSolver = new PythonInterface::PythonVelocitySolver; m_velSolver->define( m_amrDomains[0], m_constitutiveRelation, m_basalFrictionRelation, m_amrGrids, m_refinement_ratios, m_amrDx[0]*RealVect::Unit, m_thicknessIBCPtr, m_finest_level + 1 ); } #endif else if (m_solverType == InverseVerticallyIntegrated) { if (m_velSolver != NULL) { //not sure if we are OK with rebuilding solvers? delete m_velSolver; m_velSolver = NULL; } InverseVerticallyIntegratedVelocitySolver* ptr = new InverseVerticallyIntegratedVelocitySolver; ptr->define( *this, m_amrDomains[0], m_constitutiveRelation, m_basalFrictionRelation, m_amrGrids, m_refinement_ratios, m_amrDx[0]*RealVect::Unit, m_thicknessIBCPtr, m_finest_level + 1 ); m_velSolver = ptr; } else { MayDay::Error("unsupported velocity solver type"); } } //inline //Real remainder(Real a, Real b) //{ // Real p = a/b; int i(p); // return std::min( p - i, p - 1 - i); //} void AmrIce::setToZero(Vector<LevelData<FArrayBox>*>& a_data) { for (int lev=0; lev < std::min(int(a_data.size()),finestLevel()+1); lev++) { LevelData<FArrayBox>& data = *a_data[lev]; for (DataIterator dit(data.dataIterator()); dit.ok(); ++dit) { data[dit].setVal(0.0); } } } void AmrIce::run(Real a_max_time, int a_max_step) { CH_TIME("AmrIce::run"); if (s_verbosity > 3) { pout() << "AmrIce::run -- max_time= " << a_max_time << ", max_step = " << a_max_step << endl; } Real dt; // only call computeInitialDt if we're not doing restart if (!m_do_restart) { dt = computeInitialDt(); } else { dt = computeDt(); } // advance solution until done if ( !(m_plot_time_interval > TIME_EPS) || m_plot_time_interval > a_max_time) m_plot_time_interval = a_max_time; if ( !(m_report_time_interval > TIME_EPS) || m_report_time_interval > a_max_time) m_report_time_interval = a_max_time; while ( a_max_time > m_time && (m_cur_step < a_max_step)) { Real next_plot_time = m_plot_time_interval * (1.0 + Real(int((m_time/m_plot_time_interval)))); if ( !(next_plot_time > m_time)) { //trap case where machine precision results in (effectively) // m_plot_time_interval * (1.0 + Real(int((m_time/m_plot_time_interval)))) == m_time next_plot_time += m_plot_time_interval; } next_plot_time = std::min(next_plot_time, a_max_time); m_next_report_time = m_time; m_next_report_time = std::min(m_next_report_time, a_max_time); while ( (next_plot_time > m_time) && (m_cur_step < a_max_step) && (dt > TIME_EPS)) { #ifdef CH_USE_HDF5 // dump plotfile before regridding if ( (m_cur_step%m_plot_interval == 0) && m_plot_interval > 0) { writePlotFile(); } // dump checkpoint before regridding if ((m_cur_step%m_check_interval == 0) && (m_check_interval > 0) && (m_cur_step != m_restart_step)) { writeCheckpointFile(); if (m_cur_step > 0 && m_check_exit) { if (s_verbosity > 2) { pout() << "AmrIce::exit on checkpoint" << endl; return; } } } #endif setToZero(m_calvedIceThickness); setToZero(m_removedIceThickness); setToZero(m_addedIceThickness); if ((m_cur_step != 0) && (m_cur_step%m_regrid_interval ==0)) { regrid(); } if (m_cur_step != 0) { // compute dt after regridding in case number of levels has changed dt = computeDt(); } //Real trueDt = dt; //we will need to restore dt if we change it below if (next_plot_time - m_time + TIME_EPS < dt) dt = std::max(2 * TIME_EPS, next_plot_time - m_time); timeStep(dt); //m_dt = trueDt; // restores the correct timestep in cases where it was chosen just to reach a plot file //update CF data mean if (m_plot_style_cf) accumulateCFData(dt); } // end of plot_time_interval #ifdef CH_USE_HDF5 if (m_plot_interval >= 0 && abs(next_plot_time - a_max_time) > TIME_EPS) writePlotFile(); #endif } // end timestepping loop // dump out final plotfile, if appropriate #ifdef CH_USE_HDF5 if (m_plot_interval >= 0) { writePlotFile(); } // dump out final checkpoint file, if appropriate if (m_check_interval >= 0) { writeCheckpointFile(); } #endif if (s_verbosity > 2) { pout() << "AmrIce::run finished" << endl; } } void AmrIce::timeStep(Real a_dt) { CH_TIME("AmrIce::timestep"); if (s_verbosity >=2) { pout() << "Timestep " << m_cur_step << " Advancing solution from time " << m_time << " ( " << time() << ")" " with dt = " << a_dt << endl; } m_dt = a_dt; // first copy thickness into old thickness for (int lev=0; lev <= m_finest_level ; lev++) { LevelData<FArrayBox>& oldThickness = *m_old_thickness[lev]; LevelData<FArrayBox>& currentThickness = m_vect_coordSys[lev]->getH(); // this way we avoid communication and maintain ghost cells... DataIterator dit = oldThickness.dataIterator(); for (dit.begin(); dit.ok(); ++dit) { oldThickness[dit].copy(currentThickness[dit],0, 0, 1); } } // assumption here is that we've already computed the current velocity // field, most likely at initialization or at the end of the last timestep... // so, we don't need to recompute the velocity at the start. // use PatchGodunov hyperbolic solver #if 0 // this doesn't appear to be used anywhere anymore // need a grown velocity field IntVect grownVelGhost(2*IntVect::Unit); Vector<LevelData<FArrayBox>* > grownVel(m_finest_level+1, NULL); #endif // holder for half-time face velocity Vector<LevelData<FluxBox>* > H_half(m_finest_level+1,NULL); // thickness fluxes Vector<LevelData<FluxBox>* > vectFluxes(m_finest_level+1, NULL); // allocate storage for (int lev = finestTimestepLevel() ; lev>=0 ; lev--) { const DisjointBoxLayout& levelGrids = m_amrGrids[lev]; IntVect ghostVect = IntVect::Unit; H_half[lev] = new LevelData<FluxBox>(m_amrGrids[lev], 1, ghostVect); // if we're doing AMR, we'll need to average these fluxes // down to coarser levels. As things stand now, // CoarseAverageFace requires that the coarse LevelData<FluxBox> // have a ghost cell. vectFluxes[lev] = new LevelData<FluxBox>(m_amrGrids[lev],1, ghostVect); LevelData<FArrayBox>& levelOldThickness = *m_old_thickness[lev]; // ensure that ghost cells for thickness are filled in if (lev > 0) { int nGhost = levelOldThickness.ghostVect()[0]; PiecewiseLinearFillPatch thicknessFiller(levelGrids, m_amrGrids[lev-1], 1, m_amrDomains[lev-1], m_refinement_ratios[lev-1], nGhost); // since we're not subcycling, don't need to interpolate in time Real time_interp_coeff = 0.0; thicknessFiller.fillInterp(levelOldThickness, *m_old_thickness[lev-1], *m_old_thickness[lev-1], time_interp_coeff, 0, 0, 1); } // these are probably unnecessary... levelOldThickness.exchange(); // do we need to also do a coarseAverage for the vel here? } // compute face-centered thickness (H) at t + dt/2 computeH_half(H_half, a_dt); // compute face- and layer- centered E*H and H at t + dt/2 (E is internal energy) Vector<LevelData<FluxBox>* > layerEH_half(m_finest_level+1,NULL); Vector<LevelData<FluxBox>* > layerH_half(m_finest_level+1,NULL); if (!m_isothermal) computeInternalEnergyHalf(layerEH_half, layerH_half, m_layerXYFaceXYVel, a_dt, m_time); // compute thickness fluxes computeThicknessFluxes(vectFluxes, H_half, m_faceVelAdvection); if (m_report_discharge && (m_next_report_time - m_time) < (a_dt + TIME_EPS)) { m_cf_domain_diagnostic_data.computeDischarge (m_vect_coordSys, vectFluxes, m_amrGrids, m_amrDx, m_refinement_ratios, m_time, time(), m_cur_step, m_finest_level, s_verbosity); } // update ice fraction through advection //advectIceFrac(m_iceFrac, m_volumeThicknessSource, m_faceVelAdvection,vectFluxes, a_dt); advectIceFrac(m_iceFrac, m_faceVelAdvection, a_dt); // make a copy of m_vect_coordSys before it is overwritten \todo clean up Vector<RefCountedPtr<LevelSigmaCS> > vectCoords_old (m_finest_level+1); for (int lev=0; lev<= m_finest_level; lev++) { IntVect sigmaCSGhost = m_vect_coordSys[lev]->ghostVect(); RealVect dx = m_amrDx[lev]*RealVect::Unit; vectCoords_old[lev] = RefCountedPtr<LevelSigmaCS> (new LevelSigmaCS(m_amrGrids[lev], dx, sigmaCSGhost)); LevelSigmaCS& levelCoords_old = *vectCoords_old[lev]; const LevelSigmaCS& levelCoords = *m_vect_coordSys[lev]; levelCoords_old.setIceDensity(levelCoords.iceDensity()); levelCoords_old.setWaterDensity(levelCoords.waterDensity()); levelCoords_old.setGravity(levelCoords.gravity()); // todo replace the copies below with a deepCopy of levelCoords for (DataIterator dit( m_amrGrids[lev]); dit.ok(); ++dit) { FArrayBox& oldH = levelCoords_old.getH()[dit]; const FArrayBox& H = levelCoords.getH()[dit]; oldH.copy(H); } levelCoords_old.setTopography(levelCoords.getTopography()); { LevelSigmaCS* crseCoords = (lev > 0)?&(*vectCoords_old[lev-1]):NULL; int refRatio = (lev > 0)?m_refinement_ratios[lev-1]:-1; levelCoords_old.recomputeGeometry( crseCoords, refRatio); } #if BISICLES_Z == BISICLES_LAYERED levelCoords_old.setFaceSigma(levelCoords.getFaceSigma()); #endif } // compute div(F) and update geometry updateGeometry(m_vect_coordSys, vectCoords_old, vectFluxes, a_dt); // update internal energy if (!m_isothermal) { // \todo tify up in here: this also updates m_layerSFaceSVel updateInternalEnergy(layerEH_half, layerH_half, m_layerXYFaceXYVel, m_layerSFaceXYVel, a_dt, m_time, m_vect_coordSys, vectCoords_old, m_surfaceThicknessSource, m_basalThicknessSource, m_volumeThicknessSource); } notifyObservers(Observer::PostGeometryUpdate); // clean up temporary storage for (int lev=0; lev<=m_finest_level; lev++) { if (H_half[lev] != NULL) { delete H_half[lev]; H_half[lev] = NULL; } if (layerEH_half[lev] != NULL) { delete layerEH_half[lev]; layerEH_half[lev] = NULL; } if (layerH_half[lev] != NULL) { delete layerH_half[lev]; layerH_half[lev] = NULL; } if (vectFluxes[lev] != NULL) { delete vectFluxes[lev]; vectFluxes[lev] = NULL; } } if (m_temporalAccuracy > 2) { MayDay::Error("AmrIce::timestep -- un-defined temporal accuracy"); } //update time (velocity is to be computed at the step end) m_time += a_dt; m_cur_step += 1; // compute new ice velocity field if (m_evolve_velocity ) { if (s_verbosity > 3) { pout() << "AmrIce::timeStep solveVelocityField() (step end) " << endl; } solveVelocityField(); } if ((m_next_report_time - m_time) < (a_dt + TIME_EPS)) { m_cf_domain_diagnostic_data.endTimestepDiagnostics (m_vect_coordSys, m_old_thickness, m_divThicknessFlux, m_basalThicknessSource, m_surfaceThicknessSource, m_volumeThicknessSource, m_calvedIceThickness, m_addedIceThickness, m_removedIceThickness, m_amrGrids, m_refinement_ratios, m_amrDx[0], time(), m_time, m_dt, m_cur_step, m_finest_level, s_verbosity); } if (s_verbosity > 0) { pout () << "AmrIce::timestep " << m_cur_step << " -- end time = " << setiosflags(ios::fixed) << setprecision(6) << setw(12) << m_time << " ( " << time() << " )" //<< " (" << m_time/secondsperyear << " yr)" << ", dt = " //<< setiosflags(ios::fixed) << setprecision(6) << setw(12) << a_dt //<< " ( " << a_dt/secondsperyear << " yr )" << resetiosflags(ios::fixed) << endl; } int totalCellsAdvanced = 0; for (int lev=0; lev<m_num_cells.size(); lev++) { totalCellsAdvanced += m_num_cells[lev]; } if (s_verbosity > 0) { pout() << "Time = " << m_time << " cells advanced = " << totalCellsAdvanced << endl; for (int lev=0; lev<m_num_cells.size(); lev++) { pout () << "Time = " << m_time << " level " << lev << " cells advanced = " << m_num_cells[lev] << endl; } } } // compute half-time face-centered thickness using unsplit PPM void AmrIce::computeH_half(Vector<LevelData<FluxBox>* >& a_H_half, Real a_dt) { CH_TIME("AmrIce::computeH_half"); setToZero(m_volumeThicknessSource); // \todo : think about making this user settable for (int lev=0; lev<= finestTimestepLevel(); lev++) { // get AdvectPhysics object from PatchGodunov object PatchGodunov* patchGod = m_thicknessPatchGodVect[lev]; AdvectPhysics* advectPhysPtr = dynamic_cast<AdvectPhysics*>(patchGod->getGodunovPhysicsPtr()); if (advectPhysPtr == NULL) { MayDay::Error("AmrIce::timestep -- unable to upcast GodunovPhysics to AdvectPhysics"); } patchGod->setCurrentTime(m_time); // loop over grids on this level and compute H-Half const DisjointBoxLayout& levelGrids = m_amrGrids[lev]; LevelData<FluxBox>& levelFaceVel = *m_faceVelAdvection[lev]; LevelData<FArrayBox>& levelOldThickness = *m_old_thickness[lev]; LevelData<FluxBox>& levelHhalf = *a_H_half[lev]; LevelData<FArrayBox>& levelSTS = *m_surfaceThicknessSource[lev]; LevelData<FArrayBox>& levelBTS = *m_basalThicknessSource[lev]; LevelData<FArrayBox>& levelVTS = *m_volumeThicknessSource[lev]; CH_assert(m_surfaceFluxPtr != NULL); // set surface thickness source m_surfaceFluxPtr->surfaceThicknessFlux(levelSTS, *this, lev, a_dt); // set basal thickness source m_basalFluxPtr->surfaceThicknessFlux(levelBTS, *this, lev, a_dt); LevelData<FArrayBox> levelCCVel(levelGrids, SpaceDim, IntVect::Unit); EdgeToCell( levelFaceVel, levelCCVel); DataIterator dit = levelGrids.dataIterator(); for (dit.begin(); dit.ok(); ++dit) { patchGod->setCurrentBox(levelGrids[dit]); advectPhysPtr->setVelocities(&(levelCCVel[dit]), &(levelFaceVel[dit])); FArrayBox advectiveSource(levelSTS[dit].box(),1); advectiveSource.copy(levelSTS[dit]); advectiveSource.plus(levelBTS[dit]); advectiveSource.plus(levelVTS[dit]); // add a diffusive source term div(D grad H)) to advectiveSource if (m_diffusionTreatment == IMPLICIT) { for (int dir=0; dir<SpaceDim; dir++) { Box faceBox = levelGrids[dit].surroundingNodes(dir); FArrayBox flux(faceBox,1); FORT_FACEDERIV(CHF_FRA1(flux,0), CHF_CONST_FRA1(levelOldThickness[dit],0), CHF_BOX(faceBox), CHF_CONST_REAL(dx(lev)[dir]), CHF_INT(dir), CHF_INT(dir)); CH_assert(flux.norm(0) < HUGE_NORM); flux *= (*m_diffusivity[lev])[dit][dir]; CH_assert(flux.norm(0) < HUGE_NORM); FORT_DIVERGENCE(CHF_CONST_FRA(flux), CHF_FRA(advectiveSource), CHF_BOX(levelGrids[dit]), CHF_CONST_REAL(dx(lev)[dir]), CHF_INT(dir)); } } // for this part, we need the *effective* thickness FArrayBox he(levelOldThickness[dit].box(), 1); FArrayBox f(levelOldThickness[dit].box(), 1); f.copy( (*m_iceFrac[lev])[dit]); f += TINY_NORM; he.copy(levelOldThickness[dit]); he /= f; patchGod->computeWHalf(levelHhalf[dit], levelOldThickness[dit], advectiveSource, a_dt, levelGrids[dit]); } //end loop over grids } // end loop over levels for computing Whalf // coarse average new H-Half to covered regions for (int lev= finestTimestepLevel(); lev>0; lev--) { CoarseAverageFace faceAverager(m_amrGrids[lev], 1, m_refinement_ratios[lev-1]); faceAverager.averageToCoarse(*a_H_half[lev-1], *a_H_half[lev]); } } void AmrIce::computeThicknessFluxes(Vector<LevelData<FluxBox>* >& a_vectFluxes, const Vector<LevelData<FluxBox>* >& a_H_half, const Vector<LevelData<FluxBox>* >& a_faceVelAdvection) { CH_TIME("AmrIce::computeThicknessFluxes"); for (int lev=0; lev<=finestTimestepLevel(); lev++) { LevelData<FluxBox>& levelFaceVel = *a_faceVelAdvection[lev]; LevelData<FluxBox>& levelFaceH = *a_H_half[lev]; const DisjointBoxLayout& levelGrids = m_amrGrids[lev]; DataIterator dit = levelGrids.dataIterator(); for (dit.begin(); dit.ok(); ++dit) { FluxBox& faceVel = levelFaceVel[dit]; FluxBox& faceH = levelFaceH[dit]; FluxBox& flux = (*a_vectFluxes[lev])[dit]; const Box& gridBox = levelGrids[dit]; for (int dir=0; dir<SpaceDim; dir++) { Box faceBox(gridBox); faceBox.surroundingNodes(dir); flux[dir].copy(faceH[dir], faceBox); flux[dir].mult(faceVel[dir], faceBox, 0, 0, 1); } } } // end loop over levels // average fine fluxes down to coarse levels for (int lev=finestTimestepLevel(); lev>0; lev--) { CoarseAverageFace faceAverager(m_amrGrids[lev], 1, m_refinement_ratios[lev-1]); faceAverager.averageToCoarse(*a_vectFluxes[lev-1], *a_vectFluxes[lev]); } } void AmrIce::setStableSources(FArrayBox& a_smb, FArrayBox& a_bmb, FArrayBox& a_vmb, const FArrayBox& a_divuh, const BaseFab<int>& a_mask, const Box& a_box) const { bool floating_ice_stable = m_floating_ice_stable || (!m_evolve_thickness); bool grounded_ice_stable = m_grounded_ice_stable || (!m_evolve_thickness); //modify thickness sources if any part of the ice sheet is to be held stable, or dh/dt is set for (BoxIterator bit(a_box); bit.ok(); ++bit) { const IntVect& iv = bit(); if (a_mask(iv) == FLOATINGMASKVAL) { //keep floating ice stable if required, assuming that any balance is due to basal freezing/melting if ( floating_ice_stable ) { a_bmb(iv) = a_divuh(iv) - a_smb(iv) ; a_vmb(iv) = 0.0; } else if (m_floating_ice_basal_flux_is_dhdt) { a_bmb(iv) += ( a_divuh(iv) - a_smb(iv) ); a_vmb(iv) = 0.0; } else if (m_floating_ice_basal_flux_is_min_dhdt) { a_bmb(iv) -= std::max(0.0,-a_divuh(iv)+a_smb(iv)); a_vmb(iv) = 0.0; } } // end if (a_mask(iv) == FLOATINGMASKVAL) else if (a_mask(iv) == GROUNDEDMASKVAL) { //keep grounded ice stable if required if (grounded_ice_stable ) { if (a_divuh(iv) < 0) { // need to thin the ice. attempt to balance between isothermal compression and flux out of the base //a_bmb(iv) = a_divuh(iv); //a_vmb(iv) = - a_smb(iv); a_vmb(iv) = a_divuh(iv) - a_smb(iv) - a_bmb(iv); } else { //need to thicken the ice. distrubuted new energy evenly through the thickness, i.e isothermal expansion a_vmb(iv) = a_divuh(iv) - a_smb(iv) - a_bmb(iv); } } else if (m_grounded_ice_basal_flux_is_dhdt) { a_vmb(iv) = a_divuh(iv) - a_smb(iv); } } // end else if (a_mask(iv) == GROUNDEDMASKVAL) else { // ice free regions. if (!m_evolve_thickness) { a_vmb(iv) = a_divuh(iv) - a_smb(iv) - a_bmb(iv); } } } // end for (BoxIterator bit(a_box); bit.ok(); ++bit) } // update ice thickness *and* bedrock elevation void AmrIce::updateGeometry(Vector<RefCountedPtr<LevelSigmaCS> >& a_vect_coordSys_new, Vector<RefCountedPtr<LevelSigmaCS> >& a_vect_coordSys_old, const Vector<LevelData<FluxBox>* >& a_vectFluxes, Real a_dt) { CH_TIME("AmrIce::updateGeometry"); for (int lev=0; lev <= finestTimestepLevel() ; lev++) { DisjointBoxLayout& levelGrids = m_amrGrids[lev]; LevelData<FluxBox>& levelFlux = *a_vectFluxes[lev]; LevelSigmaCS& levelCoords = *(a_vect_coordSys_new[lev]); LevelData<FArrayBox>& levelNewH = levelCoords.getH(); LevelData<FArrayBox>& levelOldH = (*a_vect_coordSys_old[lev]).getH(); LevelData<FArrayBox>& levelDivThckFlux = *m_divThicknessFlux[lev]; const RealVect& dx = levelCoords.dx(); DataIterator dit = levelGrids.dataIterator(); for (dit.begin(); dit.ok(); ++dit) { const Box& gridBox = levelGrids[dit]; FArrayBox& newH = levelNewH[dit]; FArrayBox& oldH = levelOldH[dit];//(*m_old_thickness[lev])[dit]; FluxBox& thisFlux = levelFlux[dit]; newH.setVal(0.0); // loop over directions and increment with div(F) for (int dir=0; dir<SpaceDim; dir++) { // use the divergence from // Chombo/example/fourthOrderMappedGrids/util/DivergenceF.ChF FORT_DIVERGENCE(CHF_CONST_FRA(thisFlux[dir]), CHF_FRA(newH), CHF_BOX(gridBox), CHF_CONST_REAL(dx[dir]), CHF_INT(dir)); } levelDivThckFlux[dit].copy(newH); // // modify sources as required to balance div(uh) setStableSources((*m_surfaceThicknessSource[lev])[dit], (*m_basalThicknessSource[lev])[dit], (*m_volumeThicknessSource[lev])[dit], levelDivThckFlux[dit], levelCoords.getFloatingMask()[dit], gridBox); // add in thickness source // if there are still diffusive fluxes to deal // with, the source term will be included then //if (m_diffusionTreatment != IMPLICIT) { if (m_frac_sources) { // scale surface fluxes by mask values const FArrayBox& thisFrac = (*m_iceFrac[lev])[dit]; FArrayBox sources(gridBox,1); sources.setVal(0.0); sources.plus((*m_surfaceThicknessSource[lev])[dit], gridBox, 0, 0, 1); sources.plus((*m_basalThicknessSource[lev])[dit], gridBox, 0, 0, 1); sources.plus((*m_volumeThicknessSource[lev])[dit], gridBox, 0, 0, 1); sources.mult(thisFrac, gridBox, 0, 0, 1); newH.minus(sources, gridBox, 0, 0, 1); } else { // just add in sources directly newH.minus((*m_surfaceThicknessSource[lev])[dit], gridBox,0,0,1); newH.minus((*m_basalThicknessSource[lev])[dit], gridBox,0,0,1); newH.minus((*m_volumeThicknessSource[lev])[dit], gridBox,0,0,1); } } newH *= -1*a_dt; newH.plus(oldH, 0, 0, 1); for (BoxIterator bit(gridBox); bit.ok(); ++bit) { const IntVect& iv = bit(); Real H=newH(iv); // Remove negative thickness by limiting low bmb and/or smb // Calculate the effective basal and surface mass fluxes if (H < 0.0) { Real excessSource=0.0; if (a_dt > 0.0) { excessSource=H/a_dt; } Real bts = (*m_basalThicknessSource[lev])[dit](iv); Real sts = (*m_surfaceThicknessSource[lev])[dit](iv); Real oldBTS=bts; if (bts < 0.0) { bts = std::min(bts-excessSource,0.0); } sts = sts+oldBTS - excessSource - bts; (*m_basalThicknessSource[lev])[dit](iv) = bts; (*m_surfaceThicknessSource[lev])[dit](iv) = sts; newH(iv)=0.0; } } } // end loop over grids } // end loop over levels //include any diffusive fluxes if (m_evolve_thickness && m_diffusionTreatment == IMPLICIT) { if (m_grounded_ice_stable || m_floating_ice_stable) { CH_assert( !(m_grounded_ice_stable || m_floating_ice_stable)); MayDay::Error("implicit diffusion not implemented with grounded_ice_stable or floating_ice_stable "); } //MayDay::Error("m_diffusionTreatment == IMPLICIT no yet implemented"); //implicit thickness correction if (m_frac_sources) { MayDay::Error("scaling sources by ice fraction values not implemented yet"); } implicitThicknessCorrection(a_dt, m_surfaceThicknessSource, m_basalThicknessSource, m_volumeThicknessSource); } //update the topography (fixed surface case) if (m_evolve_topography_fix_surface) { // update the bedrock so that the surface remains constant on grounded ice for (int lev=0; lev <= finestTimestepLevel() ; lev++) { for (DataIterator dit(m_amrGrids[lev]);dit.ok();++dit) { FArrayBox& newH = a_vect_coordSys_new[lev]->getH()[dit]; FArrayBox& oldH = a_vect_coordSys_old[lev]->getH()[dit]; FArrayBox& topg = a_vect_coordSys_new[lev]->getTopography()[dit]; const BaseFab<int>& mask = a_vect_coordSys_old[lev]->getFloatingMask()[dit]; FORT_EVOLVEGROUNDEDBED(CHF_FRA1(newH,0), CHF_FRA1(oldH,0), CHF_FRA1(topg,0), CHF_CONST_FIA1(mask,0), CHF_BOX(topg.box())); FArrayBox& deltaTopg = (*m_deltaTopography[lev])[dit]; deltaTopg += topg; deltaTopg -= a_vect_coordSys_old[lev]->getTopography()[dit]; } } } //update the topography (gia) if (m_topographyFluxPtr != NULL) { for (int lev=0; lev <= finestTimestepLevel() ; lev++) { LevelSigmaCS& levelCoords = *(a_vect_coordSys_new[lev]); DisjointBoxLayout& levelGrids = m_amrGrids[lev]; LevelData<FArrayBox>& levelTopg = levelCoords.getTopography(); LevelData<FArrayBox>& levelDeltaTopg = *m_deltaTopography[lev]; LevelData<FArrayBox> levelSrc(levelGrids,1,IntVect::Zero); m_topographyFluxPtr->surfaceThicknessFlux(levelSrc, *this, lev, a_dt); for (DataIterator dit(levelGrids);dit.ok();++dit) { FArrayBox& src = levelSrc[dit]; src *= a_dt; levelTopg[dit] += src; levelDeltaTopg[dit] += src; } } } // average down thickness and topography to coarser levels and fill in ghost cells // before calling recomputeGeometry. int Hghost = 2; Vector<LevelData<FArrayBox>* > vectH(m_finest_level+1, NULL); Vector<LevelData<FArrayBox>* > vectB(m_finest_level+1, NULL); for (int lev=0; lev<vectH.size(); lev++) { IntVect HghostVect = Hghost*IntVect::Unit; LevelSigmaCS& levelCoords = *(a_vect_coordSys_new[lev]); vectH[lev] = &levelCoords.getH(); vectB[lev] = &levelCoords.getTopography(); } //average from the finest level down for (int lev = finestTimestepLevel() ; lev > 0 ; lev--) { CoarseAverage averager(m_amrGrids[lev], 1, m_refinement_ratios[lev-1]); averager.averageToCoarse(*vectH[lev-1], *vectH[lev]); averager.averageToCoarse(*vectB[lev-1], *vectB[lev]); } // now pass back over and do PiecewiseLinearFillPatch for (int lev=1; lev<vectH.size(); lev++) { PiecewiseLinearFillPatch filler(m_amrGrids[lev], m_amrGrids[lev-1], 1, m_amrDomains[lev-1], m_refinement_ratios[lev-1], Hghost); Real interp_coef = 0; filler.fillInterp(*vectH[lev], *vectH[lev-1], *vectH[lev-1], interp_coef, 0, 0, 1); filler.fillInterp(*vectB[lev], *vectB[lev-1], *vectB[lev-1], interp_coef, 0, 0, 1); } //re-fill ghost cells ouside the domain for (int lev=0; lev <= finestTimestepLevel() ; ++lev) { RealVect levelDx = m_amrDx[lev]*RealVect::Unit; m_thicknessIBCPtr->setGeometryBCs(*a_vect_coordSys_new[lev], m_amrDomains[lev],levelDx, m_time, m_dt); } //allow calving model to modify geometry and velocity applyCalvingCriterion(CalvingModel::PostThicknessAdvection); //dont allow thickness or iceFrac to be negative for (int lev=0; lev<= m_finest_level; lev++) { DisjointBoxLayout& levelGrids = m_amrGrids[lev]; LevelSigmaCS& levelCoords = *(a_vect_coordSys_new[lev]); LevelData<FArrayBox>& levelH = levelCoords.getH(); updateIceFrac(levelH, lev); DataIterator dit = levelGrids.dataIterator(); for (DataIterator dit(levelGrids); dit.ok(); ++dit) { Real lim = 0.0; FORT_MAXFAB1(CHF_FRA(levelH[dit]), CHF_CONST_REAL(lim), CHF_BOX(levelH[dit].box())); } } //average from the finest level down for (int lev = finestTimestepLevel() ; lev > 0 ; lev--) { CoarseAverage averager(m_amrGrids[lev], 1, m_refinement_ratios[lev-1]); averager.averageToCoarse(*vectH[lev-1], *vectH[lev]); } for (int lev=1; lev<vectH.size(); lev++) { PiecewiseLinearFillPatch filler(m_amrGrids[lev], m_amrGrids[lev-1], 1, m_amrDomains[lev-1], m_refinement_ratios[lev-1], Hghost); Real interp_coef = 0; filler.fillInterp(*vectH[lev], *vectH[lev-1], *vectH[lev-1], interp_coef, 0, 0, 1); } //interpolate levelSigmaCS to any levels above finestTimestepLevel() for (int lev = finestTimestepLevel()+1 ; lev<= m_finest_level; lev++) { m_vect_coordSys[lev]->interpFromCoarse(*m_vect_coordSys[lev-1], m_refinement_ratios[lev-1], false , true); } // recompute thickness-derived data in SigmaCS for (int lev=0; lev<= m_finest_level; lev++) { LevelSigmaCS& levelCoords = *(m_vect_coordSys[lev]); LevelSigmaCS* crseCoords = (lev > 0)?&(*m_vect_coordSys[lev-1]):NULL; int refRatio = (lev > 0)?m_refinement_ratios[lev-1]:-1; levelCoords.recomputeGeometry(crseCoords, refRatio); } } void AmrIce::levelSetup(int a_level, const DisjointBoxLayout& a_grids) { IntVect ghostVect = IntVect::Unit; // 4 ghost cells needed for advection. Could later go back and // make this a temporary if the additional storage becomes an issue... IntVect thicknessGhostVect = m_num_thickness_ghost*IntVect::Unit; m_old_thickness[a_level]->define(a_grids, 1, thicknessGhostVect); if (a_level == 0 || m_velocity[a_level] == NULL) { m_velocity[a_level] = new LevelData<FArrayBox>(a_grids, SpaceDim, ghostVect); } else { // do velocity a bit differently in order to use previously // computed velocity field as an initial guess { LevelData<FArrayBox>* newVelPtr = new LevelData<FArrayBox>(a_grids, SpaceDim, ghostVect); // first do interp from coarser level FineInterp velInterp(a_grids, SpaceDim, m_refinement_ratios[a_level-1], m_amrDomains[a_level]); velInterp.interpToFine(*newVelPtr, *m_velocity[a_level-1]); // can only copy from existing level if we're not on the // newly created level //if (a_level != new_finest_level) if (m_velocity[a_level]->isDefined()) { m_velocity[a_level]->copyTo(*newVelPtr); } // finally, do an exchange (this may wind up being unnecessary) newVelPtr->exchange(); delete (m_velocity[a_level]); m_velocity[a_level] = newVelPtr; } } // end interpolate/copy new velocity levelAllocate(&m_faceVelAdvection[a_level] ,a_grids,1,IntVect::Unit); levelAllocate(&m_faceVelTotal[a_level],a_grids,1,IntVect::Unit); levelAllocate(&m_diffusivity[a_level],a_grids, 1, IntVect::Zero); levelAllocate(&m_iceFrac[a_level],a_grids, 1, IntVect::Unit); #if BISICLES_Z == BISICLES_LAYERED levelAllocate(&m_layerXYFaceXYVel[a_level] ,a_grids, m_nLayers, IntVect::Unit); levelAllocate(&m_layerSFaceXYVel[a_level], a_grids, SpaceDim*(m_nLayers + 1), IntVect::Unit); levelAllocate(&m_layerSFaceSVel[a_level], a_grids, m_nLayers + 1, IntVect::Unit); #endif levelAllocate(&m_velBasalC[a_level],a_grids, 1, ghostVect); levelAllocate(&m_cellMuCoef[a_level],a_grids, 1, ghostVect); levelAllocate(&m_velRHS[a_level],a_grids, SpaceDim, IntVect::Zero); levelAllocate(&m_surfaceThicknessSource[a_level], a_grids, 1, IntVect::Unit) ; levelAllocate(&m_basalThicknessSource[a_level], a_grids, 1, IntVect::Unit) ; levelAllocate(&m_volumeThicknessSource[a_level], a_grids, 1, IntVect::Unit) ; levelAllocate(&m_divThicknessFlux[a_level],a_grids, 1, IntVect::Zero) ; levelAllocate(&m_calvedIceThickness[a_level],a_grids, 1, IntVect::Unit); levelAllocate(&m_removedIceThickness[a_level],a_grids, 1, IntVect::Unit); levelAllocate(&m_addedIceThickness[a_level],a_grids, 1, IntVect::Unit); levelAllocate(&m_deltaTopography[a_level],a_grids, 1, IntVect::Zero); // probably eventually want to do this differently RealVect dx = m_amrDx[a_level]*RealVect::Unit; //IntVect sigmaCSGhost = IntVect::Unit; IntVect sigmaCSGhost = thicknessGhostVect; m_vect_coordSys.resize(m_max_level+1); m_vect_coordSys[a_level] = RefCountedPtr<LevelSigmaCS >(new LevelSigmaCS(a_grids, dx, sigmaCSGhost)); m_vect_coordSys[a_level]->setIceDensity(m_iceDensity); m_vect_coordSys[a_level]->setWaterDensity(m_seaWaterDensity); m_vect_coordSys[a_level]->setGravity(m_gravity); #if BISICLES_Z == BISICLES_LAYERED //in poor-man's multidim mode, use one FArrayBox component per layer //to hold the 3D internalEnergy field levelAllocate(&m_internalEnergy[a_level],a_grids, m_nLayers,thicknessGhostVect); levelAllocate(&m_tillWaterDepth[a_level], a_grids, 1, thicknessGhostVect); levelAllocate(&m_sInternalEnergy[a_level], a_grids, 1, thicknessGhostVect); levelAllocate(&m_bInternalEnergy[a_level], a_grids, 1, thicknessGhostVect); levelAllocate(&m_sHeatFlux[a_level], a_grids, 1, thicknessGhostVect); levelAllocate(&m_bHeatFlux[a_level], a_grids, 1, thicknessGhostVect); m_vect_coordSys[a_level]->setFaceSigma(getFaceSigma()); #elif BISICLES_Z == BISICLES_FULLZ levelAllocate(&m_internalEnergy[a_level],a_grids, 1, thicknessGhostVect); #endif } void AmrIce::initData(Vector<RefCountedPtr<LevelSigmaCS> >& a_vectCoordSys, Vector<LevelData<FArrayBox>* >& a_velocity) { CH_TIME("AmrIce::initData"); // for (int i=0; i < //m_diagnostic_values[]={0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0}; if (s_verbosity > 3) { pout() << "AmrIce::initData" << endl; } m_groundingLineProximity_valid = false; m_A_valid = false; for (int lev=0; lev<=m_finest_level; lev++) { RealVect levelDx = m_amrDx[lev]*RealVect::Unit; m_thicknessIBCPtr->define(m_amrDomains[lev],levelDx[0]); LevelSigmaCS* crsePtr = (lev > 0)?&(*m_vect_coordSys[lev-1]):NULL; int refRatio = (lev > 0)?m_refinement_ratios[lev-1]:0; m_thicknessIBCPtr->initializeIceGeometry(*a_vectCoordSys[lev], levelDx, m_domainSize, m_time, crsePtr, refRatio); a_vectCoordSys[lev]->recomputeGeometry(crsePtr, refRatio); const LevelData<FArrayBox>& levelThickness = m_vect_coordSys[lev]->getH(); setIceFrac(levelThickness, lev); a_vectCoordSys[lev]->recomputeGeometry(crsePtr, refRatio); // initialize oldH to be the current value LevelData<FArrayBox>& currentH = a_vectCoordSys[lev]->getH(); currentH.copyTo(*m_old_thickness[lev]); #if BISICLES_Z == BISICLES_LAYERED m_internalEnergyIBCPtr->initializeIceInternalEnergy (*m_internalEnergy[lev], *m_tillWaterDepth[lev], *m_sInternalEnergy[lev], *m_bInternalEnergy[lev], *this, lev, 0.0); #elif BISICLES_Z == BISICLES_FULLZ m_internalEnergyIBCPtr->initializeIceInternalEnergy(*m_temperature[lev],*this, lev, 0.0); #endif } // tempearture depends on internal energy updateTemperature(); // this is a good time to check for remote ice // (don't bother if we're doing it as a matter of course, since we'd // wind up doing it 2x) if ((m_eliminate_remote_ice_after_regrid) && !(m_eliminate_remote_ice)) eliminateRemoteIce(); setToZero(m_deltaTopography); applyCalvingCriterion(CalvingModel::Initialization); // now call velocity solver to initialize velocity field, force a solve no matter what the time step solveVelocityField(true); // may be necessary to average down here for (int lev=m_finest_level; lev>0; lev--) { CoarseAverage avgDown(m_amrGrids[lev], SpaceDim, m_refinement_ratios[lev-1]); avgDown.averageToCoarse(*m_velocity[lev-1], *m_velocity[lev]); } // Check if topographyFlux initialized and store initial TOF, if so // First check to see if the pointer is NULL if (m_topographyFluxPtr != NULL) { // now use dynamic casting to see if we're looking at a BuelerGIAFlux BuelerGIAFlux* giaFluxPtr = dynamic_cast<BuelerGIAFlux*>(m_topographyFluxPtr); if (giaFluxPtr != NULL and not giaFluxPtr->isInitIceRef0()) { // we were able to cast to a BuelerGIAFlux pointer giaFluxPtr->setInitialLoad(*this); } else if (giaFluxPtr != NULL) { giaFluxPtr->computeInitialUpliftFromVelocity(*this); } // end if we have a BuelerGIAFlux // do any generic TopographyFlux sorts of things } // end if there is a topographyFlux //#define writePlotsImmediately #ifdef writePlotsImmediately if (m_plot_interval >= 0) { #ifdef CH_USE_HDF5 writePlotFile(); #endif } #endif } /// solve for velocity field void AmrIce::solveVelocityField(bool a_forceSolve, Real a_convergenceMetric) { CH_TIME("AmrIce::solveVelocityField"); notifyObservers(Observer::PreVelocitySolve); if (m_eliminate_remote_ice) eliminateRemoteIce(); //ensure A is up to date #if BISICLES_Z == BISICLES_LAYERED if (!m_A_valid) { computeA(m_A,m_sA,m_bA,m_internalEnergy,m_sInternalEnergy,m_bInternalEnergy, m_vect_coordSys); m_A_valid = true; } #else MayDay::Error("AmrIce::SolveVelocityField full z calculation of A not done"); #endif //certainly the viscous tensr field will need re-computing m_viscousTensor_valid = false; // define basal friction Vector<LevelData<FArrayBox>* > vectC(m_finest_level+1, NULL); Vector<LevelData<FArrayBox>* > vectC0(m_finest_level+1, NULL); Vector<LevelData<FArrayBox>* > vectRhs(m_finest_level+1, NULL); for (int lev=0; lev<=m_finest_level; lev++) { vectRhs[lev] = m_velRHS[lev]; vectC[lev] = m_velBasalC[lev]; vectC0[lev] = new LevelData<FArrayBox>; vectC0[lev]->define(*vectC[lev]); } // setMuCoefficient(m_cellMuCoef); // set basal friction coeffs C,C0. C = 0 for floating ice. C0 != 0 at walls setBasalFriction(vectC, vectC0); m_basalFrictionRelation->updateThermodynamics(&m_tillWaterDepth); // right hand side of the stress-balance defineVelRHS(vectRhs); // write out sumRhs if appropriate if (s_verbosity > 3) { Real sumRhs = computeSum(vectRhs, m_refinement_ratios, m_amrDx[0], Interval(0,0), 0); pout() << "Sum(rhs) for velocity solve = " << sumRhs << endl; } // put this in place to catch runs where plotfile writing is // going to hang _before_ I waste a few hours waiting for the // velocity solve //#define writeTestPlots #ifdef writeTestPlots if (m_plot_interval >= 0 && m_cur_step == 0) { writePlotFile(); } #endif if (m_doInitialVelSolve) { if (m_finest_level == 0 && m_doInitialVelGuess) { // only really want or need to do this once m_doInitialVelGuess = false; if (m_initialGuessType == SlidingLaw) { pout() << "computing an initial guess via a sliding law u = rhs/C " << endl; // compute initial guess as rhs/beta LevelData<FArrayBox>& vel = *m_velocity[0]; LevelData<FArrayBox>& C = *m_velBasalC[0]; LevelData<FArrayBox>& rhs = *m_velRHS[0]; const DisjointBoxLayout& levelGrids = m_amrGrids[0]; DataIterator dit = vel.dataIterator(); for (dit.begin(); dit.ok(); ++dit) { FORT_VELINITIALGUESS(CHF_FRA(vel[dit]), CHF_FRA(rhs[dit]), CHF_FRA1(C[dit],0), CHF_BOX(levelGrids[dit])); } } else if (m_initialGuessType == ConstMu) { if (s_verbosity > 3) { pout() << "computing an initial guess by solving the velocity equations " <<" with constant mu = " << m_initialGuessConstMu << " and constant initial velocity = " << m_initialGuessConstVel << endl; } // compute initial guess by solving a linear problem with a // modest constant viscosity constMuRelation* newPtr = new constMuRelation; newPtr->setConstVal(m_initialGuessConstMu); for (int lev=0; lev < m_finest_level + 1; lev++) { for (DataIterator dit(m_amrGrids[lev]);dit.ok();++dit) { for (int dir = 0; dir < SpaceDim; dir++) { (*m_velocity[lev])[dit].setVal(m_initialGuessConstVel[dir],dir); } } } // do this by saving the exisiting velSolver and // constitutiveRelation, re-calling defineSolver, then // doing solve. IceVelocitySolver* velSolverSave = m_velSolver; ConstitutiveRelation* constRelSave = m_constitutiveRelation; int solverTypeSave = m_solverType; // new values prior to calling defineSolver m_constitutiveRelation = static_cast<ConstitutiveRelation*>(newPtr); Real finalNorm = 0.0, initialNorm = 0.0, convergenceMetric = -1.0; //Vector<LevelData<FArrayBox>* > muCoef(m_finest_level + 1,NULL); int rc = -1; if (m_initialGuessSolverType == JFNK) { //JFNK can be instructed to assume a linear solve m_solverType = JFNK; // (DFM 2/4/14) this is not a memory leak -- velSolver is // saved in velSolverSave and will be swapped back after // the initial guess solve m_velSolver = NULL; defineSolver(); JFNKSolver* jfnkSolver = dynamic_cast<JFNKSolver*>(m_velSolver); CH_assert(jfnkSolver != NULL); const bool linear = true; rc = jfnkSolver->solve( m_velocity, m_calvedIceThickness, m_addedIceThickness, m_removedIceThickness, initialNorm,finalNorm,convergenceMetric, linear , m_velRHS, m_velBasalC, vectC0, m_A, m_cellMuCoef, m_vect_coordSys, m_time, 0, m_finest_level); } else if (m_initialGuessSolverType == Picard) { ParmParse pp("picardSolver"); Real tol = 1.e-4; int nits = 1; // since the constant-viscosity solve is a linear solve, // Picard is the best option. m_solverType = Picard; m_velSolver = NULL; defineSolver(); pp.query("linearsolver_tolerance", tol ); pp.query("max_picard_iterations", nits ); m_velSolver->setTolerance(nits); m_velSolver->setMaxIterations(tol); rc = m_velSolver->solve(m_velocity, m_calvedIceThickness, m_addedIceThickness, m_removedIceThickness, initialNorm,finalNorm,convergenceMetric, m_velRHS, m_velBasalC, vectC0, m_A, m_cellMuCoef, m_vect_coordSys, m_time, 0, m_finest_level); } else { MayDay::Error("unknown initial guess solver type"); } if (rc != 0) { MayDay::Warning("constant mu solve failed"); } // now put everything back the way it was... delete m_constitutiveRelation; delete m_velSolver; m_velSolver = velSolverSave; m_constitutiveRelation = constRelSave; m_solverType = solverTypeSave; #if 0 //put the solver back how it was m_velSolver->define(m_amrDomains[0], m_constitutiveRelation, m_basalFrictionRelation, m_amrGrids, m_refinement_ratios, dxCrse, m_thicknessIBCPtr, numLevels); #endif } else if (m_initialGuessType == Function) { ParmParse pp("amr"); std::string functionType = "constant"; pp.query("initial_velocity_function_type", functionType ); if (functionType == "flowline") { Real dx; std::string file, set; pp.get("initial_velocity_function_flowline_dx", dx); pp.get("initial_velocity_function_flowline_file", file); pp.get("initial_velocity_function_flowline_set", set); ExtrudedPieceWiseLinearFlowline f(file,set,dx); for (int lev = 0; lev < m_finest_level + 1; lev++) { LevelData<FArrayBox>& levelVel = *m_velocity[lev]; for (DataIterator dit(levelVel.disjointBoxLayout()); dit.ok(); ++dit) { FArrayBox& vel = levelVel[dit]; const Box& box = vel.box(); for (BoxIterator bit(box); bit.ok(); ++bit) { const IntVect& iv = bit(); RealVect x = RealVect(iv) * m_amrDx[lev] + 0.5 * m_amrDx[lev]; vel(iv,0) = f(x); } } } } } else { MayDay::Error("AmrIce::SolveVelocityField unknown initial guess type"); } } #ifdef CH_USE_HDF5 if (m_write_presolve_plotfiles) { string save_prefix = m_plot_prefix; m_plot_prefix.append("preSolve."); bool t_write_fluxVel = m_write_fluxVel; m_write_fluxVel = false; // turning this off in preSolve files for now writePlotFile(); m_write_fluxVel = t_write_fluxVel; m_plot_prefix = save_prefix; } #endif int solverRetVal; //set u = 0 in ice free cells for (int lev=0; lev <= m_finest_level ; ++lev) { const DisjointBoxLayout& levelGrids = m_amrGrids[lev]; LevelSigmaCS& levelCS = *m_vect_coordSys[lev]; for (DataIterator dit(levelGrids); dit.ok(); ++dit) { const BaseFab<int>& mask = levelCS.getFloatingMask()[dit]; FArrayBox& vel = (*m_velocity[lev])[dit]; for (BoxIterator bit(levelGrids[dit]); bit.ok(); ++bit) { const IntVect& iv = bit(); if (mask(iv) == OPENSEAMASKVAL || mask(iv) == OPENLANDMASKVAL ) { vel(iv,0) = 0.0; vel(iv,1) = 0.0; } } } } if (a_forceSolve || ((m_cur_step+1)%m_velocity_solve_interval == 0)) { //any thickness change within m_velSolver->solve is assumed to be calving. notifyObservers(Observer::PreCalving); solverRetVal = m_velSolver->solve(m_velocity, m_calvedIceThickness, m_addedIceThickness, m_removedIceThickness, m_velocitySolveInitialResidualNorm, m_velocitySolveFinalResidualNorm, a_convergenceMetric, m_velRHS, m_velBasalC, vectC0, m_A, m_cellMuCoef, m_vect_coordSys, m_time, 0, m_finest_level); notifyObservers(Observer::PostCalving); if (solverRetVal != 0) { pout() << " solver return value = " << solverRetVal << std::endl; //MayDay::Warning("solver return value != 0"); } for (int lev = 0; lev <= m_finest_level; lev++) { m_thicknessIBCPtr->velocityGhostBC (*m_velocity[lev],*m_vect_coordSys[lev], m_amrDomains[lev], m_time); } //special case for inverse problems : read back C and muCoef if they are ready InverseIceVelocitySolver* invPtr = dynamic_cast<InverseIceVelocitySolver*>(m_velSolver); if (invPtr) { BasalFriction* bfptr = invPtr->basalFriction(); if (bfptr) { if (m_basalFrictionPtr) delete m_basalFrictionPtr; m_basalFrictionPtr = bfptr; } MuCoefficient* mcptr = invPtr->muCoefficient(); if (mcptr) { if (m_muCoefficientPtr) delete m_muCoefficientPtr; m_muCoefficientPtr = mcptr; } } // end special case for inverse problems } // end if (a_forceSolve || ((m_cur_step+1)%m_velocity_solve_interval == 0)) // update the viscous tensor updateViscousTensor(); //allow calving model to modify geometry applyCalvingCriterion(CalvingModel::PostVelocitySolve); for (int lev=0; lev<=m_finest_level; lev++) { if (vectC0[lev] != NULL) { delete vectC0[lev]; vectC0[lev] = NULL; } } /// This is probably the most useful notification, as a velocity /// solve is carried out at the end of every major stage notifyObservers(Observer::PostVelocitySolve); } // end if (m_doInitialSolve) // update the viscous tensor updateViscousTensor(); //calculate the face centred (flux) velocity and diffusion coefficients computeFaceVelocity(m_faceVelAdvection,m_faceVelTotal,m_diffusivity,m_layerXYFaceXYVel, m_layerSFaceXYVel); } void AmrIce::defineVelRHS(Vector<LevelData<FArrayBox>* >& a_vectRhs) { Vector<RealVect> dx; Vector<LevelData<FArrayBox>*> rhs; for (int lev=0; lev<=m_finest_level; lev++) { dx.push_back(m_vect_coordSys[lev]->dx()); rhs.push_back(a_vectRhs[lev]); } IceUtility::defineRHS(rhs, m_vect_coordSys, m_amrGrids, dx); //\todo : move this into IceUtility::defineRHS for (int lev=0; lev<=m_finest_level; lev++) { // finally, modify RHS in problem-dependent ways, m_thicknessIBCPtr->modifyVelocityRHS(*a_vectRhs[lev], *m_vect_coordSys[lev], m_amrDomains[lev],m_time, m_dt); } } /// set mu coefficient (phi) prior to velocity solve void AmrIce::setMuCoefficient(Vector<LevelData<FArrayBox>* >& a_cellMuCoef) { CH_assert(m_muCoefficientPtr != NULL); for (int lev=0; lev<=m_finest_level; lev++) { m_muCoefficientPtr->setMuCoefficient(*a_cellMuCoef[lev], *m_vect_coordSys[lev], this->time(), m_dt); if (lev > 0) { PiecewiseLinearFillPatch ghostFiller (m_amrGrids[lev],m_amrGrids[lev-1],1,m_amrDomains[lev-1], m_refinement_ratios[lev-1],1); ghostFiller.fillInterp(*a_cellMuCoef[lev], *a_cellMuCoef[lev-1], *a_cellMuCoef[lev-1], 1.0,0,0,1); } a_cellMuCoef[lev]->exchange(); } } /// set basal friction coefficients C,C0 prior to velocity solve void AmrIce::setBasalFriction(Vector<LevelData<FArrayBox>* >& a_vectC,Vector<LevelData<FArrayBox>* >& a_vectC0) { // first, compute C and C0 as though there was no floating ice CH_assert(m_basalFrictionPtr != NULL); for (int lev=0; lev<=m_finest_level; lev++) { m_basalFrictionPtr->setBasalFriction(*a_vectC[lev], *m_vect_coordSys[lev], this->time(),m_dt); if (m_basalRateFactor != NULL) { //basal temperature dependence LevelData<FArrayBox>& C = *a_vectC[lev]; Vector<Real> bSigma(1,1.0); LevelData<FArrayBox> A(C.disjointBoxLayout(),1,C.ghostVect()); IceUtility::computeA(A, bSigma,*m_vect_coordSys[lev], m_basalRateFactor, *m_bInternalEnergy[lev]); for (DataIterator dit = C.dataIterator(); dit.ok(); ++dit) { C[dit] /= A[dit]; } } a_vectC[lev]->exchange(); } // compute C0 // C0 include a term (wall drag) that depends on C, // so needs to be computed before setting C = 0 in floating regions IceUtility::computeC0(a_vectC0, a_vectC, m_amrGrids, m_vect_coordSys, m_amrDx, m_finest_level); if ( m_reset_floating_friction_to_zero ) { //set C = 0 in floating region, possibly employing a thickness-above-flotation interpolation for (int lev=0; lev<=m_finest_level; lev++) { IceUtility::setFloatingBasalFriction(*a_vectC[lev], *m_vect_coordSys[lev], m_amrGrids[lev]); } } } /// given the current cell centred velocity field, compute a face centred velocity field void AmrIce::computeFaceVelocity(Vector<LevelData<FluxBox>* >& a_faceVelAdvection, Vector<LevelData<FluxBox>* >& a_faceVelTotal, Vector<LevelData<FluxBox>* >& a_diffusivity, Vector<LevelData<FluxBox>* >& a_layerXYFaceXYVel, Vector<LevelData<FArrayBox>* >& a_layerSFaceXYVel) { CH_assert(m_constitutiveRelation != NULL); LevelData<FArrayBox>* cellDiffusivity = NULL; for (int lev = 0; lev <= m_finest_level; lev++) { LevelData<FArrayBox>* crseVelPtr = (lev > 0)?m_velocity[lev-1]:NULL; int nRefCrse = (lev > 0)?m_refinement_ratios[lev-1]:1; LevelData<FArrayBox>* crseCellDiffusivityPtr = (lev > 0)?cellDiffusivity:NULL; cellDiffusivity = new LevelData<FArrayBox>(m_amrGrids[lev],1,IntVect::Unit); CH_assert(cellDiffusivity != NULL); CH_assert(a_faceVelAdvection[lev] != NULL); CH_assert(a_faceVelTotal[lev] != NULL); CH_assert(a_diffusivity[lev] != NULL); CH_assert(a_layerXYFaceXYVel[lev] != NULL); CH_assert(a_layerSFaceXYVel[lev] != NULL); CH_assert(m_velocity[lev] != NULL); CH_assert(m_vect_coordSys[lev] != NULL); CH_assert(m_A[lev] != NULL); CH_assert(m_sA[lev] != NULL); CH_assert(m_bA[lev] != NULL); IceUtility::computeFaceVelocity (*a_faceVelAdvection[lev], *a_faceVelTotal[lev], *a_diffusivity[lev], *cellDiffusivity,*a_layerXYFaceXYVel[lev], *a_layerSFaceXYVel[lev], *m_velocity[lev],*m_vect_coordSys[lev], m_thicknessIBCPtr, *m_A[lev], *m_sA[lev], *m_bA[lev], crseVelPtr,crseCellDiffusivityPtr, nRefCrse, m_constitutiveRelation, m_additionalVelocity, m_diffusionTreatment == IMPLICIT); if (crseCellDiffusivityPtr != NULL) delete crseCellDiffusivityPtr; } if (cellDiffusivity != NULL) delete cellDiffusivity; } // /// compute div(vel*H) at a given time // void // AmrIce::computeDivThicknessFlux(Vector<LevelData<FArrayBox>* >& a_divFlux, // Vector<LevelData<FluxBox>* >& a_flux, // Vector<LevelData<FArrayBox>* >& a_thickness, // Real a_time, Real a_dt) // { // //Vector<LevelData<FluxBox>* > faceVel(m_finest_level+1, NULL); // for (int lev=0; lev<= m_finest_level; lev++) // { // const DisjointBoxLayout& levelGrids = m_amrGrids[lev]; // // construct face-centered velocity field // LevelData<FluxBox> faceVel(levelGrids, 1, IntVect::Unit); // if (lev > 0) // { // int nVelGhost = m_velocity[lev]->ghostVect()[0]; // PiecewiseLinearFillPatch velFiller(levelGrids, // m_amrGrids[lev-1], // m_velocity[0]->nComp(), // m_amrDomains[lev-1], // m_refinement_ratios[lev-1], // nVelGhost); // // since we're not subcycling, don't need to interpolate in time // Real time_interp_coeff = 0.0; // velFiller.fillInterp(*m_velocity[lev], // *m_velocity[lev-1], // *m_velocity[lev-1], // time_interp_coeff, // 0, 0, m_velocity[0]->nComp()); // } // end if lev > 0 // m_velocity[lev]->exchange(); // // average velocities to faces // CellToEdge(*m_velocity[lev],faceVel); // faceVel.exchange(); // // flux = faceVel*faceH // LevelData<FluxBox>& levelFlux = *a_flux[lev]; // LevelSigmaCS& levelCoords = *m_vect_coordSys[lev]; // LevelData<FluxBox>& faceH = levelCoords.getFaceH(); // DataIterator dit = levelGrids.dataIterator(); // for (dit.begin(); dit.ok(); ++dit) // { // FluxBox& thisflux = levelFlux[dit]; // FluxBox& thisVel = faceVel[dit]; // FluxBox& thisH = faceH[dit]; // for (int dir=0; dir<SpaceDim; dir++) // { // thisflux[dir].copy(thisVel[dir]); // thisflux[dir].mult(thisH[dir]); // } // } // // average fluxes to coarser levels, if needed // if (lev>0) // { // CoarseAverageFace faceAverager(m_amrGrids[lev], // 1, m_refinement_ratios[lev-1]); // faceAverager.averageToCoarse(*a_flux[lev-1], *a_flux[lev]); // } // } // end loop over levels // // now compute div(flux) // // compute div(F) and add source term // setToZero(m_volumeThicknessFlux); // for (int lev=0; lev<= m_finest_level; lev++) // { // DisjointBoxLayout& levelGrids = m_amrGrids[lev]; // LevelData<FluxBox>& levelFlux = *a_flux[lev]; // LevelData<FArrayBox>& levelDiv = *a_divFlux[lev]; // LevelSigmaCS& levelCoords = *(m_vect_coordSys[lev]); // LevelData<FArrayBox>& surfaceThicknessSource = *m_surfaceThicknessSource[lev]; // m_surfaceFluxPtr->surfaceThicknessFlux(surfaceThicknessSource, *this, lev, a_dt); // LevelData<FArrayBox>& basalThicknessSource = *m_basalThicknessSource[lev]; // m_basalFluxPtr->surfaceThicknessFlux(basalThicknessSource, *this, lev, a_dt); // const RealVect& dx = levelCoords.dx(); // DataIterator dit = levelGrids.dataIterator(); // for (dit.begin(); dit.ok(); ++dit) // { // const Box& gridBox = levelGrids[dit]; // FArrayBox& thisDiv = levelDiv[dit]; // FluxBox& thisFlux = levelFlux[dit]; // thisDiv.setVal(0.0); // // loop over directions and increment with div(F) // for (int dir=0; dir<SpaceDim; dir++) // { // // use the divergence from // // Chombo/example/fourthOrderMappedGrids/util/DivergenceF.ChF // FORT_DIVERGENCE(CHF_CONST_FRA(thisFlux[dir]), // CHF_FRA(thisDiv), // CHF_BOX(gridBox), // CHF_CONST_REAL(dx[dir]), // CHF_INT(dir)); // } // // add in thickness source here // thisDiv.minus(surfaceThicknessSource[dit], gridBox,0,0,1); // thisDiv.minus(basalThicknessSource[dit], gridBox,0,0,1); // thisDiv.minus(volumeThicknessSource[dit], gridBox,0,0,1); // //thisDiv *= -1*a_dt; // } // end loop over grids // } // end loop over levels // } // increment phi := phi + dt*dphi void AmrIce::incrementWithDivFlux(Vector<LevelData<FArrayBox>* >& a_phi, const Vector<LevelData<FArrayBox>* >& a_dphi, Real a_dt) { for (int lev=0; lev<a_phi.size(); lev++) { LevelData<FArrayBox>& levelPhi = *a_phi[lev]; const LevelData<FArrayBox>& level_dPhi = *a_dphi[lev]; DataIterator dit = levelPhi.dataIterator(); for (dit.begin(); dit.ok(); ++dit) { levelPhi[dit].plus(level_dPhi[dit], a_dt); } } } // increment coordSys with new thickness void AmrIce::updateCoordSysWithNewThickness(const Vector<LevelData<FArrayBox>* >& a_thickness) { CH_assert(a_thickness.size() >= m_finest_level); for (int lev=0; lev<= m_finest_level; lev++) { const LevelData<FArrayBox>& levelH = *a_thickness[lev]; LevelSigmaCS& levelCS = *m_vect_coordSys[lev]; LevelData<FArrayBox>& levelCS_H = levelCS.getH(); DataIterator dit = levelH.dataIterator(); for (dit.begin(); dit.ok(); ++dit) { FArrayBox& thisH = levelCS_H[dit]; thisH.copy(levelH[dit]); } { LevelSigmaCS* crseCoords = (lev > 0)?&(*m_vect_coordSys[lev-1]):NULL; int refRatio = (lev > 0)?m_refinement_ratios[lev-1]:-1; levelCS.recomputeGeometry(crseCoords, refRatio); } } // end loop over levels } void AmrIce::setIceFrac(const LevelData<FArrayBox>& a_thickness, int a_level) { // initialize fraction to 1 if H>0, 0 o/w... DataIterator dit = m_iceFrac[a_level]->dataIterator(); for (dit.begin(); dit.ok(); ++dit) { FArrayBox& thisFrac = (*m_iceFrac[a_level])[dit]; thisFrac.setVal(0.0); const FArrayBox& thisH = a_thickness[dit]; BoxIterator bit(thisFrac.box()); for (bit.begin(); bit.ok(); ++bit) { IntVect iv = bit(); if (thisH(iv,0) > 0) thisFrac(iv,0) = 1.0; } } } void AmrIce::updateIceFrac(LevelData<FArrayBox>& a_thickness, int a_level) { // set ice fraction to 0 if no ice in cell... // "zero" thickness value // Check that this rountine doesn't interfer with diagnostics (endTimestepDiagnostics). Real ice_eps = 1.0e-6; DataIterator dit = m_iceFrac[a_level]->dataIterator(); for (dit.begin(); dit.ok(); ++dit) { FArrayBox& thisFrac = (*m_iceFrac[a_level])[dit]; FArrayBox& thisH = a_thickness[dit]; BoxIterator bit(thisFrac.box()); for (bit.begin(); bit.ok(); ++bit) { IntVect iv = bit(); if (thisH(iv,0) < ice_eps || thisFrac(iv,0) < ice_eps) { thisFrac(iv,0) = 0.0; thisH(iv,0) = 0.0; } } } } /// update covered cells, ghost cells etc, of a_iceFrac void AmrIce::updateInvalidIceFrac(Vector<LevelData<FArrayBox> * > a_iceFrac) { for (int lev=0; lev<= m_finest_level; lev++) { LevelData<FArrayBox>& levelFrac = *a_iceFrac[lev]; const DisjointBoxLayout& fracGrids = levelFrac.getBoxes(); Real levelDx = m_amrDx[lev]; if (lev < m_finest_level) { CoarseAverage av(m_amrGrids[lev+1], 1, m_refinement_ratios[lev]); av.averageToCoarse(levelFrac,*a_iceFrac[lev+1]); } if (lev > 0) { int nGhost = levelFrac.ghostVect()[0]; PiecewiseLinearFillPatch pwl(m_amrGrids[lev], m_amrGrids[lev-1], 1, m_amrDomains[lev-1], m_refinement_ratios[lev-1], nGhost); pwl.fillInterp(levelFrac,*m_iceFrac[lev-1],*m_iceFrac[lev-1],0.0, 0, 0, 1); } m_thicknessIBCPtr->setIceFractionBCs(levelFrac,m_amrDomains[lev],dx(lev), time(), m_dt); levelFrac.exchange(); } } #define ICE_FRAC_EPS 1.0e-6 // /// update real-valued ice fraction and thickness source according to the calving rate // void // AmrIce::advectIceFracUpstream // (Vector<LevelData<FArrayBox>* >& a_iceFrac, // Vector<LevelData<FArrayBox>* >& a_thicknessSource, // const Vector<LevelData<FluxBox>* >& a_faceVelAdvection, // const Vector<LevelData<FArrayBox>* >& a_calvingRate, // Real a_subDt, Real a_dt) // { // // for (int lev=0; lev<= m_finest_level; lev++) // // { // // LevelData<FArrayBox>& levelFrac = *a_iceFrac[lev]; // // const DisjointBoxLayout& fracGrids = levelFrac.getBoxes(); // // Real levelDx = m_amrDx[lev]; // // //LevelData<FluxBox> faceRate( m_amrGrids[lev], 1, IntVect::Unit); // // //CellToEdge ( (*a_calvingRate[lev]), faceRate); // // //Compute a source term from the calving rate: only applies at front cells // // //where iceFrac > epsilon and iceFrac(a neighbour) < epsilon, // // //and add to the volume sourc // // //modify iceFrac accordingly // // for (DataIterator dit(m_amrGrids[lev]); dit.ok(); ++dit) // // { // // const Box& box = m_amrGrids[lev][dit]; // // FArrayBox& src = (*a_thicknessSource[lev])[dit]; // // //src.setVal(0.0); // // FArrayBox& frac = levelFrac[dit]; // // const FArrayBox& thk = (*m_old_thickness[lev])[dit]; // // FArrayBox dh(frac.box(), 1); dh.copy(frac); // // const FArrayBox& oldfrac = dh; //might as well // // for (int dir = 0; dir < SpaceDim; dir++) // // { // // //const FArrayBox& rate = faceRate[dit][dir]; // // const FArrayBox& rate = (*a_calvingRate[lev])[dit]; // // //FArrayBox erate(rate.box(),1.0); // // //erate.setVal(1.0); // // Real eps = 0.5 * m_cfl; // // FORT_ABLATEFRAC(CHF_FRA1(frac,0),CHF_CONST_FRA1(oldfrac,0), // // CHF_CONST_FRA1(rate,0), // // CHF_REAL(levelDx), // // CHF_REAL(a_subDt), // // CHF_REAL(eps), // // CHF_BOX(box), // // CHF_INT(dir)); // // Real et = a_subDt * 1.0e-3; // // FArrayBox t(frac.box(),1); // // t.copy(frac); // // FORT_ABLATEFRAC(CHF_FRA1(frac,0),CHF_CONST_FRA1(t,0), // // CHF_CONST_FRA1(rate,0), // // CHF_REAL(levelDx), // // CHF_REAL(et), // // CHF_REAL(eps), // // CHF_BOX(box), // // CHF_INT(dir)); // // } // loop over directions // // dh -= frac; //ice fraction lost due to ablation // // dh *= thk; // ice lost to ablation // // dh /= a_dt; // rate of ice lost to ablation // // src -= dh; // include rate of ice loss in source term // // } // loop over boxes // // } // end loop over levels // } // /// update real-valued ice fraction through advection from neighboring cells // void // AmrIce::advectIceFracDownstream(Vector<LevelData<FArrayBox>* >& a_iceFrac, // Vector<LevelData<FArrayBox>* >& a_thicknessSource, // const Vector<LevelData<FluxBox>* >& a_faceVelAdvection, // const Vector<LevelData<FluxBox>* >& a_thicknessFlux, // const Vector<LevelData<FArrayBox>* >& a_calvingRate, // Real a_subDt, Real a_dt) // { // for (int lev=0; lev<= m_finest_level; lev++) // { // LevelData<FArrayBox>& levelFrac = *a_iceFrac[lev]; // const LevelData<FluxBox>& levelFaceVel = *a_faceVelAdvection[lev]; // const DisjointBoxLayout& fracGrids = levelFrac.getBoxes(); // Real levelDx = m_amrDx[lev]; // for (DataIterator dit(m_amrGrids[lev]); dit.ok(); ++dit) // { // // only update valid cells // const Box& gridBox = fracGrids[dit]; // FArrayBox& thisFrac = levelFrac[dit]; // FArrayBox oldfrac(thisFrac.box(),1); oldfrac.copy(thisFrac); // FArrayBox dh(gridBox,1); dh.setVal(0.0); // const FluxBox& thisFaceVel = levelFaceVel[dit]; // const FluxBox& faceHFlux = levelFaceVel[dit]; // int dbg = 0; // for (int dir=0; dir<SpaceDim; dir++) // { // const FArrayBox& u_ice_face = thisFaceVel[dir]; // const FArrayBox& hflux = (*a_thicknessFlux[lev])[dit][dir]; // const FArrayBox& h = (*m_old_thickness[lev])[dit]; // Box faceBox = gridBox; // faceBox.surroundingNodes(dir); // FArrayBox u_calv_face(faceBox, 1); // u_calv_face.setVal(0.0); // Real eps = 0.0005*m_cfl; // eps = 1.0e-8; // const FArrayBox& rate = (*a_calvingRate[lev])[dit]; // // FORT_ABLATERATE(CHF_FRA1(u_calv_face,0), // // CHF_CONST_FRA1(oldfrac,0), // // CHF_CONST_FRA1(rate,0), // // CHF_REAL(eps), // // CHF_BOX(faceBox), // // CHF_INT(dir)); // FORT_ADVECTFRAC(CHF_FRA1(thisFrac,0), // CHF_FRA1(dh,0), // CHF_CONST_FRA1(oldfrac,0), // CHF_CONST_FRA1(u_ice_face,0), // CHF_CONST_FRA1(u_calv_face,0), // CHF_CONST_FRA1(hflux,0), // CHF_CONST_FRA1(h,0), // CHF_REAL(levelDx), // CHF_REAL(a_subDt), // CHF_REAL(eps), // CHF_BOX(gridBox), // CHF_INT(dir)); // } // end loop over directions // // thickness sink // // on return from FORT_ADVECTFRAC, dh = - df/dt * dt due to void growth, // // we want dh/dt = - h / f df/dt (h/f is constant) // // dh *= (*m_old_thickness[lev])[dit]; // // oldfrac += TINY_NORM; // // dh /= oldfrac; // if (m_frac_sources) // { // // source will be multiplied by f, so // //thisFrac += TINY_NORM; // dh /= thisFrac; // } // dh /= a_dt; // //(*a_thicknessSource[lev])[dit] += dh; // dbg++; // } // end loop over boxes // } // end loop over levels // } // /// update real-valued ice fraction through advection from neighboring cells // void // AmrIce::advectIceFrac(Vector<LevelData<FArrayBox>* >& a_iceFrac, // Vector<LevelData<FArrayBox>* >& a_thicknessSource, // const Vector<LevelData<FluxBox>* >& a_faceVelAdvection, // const Vector<LevelData<FluxBox>* >& a_thicknessFlux, // Real a_dt) // { // ///compute and store the cell-centered calving rate // Vector<LevelData<FArrayBox> *> calvingRate(m_finest_level + 1, NULL); // for (int lev=0; lev<= m_finest_level; lev++) // { // calvingRate[lev] = new LevelData<FArrayBox>(m_amrGrids[lev], 1, IntVect::Unit); // (*m_calvingModelPtr).getCalvingRate(*calvingRate[lev], *this, lev); // if (lev > 0) // { // PiecewiseLinearFillPatch pwl(m_amrGrids[lev], m_amrGrids[lev-1], // 1, m_amrDomains[lev-1], m_refinement_ratios[lev-1], // 1); // pwl.fillInterp(*calvingRate[lev],*calvingRate[lev-1],*calvingRate[lev-1],0.0, 0, 0, 1); // } // calvingRate[lev]->exchange(); // //while we are here, initialize thickness source // for (DataIterator dit(m_amrGrids[lev]); dit.ok(); ++dit) // { // FArrayBox& src = (*a_thicknessSource[lev])[dit]; // src.setVal(0.0); // } // } // Real max_calving_rate = computeNorm(calvingRate, refRatios() , m_amrDx[0], Interval(0,0), 0); // Real dt_max = m_cfl * m_amrDx[finestLevel()] / max_calving_rate; // //advection step. // int n_sub_step = int (a_dt / dt_max); // for (int sub_step = 0; sub_step < n_sub_step; sub_step++) // { // Real sub_step_dt = a_dt / Real(n_sub_step); // updateInvalidIceFrac(a_iceFrac); // applyCalvingCriterion(CalvingModel::PostThicknessAdvection); // advectIceFracDownstream(a_iceFrac, a_thicknessSource, // a_faceVelAdvection, a_thicknessFlux, calvingRate, sub_step_dt, a_dt); // } // // clean up // updateInvalidIceFrac(a_iceFrac); // for (int lev=0; lev<= m_finest_level; lev++) // { // if ( calvingRate[lev] ) delete calvingRate[lev]; // } // } /// update real-valued ice fraction through advection from neighboring cells void AmrIce::advectIceFrac(Vector<LevelData<FArrayBox>* >& a_iceFrac, const Vector<LevelData<FluxBox>* >& a_faceVelAdvection, Real a_dt) { // for now, set fill threshold to be (1-cfl) on the theory // that we want to declare a cell full before it actually over-fills Real fillThreshold = (1.0 - m_cfl); Real epsFrac = 1.0e-8; Real epsVel = 1.0e-8; int calvingNormalToFront = 1; for (int lev=0; lev<= m_finest_level; lev++) { LevelSigmaCS& levelCoords = *m_vect_coordSys[lev]; LevelData<FArrayBox>& levelFrac = *a_iceFrac[lev]; levelFrac.exchange(); const LevelData<FluxBox>& levelFaceVel = *a_faceVelAdvection[lev]; const LevelData<FArrayBox>& levelCCVel = *m_velocity[lev]; //LevelData<FArrayBox>& levelFrontVel = *a_frontVel[lev]; const DisjointBoxLayout& fracGrids = levelFrac.getBoxes(); const LevelData<FArrayBox>& levelTopg = levelCoords.getTopography(); const LevelData<BaseFab<int> >& levelMask = levelCoords.getFloatingMask(); const LevelData<FArrayBox>& levelThck = levelCoords.getH(); Real levelDx = m_amrDx[lev]; LevelData<FArrayBox> levelOldFrac(fracGrids, 1, levelFrac.ghostVect()); LevelData<FArrayBox> levelCopyFrac(fracGrids, 1, levelFrac.ghostVect()); LevelData<FArrayBox> levelTmpVel(fracGrids, 2, levelFrac.ghostVect()); LevelData<FArrayBox> levelFrontVel(fracGrids, 2, levelFrac.ghostVect()); for (DataIterator dit(fracGrids); dit.ok(); ++dit) { //FArrayBox& oldFrac= levelFrac[dit]; levelOldFrac[dit].copy(levelFrac[dit]); levelCopyFrac[dit].setVal(0.0); levelTmpVel[dit].setVal(0.0); } levelOldFrac.exchange(); LevelData<FArrayBox> levelCalvingRate(fracGrids, 1, levelFrac.ghostVect()); (*m_calvingModelPtr).getCalvingRate(levelCalvingRate, *this, lev); DataIterator dit = levelFrac.dataIterator(); for (dit.begin(); dit.ok(); ++dit) { // only update valid cells const Box& gridBox = fracGrids[dit]; const FArrayBox& oldFrac = levelOldFrac[dit]; const FluxBox& thisFaceVel = levelFaceVel[dit]; const FArrayBox& thisCCVel = levelCCVel[dit]; FArrayBox& calvingRate = levelCalvingRate[dit]; bool matt_option = false; ParmParse pp("amr"); pp.query("matt_option", matt_option); if (matt_option) { const FArrayBox& thck = levelThck[dit]; const FArrayBox& frac = levelFrac[dit]; FArrayBox t(calvingRate.box(), 1); // allocate some memory for the calculation t.copy(thck); // t = h t += 1.0e-10; // t = h + epsilon calvingRate *= frac; // Uc = Uc * f calvingRate /= t; // Uc = Uc * f/(h+ epsilon) } const FArrayBox& topg = levelTopg[dit]; const BaseFab<int>& mask = levelMask[dit]; FArrayBox& thisFrontVel = levelFrontVel[dit]; FArrayBox& thisTmpVel = levelTmpVel[dit]; FORT_FINDFRONTVEL(CHF_CONST_FRA1(oldFrac,0), CHF_CONST_FRA1(thisFaceVel[0],0), CHF_CONST_FRA1(thisFaceVel[1],0), CHF_CONST_FRA1(calvingRate,0), CHF_CONST_FRA1(topg,0), CHF_CONST_FIA1(mask,0), CHF_CONST_FRA(thisCCVel), CHF_FRA(thisTmpVel), CHF_FRA(thisFrontVel), CHF_CONST_INT(calvingNormalToFront), CHF_CONST_REAL(epsFrac), CHF_CONST_REAL(epsVel), CHF_CONST_REAL(levelDx), CHF_CONST_INT(m_cur_step), CHF_BOX(gridBox)); } // end loop over boxes levelFrontVel.exchange(); m_thicknessIBCPtr->velocityGhostBC( levelFrontVel , *m_vect_coordSys[lev],m_amrDomains[lev],m_time); for (dit.begin(); dit.ok(); ++dit) { const Box& gridBox = fracGrids[dit]; FArrayBox& thisFrac = levelFrac[dit]; const FArrayBox& oldFrac = levelOldFrac[dit]; const FArrayBox& thisFrontVel = levelFrontVel[dit]; for (int dir=0; dir<SpaceDim; dir++) { FORT_ADVECTFRAC(CHF_FRA1(thisFrac,0), CHF_CONST_FRA1(oldFrac,0), CHF_CONST_FRA1(thisFrontVel,dir), CHF_CONST_REAL(levelDx), CHF_CONST_REAL(a_dt), CHF_CONST_REAL(epsFrac), CHF_CONST_REAL(epsVel), CHF_BOX(gridBox), CHF_INT(dir)); } // end loop over directions } // end loop over boxes m_thicknessIBCPtr->setIceFractionBCs(levelFrac,m_amrDomains[lev],dx(lev), time(), m_dt); int sumOutOfRange=0; int MaxIt=m_max_box_size*(lev+1); for (int ii=0; ii<MaxIt; ii++) { if (sumOutOfRange > 0 || ii==0) { sumOutOfRange=0; for (dit.begin(); dit.ok(); ++dit) { const Box& gridBox = fracGrids[dit]; FArrayBox& thisFrac = levelFrac[dit]; const FArrayBox& oldFrac = levelOldFrac[dit]; const FArrayBox& thisFrontVel = levelFrontVel[dit]; FArrayBox& copyFrac=levelCopyFrac[dit]; copyFrac.copy(thisFrac); int outOfRange=0; FORT_GETFRAC(CHF_FRA1(thisFrac,0), CHF_CONST_FRA1(oldFrac,0), CHF_CONST_FRA1(copyFrac,0), CHF_CONST_FRA(thisFrontVel), CHF_CONST_REAL(epsFrac), CHF_CONST_REAL(epsVel), CHF_CONST_INT(m_cur_step), CHF_CONST_INT(ii), CHF_INT(outOfRange), CHF_CONST_INT(lev), CHF_CONST_INT(MaxIt), CHF_BOX(gridBox)); sumOutOfRange += outOfRange; } // end loop over boxes } m_thicknessIBCPtr->setIceFractionBCs(levelFrac,m_amrDomains[lev],dx(lev), time(), m_dt); } // end loop over ii for (dit.begin(); dit.ok(); ++dit) { const Box& gridBox = fracGrids[dit]; FArrayBox& thisFrac = levelFrac[dit]; const FArrayBox& oldFrac = levelOldFrac[dit]; const FArrayBox& thisFrontVel = levelFrontVel[dit]; //FArrayBox& thisFrontVel = levelFrontVel[dit]; FArrayBox& thisTmpVel = levelTmpVel[dit]; FORT_ISOLATEDFRAC(CHF_FRA1(thisFrac,0), CHF_CONST_FRA1(oldFrac,0), CHF_CONST_FRA(thisFrontVel), CHF_CONST_INT(m_cur_step), CHF_CONST_INT(lev), CHF_BOX(gridBox)); //thisFrontVel.copy(thisTmpVel); } // end loop over boxes } // end loop over levels //coarse average from finer levels & exchange for (int lev = m_finest_level; lev >= 0 ; --lev) { if (lev > 0) { CoarseAverage averager(m_amrGrids[lev], a_iceFrac[lev]->nComp(), m_refinement_ratios[lev-1]); averager.averageToCoarse(*a_iceFrac[lev-1], *a_iceFrac[lev]); } } } // compute timestep Real AmrIce::computeDt() { if (s_verbosity > 3) { pout() << "AmrIce::computeDt" << endl; } if (m_fixed_dt > TIME_EPS) return m_fixed_dt; Real dt = 1.0e50; Real maxVelAll = 0.0; for (int lev=0; lev<= finestTimestepLevel(); lev++) { Real dtLev = dt; Real maxVelLev = maxVelAll; const DisjointBoxLayout& levelGrids = m_amrGrids[lev]; const LevelData<FluxBox>& levelVel = *m_faceVelAdvection[lev]; DataIterator levelDit = levelVel.dataIterator(); for (levelDit.reset(); levelDit.ok(); ++levelDit) { for (int dir = 0; dir < SpaceDim; dir++) { int p = 0; Box faceBox = levelGrids[levelDit]; faceBox.surroundingNodes(dir); Real maxVel = 1.0e-10 + levelVel[levelDit][dir].norm(faceBox,p, 0, 1); Real localDt = m_amrDx[lev]/maxVel; dtLev = min(dtLev, localDt); maxVelLev = std::max(maxVelLev, maxVel); } } if (m_diffusionTreatment == EXPLICIT){ MayDay::Error("diffusion_treatment == explicit not supported now : use none"); } dt = min(dt, dtLev); maxVelAll = std::max(maxVelAll, maxVelLev); } #ifdef CH_MPI Real tmp = 1.; int result = MPI_Allreduce(&dt, &tmp, 1, MPI_CH_REAL, MPI_MIN, Chombo_MPI::comm); if (result != MPI_SUCCESS) { MayDay::Error("communication error on norm"); } dt = tmp; result = MPI_Allreduce(&maxVelAll, &tmp, 1, MPI_CH_REAL, MPI_MAX, Chombo_MPI::comm); if (result != MPI_SUCCESS) { MayDay::Error("communication error on norm"); } maxVelAll = tmp; #endif if (m_cur_step == 0) { dt *= m_initial_cfl; } else { dt *= m_cfl; } // also check to see if max grow rate applies // (m_dt > 0 test screens out initial time, when we set m_dt to a negative // number by default) // Use the value stored in m_stable_dt in case dt was altered to hit a plot interval // m_max_dt_grow < 0 implies that we don't enforce this. if ((m_max_dt_grow > 0) && (dt > m_max_dt_grow*m_stable_dt) && (m_stable_dt > 0) ) dt = m_max_dt_grow*m_stable_dt; if (m_timeStepTicks){ // reduce time step to integer power of two dt = std::pow(2.0, std::floor(std::log(dt)/std::log(two))); } m_stable_dt = dt; if (s_verbosity > 3) { pout() << "AmrIce::computeDt dt = " << dt << ", max vel = " << maxVelAll << endl; } if (maxVelAll > m_velocity_exit || dt < TIME_EPS) { std::stringstream ss; ss << " max(vel) = " << maxVelAll << " > amr.velocity_exit = " << m_velocity_exit << " || dt = " << dt << " < TIME_EPS = " << TIME_EPS; m_plot_prefix = std::string("error_") + m_plot_prefix; writePlotFile(); pout() << " AmrIce::computeDt exit because " << ss.str() << endl; MayDay::Error(ss.str().c_str()); } return dt; } Real AmrIce::computeInitialDt() { if (s_verbosity > 3) { pout() << "AmrIce::computeInitialDt" << endl; } // for now, just call computeDt; Real dt = computeDt(); return dt; } //determine the grouding line proximity /** Solves the elliptic problem a * phi - b* grad^2 phi = 0; with natural boundary conditions. for grounded ice, a = 10^5 and b = 1 for floating ice, s = 0 and b = 1 */ void AmrIce::updateGroundingLineProximity() const { CH_TIME("AmrIce::updateGroundingLineProximity"); if (m_groundingLineProximity_valid) return; if (m_groundingLineProximity.size() < m_finest_level + 1) { m_groundingLineProximity.resize(m_finest_level + 1, NULL); } if (s_verbosity > 0) { pout() << "AmrIce::updateGroundingLineProximity() max level = " << m_finest_level << " " << endl; } //Natural boundary conditions BCHolder bc(ConstDiriNeumBC(IntVect::Zero, RealVect::Zero, IntVect::Zero, RealVect::Zero)); //BCHolder bc(ConstDiriNeumBC(IntVect(0,0), RealVect(-1.0,-1.0), // IntVect(0,0), RealVect(1.0,1.0))); Vector<RefCountedPtr<LevelData<FArrayBox> > > a(m_finest_level + 1); Vector<RefCountedPtr<LevelData<FluxBox> > > b(m_finest_level + 1); Vector<LevelData<FArrayBox>* > rhs(m_finest_level+ 1,NULL); Vector<DisjointBoxLayout> grids(finestTimestepLevel() + 1); Vector<ProblemDomain> domains(finestTimestepLevel() + 1); Vector<RealVect> dx(finestTimestepLevel() + 1); for (int lev=0; lev <= m_finest_level; ++lev) { dx[lev] = m_amrDx[lev]*RealVect::Unit; domains[lev] = m_amrDomains[lev]; const LevelSigmaCS& levelCS = *m_vect_coordSys[lev]; const LevelData<BaseFab<int> >& levelMask = levelCS.getFloatingMask(); const DisjointBoxLayout& levelGrids = m_amrGrids[lev]; a[lev] = RefCountedPtr<LevelData<FArrayBox> > (new LevelData<FArrayBox>(levelGrids, 1, IntVect::Zero)); b[lev] = RefCountedPtr<LevelData<FluxBox> > (new LevelData<FluxBox>(levelGrids, 1, IntVect::Zero)); rhs[lev] = new LevelData<FArrayBox>(levelGrids, 1, IntVect::Zero); grids[lev] = levelGrids; if (m_groundingLineProximity[lev] != NULL) { delete m_groundingLineProximity[lev]; m_groundingLineProximity[lev] = NULL; } m_groundingLineProximity[lev] = new LevelData<FArrayBox>(levelGrids, 1, IntVect::Unit); LevelData<FArrayBox>& levelPhi = *m_groundingLineProximity[lev]; const Real& crseDx = m_amrDx[0]; Real crseDxSq = crseDx*crseDx; for (DataIterator dit(levelGrids); dit.ok(); ++dit) { FluxBox& B = (*b[lev])[dit]; for (int dir = 0; dir < SpaceDim; dir++) { B[dir].setVal(crseDxSq); } FArrayBox& r = (*rhs[lev])[dit]; r.setVal(0.0); FArrayBox& A = (*a[lev])[dit]; A.setVal(0.0); FArrayBox& phi = levelPhi[dit]; phi.setVal(0.0); const BaseFab<int>& mask = levelMask[dit]; const Box& gridBox = levelGrids[dit]; // const FArrayBox& u = (*m_velocity[lev])[dit]; Real AcoefF = crseDx / m_groundingLineProximityScale; Real AcoefG = 1.0 ; if (m_groundingLineProximityCalcType > 0) { AcoefF = crseDx / m_groundingLineProximityScale; AcoefF *= AcoefF; } for (BoxIterator bit(gridBox);bit.ok();++bit) { const IntVect& iv = bit(); if (mask(iv) == GROUNDEDMASKVAL ) { A(iv) = AcoefG; r(iv) = AcoefG; } else { A(iv) = AcoefF; r(iv) = 0.0; } } phi.copy(r); } rhs[lev]->exchange(); levelPhi.exchange(); m_groundingLineProximity[lev]->exchange(); a[lev]->exchange(); b[lev]->exchange(); } VCAMRPoissonOp2Factory* poissonOpFactory = new VCAMRPoissonOp2Factory; poissonOpFactory->define(domains[0], grids , m_refinement_ratios, m_amrDx[0], bc, 1.0, a, 1.0 , b); RefCountedPtr< AMRLevelOpFactory<LevelData<FArrayBox> > > opFactoryPtr(poissonOpFactory); MultilevelLinearOp<FArrayBox> poissonOp; poissonOp.define(grids, m_refinement_ratios, domains, dx, opFactoryPtr, 0); RelaxSolver<Vector<LevelData<FArrayBox>* > >* relaxSolver = new RelaxSolver<Vector<LevelData<FArrayBox>* > >(); relaxSolver->define(&poissonOp,false); relaxSolver->m_verbosity = s_verbosity; relaxSolver->m_normType = 0; relaxSolver->m_eps = 1.0e-8; relaxSolver->m_imax = 12; relaxSolver->m_hang = 0.05; relaxSolver->solve(m_groundingLineProximity,rhs); delete(relaxSolver); #ifdef DUMP_PROXIMITY std::string file("proximity.2d.hdf5"); Real dt = 0.0; Real time = 0.0; Vector<std::string> names(1,"proximity"); WriteAMRHierarchyHDF5(file ,grids, m_groundingLineProximity ,names, m_amrDomains[0].domainBox(), m_amrDx[0], dt, m_time, m_refinement_ratios, m_groundingLineProximity.size()); #endif for (int lev=0; lev <= m_finest_level ; ++lev) { if (rhs[lev] != NULL) { delete rhs[lev]; rhs[lev] = NULL; } } m_groundingLineProximity_valid = true; } //access the viscous tensor (cell-centered) const LevelData<FArrayBox>* AmrIce::viscousTensor(int a_level) const { //updateViscousTensor(); CH_assert(m_viscousTensor_valid); if (!(m_viscousTensorCell.size() > a_level)) { std::string msg("AmrIce::viscousTensor !(m_viscousTensorCell.size() > a_level))"); pout() << msg << endl; CH_assert((m_viscousTensorCell.size() > a_level)); MayDay::Error(msg.c_str()); } LevelData<FArrayBox>* ptr = m_viscousTensorCell[a_level]; if (ptr == NULL) { std::string msg("AmrIce::viscousTensor m_viscousTensorCell[a_level] == NULL "); pout() << msg << endl; CH_assert(ptr != NULL); MayDay::Error(msg.c_str()); } return ptr; } //access the viscous tensor (cell-centered) const LevelData<FArrayBox>* AmrIce::viscosityCoefficient(int a_level) const { CH_assert(m_viscousTensor_valid); //updateViscousTensor(); if (!(m_viscosityCoefCell.size() > a_level)) { std::string msg("AmrIce::viscosityCoef !(m_viscosityCoefCell.size() > a_level))"); pout() << msg << endl; CH_assert((m_viscosityCoefCell.size() > a_level)); MayDay::Error(msg.c_str()); } LevelData<FArrayBox>* ptr = m_viscosityCoefCell[a_level]; if (ptr == NULL) { std::string msg("AmrIce::viscosityCoef m_viscosityCoefCell[a_level] == NULL "); pout() << msg << endl; CH_assert(ptr != NULL); MayDay::Error(msg.c_str()); } return ptr; } const LevelData<FArrayBox>* AmrIce::surfaceThicknessSource(int a_level) const { if (!(m_surfaceThicknessSource.size() > a_level)) { std::string msg("AmrIce::surfaceThicknessSource !(m_surfaceThicknessSource.size() > a_level))"); pout() << msg << endl; CH_assert((m_surfaceThicknessSource.size() > a_level)); MayDay::Error(msg.c_str()); } LevelData<FArrayBox>* ptr = m_surfaceThicknessSource[a_level]; if (ptr == NULL) { std::string msg("AmrIce::surfaceThicknessSource m_surfaceThicknessSource[a_level] == NULL "); pout() << msg << endl; CH_assert(ptr != NULL); MayDay::Error(msg.c_str()); } return ptr; } const LevelData<FArrayBox>* AmrIce::basalThicknessSource(int a_level) const { if (!(m_basalThicknessSource.size() > a_level)) { std::string msg("AmrIce::basalThicknessSource !(m_basalThicknessSource.size() > a_level))"); pout() << msg << endl; CH_assert((m_basalThicknessSource.size() > a_level)); MayDay::Error(msg.c_str()); } LevelData<FArrayBox>* ptr = m_basalThicknessSource[a_level]; if (ptr == NULL) { std::string msg("AmrIce::basalThicknessSource m_basalThicknessSource[a_level] == NULL "); pout() << msg << endl; CH_assert(ptr != NULL); MayDay::Error(msg.c_str()); } return ptr; } //access the drag coefficient (cell-centered) const LevelData<FArrayBox>* AmrIce::dragCoefficient(int a_level) const { //updateViscousTensor(); CH_assert(m_viscousTensor_valid); if (!(m_dragCoef.size() > a_level)) { std::string msg("AmrIce::dragCoef !(m_dragCoef.size() > a_level))"); pout() << msg << endl; CH_assert((m_dragCoef.size() > a_level)); MayDay::Error(msg.c_str()); } LevelData<FArrayBox>* ptr = m_dragCoef[a_level]; if (ptr == NULL) { std::string msg("AmrIce::dragCoef m_dragCoefCell[a_level] == NULL "); pout() << msg << endl; CH_assert(ptr != NULL); MayDay::Error(msg.c_str()); } return ptr; } //update the viscous tensor components void AmrIce::updateViscousTensor() const { CH_TIME("AmrIce::updateViscousTensor"); if (m_viscousTensor_valid) return; if (m_viscousTensorCell.size() < m_finest_level + 1) { m_viscousTensorCell.resize(m_finest_level + 1, NULL); } if (m_viscosityCoefCell.size() < m_finest_level + 1) { m_viscosityCoefCell.resize(m_finest_level + 1, NULL); } if (m_dragCoef.size() < m_finest_level + 1) { m_dragCoef.resize(m_finest_level + 1, NULL); } // if (m_magnitudeBasalDrag.size() < m_finest_level + 1) // { // m_magnitudeBasalDrag..resize(m_finest_level + 1, NULL); // } if (m_viscousTensorFace.size() < m_finest_level + 1) { m_viscousTensorFace.resize(m_finest_level + 1, NULL); } Vector<LevelData<FluxBox>*> faceA(m_finest_level + 1,NULL); Vector<RefCountedPtr<LevelData<FluxBox> > > viscosityCoef; Vector<RefCountedPtr<LevelData<FArrayBox> > > dragCoef; Vector<LevelData<FArrayBox>* > C0(m_finest_level + 1, NULL); Vector<RealVect> vdx(m_finest_level + 1); for (int lev =0; lev <= m_finest_level; lev++) { faceA[lev] = new LevelData<FluxBox>(m_amrGrids[lev],m_A[lev]->nComp(),IntVect::Unit); CellToEdge(*m_A[lev],*faceA[lev]); if (m_viscousTensorFace[lev] != NULL) { delete m_viscousTensorFace[lev];m_viscousTensorFace[lev]=NULL; } m_viscousTensorFace[lev] = new LevelData<FluxBox>(m_amrGrids[lev],SpaceDim,IntVect::Unit); if (m_viscousTensorCell[lev] != NULL) { delete m_viscousTensorCell[lev];m_viscousTensorCell[lev]=NULL; } m_viscousTensorCell[lev] = new LevelData<FArrayBox>(m_amrGrids[lev],SpaceDim*SpaceDim,IntVect::Unit); if (m_dragCoef[lev] != NULL) { delete m_dragCoef[lev]; m_dragCoef[lev] = NULL; } m_dragCoef[lev] = new LevelData<FArrayBox>(m_amrGrids[lev],SpaceDim,IntVect::Zero); // if (m_magnitudeBasalDrag[lev] != NULL) // { // delete m_[lev]; m_dragCoef[lev] = NULL; // } // m_dragCoef[lev] = new LevelData<FArrayBox>(m_amrGrids[lev],SpaceDim,IntVect::Zero); if (m_viscosityCoefCell[lev] != NULL) { delete m_viscosityCoefCell[lev]; m_viscosityCoefCell[lev] = NULL; } m_viscosityCoefCell[lev] = new LevelData<FArrayBox>(m_amrGrids[lev],SpaceDim,IntVect::Zero); if (C0[lev] != NULL) { delete C0[lev];C0[lev] = NULL; } C0[lev] = new LevelData<FArrayBox>(m_amrGrids[lev],1,m_velBasalC[0]->ghostVect()); DataIterator dit = m_amrGrids[lev].dataIterator(); for (dit.begin(); dit.ok(); ++dit) { (*C0[lev])[dit].setVal(0.0); } vdx[lev] = RealVect::Unit*m_amrDx[lev]; } //these parameters don't matter because we don't solve anything here. Real vtopSafety = 1.0; int vtopRelaxMinIter = 4; Real vtopRelaxTol = 1.0; Real muMin = 0.0; Real muMax = 1.23456789e+300; int numLevels = m_finest_level + 1; IceNonlinearViscousTensor state(m_amrGrids, m_refinement_ratios, m_amrDomains, vdx, m_vect_coordSys, m_velocity, m_velBasalC, C0, numLevels-1, *m_constitutiveRelation, *m_basalFrictionRelation, *m_thicknessIBCPtr, m_A, faceA, m_time, vtopSafety, vtopRelaxMinIter, vtopRelaxTol, muMin, muMax); state.setState(m_velocity); viscosityCoef = state.mu(); dragCoef = state.alpha(); state.computeViscousTensorFace(m_viscousTensorFace); for (int lev =0; lev < numLevels; lev++) { //If a cell is adjacent to a calving front, we set the (vertically integrated) //viscous tensor components at the intervening face to zero. That works well enough for the velocity solves, //but causes pain here because the cell average (in EdgeToCell) will end up half the value at the other face. for (DataIterator dit(m_amrGrids[lev]); dit.ok(); ++dit) { const FArrayBox& thck = m_vect_coordSys[lev]->getH()[dit]; //const FArrayBox& dsdx = m_vect_coordSys[lev]->getGradSurface()[dit]; const FArrayBox& usrf = m_vect_coordSys[lev]->getSurfaceHeight()[dit]; const BaseFab<int>& mask = m_vect_coordSys[lev]->getFloatingMask()[dit]; const Real& rhoi = m_vect_coordSys[lev]->iceDensity(); //const Real& rhoo = m_vect_coordSys[lev]->waterDensity(); const Real& gravity = m_vect_coordSys[lev]->gravity(); //const Real rgr = rhoi * gravity * (1.0-rhoi/rhoo); //const RealVect& dx = m_vect_coordSys[lev]->dx(); for (int dir = 0; dir < SpaceDim; dir++) { FArrayBox& facevt = (*m_viscousTensorFace[lev])[dit][dir]; Real factor = rhoi * gravity; FORT_SETFRONTFACEVT(CHF_FRA1(facevt,dir), CHF_CONST_FRA1(thck,0), CHF_CONST_FRA1(usrf,0), CHF_CONST_FIA1(mask,0), CHF_CONST_INT(dir), CHF_CONST_REAL(factor), CHF_BOX(m_amrGrids[lev][dit])); } } EdgeToCell(*m_viscousTensorFace[lev],*m_viscousTensorCell[lev]); if (lev > 0) { PiecewiseLinearFillPatch ghostFiller (m_amrGrids[lev], m_amrGrids[lev-1], m_viscousTensorCell[lev-1]->nComp(), m_amrDomains[lev-1], m_refinement_ratios[lev-1], m_viscousTensorCell[lev-1]->ghostVect()[0]); ghostFiller.fillInterp(*m_viscousTensorCell[lev], *m_viscousTensorCell[lev-1], *m_viscousTensorCell[lev-1],1.0,0,0, m_viscousTensorCell[lev-1]->nComp()); } m_viscousTensorCell[lev]->exchange(); EdgeToCell(*viscosityCoef[lev],*m_viscosityCoefCell[lev]); for (DataIterator dit(m_amrGrids[lev]); dit.ok(); ++dit) { const BaseFab<int>& mask = m_vect_coordSys[lev]->getFloatingMask()[dit]; FArrayBox& cellvt = (*m_viscousTensorCell[lev])[dit]; const Real z = 0.0; for (int comp = 0; comp < SpaceDim * SpaceDim; comp++) { FORT_SETICEFREEVAL(CHF_FRA1(cellvt,comp), CHF_CONST_FIA1(mask,0), CHF_CONST_REAL(z), CHF_BOX(m_amrGrids[lev][dit])); } } dragCoef[lev]->copyTo(Interval(0,0),*m_dragCoef[lev],Interval(0,0)); if (faceA[lev] != NULL) { delete faceA[lev]; faceA[lev] = NULL; } if (C0[lev] != NULL) { delete C0[lev]; C0[lev] = NULL; } } m_viscousTensor_valid = true; } //access the grounding line proximity const LevelData<FArrayBox>* AmrIce::groundingLineProximity(int a_level) const { updateGroundingLineProximity(); if (!(m_groundingLineProximity.size() > a_level)) { std::string msg("AmrIce::groundingLineProximity !(m_groundingLineProximity.size() > a_level)"); pout() << msg << endl; CH_assert((m_groundingLineProximity.size() > a_level)); MayDay::Error(msg.c_str()); } LevelData<FArrayBox>* ptr = m_groundingLineProximity[a_level]; if (ptr == NULL) { std::string msg("AmrIce::groundingLineProximity m_groundingLineProximity[a_level] == NULL)"); pout() << msg << endl; CH_assert(ptr != NULL); MayDay::Error(msg.c_str()); } return ptr; } void AmrIce::applyCalvingCriterion(CalvingModel::Stage a_stage) { CH_TIME("AmrIce::applyCalvingCriterion"); CH_assert(m_calvingModelPtr != NULL); // observers (e.g AMRMelange) may care about the calved ice if (a_stage != CalvingModel::Initialization) notifyObservers(Observer::PreCalving); //allow calving model to modify geometry for (int lev=0; lev<= m_finest_level; lev++) { LevelData<FArrayBox>& thck = m_vect_coordSys[lev]->getH(); LevelData<FArrayBox>& frac = *m_iceFrac[lev]; LevelData<FArrayBox>& calvedIce = *m_calvedIceThickness[lev]; LevelData<FArrayBox>& addedIce = *m_addedIceThickness[lev]; LevelData<FArrayBox>& removedIce = *m_removedIceThickness[lev]; m_calvingModelPtr->applyCriterion(thck, calvedIce, addedIce, removedIce, frac, *this, lev, a_stage); } // observers (e.g AMRMelange) may care about the calved ice if (a_stage != CalvingModel::Initialization) notifyObservers(Observer::PostCalving); // usually a good time to eliminate remote ice if (m_eliminate_remote_ice) eliminateRemoteIce(); } ///Identify regions of floating ice that are remote ///from grounded ice and eliminate them. void AmrIce::eliminateRemoteIce() { //any thickness change in eliminateRemoteIce is assumed to be calving: observers may care notifyObservers(Observer::PreCalving); IceUtility::eliminateRemoteIce(m_vect_coordSys, m_velocity, m_calvedIceThickness, m_addedIceThickness, m_removedIceThickness, m_amrGrids, m_amrDomains, m_refinement_ratios, m_amrDx[0], m_finest_level, m_eliminate_remote_ice_max_iter, m_eliminate_remote_ice_tol,s_verbosity); //any thickness change in eliminateRemoteIce is assumed to be calving: observers may care notifyObservers(Observer::PostCalving); } void AmrIce::implicitThicknessCorrection(Real a_dt, const Vector<LevelData<FArrayBox>* >& a_sts, const Vector<LevelData<FArrayBox>* >& a_bts, const Vector<LevelData<FArrayBox>* >& a_vts ) { CH_TIME("AmrIce::implicitThicknessCorrection"); if (s_verbosity > 3) { pout() << "AmrIce::implicitThicknessCorrection" << std::endl; } if (m_temporalAccuracy == 1) { //implicit Euler : solve (I - dt P) H = H_pred + dt * S //slc: at the moment, I'm setting eveything up every time-step, //pretending that diffusion is constant in time, and using the multi-grid //solver only. All these things are to be improved //Natural boundary conditions - OK for now, but ought to get //moved into subclasses of IceThicknessIBC BCHolder bc(ConstDiriNeumBC(IntVect::Zero, RealVect::Zero, IntVect::Zero, RealVect::Zero)); Vector<RefCountedPtr<LevelData<FArrayBox> > > I(finestTimestepLevel() + 1); Vector<RefCountedPtr<LevelData<FluxBox> > > D(finestTimestepLevel() + 1); Vector<LevelData<FArrayBox>* > H(finestTimestepLevel() + 1); Vector<LevelData<FArrayBox>* > rhs(finestTimestepLevel()+ 1); Vector<DisjointBoxLayout> grids(finestTimestepLevel() + 1); for (int lev=0; lev <= finestTimestepLevel(); ++lev) { LevelSigmaCS& levelCoords = *m_vect_coordSys[lev]; const DisjointBoxLayout& levelGrids = m_amrGrids[lev]; I[lev] = RefCountedPtr<LevelData<FArrayBox> > (new LevelData<FArrayBox>(levelGrids, 1, IntVect::Unit)); H[lev] = new LevelData<FArrayBox>(levelGrids, 1, IntVect::Unit); D[lev] = RefCountedPtr<LevelData<FluxBox> >(m_diffusivity[lev]); D[lev].neverDelete(); rhs[lev] = new LevelData<FArrayBox>(levelGrids, 1, IntVect::Unit); grids[lev] = levelGrids; const LevelData<FArrayBox>& levelSTS = *a_sts[lev]; const LevelData<FArrayBox>& levelBTS = *a_bts[lev]; const LevelData<FArrayBox>& levelVTS = *a_vts[lev]; for (DataIterator dit(levelGrids); dit.ok(); ++dit) { (*I[lev])[dit].setVal(one); (*H[lev])[dit].copy(levelCoords.getH()[dit] , 0 , 0, 1); (*rhs[lev])[dit].copy( (*H[lev])[dit] , 0 , 0, 1); //(*rhs[lev])[dit].plus(levelSTS[dit],a_dt); //(*rhs[lev])[dit].plus(levelBTS[dit],a_dt); //(*rhs[lev])[dit].plus(levelVTS[dit],a_dt); (*D[lev])[dit][0].plus(m_additionalDiffusivity); (*D[lev])[dit][1].plus(m_additionalDiffusivity); } rhs[lev]->exchange(); H[lev]->exchange(); m_diffusivity[lev]->exchange(); I[lev]->exchange(); } VCAMRPoissonOp2Factory poissonOpFactory;//= new VCAMRPoissonOp2Factory; poissonOpFactory.define(m_amrDomains[0], grids , m_refinement_ratios, m_amrDx[0], bc, 1.0, I, a_dt, D); //Plain MG BiCGStabSolver<LevelData<FArrayBox> > bottomSolver; AMRMultiGrid<LevelData<FArrayBox> > mgSolver; mgSolver.define(m_amrDomains[0], poissonOpFactory , &bottomSolver, finestTimestepLevel()+1); //parse these mgSolver.m_eps = 1.0e-10; mgSolver.m_normThresh = 1.0e-10; int numMGSmooth = 4; mgSolver.m_pre = numMGSmooth; mgSolver.m_post = numMGSmooth; mgSolver.m_bottom = numMGSmooth; mgSolver.solve(H, rhs, finestTimestepLevel(), 0, false); for (int lev=0; lev <= finestTimestepLevel() ; ++lev) { const DisjointBoxLayout& levelGrids = m_amrGrids[lev]; LevelSigmaCS& levelCoords = *m_vect_coordSys[lev]; LevelData<FArrayBox>& levelCoord_H = levelCoords.getH(); for (DataIterator dit(levelGrids); dit.ok(); ++dit) { CH_assert( (*H[lev])[dit].norm(0,0,1) < HUGE_THICKNESS); levelCoord_H[dit].copy( (*H[lev])[dit], 0, 0, 1); //put sensible values into the corners. FArrayBox &thisH = levelCoord_H[dit]; Box sbox = thisH.box(); sbox.grow(-levelCoord_H.ghostVect()[0]); FORT_EXTRAPCORNER2D(CHF_FRA(thisH), CHF_BOX(sbox)); } if (rhs[lev] != NULL) { delete rhs[lev]; rhs[lev] = NULL; } if (H[lev] != NULL) { delete H[lev]; H[lev] = NULL; } } } else { MayDay::Error("AmrIce::implicitThicknessCorrection, invalid temporal accuracy"); } } void AmrIce::helmholtzSolve (Vector<LevelData<FArrayBox>* >& a_phi, const Vector<LevelData<FArrayBox>* >& a_rhs, Real a_alpha, Real a_beta) const { // AMRPoissonOp supports only one component of phi // if m_finest_level > 0 (its LevelFluxRegisters are // defined with only one component, so we will do // one component at a time. should try to avoid some // of the rhs copies... for (int icomp = 0; icomp < a_phi[0]->nComp(); ++icomp) { //make a copy of a_phi with one ghost cell Vector<LevelData<FArrayBox>* > phi(m_finest_level + 1, NULL); Vector<LevelData<FArrayBox>* > rhs(m_finest_level + 1, NULL); Vector<DisjointBoxLayout> grids(m_finest_level + 1); for (int lev=0; lev < m_finest_level + 1; ++lev) { grids[lev] = m_amrGrids[lev]; const LevelData<FArrayBox>& levelPhi = *a_phi[lev]; phi[lev] = new LevelData<FArrayBox>(m_amrGrids[lev], 1, IntVect::Unit); levelPhi.copyTo(Interval(icomp,icomp),*phi[lev], Interval(0,0)); phi[lev]->exchange(); const LevelData<FArrayBox>& levelRhs = *a_rhs[lev]; rhs[lev] = new LevelData<FArrayBox>(m_amrGrids[lev], 1, IntVect::Zero); levelRhs.copyTo(Interval(icomp,icomp),*rhs[lev], Interval(0,0)); rhs[lev]->exchange(); } //Natural boundary conditions BCHolder bc(ConstDiriNeumBC(IntVect::Zero, RealVect::Zero, IntVect::Zero, RealVect::Zero)); AMRPoissonOpFactory opf; opf.define(m_amrDomains[0], grids , m_refinement_ratios, m_amrDx[0], bc, a_alpha, -a_beta ); AMRMultiGrid<LevelData<FArrayBox> > mgSolver; BiCGStabSolver<LevelData<FArrayBox> > bottomSolver; mgSolver.define(m_amrDomains[0], opf, &bottomSolver, m_finest_level+1); mgSolver.m_eps = TINY_NORM; mgSolver.m_normThresh = TINY_NORM; mgSolver.m_iterMax = 1; int numMGSmooth = 1; mgSolver.m_pre = numMGSmooth; mgSolver.m_post = numMGSmooth; mgSolver.m_bottom = numMGSmooth; mgSolver.m_verbosity = s_verbosity - 1; mgSolver.solve(phi, rhs, m_finest_level, 0, false); for (int lev=0; lev < m_finest_level + 1; ++lev) { LevelData<FArrayBox>& levelPhi = *a_phi[lev]; phi[lev]->copyTo(Interval(0,0), levelPhi, Interval(icomp, icomp)); if (phi[lev] != NULL){ delete phi[lev]; phi[lev] = NULL; } } } } void AmrIce::helmholtzSolve (Vector<LevelData<FArrayBox>* >& a_phi, Real a_alpha, Real a_beta) const { Vector<LevelData<FArrayBox>* > rhs(m_finest_level + 1, NULL); for (int lev=0; lev < m_finest_level + 1; ++lev) { const LevelData<FArrayBox>& levelPhi = *a_phi[lev]; rhs[lev] = new LevelData<FArrayBox> (m_amrGrids[lev], levelPhi.nComp(), IntVect::Zero); levelPhi.copyTo(*rhs[lev]); } helmholtzSolve(a_phi, rhs, a_alpha, a_beta); for (int lev=0; lev < m_finest_level + 1; ++lev) { if (rhs[lev] != NULL){ delete rhs[lev]; rhs[lev] = NULL; } } } #if BISICLES_Z == BISICLES_LAYERED /// update the flow law coefficient A void AmrIce::computeA(Vector<LevelData<FArrayBox>* >& a_A, Vector<LevelData<FArrayBox>* >& a_sA, Vector<LevelData<FArrayBox>* >& a_bA, const Vector<LevelData<FArrayBox>* >& a_internalEnergy, const Vector<LevelData<FArrayBox>* >& a_sInternalEnergy, const Vector<LevelData<FArrayBox>* >& a_bInternalEnergy, const Vector<RefCountedPtr<LevelSigmaCS> >& a_coordSys) const { if (s_verbosity > 0) { pout() << "AmrIce::computeA" << std::endl; } //for now, throw a_A etc away and recompute for (int lev = 0; lev < a_A.size(); ++lev) { if (a_A[lev] != NULL) { delete a_A[lev]; a_A[lev] = NULL; } if (a_sA[lev] != NULL) { delete a_sA[lev]; a_sA[lev] = NULL; } if (a_bA[lev] != NULL) { delete a_bA[lev]; a_bA[lev] = NULL; } } a_A.resize(m_finest_level+1,NULL); a_sA.resize(m_finest_level+1,NULL); a_bA.resize(m_finest_level+1,NULL); for (int lev = 0; lev <= m_finest_level; ++lev) { const LevelSigmaCS& levelCoords = *a_coordSys[lev]; const Vector<Real>& sigma = levelCoords.getSigma(); a_A[lev] = new LevelData<FArrayBox>(m_amrGrids[lev], m_nLayers, IntVect::Unit); IceUtility::computeA(*a_A[lev], sigma, levelCoords, m_rateFactor, *a_internalEnergy[lev] ); Vector<Real> sSigma(1,0.0); a_sA[lev] = new LevelData<FArrayBox>(m_amrGrids[lev],1, IntVect::Unit); IceUtility::computeA(*a_sA[lev], sSigma, levelCoords, m_rateFactor, *a_sInternalEnergy[lev]); Vector<Real> bSigma(1,1.0); a_bA[lev] = new LevelData<FArrayBox>(m_amrGrids[lev],1, IntVect::Unit); IceUtility::computeA(*a_bA[lev], bSigma, levelCoords, m_rateFactor, *a_bInternalEnergy[lev]); }//end loop over AMR levels if (s_verbosity > 0) { Real Amin = computeMin(a_A, m_refinement_ratios, Interval(0,a_A[0]->nComp()-1)); Real Amax = computeMax(a_A, m_refinement_ratios, Interval(0,a_A[0]->nComp()-1)); pout() << Amin << " <= A(x,y,sigma) <= " << Amax << std::endl; } } #endif /// diagnostic function -- integrates thickness over domain Real AmrIce::computeTotalIce() const { Vector<LevelData<FArrayBox>* > thickness(m_finest_level+1, NULL); for (int lev=0; lev<=m_finest_level; lev++) { const LevelSigmaCS& levelCoords = *m_vect_coordSys[lev]; // need a const_cast to make things all line up right // (but still essentially const) thickness[lev] = const_cast<LevelData<FArrayBox>* >(&levelCoords.getH()); } Interval thicknessInt(0,0); Real totalIce = computeSum(thickness, m_refinement_ratios, m_amrDx[0], thicknessInt, 0); return totalIce; } void AmrIce::computeAreaFraction(LevelData<FArrayBox>& a_area, int a_maskVal, int a_level) const { CH_assert(a_level <= m_finest_level) { const LevelData<BaseFab<int> >& levelMask = m_vect_coordSys[a_level]->getFloatingMask(); // set a_area = 1.0 where we have grounded ice DataIterator dit=a_area.dataIterator(); for (dit.begin(); dit.ok(); ++dit) { const BaseFab<int>& thisMask = levelMask[dit]; FArrayBox& thisIce = a_area[dit]; thisIce.setVal(0.0); BoxIterator bit(thisIce.box()); for (bit.begin(); bit.ok(); ++bit) { IntVect iv = bit(); if (thisMask(iv,0) == a_maskVal) { thisIce(iv,0) = 1.0; } } } } } void AmrIce::setLayers(const Vector<Real>& a_sigma) { if (m_sigmaSet) MayDay::Error("AmrIce::SetLayers should only be called once"); m_faceSigma = a_sigma; m_nLayers = m_faceSigma.size()-1; CH_assert(m_nLayers > 0 && m_faceSigma[0] < TINY_NORM && abs(m_faceSigma[m_nLayers] - 1.0) < TINY_NORM); m_sigmaSet = true; } void AmrIce::incrementIceThickness (Vector<LevelData<FArrayBox>*> a_delta_thk) { for (int lev = 0 ; lev <= m_finest_level; lev++) { LevelSigmaCS& coords = *m_vect_coordSys[lev]; LevelData<FArrayBox>& thk = coords.getH(); for (DataIterator dit( m_amrGrids[lev]); dit.ok(); ++dit) { thk[dit] += ( (*a_delta_thk[lev])[dit] ); } } // average down thickness and topography to coarser levels, fill in ghost cells int Hghost = 2; Vector<LevelData<FArrayBox>* > vectH(m_finest_level+1, NULL); for (int lev=0; lev<vectH.size(); lev++) { IntVect HghostVect = Hghost*IntVect::Unit; LevelSigmaCS& levelCoords = *(m_vect_coordSys[lev]); vectH[lev] = &levelCoords.getH(); } //average from the finest level down for (int lev = finestTimestepLevel() ; lev > 0 ; lev--) { CoarseAverage averager(m_amrGrids[lev], 1, m_refinement_ratios[lev-1]); averager.averageToCoarse(*vectH[lev-1], *vectH[lev]); } // now pass back over and do PiecewiseLinearFillPatch for (int lev=1; lev<vectH.size(); lev++) { PiecewiseLinearFillPatch filler(m_amrGrids[lev], m_amrGrids[lev-1], 1, m_amrDomains[lev-1], m_refinement_ratios[lev-1], Hghost); Real interp_coef = 0; filler.fillInterp(*vectH[lev], *vectH[lev-1], *vectH[lev-1], interp_coef, 0, 0, 1); } //re-fill ghost cells ouside the domain for (int lev=0; lev <= finestTimestepLevel() ; ++lev) { RealVect levelDx = m_amrDx[lev]*RealVect::Unit; m_thicknessIBCPtr->setGeometryBCs(*m_vect_coordSys[lev], m_amrDomains[lev],levelDx, m_time, m_dt); } //allow calving model to modify geometry and velocity //applyCalvingCriterion(CalvingModel::PostThicknessAdvection); //dont allow thickness to be negative for (int lev=0; lev<= m_finest_level; lev++) { DisjointBoxLayout& levelGrids = m_amrGrids[lev]; LevelSigmaCS& levelCoords = *(m_vect_coordSys[lev]); LevelData<FArrayBox>& levelH = levelCoords.getH(); DataIterator dit = levelGrids.dataIterator(); for (DataIterator dit(levelGrids); dit.ok(); ++dit) { Real lim = 0.0; FORT_MAXFAB1(CHF_FRA(levelH[dit]), CHF_CONST_REAL(lim), CHF_BOX(levelH[dit].box())); } } //average from the finest level down for (int lev = finestTimestepLevel() ; lev > 0 ; lev--) { CoarseAverage averager(m_amrGrids[lev], 1, m_refinement_ratios[lev-1]); averager.averageToCoarse(*vectH[lev-1], *vectH[lev]); } for (int lev=1; lev<vectH.size(); lev++) { PiecewiseLinearFillPatch filler(m_amrGrids[lev], m_amrGrids[lev-1], 1, m_amrDomains[lev-1], m_refinement_ratios[lev-1], Hghost); Real interp_coef = 0; filler.fillInterp(*vectH[lev], *vectH[lev-1], *vectH[lev-1], interp_coef, 0, 0, 1); } // recompute thickness-derived data in SigmaCS for (int lev=0; lev<= m_finest_level; lev++) { LevelSigmaCS& levelCoords = *(m_vect_coordSys[lev]); LevelSigmaCS* crseCoords = (lev > 0)?&(*m_vect_coordSys[lev-1]):NULL; int refRatio = (lev > 0)?m_refinement_ratios[lev-1]:-1; levelCoords.recomputeGeometry(crseCoords, refRatio); } } #include "NamespaceFooter.H"
31.306916
136
0.612901
[ "geometry", "object", "vector", "model", "3d" ]
853c640e162322cba767874454daced9227a9dd2
11,941
cpp
C++
lib/IRremoteESP8266/src/ir_Truma.cpp
Eliauk-Forever/JARVIS
69569e530f0bc66c90bc2ba2a266edb65006bd6f
[ "MulanPSL-1.0" ]
14
2019-07-09T09:38:59.000Z
2022-02-11T13:57:18.000Z
lib/IRremoteESP8266/src/ir_Truma.cpp
Eliauk-Forever/JARVIS
69569e530f0bc66c90bc2ba2a266edb65006bd6f
[ "MulanPSL-1.0" ]
null
null
null
lib/IRremoteESP8266/src/ir_Truma.cpp
Eliauk-Forever/JARVIS
69569e530f0bc66c90bc2ba2a266edb65006bd6f
[ "MulanPSL-1.0" ]
1
2021-06-26T22:26:58.000Z
2021-06-26T22:26:58.000Z
// Copyright 2021 David Conran (crankyoldgit) /// @file /// @brief Support for Truma protocol. /// This protocol uses mark length bit encoding. /// @see https://github.com/crankyoldgit/IRremoteESP8266/issues/1440 /// @see https://docs.google.com/spreadsheets/d/1k-RHu0vSIB6IweiTZSa3Rxy3Z_qPUtqwcqot8uXVO6I/edit?usp=sharing #include "ir_Truma.h" #include <algorithm> #include "IRrecv.h" #include "IRsend.h" #include "IRtext.h" #include "IRutils.h" using irutils::addBoolToString; using irutils::addFanToString; using irutils::addModeToString; using irutils::addTempToString; // Constants const uint16_t kTrumaLdrMark = 20200; const uint16_t kTrumaLdrSpace = 1000; const uint16_t kTrumaHdrMark = 1800; const uint16_t kTrumaSpace = 630; const uint16_t kTrumaOneMark = 600; const uint16_t kTrumaZeroMark = 1200; const uint16_t kTrumaFooterMark = kTrumaOneMark; const uint32_t kTrumaGap = kDefaultMessageGap; // Just a guess. #if SEND_TRUMA /// Send a Truma formatted message. /// Status: STABLE / Confirmed working. /// @param[in] data The message to be sent. /// @param[in] nbits The bit size of the message being sent. /// @param[in] repeat The number of times the message is to be repeated. void IRsend::sendTruma(const uint64_t data, const uint16_t nbits, const uint16_t repeat) { for (uint16_t r = 0; r <= repeat; r++) { enableIROut(38000); mark(kTrumaLdrMark); space(kTrumaLdrSpace); sendGeneric(kTrumaHdrMark, kTrumaSpace, // Header kTrumaOneMark, kTrumaSpace, // Data kTrumaZeroMark, kTrumaSpace, kTrumaFooterMark, kTrumaGap, // Footer data, nbits, 38, false, 0, kDutyDefault); } } #endif // SEND_TRUMA #if DECODE_TRUMA /// Decode the supplied Truma message. /// Status: STABLE / Confirmed working with real device. /// @param[in,out] results Ptr to the data to decode & where to store the decode /// result. /// @param[in] offset The starting index to use when attempting to decode the /// raw data. Typically/Defaults to kStartOffset. /// @param[in] nbits The number of data bits to expect. Typically kTrumaBits. /// @param[in] strict Flag indicating if we should perform strict matching. /// @return A boolean. True if it can decode it, false if it can't. bool IRrecv::decodeTruma(decode_results *results, uint16_t offset, const uint16_t nbits, const bool strict) { if (results->rawlen < 2 * nbits + kHeader - 1 + offset) return false; // Can't possibly be a valid message. if (strict && nbits != kTrumaBits) return false; // Not strictly a message. // Leader. if (!matchMark(results->rawbuf[offset++], kTrumaLdrMark)) return false; if (!matchSpace(results->rawbuf[offset++], kTrumaLdrSpace)) return false; uint64_t data = 0; uint16_t used; used = matchGeneric(results->rawbuf + offset, &data, results->rawlen - offset, nbits, kTrumaHdrMark, kTrumaSpace, kTrumaOneMark, kTrumaSpace, kTrumaZeroMark, kTrumaSpace, kTrumaFooterMark, kTrumaGap, true, kUseDefTol, kMarkExcess, false); if (!used) return false; // Compliance if (strict && !IRTrumaAc::validChecksum(data)) return false; // Checksum. // Success results->value = data; results->decode_type = decode_type_t::TRUMA; results->bits = nbits; results->address = 0; results->command = 0; return true; } #endif // DECODE_TRUMA /// Class constructor /// @param[in] pin GPIO to be used when sending. /// @param[in] inverted Is the output signal to be inverted? /// @param[in] use_modulation Is frequency modulation to be used? IRTrumaAc::IRTrumaAc(const uint16_t pin, const bool inverted, const bool use_modulation) : _irsend(pin, inverted, use_modulation) { stateReset(); } /// Set up hardware to be able to send a message. void IRTrumaAc::begin(void) { _irsend.begin(); } #if SEND_TRUMA /// Send the current internal state as an IR message. /// @param[in] repeat Nr. of times the message will be repeated. void IRTrumaAc::send(const uint16_t repeat) { _irsend.sendTruma(getRaw(), kTrumaBits, repeat); } #endif // SEND_TRUMA /// Calculate the checksum for a given state. /// @param[in] state The value to calc the checksum of. /// @return The calculated checksum value. uint8_t IRTrumaAc::calcChecksum(const uint64_t state) { uint8_t sum = kTrumaChecksumInit; uint64_t to_checksum = state; for (uint16_t i = 8; i < kTrumaBits; i += 8) { sum += (to_checksum & 0xFF); to_checksum >>= 8; } return sum; } /// Verify the checksum is valid for a given state. /// @param[in] state The value to verify the checksum of. /// @return true, if the state has a valid checksum. Otherwise, false. bool IRTrumaAc::validChecksum(const uint64_t state) { TrumaProtocol state_copy; state_copy.raw = state; return state_copy.Sum == calcChecksum(state); } /// Calculate & set the checksum for the current internal state of the remote. void IRTrumaAc::checksum(void) { _.Sum = calcChecksum(_.raw); } /// Reset the state of the remote to a known good state/sequence. void IRTrumaAc::stateReset(void) { setRaw(kTrumaDefaultState); } /// Get a copy of the internal state/code for this protocol. /// @return The code for this protocol based on the current internal state. uint64_t IRTrumaAc::getRaw(void) { checksum(); return _.raw; } /// Set the internal state from a valid code for this protocol. /// @param[in] state A valid code for this protocol. void IRTrumaAc::setRaw(const uint64_t state) { _.raw = state; _lastfan = _.Fan; _lastmode = _.Mode; } /// Set the requested power state of the A/C to on. void IRTrumaAc::on(void) { setPower(true); } /// Set the requested power state of the A/C to off. void IRTrumaAc::off(void) { setPower(false); } /// Change the power setting. /// @param[in] on true, the setting is on. false, the setting is off. void IRTrumaAc::setPower(const bool on) { _.PowerOff = !on; _.Mode = on ? _lastmode : kTrumaFan; // Off temporarily sets mode to Fan. } /// Get the value of the current power setting. /// @return true, the setting is on. false, the setting is off. bool IRTrumaAc::getPower(void) const { return !_.PowerOff; } /// Set the speed of the fan. /// @param[in] speed The desired setting. void IRTrumaAc::setFan(const uint8_t speed) { switch (speed) { case kTrumaFanHigh: case kTrumaFanMed: case kTrumaFanLow: _lastfan = speed; // Never allow _lastfan to be Quiet. _.Fan = speed; break; case kTrumaFanQuiet: if (_.Mode == kTrumaCool) _.Fan = kTrumaFanQuiet; // Only in Cool mode. break; default: setFan(kTrumaFanHigh); } } /// Get the current fan speed setting. /// @return The current fan speed/mode. uint8_t IRTrumaAc::getFan(void) const { return _.Fan; } /// Set the operating mode of the A/C. /// @param[in] mode The desired operating mode. void IRTrumaAc::setMode(const uint8_t mode) { switch (mode) { case kTrumaAuto: case kTrumaFan: if (getQuiet()) setFan(kTrumaFanHigh); // Can only have quiet in Cool. // FALL THRU case kTrumaCool: _.Mode = _.PowerOff ? kTrumaFan : mode; // When Off, only set Fan mode. _lastmode = mode; break; default: setMode(kTrumaAuto); } } /// Get the operating mode setting of the A/C. /// @return The current operating mode setting. uint8_t IRTrumaAc::getMode(void) const { return _.Mode; } /// Set the temperature. /// @param[in] celsius The temperature in degrees celsius. void IRTrumaAc::setTemp(const uint8_t celsius) { uint8_t temp = std::max(celsius, kTrumaMinTemp); temp = std::min(temp, kTrumaMaxTemp); _.Temp = temp - kTrumaTempOffset; } /// Get the current temperature setting. /// @return The current setting for temp. in degrees celsius. uint8_t IRTrumaAc::getTemp(void) const { return _.Temp + kTrumaTempOffset; } /// Change the Quiet setting. /// @param[in] on true, the setting is on. false, the setting is off. /// @note Quiet is only available in Cool mode. void IRTrumaAc::setQuiet(const bool on) { if (on && _.Mode == kTrumaCool) setFan(kTrumaFanQuiet); else setFan(_lastfan); } /// Get the value of the current quiet setting. /// @return true, the setting is on. false, the setting is off. bool IRTrumaAc::getQuiet(void) const { return _.Fan == kTrumaFanQuiet; } /// Convert a stdAc::opmode_t enum into its native mode. /// @param[in] mode The enum to be converted. /// @return The native equivalent of the enum. uint8_t IRTrumaAc::convertMode(const stdAc::opmode_t mode) { switch (mode) { case stdAc::opmode_t::kCool: return kTrumaCool; case stdAc::opmode_t::kFan: return kTrumaFan; default: return kTrumaAuto; } } /// Convert a stdAc::fanspeed_t enum into it's native speed. /// @param[in] speed The enum to be converted. /// @return The native equivalent of the enum. uint8_t IRTrumaAc::convertFan(const stdAc::fanspeed_t speed) { switch (speed) { case stdAc::fanspeed_t::kMin: return kTrumaFanQuiet; case stdAc::fanspeed_t::kLow: return kTrumaFanLow; case stdAc::fanspeed_t::kMedium: return kTrumaFanMed; default: return kTrumaFanHigh; } } /// Convert a native mode into its stdAc equivalent. /// @param[in] mode The native setting to be converted. /// @return The stdAc equivalent of the native setting. stdAc::opmode_t IRTrumaAc::toCommonMode(const uint8_t mode) { switch (mode) { case kTrumaCool: return stdAc::opmode_t::kCool; case kTrumaFan: return stdAc::opmode_t::kFan; default: return stdAc::opmode_t::kAuto; } } /// Convert a native fan speed into its stdAc equivalent. /// @param[in] spd The native setting to be converted. /// @return The stdAc equivalent of the native setting. stdAc::fanspeed_t IRTrumaAc::toCommonFanSpeed(const uint8_t spd) { switch (spd) { case kTrumaFanMed: return stdAc::fanspeed_t::kMedium; case kTrumaFanLow: return stdAc::fanspeed_t::kLow; case kTrumaFanQuiet: return stdAc::fanspeed_t::kMin; default: return stdAc::fanspeed_t::kHigh; } } /// Convert the current internal state into its stdAc::state_t equivalent. /// @return The stdAc equivalent of the native settings. stdAc::state_t IRTrumaAc::toCommon(void) const { stdAc::state_t result; result.protocol = decode_type_t::TRUMA; result.model = -1; // Not supported. // Do we have enough current state info to override any previous state? // i.e. Was the class just setRaw()'ed with a short "swing" message. // This should enables us to also ignore the Swing msg's special 17C setting. result.power = getPower(); result.mode = toCommonMode(getMode()); result.celsius = true; result.degrees = getTemp(); result.fanspeed = toCommonFanSpeed(getFan()); result.quiet = getQuiet(); // Not supported. result.turbo = false; result.econo = false; result.light = false; result.filter = false; result.swingv = stdAc::swingv_t::kOff; result.swingh = stdAc::swingh_t::kOff; result.clean = false; result.beep = false; result.sleep = -1; result.clock = -1; return result; } /// Convert the current internal state into a human readable string. /// @return A human readable string. String IRTrumaAc::toString(void) const { String result = ""; result.reserve(80); result += addBoolToString(getPower(), kPowerStr, false); if (getPower()) // Only show the Operating Mode if the unit is on. result += addModeToString(_.Mode, kTrumaAuto, kTrumaCool, kTrumaAuto, kTrumaAuto, kTrumaFan); result += addTempToString(getTemp()); result += addFanToString(_.Fan, kTrumaFanHigh, kTrumaFanLow, kTrumaFanHigh, kTrumaFanQuiet, kTrumaFanMed); result += addBoolToString(getQuiet(), kQuietStr); return result; }
35.017595
109
0.689473
[ "model" ]
8543a0f36c10f0db060d98037cf7b59fd57db99f
2,629
cpp
C++
GongDolHoon/OpenGlSample/renderer.cpp
qkrtmdgns23/GameEngineArchitecture_GDH_Engine
042c3b04ffbacaccce22aea9a763dba35153d07d
[ "MIT" ]
1
2020-10-28T07:08:39.000Z
2020-10-28T07:08:39.000Z
GongDolHoon/OpenGlSample/renderer.cpp
qkrtmdgns23/GameEngineArchitecture_GDH_Engine
042c3b04ffbacaccce22aea9a763dba35153d07d
[ "MIT" ]
1
2020-10-30T12:18:24.000Z
2020-10-31T08:59:58.000Z
GongDolHoon/OpenGlSample/renderer.cpp
qkrtmdgns23/GameEngineArchitecture_GDH_Engine
042c3b04ffbacaccce22aea9a763dba35153d07d
[ "MIT" ]
null
null
null
#include <iostream> // library #include "include/GL/glew.h" #include "glm/gtc/matrix_transform.hpp" // custom header #include "renderer.h" namespace gdh_engine { namespace manager { Renderer* Renderer::instance_ = nullptr; Renderer::Renderer(const char* title, const unsigned int kMajorVersion, const unsigned int kMinorVersion, const unsigned int kWindowHeight, const unsigned int kWindowWidth) : kGlfwContextMajorVersion(kMajorVersion), kGlfwContextMinorVersion(kMinorVersion) { this->engine_window_title_ = title; this->window_height_ = kWindowHeight; this->window_width_ = kWindowWidth; this->engine_window_ = nullptr; glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, kGlfwContextMajorVersion); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, kGlfwContextMinorVersion); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); this->engine_window_ = glfwCreateWindow(window_width_, window_height_, engine_window_title_.c_str(), NULL, NULL); if (engine_window_ == NULL) { fprintf(stderr, "Failed to Create Glfw Window.\n"); glfwTerminate(); } glfwMakeContextCurrent(engine_window_); glfwSetFramebufferSizeCallback(engine_window_, ResizeWindowFrameBuffer); glewExperimental = true; // Needed for core profile if (glewInit() != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW\n"); glfwTerminate(); } glEnable(GL_DEPTH_TEST); } void Renderer::ShutDown() { glfwTerminate(); } void Renderer::ClearWindowToRender() { glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void Renderer::SwapBuffearsOnWindow() { glfwSwapBuffers(engine_window_); glfwPollEvents(); } bool Renderer::IsWindowShouldClose() { if (glfwWindowShouldClose(this->engine_window_)) { return true; } else { return false; } } void Renderer::ConvertCoordinatesForRender(object::Camera* camera, object::VisibleObject* target_object) { projection_matrix_ = glm::perspective(glm::radians(camera->get_zoom()), (float)1024 / 728, 0.1f, 100.0f); view_matrix_ = camera->get_view_matrix(); target_object->SendProjectionAndViewMatrixToShader(projection_matrix_, view_matrix_); } void Renderer::Render(object::VisibleObject* target_obj) { ClearWindowToRender(); target_obj->ActiveTextureRendering(); target_obj->Render(); SwapBuffearsOnWindow(); } void Renderer::ResizeWindowFrameBuffer(GLFWwindow* window, int fbw, int fbh) { glViewport(0, 0, fbw, fbh); } } // namespace manager } // namespace gdh_engine
26.555556
116
0.731076
[ "render", "object" ]
8544d4fa45319d9e67e41a91dd580d22b9c5b0e8
1,620
cpp
C++
CSGOSimple/features/skins/parser.cpp
YMY1666527646/CustomHooks-csgo
c79cb831dbcab044969abf556b5bfe6fab5b187c
[ "MIT" ]
7
2022-02-08T18:19:07.000Z
2022-03-25T22:17:55.000Z
CSGOSimple/features/skins/parser.cpp
Kajus14/CustomHooks-csgo
aebc092ff4c5930ec7672501ba5b450dc0cbe5ba
[ "MIT" ]
null
null
null
CSGOSimple/features/skins/parser.cpp
Kajus14/CustomHooks-csgo
aebc092ff4c5930ec7672501ba5b450dc0cbe5ba
[ "MIT" ]
5
2022-02-04T09:29:11.000Z
2022-03-21T15:09:13.000Z
#include "parser.h" namespace valve_parser { object::object(document* doc) : node(doc) {} object* object::to_object() { return this; } std::shared_ptr<node> object::get_key_by_name(char* name) { for (auto& child : children) { if (child->to_key_value()) { if (util::str_equ(child->to_key_value()->key, name)) return child; } } return nullptr; } bool object::parse() { std::shared_ptr<node> n; while (*_doc->p_) { //check for object close const auto string_begin = str::parse_text_expected_tag(_doc->p_, STRING, true); if (!string_begin) { const auto obj_close = str::parse_text_expected_tag(_doc->p_, OBJECT_CLOSE, true); if (obj_close) { _doc->p_ = obj_close + 1; return true; } else return false; } if (!_doc->identify(n)) return false; if (n->to_key_value()) { this->children.push_back(n); } if (n->to_object()) { this->children.push_back(n); object* obj = n->to_object(); if (!obj->parse()) return false; } } return false; } bool node::parse() { std::shared_ptr<node> n; while (*_doc->p_) { if (!_doc->identify(n)) { if (!str::end_reached(_doc->p_, OBJECT_OPEN) && !str::end_reached(_doc->p_, OBJECT_CLOSE) && !str::end_reached(_doc->p_, STRING)) return true; else return false; } if (n->to_key_value()) { this->children.push_back(n); } if (n->to_object()) { this->children.push_back(n); object* obj = n->to_object(); if (!obj->parse()) return false; } } return false; } }
17.052632
86
0.582099
[ "object" ]
855cfa114d4bdaae81c0d722cf44e7da52a4d744
1,330
hpp
C++
test/util.hpp
amallia/Simple
63ae6cf58ab3a34cef94b910c9fe245f6f95c4b5
[ "Apache-2.0" ]
1
2020-03-17T14:34:16.000Z
2020-03-17T14:34:16.000Z
test/util.hpp
amallia/Simple
63ae6cf58ab3a34cef94b910c9fe245f6f95c4b5
[ "Apache-2.0" ]
null
null
null
test/util.hpp
amallia/Simple
63ae6cf58ab3a34cef94b910c9fe245f6f95c4b5
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2018-present Antonio Mallia <me@antoniomallia.it> * * 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 <vector> #include <random> #include <limits> std::vector<uint32_t> generate_random_vector(size_t n, uint32_t max_value = std::numeric_limits<uint32_t>::max()) { std::random_device rd; std::mt19937 gen(rd()); std::vector<uint32_t> values(n); std::uniform_int_distribution<> dis(uint32_t(0), max_value); std::generate(values.begin(), values.end(), [&](){ return dis(gen); }); return values; } void make_strict(std::vector<uint32_t> &vec){ for (size_t i = 1; i < vec.size(); ++i) { vec[i] += vec[i-1]; } } void delta_encode(std::vector<uint32_t> &vec){ for (size_t i = 1; i < vec.size(); ++i) { vec[i] -= vec[i-1]; } }
30.930233
115
0.672932
[ "vector" ]
85641f7669f74ef7d59e2a223490dfd18ab7a966
6,528
cpp
C++
code/src/pdflib/cidfontdictionary.cpp
jgresula/jagpdf
6c36958b109e6522e6b57d04144dd83c024778eb
[ "MIT" ]
54
2015-02-16T14:25:16.000Z
2022-03-16T07:54:25.000Z
code/src/pdflib/cidfontdictionary.cpp
jgresula/jagpdf
6c36958b109e6522e6b57d04144dd83c024778eb
[ "MIT" ]
null
null
null
code/src/pdflib/cidfontdictionary.cpp
jgresula/jagpdf
6c36958b109e6522e6b57d04144dd83c024778eb
[ "MIT" ]
30
2015-03-05T08:52:25.000Z
2022-02-17T13:49:15.000Z
// Copyright (c) 2005-2009 Jaroslav Gresula // // Distributed under the MIT license (See accompanying file // LICENSE.txt or copy at http://jagpdf.org/LICENSE.txt) // #include "precompiled.h" #include "cidfontdictionary.h" #include "pdffont.h" #include "objfmt.h" #include "docwriterimpl.h" #include "resourcemanagement.h" #include "fontdictionary.h" #include "fontdescriptor.h" #include "datatypecasts.h" #include <core/jstd/unicode.h> #include <core/generic/scopeguard.h> #include <resources/typeman/typefaceutils.h> using namespace jag::jstd; namespace jag { namespace pdf { namespace { } ////////////////////////////////////////////////////////////////////////// CIDFontDictionary::CIDFontDictionary(DocWriterImpl& doc, FontDictionary& dict) : IndirectObjectImpl(doc) , m_fdict(dict) { JAG_PRECONDITION(PDFFontData::COMPOSITE_FONT == m_fdict.fdict_data().font_data().font_type()); } ////////////////////////////////////////////////////////////////////////// void CIDFontDictionary::on_output_definition() { // !! As far CIDSystemInfo dictionary is concerned at the moment of writing this I'm not // quite sure whether it has any sense to use any TrueType fonts with predefined // CIDSystemInfo dictionaries or Identity should be always used. // // If it is not really possible then we have to detect it sooner during font registration // and set font encoding to identity when TrueType is used std::pair<char const*, int> collection = character_collection_str(m_fdict.fdict_data().font_encoding(), doc().version()); object_writer() .dict_start() .dict_key("Type").output("Font") .dict_key("BaseFont").name(m_fdict.font_descriptor()->basename()) .dict_key("FontDescriptor").space().ref(*m_fdict.font_descriptor()) .dict_key("CIDSystemInfo") .dict_start() .dict_key("Registry").text_string("Adobe") .dict_key("Ordering").text_string(collection.first) .dict_key("Supplement").space().output(collection.second) .dict_end() ; // typeface distingiuish type2 and type0 based on typeface type object_writer().dict_key("Subtype"); FaceType face_type = m_fdict.fdict_data().font_data().typeface().type(); switch(face_type) { case FACE_TRUE_TYPE: object_writer().output("CIDFontType2"); break; case FACE_OPEN_TYPE_CFF: object_writer().output("CIDFontType0"); break; default: // find out what is allowed here JAG_TBD; } output_widths(); object_writer().dict_end(); } ////////////////////////////////////////////////////////////////////////// void CIDFontDictionary::output_widths() { ITypeface const& face(m_fdict.fdict_data().typeface()); resources::FontSpaceToGlyphSpace fs2gs(face.metrics()); ObjFmt& writer(object_writer()); writer .dict_key("DW") .space() .output(fs2gs(face.metrics().missing_width)) ; // retrieve used cids UsedGlyphs::Glyphs const& used_glyphs(m_fdict.get_used_cids().glyphs()); std::vector<UInt16> cids; cids.reserve(used_glyphs.size()); std::copy(used_glyphs.begin(), used_glyphs.end(), std::back_inserter(cids)); std::vector<Int> widths; JAG_ASSERT(cids.size()); fetch_widths(cids, widths); writer .dict_key("W") .array_start() ; UInt start_cid = cids[0]; size_t start_cid_index = 0; enum { RANGE_CLOSED, RANGE_OPENED } status = RANGE_CLOSED; const size_t cids_len = cids.size(); for(size_t i=1; i<cids_len; ++i) { if (RANGE_CLOSED == status) { // range start writer .output(start_cid) .array_start() .output(widths[start_cid_index]) ; status = RANGE_OPENED; } if (cids[i] == cids[i-1]+1) { // range continuation JAG_ASSERT(status == RANGE_OPENED); writer .space() .output(widths[i]) ; } else { // range end writer.array_end(); status = RANGE_CLOSED; start_cid = cids[i]; start_cid_index = i; } } if (RANGE_OPENED == status) { writer.array_end(); } else { // last orphaned gid writer .output(start_cid) .array_start() .output(widths[start_cid_index] ) .array_end() ; } writer.array_end(); } /** * @brief For given vector of cids fetches corresponding widths from typeface. * * @param cids encoded characters or glyph indices (determined by font dictionary encoding) * @param widths filled in with corresponding widhts (in glyph space) */ void CIDFontDictionary::fetch_widths(std::vector<UInt16> const& cids, std::vector<Int>& widths) { ITypeface const& face(m_fdict.fdict_data().typeface()); resources::FontSpaceToGlyphSpace fs2gs(face.metrics()); // Font dictionary can be formed either by encoded characters (cids) or // glyph indices (gids). widths.reserve(cids.size()); const size_t cids_len = cids.size(); if (ENC_IDENTITY == m_fdict.fdict_data().font_encoding()) { // gids for(size_t i=0; i<cids_len; ++i) widths.push_back(fs2gs(face.gid_horizontal_advance(cids[i]))); } else { // cids std::vector<Char> cids_byte_arr(cids_len*2); for(size_t i=0,j=0; i<cids_len; ++i) { cids_byte_arr[++j] = static_cast<Char>(cids[i] & 8); cids_byte_arr[++j] = static_cast<Char>(cids[i] >> 8); } UnicodeConverter* conv(m_fdict.acquire_converter()); JAG_ASSERT(conv); ON_BLOCK_EXIT_OBJ(m_fdict, &FontDictionary::release_converter); std::vector<Int> codepoints; codepoints.reserve(cids_len); JAG_ASSERT(cids_byte_arr.size()); Char const* cids_start = &cids_byte_arr[0]; Char const*const cids_end = cids_start + cids_byte_arr.size(); while (cids_start!=cids_end) codepoints.push_back(conv->next_code_point(&cids_start, cids_end)); JAG_ASSERT_MSG(cids_len==codepoints.size(), "?number of codepoints should correspond to #cids"); for(size_t i=0; i<cids_len; ++i) widths.push_back(fs2gs(face.char_horizontal_advance(codepoints[i]))); } } }} //namespace jag::pdf
28.137931
125
0.605086
[ "vector" ]
856627c38d5bbd5d3df35cb864553ae06f1c9f88
2,044
cpp
C++
src/Skybox.cpp
Loic-Corenthy/miniGL
47976ea80e253e115eafae5934ec3ebdd2275d16
[ "MIT" ]
1
2021-08-18T03:54:22.000Z
2021-08-18T03:54:22.000Z
src/Skybox.cpp
Loic-Corenthy/miniGL
47976ea80e253e115eafae5934ec3ebdd2275d16
[ "MIT" ]
null
null
null
src/Skybox.cpp
Loic-Corenthy/miniGL
47976ea80e253e115eafae5934ec3ebdd2275d16
[ "MIT" ]
null
null
null
//===============================================================================================// /*! * \file Skybox.cpp * \author Loïc Corenthy * \version 1.0 */ //===============================================================================================// #include "Skybox.hpp" #include <cassert> #include "Transform.hpp" #include "EngineCommon.hpp" using std::make_unique; using std::shared_ptr; using std::string; using std::initializer_list; using miniGL::SkyBox; using miniGL::SkyBoxRender; using miniGL::CubemapTexture; using miniGL::MeshAOS; using miniGL::Transform; using miniGL::Camera; SkyBox::SkyBox(shared_ptr<Camera> pCamera) :mCamera(pCamera) { } SkyBox::~SkyBox(void) { } void SkyBox::init(const initializer_list<string> & pFilenames) { mRenderer = make_unique<SkyBoxRender>(); mRenderer->init("./Shaders/SkyBox.vert", "./Shaders/SkyBox.frag"); mRenderer->use(); mRenderer->textureUnit(COLOR_TEXTURE_UNIT_INDEX); mCubemapTexture = make_unique<CubemapTexture>(); mCubemapTexture->load(pFilenames); mBox = make_unique<MeshAOS>(); mBox->load("./sphere.obj"); // Validate our program with the mesh (box) mBox->bindVAO(0); mRenderer->validate(); mBox->unbindVAO(); } void SkyBox::render(void) { mRenderer->use(); GLint lOldCullFaceMode; glGetIntegerv(GL_CULL_FACE_MODE, & lOldCullFaceMode); GLint lOldDepthMode; glGetIntegerv(GL_DEPTH_FUNC, & lOldDepthMode); // glEnable(GL_CULL_FACE); // Using front face culling makes the skybox disapear -> go normal back face culling //glCullFace(GL_FRONT); glDepthFunc(GL_LEQUAL); Transform lTransformation; lTransformation.scaling(100.0f,100.0f,100.0f); mat4f lWorld = lTransformation.final(); mat4f lWVP = mCamera->projection() * mCamera->view() * lWorld; mRenderer->WVP(lWVP); mCubemapTexture->bind(COLOR_TEXTURE_UNIT); mBox->render(); glCullFace(lOldCullFaceMode); glDepthFunc(lOldDepthMode); // glDisable(GL_CULL_FACE); }
23.227273
99
0.630137
[ "mesh", "render", "transform" ]
85663406da34259569469b83ec37953de1bf2ab3
17,001
cpp
C++
pong.cpp
AlexViaColl/Pong2
2e34263893c1154731cdecb84265de67fafdba61
[ "MIT" ]
null
null
null
pong.cpp
AlexViaColl/Pong2
2e34263893c1154731cdecb84265de67fafdba61
[ "MIT" ]
null
null
null
pong.cpp
AlexViaColl/Pong2
2e34263893c1154731cdecb84265de67fafdba61
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/keysym.h> #include <GL/glx.h> #include <alsa/asoundlib.h> typedef unsigned char u8; typedef unsigned short u16; typedef unsigned int u32; typedef unsigned long long u64; typedef signed char s8; typedef signed short s16; typedef signed int s32; typedef signed long long s64; typedef float f32; typedef double f64; typedef u32 RGBA; struct Glyph { u8 width; u8 height; u8 data[32]; }; int WINDOW_WIDTH = 800; int WINDOW_HEIGHT = 600; const char *WINDOW_CAPTION = "Pong"; void set_projection_matrix(f32 width, f32 height) { glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Convert from screen space (left-right, top-down) to NDC GLfloat proj_mat[] = { 2.0f / width, 0.0f, 0.0f, -1.0f, 0.0f, 2.0f / -height, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; glLoadTransposeMatrixf(proj_mat); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void draw_quad(f32 x, f32 y, f32 width, f32 height, RGBA color = 0) { set_projection_matrix(800.0f, 600.0f); glBegin(GL_QUADS); f32 r = ((color >> 24) & 0xFF) / 255.0f; f32 g = ((color >> 16) & 0xFF) / 255.0f; f32 b = ((color >> 8) & 0xFF) / 255.0f; glColor3f(r, g, b); glVertex2f(x, y); glVertex2f(x + width, y); glVertex2f(x + width, y + height); glVertex2f(x, y + height); glEnd(); } void draw_line(f32 xstart, f32 ystart, f32 xend, f32 yend) { set_projection_matrix(800.0f, 600.0f); glBegin(GL_LINES); glColor3f(1.0f, 1.0f, 1.0f); glVertex2f(xstart, ystart); glVertex2f(xend, yend); glEnd(); } void draw_number(u8 number, f32 x, f32 y) { // assert(0 <= number <= 9); u8 font_data[10][3*5] = { {1,1,1, 1,0,1, 1,0,1, 1,0,1, 1,1,1}, // 0 {1,1,0, 0,1,0, 0,1,0, 0,1,0, 1,1,1}, // 1 {1,1,1, 0,0,1, 1,1,1, 1,0,0, 1,1,1}, // 2 {1,1,1, 0,0,1, 0,1,1, 0,0,1, 1,1,1}, // 3 {1,0,1, 1,0,1, 1,1,1, 0,0,1, 0,0,1}, // 4 {1,1,1, 1,0,0, 1,1,1, 0,0,1, 1,1,1}, // 5 {1,1,1, 1,0,0, 1,1,1, 1,0,1, 1,1,1}, // 6 {1,1,1, 0,0,1, 0,0,1, 0,0,1, 0,0,1}, // 7 {1,1,1, 1,0,1, 1,1,1, 1,0,1, 1,1,1}, // 8 {1,1,1, 1,0,1, 1,1,1, 0,0,1, 1,1,1} // 9 }; f32 pixel_dim = 10.0f; u8 *pixels = font_data[number]; for (int row = 0; row < 5; row++) { for (int col = 0; col < 3; col++) { if (pixels[3*row + col]) { draw_quad(x + col*pixel_dim, y + row*pixel_dim, pixel_dim, pixel_dim, 0xFFFFFFFF); } } } } f32 draw_character(char c, f32 x, f32 y, f32 pixel_dim = 5.0f) { Glyph glyphs[] = { {4, 5, {0,1,1,0, 1,0,0,1, 1,1,1,1, 1,0,0,1, 1,0,0,1}}, // A {4, 5, {1,1,1,0, 1,0,0,1, 1,1,1,1, 1,0,0,1, 1,1,1,0}}, // B {4, 5, {0,1,1,1, 1,0,0,0, 1,0,0,0, 1,0,0,0, 0,1,1,1}}, // C {4, 5, {1,1,1,0, 1,0,0,1, 1,0,0,1, 1,0,0,1, 1,1,1,0}}, // D {4, 5, {1,1,1,1, 1,0,0,0, 1,1,1,0, 1,0,0,0, 1,1,1,1}}, // E {4, 5, {1,1,1,1, 1,0,0,0, 1,1,1,0, 1,0,0,0, 1,0,0,0}}, // F {4, 5, {0,1,1,1, 1,0,0,0, 1,0,1,1, 1,0,0,1, 0,1,1,1}}, // G {4, 5, {1,0,0,1, 1,0,0,1, 1,1,1,1, 1,0,0,1, 1,0,0,1}}, // H {3, 5, {1,1,1, 0,1,0, 0,1,0, 0,1,0, 1,1,1}}, // I (3x5) {4, 5, {0,0,1,1, 0,0,0,1, 0,0,0,1, 1,0,0,1, 1,1,1,1}}, // J {4, 5, {1,0,0,1, 1,0,1,0, 1,1,1,1, 1,0,0,1, 1,0,0,1}}, // K {4, 5, {1,0,0,0, 1,0,0,0, 1,0,0,0, 1,0,0,1, 1,1,1,1}}, // L {5, 5, {1,0,0,0,1, 1,1,0,1,1, 1,0,1,0,1, 1,0,0,0,1, 1,0,0,0,1}},// M (5x5) {5, 5, {1,0,0,0,1, 1,1,0,0,1, 1,0,1,0,1, 1,0,0,1,1, 1,0,0,0,1}},// N (5x5) {4, 5, {0,1,1,0, 1,0,0,1, 1,0,0,1, 1,0,0,1, 0,1,1,0}}, // O {4, 5, {1,1,1,1, 1,0,0,1, 1,1,1,1, 1,0,0,0, 1,0,0,0}}, // P {5, 5, {0,1,1,0,0, 1,0,0,1,0, 1,0,0,1,0, 1,0,0,1,0, 0,1,1,1,1}},// Q (5x5) {4, 5, {1,1,1,0, 1,0,0,1, 1,1,1,1, 1,0,1,0, 1,0,0,1}}, // R {4, 5, {0,1,1,1, 1,0,0,0, 1,1,1,1, 0,0,0,1, 1,1,1,1}}, // S {5, 5, {1,1,1,1,1, 0,0,1,0,0, 0,0,1,0,0, 0,0,1,0,0, 0,1,1,1,0}},// T {4, 5, {1,0,0,1, 1,0,0,1, 1,0,0,1, 1,0,0,1, 0,1,1,1}}, // U {5, 5, {1,0,0,0,1, 1,0,0,0,1, 1,0,0,0,1, 0,1,0,1,0, 0,0,1,0,0}},// V (5x5) {5, 5, {1,0,0,0,1, 1,0,0,0,1, 1,0,1,0,1, 1,1,0,1,1, 1,0,0,0,1}},// W (5x5) {5, 5, {1,0,0,0,1, 0,1,0,1,0, 0,0,1,0,0, 0,1,0,1,0, 1,0,0,0,1}},// X (5x5) {4, 5, {1,0,0,1, 1,0,0,1, 1,1,1,1, 0,0,0,1, 1,1,1,0}}, // Y {4, 5, {1,1,1,1, 0,0,0,1, 0,1,1,0, 1,0,0,0, 1,1,1,1}} // Z }; if (c >= 'A' && c <= 'Z') { Glyph *glyph = glyphs + (c - 'A'); for (int row = 0; row < glyph->height; row++) { for (int col = 0; col < glyph->width; col++) { if (glyph->data[glyph->width*row + col]) { draw_quad(x + col*pixel_dim, y + row*pixel_dim, pixel_dim, pixel_dim, 0xFFFFFFFF); } } } return (glyph->width + 1) * pixel_dim; } return 3 * pixel_dim; } void draw_string(const char *str, f32 x, f32 y, f32 pixel_dim = 5.0f) { int n = strlen(str); f32 xoffset = x; for (int i = 0; i < n; i++) { f32 stride = draw_character(str[i], xoffset, y, pixel_dim); xoffset += stride; } } enum GameState { TUTORIAL, PLAY, GAMEOVER, }; struct Mixer { snd_pcm_t *device; u16 sample_rate; u16 channel_count; int samples_to_play; int sample_offset; s16 samples[48000]; }; void check(int ret) { if (ret < 0) { fprintf(stderr, "error: %s (%d)\n", snd_strerror(ret), ret); exit(1); } } void mixer_init(Mixer *mixer) { mixer->sample_rate = 48000; mixer->channel_count = 1; check(snd_pcm_open(&mixer->device, "default", SND_PCM_STREAM_PLAYBACK, 0)); snd_pcm_t *pcm = mixer->device; snd_pcm_hw_params_t *hw_params; snd_pcm_hw_params_alloca(&hw_params); check(snd_pcm_hw_params_any(pcm, hw_params)); check(snd_pcm_hw_params_set_access(pcm, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED)); check(snd_pcm_hw_params_set_format(pcm, hw_params, SND_PCM_FORMAT_S16_LE)); check(snd_pcm_hw_params_set_channels(pcm, hw_params, 1)); check(snd_pcm_hw_params_set_rate(pcm, hw_params, 48000, 0)); check(snd_pcm_hw_params_set_periods(pcm, hw_params, 4, 0)); check(snd_pcm_hw_params_set_period_time(pcm, hw_params, 16667, 0)); check(snd_pcm_hw_params(pcm, hw_params)); } void mixer_update(Mixer *mixer) { if (mixer->samples_to_play <= 0) { s16 silence[800] = {0}; check(snd_pcm_writei(mixer->device, silence, 800)); } else { check(snd_pcm_writei(mixer->device, mixer->samples + mixer->sample_offset, 800)); mixer->sample_offset = (mixer->sample_offset + 800) % 48000; mixer->samples_to_play -= 800; } } void mixer_shutdown(Mixer *mixer) { snd_pcm_drain(mixer->device); snd_pcm_close(mixer->device); } void play_sound(Mixer *mixer, f32 freq, u32 ms) { for (int i = 0; i < 48000; i++) { mixer->samples[i] = 10000 * sinf(((f32)i / 48000) * 2 * M_PI * freq); } mixer->samples_to_play += ms * 48000 / 1000; } int main() { Mixer mixer = {}; mixer_init(&mixer); Display *display = XOpenDisplay(nullptr); if (!display) { fprintf(stderr, "Unable to connect to display, check your XServer configuration\n"); exit(1); } Window window = XCreateSimpleWindow( display, XDefaultRootWindow(display), 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT, 0, 0x00000000, 0x00000000 // 0x00FF00FF ); if (!window) { fprintf(stderr, "Failed to create window\n"); exit(1); } XStoreName(display, window, WINDOW_CAPTION); XSelectInput(display, window, KeyPressMask|KeyReleaseMask); XMapWindow(display, window); XWindowAttributes win_attribs = {}; XGetWindowAttributes(display, window, &win_attribs); printf("dimensions: (%d, %d)\n", win_attribs.width, win_attribs.height); int visual_attributes[] = {GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None}; XVisualInfo *visual = glXChooseVisual(display, 0, visual_attributes); if (!visual) { fprintf(stderr, "Unable to choose a visual appropriate for OpenGL\n"); exit(1); } GLXContext gl_context = glXCreateContext(display, visual, nullptr, True); if (!gl_context) { fprintf(stderr, "Failed to create GL context\n"); exit(1); } glXMakeCurrent(display, window, gl_context); glViewport(0, 0, win_attribs.width, win_attribs.height); RGBA paddle_color = 0xFFFFFFFF; RGBA ball_color = 0xFFFFFFFF; f32 paddle_width = WINDOW_WIDTH / 20.0f; f32 paddle_height = paddle_width * 4; f32 paddle_left_x = 0.0f; f32 paddle_left_y = WINDOW_HEIGHT / 2.0f - paddle_height / 2.0; f32 paddle_right_x = WINDOW_WIDTH - paddle_width; f32 paddle_right_y = paddle_left_y; f32 paddle_speed = 10.0f; f32 ball_width = paddle_width * 0.5; f32 ball_height = ball_width; f32 ball_start_x = (WINDOW_WIDTH / 2.0) - (ball_width / 2.0); f32 ball_start_y = (WINDOW_HEIGHT / 2.0f) - (ball_height / 2.0); f32 ball_x = ball_start_x; f32 ball_y = ball_start_y; f32 ball_vx = 2 * -5.0f;// / 10.0f; // TODO: Set velocity to a low value to troubleshoot collision f32 ball_vy = 2 * 2.0f;// / 10.0f; GameState state = TUTORIAL; bool multiplayer = false; int score_left = 0; int score_right = 0; bool first_move = false; bool up_pressed = false; bool down_pressed = false; bool w_pressed = false; bool s_pressed = false; bool quit = false; f32 dt = 1.0f; while (!quit) { while (XPending(display) > 0) { XEvent event = {}; XNextEvent(display, &event); switch (event.type) { case KeyPress: { KeySym keysym = XLookupKeysym(&event.xkey, 0); if (keysym == XK_Escape) { printf("Exiting...\n"); quit = true; } if (keysym == XK_Up) {up_pressed = true;} if (keysym == XK_Down) {down_pressed = true;} if (keysym == XK_w) {w_pressed = true;} if (keysym == XK_s) {s_pressed = true;} } break; case KeyRelease: { KeySym keysym = XLookupKeysym(&event.xkey, 0); if (keysym == XK_Up) {up_pressed = false;} if (keysym == XK_Down) {down_pressed = false;} if (keysym == XK_w) {w_pressed = false;} if (keysym == XK_s) {s_pressed = false;} } break; } } // Update and Render mixer_update(&mixer); RGBA bg_color = 0x121210FF; f32 r = ((bg_color >> 24) & 0xFF) / 255.0; f32 g = ((bg_color >> 16) & 0xFF) / 255.0; f32 b = ((bg_color >> 8) & 0xFF) / 255.0; f32 a = ((bg_color >> 0) & 0xFF) / 255.0; glClearColor(r, g, b, a); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); switch (state) { case TUTORIAL: { draw_string("PRESS UP OR DOWN TO MOVE", WINDOW_WIDTH * 0.12, 20); if (up_pressed || down_pressed || w_pressed || s_pressed) { state = PLAY; score_left = 0; score_right = 0; } } break; case PLAY: { if (score_left >= 10 || score_right >= 10) { state = GAMEOVER; } } break; case GAMEOVER: { draw_string("GAME OVER", WINDOW_WIDTH * 0.2, 20, 10); draw_string("PRESS UP OR DOWN TO MOVE", WINDOW_WIDTH * 0.12, 100); if (up_pressed || down_pressed) { state = PLAY; score_left = 0; score_right = 0; } } break; default: fprintf(stderr, "Invalid game state: %d\n", state); exit(1); } if (state == PLAY) { // Update Paddles if (up_pressed) { paddle_right_y -= paddle_speed*dt; } if (down_pressed) { paddle_right_y += paddle_speed*dt; } if (w_pressed) { paddle_left_y -= paddle_speed*dt; } if (s_pressed) { paddle_left_y += paddle_speed*dt; } // Update Ball ball_x = ball_x + ball_vx*dt; ball_y = ball_y + ball_vy*dt; if (ball_x < 0.0f) { ball_x = ball_start_x; score_right += 1; } if (ball_x > WINDOW_WIDTH) { ball_x = ball_start_x; score_left += 1; } if (ball_x < (paddle_left_x + paddle_width) && (ball_y + ball_height) > paddle_left_x && ball_y < (paddle_left_y + paddle_height) && ball_vx < 0.0f) { play_sound(&mixer, 400.0f, 100); ball_vx = -ball_vx; } if ((ball_x + ball_width) > paddle_right_x && (ball_y + ball_height) > paddle_right_y && ball_y < (paddle_right_y + paddle_height) && ball_vx > 0.0f) { play_sound(&mixer, 200.0f, 100); ball_vx = -ball_vx; } // if ((ball_x + ball_width) > WINDOW_WIDTH) {ball_vx = -ball_vx;} if (ball_y < 0.0f || (ball_y + ball_height) > WINDOW_HEIGHT) {ball_vy = -ball_vy;} // Score draw_number(score_left, WINDOW_WIDTH * 0.25, 20); draw_number(score_right, WINDOW_WIDTH * 0.75, 20); // Ball draw_quad(ball_x, ball_y, ball_width, ball_height, ball_color); if (!multiplayer) { if (ball_vx > 0.0 && ball_x > 0.8*WINDOW_WIDTH) { f32 tx = (800.0 - ball_x) / ball_vx; f32 new_y = (ball_y + ball_vy * tx) - paddle_height / 2.0; if (new_y > 0.0 && new_y < WINDOW_HEIGHT) { if (fabs(paddle_right_y - new_y) < 10) {up_pressed = false; down_pressed = false;} else if (new_y < paddle_right_y) {up_pressed = true; down_pressed = false;} else if (new_y > paddle_right_y) {up_pressed = false; down_pressed = true;} } // draw_line(ball_x, ball_y, ball_x + ball_vx * tx, ball_y + ball_vy * tx); } else { up_pressed = false; down_pressed = false; } } // Net f32 net_width = 20.0f; int net_segment_count = 10; f32 net_segment_height = WINDOW_HEIGHT / (net_segment_count * 2.0); f32 x = WINDOW_WIDTH / 2.0 - net_width / 2.0; for (int i = 0; i < net_segment_count; i++) { f32 y = (2.0 * i * net_segment_height) + (net_segment_height / 2.0); draw_quad(x, y, net_width, net_segment_height, 0xFFFFFFFF); } } // Paddles draw_quad(paddle_left_x, paddle_left_y, paddle_width, paddle_height, paddle_color); draw_quad(paddle_right_x, paddle_right_y, paddle_width, paddle_height, paddle_color); glXSwapBuffers(display, window); } XCloseDisplay(display); mixer_shutdown(&mixer); return 0; }
36.249467
106
0.482501
[ "render" ]
856cf77b52bc835a7feecb4f23714d3205c82c01
2,262
cpp
C++
opensoap/src/server/XmlDoc.cpp
kbore/pbis-open
a05eb9309269b6402b4d6659bc45961986ea5eab
[ "Apache-2.0" ]
372
2016-10-28T10:50:35.000Z
2022-03-18T19:54:37.000Z
opensoap/src/server/XmlDoc.cpp
kbore/pbis-open
a05eb9309269b6402b4d6659bc45961986ea5eab
[ "Apache-2.0" ]
317
2016-11-02T17:41:48.000Z
2021-11-08T20:28:19.000Z
opensoap/src/server/XmlDoc.cpp
kenferrara/pbis-open
690c325d947b2bf6fb3032f9d660e41b94aea4be
[ "Apache-2.0" ]
107
2016-11-03T19:25:16.000Z
2022-03-20T21:15:22.000Z
/* -*- mode: c++; -*- *----------------------------------------------------------------------------- * $RCSfile: XmlDoc.cpp,v $ * * See Copyright for the status of this software. * * The OpenSOAP Project * http://opensoap.jp/ *----------------------------------------------------------------------------- */ #include <iostream> #include <sstream> #include <fstream> #include <stdexcept> //for libxml2 #include <libxml/parser.h> #include "XmlDoc.h" using namespace std; using namespace OpenSOAP; XmlDoc::XmlDoc() : doc(NULL) , rootElem(NULL) { } XmlDoc::~XmlDoc() { if (doc) { //release doc xmlFreeDoc(doc); } } void XmlDoc::parse() { /* xmlNodePtr node = xmlDocGetRootElement(doc); if (node == NULL) { throw runtime_error("invalid rootElem"); } */ /* rootElem = new XmlElem(node); rootElem.parse(); */ } void XmlDoc::serialize(string& str) const { vector<char> barray; serialize(barray); str = string(&(*barray.begin()), barray.size()); } void XmlDoc::serialize(vector<char>& bytearray) const { xmlChar* dumpArea = NULL; int dumpSize = 0; xmlDocDumpMemory(doc, &dumpArea, &dumpSize); //xmlDocDumpFormatMemory(doc, &dumpArea, &dumpSize, 1); bytearray.resize(dumpSize); memcpy(&(*bytearray.begin()), dumpArea, bytearray.size()); xmlFree(dumpArea); } void XmlDoc::serialize(ostream& ost) const { vector<char> barray; serialize(barray); ost.write(&(*barray.begin()), barray.size()); } void XmlDoc::deserialize(const string& str) { if (doc) { //release doc xmlFreeDoc(doc); } doc = xmlParseMemory(str.c_str(), str.length()); } void XmlDoc::deserialize(const vector<char>& bytearray) { if (doc) { //release doc xmlFreeDoc(doc); } doc = xmlParseMemory(&(*bytearray.begin()), bytearray.size()); } void XmlDoc::deserialize(const istream& ist) { stringstream strst; strst << ist.rdbuf(); string xmlString(strst.str()); if (doc) { //release doc xmlFreeDoc(doc); } doc = xmlParseMemory(xmlString.c_str(), xmlString.length()); } //------------------------------------ // End of XmlDoc.cpp //------------------------------------
18.85
79
0.549956
[ "vector" ]
8574aefa28e6054c07576879bc8fed7e8e7ee257
2,514
hpp
C++
thread_pool/thread_pool.hpp
huangsunyang/shiyanlou
0b42f783d6aae639c1b0c2a33883a94e127038f7
[ "MIT" ]
30
2017-05-24T06:24:29.000Z
2020-12-18T11:09:53.000Z
thread_pool/thread_pool.hpp
huangsunyang/shiyanlou
0b42f783d6aae639c1b0c2a33883a94e127038f7
[ "MIT" ]
null
null
null
thread_pool/thread_pool.hpp
huangsunyang/shiyanlou
0b42f783d6aae639c1b0c2a33883a94e127038f7
[ "MIT" ]
15
2017-05-24T06:24:33.000Z
2020-04-21T11:32:36.000Z
// // thread_pool.hpp // thread_pool // // Created by huangsunyang on 5/20/2017. // Copyright © 2017年 huangsunyang. All rights reserved. // #ifndef thread_pool_hpp #define thread_pool_hpp #include <stdio.h> #include <iostream> #include <thread> #include <chrono> #include <future> #include <string> #include <vector> #include <queue> #include <memory> #include <functional> class ThreadPool { public: ThreadPool(size_t threads); ~ThreadPool(); template<typename F, typename... Args> auto enqueue(F &&f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type>; private: std::vector<std::thread> workers; std::queue<std::function<void()>> tasks; std::mutex queue_mutex; std::condition_variable condition; bool stop; }; inline ThreadPool::ThreadPool(size_t threads): stop(false) { for (size_t i = 0; i < threads; ++i) { workers.emplace_back([this] { for (;;) { std::function<void()> task; { std::unique_lock<std::mutex> lock(this->queue_mutex); this->condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); }); if (this->stop && this->tasks.empty()) return; task = std::move(this->tasks.front()); this->tasks.pop(); } task(); } }); } } inline ThreadPool::~ThreadPool() { { std::unique_lock<std::mutex> lock(queue_mutex); stop = true; } condition.notify_all(); for (std::thread &worker: workers) worker.join(); } template <typename F, typename... Args> auto ThreadPool::enqueue(F&& f, Args&&... args) ->std::future<typename std::result_of<F(Args...)>::type> { using return_type = typename std::result_of<F((Args...))>::type; auto task = std::make_shared<std::packaged_task<return_type()>> (std::bind(std::forward<F>(f), std::forward<Args>(args)...)); std::future<return_type> res = task->get_future(); { std::unique_lock<std::mutex> lock(queue_mutex); if (stop) throw std::runtime_error("enqueue on stopped ThreadPool"); tasks.emplace([task]{(*task)();}); } condition.notify_one(); return res; } #endif /* thread_pool_hpp */
23.942857
73
0.541368
[ "vector" ]
85774b369ff40ae4cccacc60b840b00dc7eff57d
9,498
cpp
C++
animation-lab2/tankLab/Particles.cpp
marcus1337/DH2323
9d2f3815baba85a90384c58a8e49f78399890d86
[ "MIT" ]
null
null
null
animation-lab2/tankLab/Particles.cpp
marcus1337/DH2323
9d2f3815baba85a90384c58a8e49f78399890d86
[ "MIT" ]
null
null
null
animation-lab2/tankLab/Particles.cpp
marcus1337/DH2323
9d2f3815baba85a90384c58a8e49f78399890d86
[ "MIT" ]
null
null
null
#define GL_GLEXT_PROTOTYPES #include "stdlib.h" #include "stdio.h" #include "windows.h" #include <gl/gl.h> // standard OpenGL include #include <gl/glu.h> // OpenGL utilties #include "glut.h" // OpenGL utilties #include "Particles.h" #include "myVector.h" #include <iostream> using namespace MyMathLibrary; Particles::Particles() : activated1(false) {} void Particles::init() { g_dCurTime = timeGetTime(); g_fElpasedTime = (float)((g_dCurTime - g_dLastTime) * 0.001); g_dLastTime = g_dCurTime; g_pParticleSystems[0] = new CParticleSystem(); //g_pParticleSystems[0]->SetTexture( "..\\particle.bmp" ); g_pParticleSystems[0]->SetTexture("particle.bmp"); g_pParticleSystems[0]->SetMaxParticles(100); g_pParticleSystems[0]->SetNumToRelease(100); g_pParticleSystems[0]->SetReleaseInterval(0.05f); g_pParticleSystems[0]->SetLifeCycle(0.5f); g_pParticleSystems[0]->SetSize(30.0f); g_pParticleSystems[0]->SetColor(MyVector(1.0f, 0.0f, 0.0f)); g_pParticleSystems[0]->SetPosition(MyVector(0.0f, 5.0f, 0.0f)); g_pParticleSystems[0]->SetVelocity(MyVector(0.0f, 0.0f, 0.0f)); g_pParticleSystems[0]->SetGravity(MyVector(0.0f, 0.0f, 0.0f)); g_pParticleSystems[0]->SetWind(MyVector(0.0f, 0.0f, 0.0f)); g_pParticleSystems[0]->SetVelocityVar(10.0f); g_pParticleSystems[0]->Init(); // // Wind blown fountain // g_pParticleSystems[1] = new CParticleSystem(); // g_pParticleSystems[1]->SetTexture( "..\\particle.bmp" ); g_pParticleSystems[1]->SetTexture("particle.bmp"); g_pParticleSystems[1]->SetMaxParticles(500); g_pParticleSystems[1]->SetNumToRelease(5); g_pParticleSystems[1]->SetReleaseInterval(0.05f); g_pParticleSystems[1]->SetLifeCycle(4.0f); g_pParticleSystems[1]->SetSize(30.0f); g_pParticleSystems[1]->SetColor(MyVector(1.0f, 1.0f, 1.0f)); g_pParticleSystems[1]->SetPosition(MyVector(0.0f, 0.0f, 0.0f)); g_pParticleSystems[1]->SetVelocity(MyVector(0.0f, 5.0f, 0.0f)); g_pParticleSystems[1]->SetGravity(MyVector(0.0f, 0.0f, 0.0f)); g_pParticleSystems[1]->SetWind(MyVector(2.0f, 0.0f, 0.0f)); g_pParticleSystems[1]->SetVelocityVar(1.5f); g_pParticleSystems[1]->Init(); // // Omni-directiional emission expanding into space with no air resistence // g_pParticleSystems[2] = new CParticleSystem(); g_pParticleSystems[2]->SetTexture("particle.bmp"); g_pParticleSystems[2]->SetMaxParticles(2048); g_pParticleSystems[2]->SetNumToRelease(10); g_pParticleSystems[2]->SetReleaseInterval(0.05f); g_pParticleSystems[2]->SetLifeCycle(5.0f); g_pParticleSystems[2]->SetSize(30.0f); g_pParticleSystems[2]->SetColor(MyVector(1.0f, 1.0f, 1.0f)); g_pParticleSystems[2]->SetPosition(MyVector(0.0f, 0.0f, 0.0f)); g_pParticleSystems[2]->SetVelocity(MyVector(0.0f, 0.0f, 0.0f)); g_pParticleSystems[2]->SetGravity(MyVector(0.0f, 0.0f, 0.0f)); g_pParticleSystems[2]->SetWind(MyVector(0.0f, 0.0f, 0.0f)); g_pParticleSystems[2]->SetAirResistence(false); g_pParticleSystems[2]->SetVelocityVar(2.0f); g_pParticleSystems[2]->Init(); // // Fountain particles behave like paint spots when striking a plane as // the wind blowing them towards us // g_pParticleSystems[3] = new CParticleSystem(); g_pParticleSystems[3]->SetTexture("particle.bmp"); g_pParticleSystems[3]->SetMaxParticles(100); g_pParticleSystems[3]->SetNumToRelease(10); g_pParticleSystems[3]->SetReleaseInterval(0.05f); g_pParticleSystems[3]->SetLifeCycle(3.0f); g_pParticleSystems[3]->SetSize(30.0f); g_pParticleSystems[3]->SetColor(MyVector(1.0f, 1.0f, 1.0f)); g_pParticleSystems[3]->SetPosition(MyVector(0.0f, 0.0f, 0.0f)); g_pParticleSystems[3]->SetVelocity(MyVector(0.0f, 5.0f, 0.0f)); g_pParticleSystems[3]->SetGravity(MyVector(0.0f, 0.0f, 0.0f)); g_pParticleSystems[3]->SetWind(MyVector(0.0f, 0.0f, -20.0f)); g_pParticleSystems[3]->SetVelocityVar(2.5f); g_pParticleSystems[3]->SetCollisionPlane(MyVector(0.0f, 0.0f, 1.0f), MyVector(0.0f, 0.0f, -5.0f), 1.0f, CR_STICK); g_pParticleSystems[3]->Init(); // // Fountain using a single collision plane acting as a floor // g_pParticleSystems[4] = new CParticleSystem(); g_pParticleSystems[4]->SetTexture("particle.bmp"); g_pParticleSystems[4]->SetMaxParticles(200); g_pParticleSystems[4]->SetNumToRelease(10); g_pParticleSystems[4]->SetReleaseInterval(0.05f); g_pParticleSystems[4]->SetLifeCycle(5.0f); g_pParticleSystems[4]->SetSize(30.0f); g_pParticleSystems[4]->SetColor(MyVector(1.0f, 1.0f, 1.0f)); g_pParticleSystems[4]->SetPosition(MyVector(0.0f, 0.0f, 0.0f)); g_pParticleSystems[4]->SetVelocity(MyVector(0.0f, 0.0f, 0.0f)); g_pParticleSystems[4]->SetGravity(MyVector(0.0f, -9.8f, 0.0f)); g_pParticleSystems[4]->SetWind(MyVector(0.0f, 0.0f, 0.0f)); g_pParticleSystems[4]->SetVelocityVar(20.0f); g_pParticleSystems[4]->SetCollisionPlane(MyVector(0.0f, 1.0f, 0.0f), MyVector(0.0f, 0.0f, 0.0f)); g_pParticleSystems[4]->Init(); // // Fountain boxed-in by 6 collision planes // g_pParticleSystems[5] = new CParticleSystem(); g_pParticleSystems[5]->SetTexture("particle.bmp"); g_pParticleSystems[5]->SetMaxParticles(100); g_pParticleSystems[5]->SetNumToRelease(5); g_pParticleSystems[5]->SetReleaseInterval(0.05f); g_pParticleSystems[5]->SetLifeCycle(5.0f); g_pParticleSystems[5]->SetSize(30.0f); g_pParticleSystems[5]->SetColor(MyVector(1.0f, 1.0f, 1.0f)); g_pParticleSystems[5]->SetPosition(MyVector(0.0f, 0.0f, 0.0f)); g_pParticleSystems[5]->SetVelocity(MyVector(0.0f, 0.0f, 0.0f)); g_pParticleSystems[5]->SetGravity(MyVector(0.0f, -9.8f, 0.0f)); g_pParticleSystems[5]->SetWind(MyVector(0.0f, 0.0f, 0.0f)); g_pParticleSystems[5]->SetVelocityVar(20.0f); // Create a series of planes to collide with g_pParticleSystems[5]->SetCollisionPlane(MyVector(0.0f, 1.0f, 0.0f), MyVector(0.0f, 0.0f, 0.0f)); // Floor g_pParticleSystems[5]->SetCollisionPlane(MyVector(1.0f, 0.0f, 0.0f), MyVector(-3.0f, 0.0f, 0.0f)); // Left Wall g_pParticleSystems[5]->SetCollisionPlane(MyVector(-1.0f, 0.0f, 0.0f), MyVector(3.0f, 0.0f, 0.0f)); // Right Wall g_pParticleSystems[5]->SetCollisionPlane(MyVector(0.0f, 0.0f, 1.0f), MyVector(0.0f, 0.0f, -3.0f)); // Front Wall g_pParticleSystems[5]->SetCollisionPlane(MyVector(0.0f, 0.0f, -1.0f), MyVector(0.0f, 0.0f, 3.0f)); // Back Wall g_pParticleSystems[5]->SetCollisionPlane(MyVector(0.0f, -1.0f, 0.0f), MyVector(0.0f, 5.0f, 0.0f)); // Ceiling g_pParticleSystems[5]->Init(); ///////////////////////////////////////////////////////////////////////////////////// g_pParticleSystems[6] = new CParticleSystem(); g_pParticleSystems[6]->SetTexture("particle.bmp"); g_pParticleSystems[6]->SetMaxParticles(408); g_pParticleSystems[6]->SetNumToRelease(10); g_pParticleSystems[6]->SetReleaseInterval(0.02f); g_pParticleSystems[6]->SetLifeCycle(5.0f); g_pParticleSystems[6]->SetSize(50.0f); g_pParticleSystems[6]->SetColor(MyVector(0.0f, 1.0f, 0.0f)); g_pParticleSystems[6]->SetPosition(MyVector(0.5f, 0.5f, 0.0f)); g_pParticleSystems[6]->SetVelocity(MyVector(5.0f, 0.0f, 0.0f)); g_pParticleSystems[6]->SetGravity(MyVector(0.0f, 0.0f, 0.0f)); g_pParticleSystems[6]->SetWind(MyVector(0.0f, 5.0f, 0.0f)); g_pParticleSystems[6]->SetAirResistence(false); g_pParticleSystems[6]->SetVelocityVar(2.0f); g_pParticleSystems[6]->SetCollisionPlane(MyVector(-0.3f, 1.0f, 0.0f), MyVector(-0.5f, 0.0f, 0.0f)); // Floor g_pParticleSystems[6]->SetCollisionPlane(MyVector(0.0f, -1.0f, 0.0f), MyVector(0.0f, 3.0f, 0.0f)); // Ceiling g_pParticleSystems[6]->SetCollisionPlane(MyVector(1.0f, 0.0f, 0.0f), MyVector(-3.0f, 0.0f, 0.0f)); // Left Wall g_pParticleSystems[6]->SetCollisionPlane(MyVector(-1.0f, 0.0f, 0.0f), MyVector(3.0f, 0.0f, 0.0f)); // Right Wall g_pParticleSystems[6]->Init(); } void Particles::onIdle() { // if (!activated1) // return; g_dCurTime = timeGetTime(); g_fElpasedTime = (float)((g_dCurTime - g_dLastTime) * 0.001); g_dLastTime = g_dCurTime; g_pParticleSystems[g_nActiveSystem]->Update((float)g_fElpasedTime); } void Particles::draw(float x, float y, float z) { if (!activated1) return; glPushMatrix(); glScalef(0.1, 0.1, 0.1); glTranslatef(x, y, z); //move the camera back to view the scene glEnable(GL_DEPTH_TEST); glDepthMask(GL_FALSE); bool doTestRender = false; if (doTestRender) { glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); g_pParticleSystems[g_nActiveSystem]->RenderSimple(); glEnable(GL_TEXTURE_2D); } else { glEnable(GL_DEPTH_TEST); glDepthMask(GL_FALSE); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE); glBindTexture(GL_TEXTURE_2D, g_pParticleSystems[g_nActiveSystem]->GetTextureID()); // g_pParticleSystems[g_nActiveSystem]->SetPosition(MyVector(x, y, z)); g_pParticleSystems[g_nActiveSystem]->Render(); } // // Reset OpenGL states... // glDepthMask(GL_TRUE); glDisable(GL_BLEND); glPopMatrix(); }
36.114068
90
0.66772
[ "render" ]
85825d49bded8b39a9c2f5075315d40a124c6762
77,301
cpp
C++
inetcore/outlookexpress/mailnews/rules/rulesui.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetcore/outlookexpress/mailnews/rules/rulesui.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetcore/outlookexpress/mailnews/rules/rulesui.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/////////////////////////////////////////////////////////////////////////////// // // RulesUI.cpp // /////////////////////////////////////////////////////////////////////////////// #include <pch.hxx> #include "rulesui.h" #include "aplyrule.h" #include "editrule.h" #include "ruledesc.h" #include "ruleutil.h" #include "rulesmgr.h" #include "rule.h" #include "spamui.h" #include "reutil.h" #include <rulesdlg.h> #include <imagelst.h> #include <newfldr.h> #include <instance.h> #include "shlwapip.h" #include <demand.h> // Constants class COEMailRulesPageUI : public COERulesPageUI { private: enum MOVE_DIR {MOVE_RULE_UP = 0, MOVE_RULE_DOWN = 1}; private: HWND m_hwndOwner; HWND m_hwndDlg; HWND m_hwndList; HWND m_hwndDescript; RULE_TYPE m_typeRule; CRuleDescriptUI * m_pDescriptUI; public: COEMailRulesPageUI(); enum INIT_TYPE { INIT_MAIL = 0x00000000, INIT_NEWS = 0x00000001 }; COEMailRulesPageUI(DWORD dwFlagsInit) : COERulesPageUI(iddRulesMail, (0 != (dwFlagsInit & INIT_NEWS)) ? idsRulesNews : idsRulesMail, 0, 0), m_hwndOwner(NULL), m_hwndDlg(NULL), m_hwndList(NULL), m_hwndDescript(NULL), m_typeRule((0 != (dwFlagsInit & INIT_NEWS)) ? RULE_TYPE_NEWS : RULE_TYPE_MAIL), m_pDescriptUI(NULL) {} virtual ~COEMailRulesPageUI(); virtual HRESULT HrInit(HWND hwndOwner, DWORD dwFlags); virtual HRESULT HrCommitChanges(DWORD dwFlags, BOOL fClearDirty); static INT_PTR CALLBACK FMailRulesPageDlgProc(HWND hwndDlg, UINT uiMsg, WPARAM wParam, LPARAM lParam); DLGPROC DlgProcGetPageDlgProc(VOID) {return FMailRulesPageDlgProc;} BOOL FGetRules(RULE_TYPE typeRule, RULENODE ** pprnode); // Message handling methods BOOL FOnInitDialog(HWND hwndDlg); BOOL FOnCommand(UINT uiNotify, INT iCtl, HWND hwndCtl); BOOL FOnNotify(INT iCtl, NMHDR * pnmhdr); BOOL FOnDestroy(VOID); private: BOOL _FInitListCtrl(VOID); BOOL _FLoadListCtrl(VOID); BOOL _FAddRuleToList(DWORD dwIndex, RULEID ridRule, IOERule * pIRule); VOID _EnableButtons(INT iSelected); VOID _EnableRule(INT iSelected); // For dealing with the description field VOID _LoadRule(INT iSelected); BOOL _FSaveRule(INT iSelected); // Functions to deal with the basic actions VOID _NewRule(VOID); VOID _EditRule(INT iSelected); VOID _MoveRule(INT iSelected, MOVE_DIR dir); VOID _RemoveRule(INT iSelected); VOID _CopyRule(INT iSelected); VOID _OnApplyTo(INT iSelected); BOOL _FOnLabelEdit(BOOL fBegin, NMLVDISPINFO * pdi); BOOL _FOnRuleDescValid(VOID); }; // Global data const static HELPMAP g_rgCtxMapRulesMgr[] = { {0, 0}}; const static HELPMAP g_rgCtxMapMailRules[] = { {idbNewRule, idhNewRule}, {idbModifyRule, idhModifyRule}, {idbCopyRule, idhCopyRule}, {idbDeleteRule, idhRemoveRule}, {idbRulesApplyTo, idhRuleApply}, {idbMoveUpRule, idhRuleUp}, {idbMoveDownRule, idhRuleDown}, {idredtRuleDescription, idhRuleDescription}, {0, 0}}; COERulesMgrUI::COERulesMgrUI() : m_hwndOwner(NULL), m_dwFlags(0), m_dwState(0), m_hwndDlg(NULL), m_hwndTab(NULL) { ZeroMemory(m_rgRuleTab, sizeof(m_rgRuleTab)); } COERulesMgrUI::~COERulesMgrUI() { ULONG ulIndex = 0; for (ulIndex = 0; ulIndex < RULE_PAGE_MAX; ulIndex++) { if (NULL != m_rgRuleTab[ulIndex]) { delete m_rgRuleTab[ulIndex]; } } } HRESULT COERulesMgrUI::HrInit(HWND hwndOwner, DWORD dwFlags) { HRESULT hr = S_OK; // Check incoming params if (NULL == hwndOwner) { hr = E_INVALIDARG; goto exit; } if (0 != (m_dwState & STATE_INITIALIZED)) { hr = E_UNEXPECTED; goto exit; } m_hwndOwner = hwndOwner; m_dwFlags = dwFlags; // Create each of the rule pages if (!(g_dwAthenaMode & MODE_NEWSONLY)) { // Create the mail page m_rgRuleTab[RULE_PAGE_MAIL] = new COEMailRulesPageUI(COEMailRulesPageUI::INIT_MAIL); if (NULL == m_rgRuleTab[RULE_PAGE_MAIL]) { hr = E_OUTOFMEMORY; goto exit; } } // Create the news page m_rgRuleTab[RULE_PAGE_NEWS] = new COEMailRulesPageUI(COEMailRulesPageUI::INIT_NEWS); if (NULL == m_rgRuleTab[RULE_PAGE_NEWS]) { hr = E_OUTOFMEMORY; goto exit; } // Create the junk page if ((0 == (g_dwAthenaMode & MODE_NEWSONLY)) && (0 != (g_dwAthenaMode & MODE_JUNKMAIL))) { m_rgRuleTab[RULE_PAGE_JUNK] = new COEJunkRulesPageUI(); if (NULL == m_rgRuleTab[RULE_PAGE_JUNK]) { hr = E_OUTOFMEMORY; goto exit; } } // Create the senders page m_rgRuleTab[RULE_PAGE_SENDERS] = new COESendersRulesPageUI(); if (NULL == m_rgRuleTab[RULE_PAGE_SENDERS]) { hr = E_OUTOFMEMORY; goto exit; } m_dwState |= STATE_INITIALIZED; hr = S_OK; exit: return hr; } HRESULT COERulesMgrUI::HrShow(VOID) { HRESULT hr = S_OK; int iRet = 0; if (0 == (m_dwState & STATE_INITIALIZED)) { hr = E_UNEXPECTED; goto exit; } // We need to load richedit if (FALSE == FInitRichEdit(TRUE)) { hr = E_FAIL; goto exit; } iRet = (INT) DialogBoxParam(g_hLocRes, MAKEINTRESOURCE(iddRulesManager), m_hwndOwner, COERulesMgrUI::FOERuleMgrDlgProc, (LPARAM) this); if (-1 == iRet) { hr = E_FAIL; goto exit; } // Set the proper return code hr = (IDOK == iRet) ? S_OK : S_FALSE; exit: return hr; } INT_PTR CALLBACK COERulesMgrUI::FOERuleMgrDlgProc(HWND hwndDlg, UINT uiMsg, WPARAM wParam, LPARAM lParam) { BOOL fRet = FALSE; COERulesMgrUI * pRulesUI = NULL; pRulesUI = (COERulesMgrUI *) GetWindowLongPtr(hwndDlg, GWLP_USERDATA); switch (uiMsg) { case WM_INITDIALOG: // Grab the UI object pointer pRulesUI = (COERulesMgrUI *) lParam; // Set it into the dialog so we can get it back SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR) pRulesUI); if (FALSE == pRulesUI->FOnInitDialog(hwndDlg)) { EndDialog(hwndDlg, -1); fRet = TRUE; goto exit; } // We set the focus fRet = FALSE; break; case WM_COMMAND: fRet = pRulesUI->FOnCommand((UINT) HIWORD(wParam), (INT) LOWORD(wParam), (HWND) lParam); break; case WM_NOTIFY: fRet = pRulesUI->FOnNotify((INT) LOWORD(wParam), (NMHDR *) lParam); break; case WM_DESTROY: fRet = pRulesUI->FOnDestroy(); break; case WM_OE_GET_RULES: fRet = pRulesUI->FOnGetRules((RULE_TYPE) wParam, (RULENODE **) lParam); break; case WM_HELP: case WM_CONTEXTMENU: fRet = OnContextHelp(hwndDlg, uiMsg, wParam, lParam, g_rgCtxMapRulesMgr); break; } exit: return fRet; } BOOL COERulesMgrUI::FOnInitDialog(HWND hwndDlg) { BOOL fRet = FALSE; HRESULT hr = S_OK; // Check incoming params if (NULL == hwndDlg) { fRet = FALSE; goto exit; } // Save off the dialog window handle m_hwndDlg = hwndDlg; // Set the default font onto the dialog SetIntlFont(m_hwndDlg); // Save off some of the controls m_hwndTab = GetDlgItem(hwndDlg, idtbRulesTab); if (NULL == m_hwndTab) { fRet = FALSE; goto exit; } // Initialize tab control fRet = _FInitTabCtrl(); if (FALSE == fRet) { goto exit; } // Everything's AOK fRet = TRUE; exit: return fRet; } BOOL COERulesMgrUI::FOnCommand(UINT uiNotify, INT iCtl, HWND hwndCtl) { BOOL fRet = FALSE; INT iSel = 0; TCITEM tcitem = {0}; switch (iCtl) { case IDOK: if (FALSE != _FOnOK()) { EndDialog(m_hwndDlg, IDOK); fRet = TRUE; } break; case IDCANCEL: EndDialog(m_hwndDlg, IDCANCEL); fRet = TRUE; break; default: iSel = TabCtrl_GetCurSel(m_hwndTab); if (-1 == iSel) { fRet = FALSE; goto exit; } tcitem.mask = TCIF_PARAM; if (FALSE == TabCtrl_GetItem(m_hwndTab, iSel, &tcitem)) { fRet = FALSE; goto exit; } fRet = !!SendMessage((HWND) (tcitem.lParam), WM_COMMAND, MAKEWPARAM(iCtl, uiNotify), (LPARAM) hwndCtl); break; } exit: return fRet; } BOOL COERulesMgrUI::FOnNotify(INT iCtl, NMHDR * pnmhdr) { BOOL fRet = FALSE; INT iSel = 0; TCITEM tcitem = {0}; HWND hwndDlg = NULL; HWND hwndFocus = NULL; switch (pnmhdr->code) { case TCN_SELCHANGING: // Get the window handle for the currently // selected tab iSel = TabCtrl_GetCurSel(m_hwndTab); if (-1 == iSel) { fRet = FALSE; goto exit; } tcitem.mask = TCIF_PARAM; if (FALSE == TabCtrl_GetItem(m_hwndTab, iSel, &tcitem)) { fRet = FALSE; goto exit; } hwndDlg = (HWND) tcitem.lParam; Assert(NULL != hwndDlg); // Hide and disable the current dialog ShowWindow(hwndDlg, SW_HIDE); EnableWindow(hwndDlg, FALSE); SetDlgMsgResult(hwndDlg, WM_NOTIFY, FALSE); fRet = TRUE; break; case TCN_SELCHANGE: // Get the window handle for the currently // selected tab iSel = TabCtrl_GetCurSel(m_hwndTab); if (-1 == iSel) { fRet = FALSE; goto exit; } tcitem.mask = TCIF_PARAM; if (FALSE == TabCtrl_GetItem(m_hwndTab, iSel, &tcitem)) { fRet = FALSE; goto exit; } hwndDlg = (HWND) tcitem.lParam; Assert(NULL != hwndDlg); // Hide and disable the current dialog ShowWindow(hwndDlg, SW_SHOW); EnableWindow(hwndDlg, TRUE); // Set the focus to the first control // if the focus isn't in the tab hwndFocus = GetFocus(); if (hwndFocus != m_hwndTab) { SendMessage(hwndDlg, WM_NEXTDLGCTL, (WPARAM) GetNextDlgTabItem(hwndDlg, NULL, FALSE), (LPARAM) TRUE); } fRet = TRUE; break; } exit: return fRet; } BOOL COERulesMgrUI::FOnDestroy(VOID) { BOOL fRet = FALSE; UINT cTabs = 0; UINT uiIndex = 0; TC_ITEM tcitem; // Get the number of tabs cTabs = TabCtrl_GetItemCount(m_hwndTab); // Initialize the Tab control structure... ZeroMemory(&tcitem, sizeof(tcitem)); tcitem.mask = TCIF_PARAM; // Destroy the dialogs from each page for (uiIndex = 0; uiIndex < cTabs; uiIndex++) { // Get the window handle for the dialog if (FALSE != TabCtrl_GetItem(m_hwndTab, uiIndex, &tcitem)) { // Destroy the dialog DestroyWindow((HWND) tcitem.lParam); } } fRet = TRUE; return fRet; } BOOL COERulesMgrUI::FOnGetRules(RULE_TYPE typeRule, RULENODE ** pprnode) { BOOL fRet = FALSE; RULENODE * prnodeList = NULL; RULENODE * prnodeSender = NULL; RULENODE * prnodeJunk = NULL; RULENODE * prnodeWalk = NULL; if (NULL == pprnode) { fRet = FALSE; goto exit; } // Initialize the outgoing param *pprnode = NULL; // Forward the message to the correct dialog switch(typeRule) { case RULE_TYPE_MAIL: // Get the rules from the senders page if (NULL != m_rgRuleTab[RULE_PAGE_SENDERS]) { fRet = m_rgRuleTab[RULE_PAGE_SENDERS]->FGetRules(RULE_TYPE_MAIL, &prnodeSender); } // Get the rules from the mail rules page if (NULL != m_rgRuleTab[RULE_PAGE_MAIL]) { fRet = m_rgRuleTab[RULE_PAGE_MAIL]->FGetRules(RULE_TYPE_MAIL, &prnodeList); } // Get the rules from the junk mail page if (NULL != m_rgRuleTab[RULE_PAGE_JUNK]) { fRet = m_rgRuleTab[RULE_PAGE_JUNK]->FGetRules(RULE_TYPE_MAIL, &prnodeJunk); } break; case RULE_TYPE_NEWS: // Get the rules from the senders page if (NULL != m_rgRuleTab[RULE_PAGE_SENDERS]) { fRet = m_rgRuleTab[RULE_PAGE_SENDERS]->FGetRules(RULE_TYPE_NEWS, &prnodeSender); } // Get the rules from the news rules page if (NULL != m_rgRuleTab[RULE_PAGE_NEWS]) { fRet = m_rgRuleTab[RULE_PAGE_NEWS]->FGetRules(RULE_TYPE_NEWS, &prnodeList); } break; default: Assert(FALSE); fRet = FALSE; goto exit; break; } // Set up the list if (NULL != prnodeJunk) { Assert(NULL == prnodeJunk->pNext); if (NULL == prnodeList) { prnodeList = prnodeJunk; } else { prnodeWalk = prnodeList; while (NULL != prnodeWalk->pNext) { prnodeWalk = prnodeWalk->pNext; } prnodeWalk->pNext = prnodeJunk; } prnodeJunk = NULL; } if (NULL != prnodeSender) { Assert(NULL == prnodeSender->pNext); prnodeSender->pNext = prnodeList; prnodeList = prnodeSender; prnodeSender = NULL; } // Set the outgoing param *pprnode = prnodeList; prnodeList = NULL; // Tell the dialog it's aok to proceed SetDlgMsgResult(m_hwndDlg, WM_OE_GET_RULES, TRUE); fRet = TRUE; exit: while (NULL != prnodeList) { prnodeWalk = prnodeList; if (NULL != prnodeWalk->pIRule) { prnodeWalk->pIRule->Release(); } prnodeList = prnodeList->pNext; delete prnodeWalk; //MemFree(prnodeWalk); } if (NULL != prnodeJunk) { if (NULL != prnodeJunk->pIRule) { prnodeJunk->pIRule->Release(); } delete prnodeJunk; // MemFree(prnodeJunk); } if (NULL != prnodeSender) { if (NULL != prnodeSender->pIRule) { prnodeSender->pIRule->Release(); } delete prnodeSender; //MemFree(prnodeSender); } return fRet; } BOOL COERulesMgrUI::_FOnOK(VOID) { BOOL fRet = FALSE; UINT uiRuleTab = 0; HRESULT hr = S_OK; // Add the tabs to the tab control for (uiRuleTab = 0; uiRuleTab < RULE_PAGE_MAX; uiRuleTab++) { if (NULL == m_rgRuleTab[uiRuleTab]) { continue; } hr = m_rgRuleTab[uiRuleTab]->HrCommitChanges(0, TRUE); if ((FAILED(hr)) && (E_UNEXPECTED != hr)) { fRet = FALSE; goto exit; } } fRet = TRUE; exit: return fRet; } BOOL COERulesMgrUI::_FOnCancel(VOID) { return TRUE; } BOOL COERulesMgrUI::_FInitTabCtrl(VOID) { BOOL fRet = FALSE; TCITEM tcitem; TCHAR szRes[CCHMAX_STRINGRES]; UINT uiRuleTab = 0; HWND hwndDlg = NULL; UINT cRuleTab = 0; UINT uiDefaultTab = 0; NMHDR nmhdr; // Make sure we have a resource dll Assert(g_hLocRes); // Initialize the Tab control structure... ZeroMemory(&tcitem, sizeof(tcitem)); tcitem.mask = TCIF_PARAM | TCIF_TEXT; tcitem.pszText = szRes; tcitem.iImage = -1; // Add the tabs to the tab control for (uiRuleTab = 0; uiRuleTab < RULE_PAGE_MAX; uiRuleTab++) { // Initialize each of the pages if ((NULL == m_rgRuleTab[uiRuleTab]) || (FAILED(m_rgRuleTab[uiRuleTab]->HrInit(m_hwndDlg, m_dwFlags)))) { continue; } // Create the child dialog for the tab hwndDlg = CreateDialogParam(g_hLocRes, MAKEINTRESOURCE(m_rgRuleTab[uiRuleTab]->UiGetDlgRscId()), m_hwndDlg, m_rgRuleTab[uiRuleTab]->DlgProcGetPageDlgProc(), (LPARAM) (m_rgRuleTab[uiRuleTab])); if (NULL == hwndDlg) { continue; } tcitem.lParam = (LPARAM) hwndDlg; // Load in the display string for the tab LoadString(g_hLocRes, m_rgRuleTab[uiRuleTab]->UiGetTabLabelId(), szRes, ARRAYSIZE(szRes)); // Insert the tab TabCtrl_InsertItem(m_hwndTab, cRuleTab, &tcitem); // Save off the default tab if (uiRuleTab == (m_dwFlags & RULE_PAGE_MASK)) { uiDefaultTab = cRuleTab; } cRuleTab++; } if (0 == cRuleTab) { fRet = FALSE; goto exit; } // Select the proper tab if (-1 != TabCtrl_SetCurSel(m_hwndTab, uiDefaultTab)) { nmhdr.hwndFrom = m_hwndTab; nmhdr.idFrom = idtbRulesTab; nmhdr.code = TCN_SELCHANGE; SideAssert(FALSE != FOnNotify(idtbRulesTab, &nmhdr)); } // Need to set the tab control to the bottom of the Z-order // to prevent overlapping redraws SetWindowPos(m_hwndTab, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE); // We worked fRet = TRUE; exit: return fRet; } // Default destructor for the Mail Rules UI COEMailRulesPageUI::~COEMailRulesPageUI() { if (NULL != m_pDescriptUI) { delete m_pDescriptUI; } } /////////////////////////////////////////////////////////////////////////////// // // HrInit // // This initializes the mail rules UI dialog // // hwndOwner - the handle to the owner window of this dialog // dwFlags - modifiers on how this dialog should act // // Returns: S_OK, if it was successfully initialized // /////////////////////////////////////////////////////////////////////////////// HRESULT COEMailRulesPageUI::HrInit(HWND hwndOwner, DWORD dwFlags) { HRESULT hr = S_OK; // Check incoming params if (NULL == hwndOwner) { hr = E_INVALIDARG; goto exit; } if (0 != (m_dwState & STATE_INITIALIZED)) { hr = E_UNEXPECTED; goto exit; } m_hwndOwner = hwndOwner; m_dwFlags = dwFlags; // Setup the description field m_pDescriptUI = new CRuleDescriptUI; if (NULL == m_pDescriptUI) { hr = E_OUTOFMEMORY; goto exit; } m_dwState |= STATE_INITIALIZED; hr = S_OK; exit: return hr; } /////////////////////////////////////////////////////////////////////////////// // // HrCommitChanges // // This commits the changes to the rules // // dwFlags - modifiers on how we should commit the changes // fClearDirty - should we clear the dirty state // // Returns: S_OK, if it was successfully committed // /////////////////////////////////////////////////////////////////////////////// HRESULT COEMailRulesPageUI::HrCommitChanges(DWORD dwFlags, BOOL fClearDirty) { HRESULT hr = S_OK; LONG cRules = 0; INT iSelected = 0; RULEINFO * pinfoRule = NULL; ULONG cpinfoRule = 0; LVITEM lvitem = {0}; Assert(NULL != m_hwndList); // Check incoming params if (0 != dwFlags) { hr = E_INVALIDARG; goto exit; } // Fail if we weren't initialized if (0 == (m_dwState & STATE_INITIALIZED)) { hr = E_UNEXPECTED; goto exit; } // If we aren't dirty, then there's // nothing to do if ((0 == (m_dwState & STATE_DIRTY)) && (S_OK != m_pDescriptUI->HrIsDirty())) { hr = S_FALSE; goto exit; } // Get the number of rules in the list view cRules = ListView_GetItemCount(m_hwndList); if (0 != cRules) { // Let's make sure the selected rule is saved... iSelected = ListView_GetNextItem(m_hwndList, -1, LVNI_SELECTED); if (-1 != iSelected) { _FSaveRule(iSelected); } // Allocate space to hold the rules hr = HrAlloc( (void **) &pinfoRule, cRules * sizeof(*pinfoRule)); if (FAILED(hr)) { goto exit; } ZeroMemory(pinfoRule, cRules * sizeof(*pinfoRule)); lvitem.mask = LVIF_PARAM; cpinfoRule = 0; for (lvitem.iItem = 0; lvitem.iItem < cRules; lvitem.iItem++) { // Grab the rule from the list view if (FALSE != ListView_GetItem(m_hwndList, &lvitem)) { if (NULL == lvitem.lParam) { continue; } pinfoRule[cpinfoRule] = *((RULEINFO *) (lvitem.lParam)); cpinfoRule++; } } } // Set the rules into the rules manager hr = g_pRulesMan->SetRules(SETF_CLEAR, m_typeRule, pinfoRule, cpinfoRule); if (FAILED(hr)) { goto exit; } // Should we clear the dirty state if (FALSE != fClearDirty) { m_dwState &= ~STATE_DIRTY; } hr = S_OK; exit: SafeMemFree(pinfoRule); return hr; } INT_PTR CALLBACK COEMailRulesPageUI::FMailRulesPageDlgProc(HWND hwndDlg, UINT uiMsg, WPARAM wParam, LPARAM lParam) { BOOL fRet = FALSE; COEMailRulesPageUI * pMailUI = NULL; HWND hwndRE = 0; pMailUI = (COEMailRulesPageUI *) GetWindowLongPtr(hwndDlg, GWLP_USERDATA); switch (uiMsg) { case WM_INITDIALOG: // Grab the UI object pointer pMailUI = (COEMailRulesPageUI *) lParam; // Set it into the dialog so we can get it back SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR) pMailUI); hwndRE = CreateREInDialogA(hwndDlg, idredtRuleDescription); if (!hwndRE || (FALSE == pMailUI->FOnInitDialog(hwndDlg))) { EndDialog(hwndDlg, -1); fRet = TRUE; goto exit; } // We didn't set the focus so return TRUE fRet = TRUE; break; case WM_COMMAND: fRet = pMailUI->FOnCommand((UINT) HIWORD(wParam), (INT) LOWORD(wParam), (HWND) lParam); break; case WM_NOTIFY: fRet = pMailUI->FOnNotify((INT) LOWORD(wParam), (NMHDR *) lParam); break; case WM_DESTROY: fRet = pMailUI->FOnDestroy(); break; case WM_HELP: case WM_CONTEXTMENU: fRet = OnContextHelp(hwndDlg, uiMsg, wParam, lParam, g_rgCtxMapMailRules); break; } exit: return fRet; } /////////////////////////////////////////////////////////////////////////////// // // FGetRules // // This brings up the edit UI for the selected rule from the mail rules list // // fBegin - is this for the LVN_BEGINLABELEDIT notification // pdi - the display info for the message // // Returns: TRUE, if the message was handled // FALSE, otherwise // /////////////////////////////////////////////////////////////////////////////// BOOL COEMailRulesPageUI::FGetRules(RULE_TYPE typeRule, RULENODE ** pprnode) { BOOL fRet = FALSE; INT iSelected = 0; INT cRules = 0; LVITEM lvitem; IOERule * pIRule = NULL; RULENODE * prnodeNew = NULL; RULENODE * prnodeList = NULL; RULENODE * prnodeWalk = NULL; HRESULT hr = S_OK; RULEINFO * pinfoRule = NULL; Assert(NULL != m_hwndList); if (NULL == pprnode) { fRet = FALSE; goto exit; } // Fail if we weren't initialized if ((0 == (m_dwState & STATE_INITIALIZED)) || (NULL == m_hwndList)) { fRet = FALSE; goto exit; } // Initialize the outgoing param *pprnode = NULL; // Get the selected item iSelected = ListView_GetNextItem(m_hwndList, -1, LVNI_SELECTED); // Make sure we don't loose any changes _FSaveRule(iSelected); // Check the count of items in the list view cRules = ListView_GetItemCount(m_hwndList); if (0 == cRules) { fRet = TRUE; goto exit; } // Initialize the list view item ZeroMemory(&lvitem, sizeof(lvitem)); lvitem.mask = LVIF_PARAM | LVIF_STATE; lvitem.stateMask = LVIS_STATEIMAGEMASK; // Create the list of rules for (lvitem.iItem = 0; lvitem.iItem < cRules; lvitem.iItem++) { // Grab the rule from the listview if (FALSE == ListView_GetItem(m_hwndList, &lvitem)) { fRet = FALSE; goto exit; } pinfoRule = (RULEINFO *) (lvitem.lParam); if ((NULL == pinfoRule) || (NULL == pinfoRule->pIRule)) { continue; } // Skip over invalid rules hr = pinfoRule->pIRule->Validate(0); if (FAILED(hr) || (S_FALSE == hr)) { continue; } // Create a new rule node prnodeNew = new RULENODE; if (NULL == prnodeNew) { fRet = FALSE; goto exit; } prnodeNew->pNext = NULL; prnodeNew->pIRule = pinfoRule->pIRule; prnodeNew->pIRule->AddRef(); // Add the new node to the list if (NULL == prnodeWalk) { prnodeList = prnodeNew; } else { prnodeWalk->pNext = prnodeNew; } prnodeWalk = prnodeNew; prnodeNew = NULL; } // Set the outgoing param *pprnode = prnodeList; prnodeList = NULL; fRet = TRUE; exit: while (NULL != prnodeList) { prnodeWalk = prnodeList; if (NULL != prnodeWalk->pIRule) { prnodeWalk->pIRule->Release(); } prnodeList = prnodeList->pNext; delete prnodeWalk; //MemFree(prnodeWalk); } return fRet; } /////////////////////////////////////////////////////////////////////////////// // // FOnInitDialog // // This handles the WM_INITDIALOG message for the mail rules UI dialog // // hwndDlg - the handle to the dialog window // // Returns: TRUE, if it was successfully initialized // FALSE, otherwise // /////////////////////////////////////////////////////////////////////////////// BOOL COEMailRulesPageUI::FOnInitDialog(HWND hwndDlg) { BOOL fRet = FALSE; HRESULT hr = S_OK; TCHAR szRes[CCHMAX_STRINGRES]; // Check incoming params if (NULL == hwndDlg) { fRet = FALSE; goto exit; } // If we haven't been initialized yet... if (0 == (m_dwState & STATE_INITIALIZED)) { fRet = FALSE; goto exit; } // Save off the dialog window handle m_hwndDlg = hwndDlg; // Set the default font onto the dialog SetIntlFont(m_hwndDlg); // Save off some of the controls m_hwndList = GetDlgItem(hwndDlg, idlvRulesList); m_hwndDescript = GetDlgItem(hwndDlg, idredtRuleDescription); if ((NULL == m_hwndList) || (NULL == m_hwndDescript)) { fRet = FALSE; goto exit; } // We need to change the title if we are a news page if (RULE_TYPE_NEWS == m_typeRule) { if (0 == LoadString(g_hLocRes, idsRuleTitleNews, szRes, ARRAYSIZE(szRes))) { goto exit; } SetDlgItemText(m_hwndDlg, idcRuleTitle, szRes); } else { if (FALSE != FIsIMAPOrHTTPAvailable()) { AthLoadString(idsRulesNoIMAP, szRes, sizeof(szRes)); SetDlgItemText(m_hwndDlg, idcRuleTitle, szRes); } } if (FAILED(m_pDescriptUI->HrInit(m_hwndDescript, 0))) { fRet = FALSE; goto exit; } // Initialize the list view fRet = _FInitListCtrl(); if (FALSE == fRet) { goto exit; } // Load the list view fRet = _FLoadListCtrl(); if (FALSE == fRet) { goto exit; } // Check to see if the list is empty if (0 == ListView_GetItemCount(m_hwndList)) { if (((m_typeRule == RULE_TYPE_MAIL) && (RMF_MAIL == m_dwFlags)) || ((m_typeRule == RULE_TYPE_NEWS) && (RMF_NEWS == m_dwFlags))) { PostMessage(m_hwndDlg, WM_COMMAND, MAKEWPARAM(idbNewRule, 0), (LPARAM) (GetDlgItem(m_hwndDlg, idbNewRule))); } } // Everything's AOK fRet = TRUE; exit: return fRet; } /////////////////////////////////////////////////////////////////////////////// // // FOnCommand // // This handles the WM_COMMAND message for the mail rules UI dialog // // Returns: TRUE, if it was successfully handled // FALSE, otherwise // /////////////////////////////////////////////////////////////////////////////// BOOL COEMailRulesPageUI::FOnCommand(UINT uiNotify, INT iCtl, HWND hwndCtl) { BOOL fRet = FALSE; LVITEM lvitem; INT iSelected = 0; // We only handle menu and accelerator commands if ((0 != uiNotify) && (1 != uiNotify)) { fRet = FALSE; goto exit; } switch (iCtl) { case idbNewRule: _NewRule(); fRet = TRUE; break; case idbModifyRule: // Get the selected item from the rule list iSelected = ListView_GetNextItem(m_hwndList, -1, LVNI_SELECTED); if (-1 != iSelected) { // Bring up the rule editor for that item _EditRule(iSelected); fRet = TRUE; } break; case idbMoveUpRule: case idbMoveDownRule: // Get the selected item from the rule list iSelected = ListView_GetNextItem(m_hwndList, -1, LVNI_SELECTED); if (-1 != iSelected) { // Move the rule in the desired direction _MoveRule(iSelected, (idbMoveUpRule == iCtl) ? MOVE_RULE_UP : MOVE_RULE_DOWN); fRet = TRUE; } break; case idbDeleteRule: // Get the selected item from the rule list iSelected = ListView_GetNextItem(m_hwndList, -1, LVNI_SELECTED); if (-1 != iSelected) { // Remove the rule from the list _RemoveRule(iSelected); fRet = TRUE; } break; case idbCopyRule: // Get the selected item from the rule list iSelected = ListView_GetNextItem(m_hwndList, -1, LVNI_SELECTED); if (-1 != iSelected) { // Copy the rule from the list _CopyRule(iSelected); fRet = TRUE; } break; case idbRulesApplyTo: // Apply the rule from the list _OnApplyTo(ListView_GetNextItem(m_hwndList, -1, LVNI_SELECTED)); fRet = TRUE; break; } exit: return fRet; } /////////////////////////////////////////////////////////////////////////////// // // FOnNotify // // This handles the WM_NOTIFY message for the mail rules UI dialog // // Returns: TRUE, if it was successfully destroyed // FALSE, otherwise // /////////////////////////////////////////////////////////////////////////////// BOOL COEMailRulesPageUI::FOnNotify(INT iCtl, NMHDR * pnmhdr) { BOOL fRet = FALSE; NMLISTVIEW * pnmlv = NULL; NMLVKEYDOWN * pnmlvkd = NULL; INT iSelected = 0; LVHITTESTINFO lvh; // We only handle notifications for the list control // or the desscription field if ((idlvRulesList != pnmhdr->idFrom) && (idredtRuleDescription != pnmhdr->idFrom)) { fRet = FALSE; goto exit; } pnmlv = (LPNMLISTVIEW) pnmhdr; switch (pnmlv->hdr.code) { case NM_CLICK: // Did we click on an item? if (-1 != pnmlv->iItem) { ZeroMemory(&lvh, sizeof(lvh)); lvh.pt = pnmlv->ptAction; iSelected = ListView_HitTest(m_hwndList, &lvh); if (-1 != iSelected) { // Did we click on the enable field? if ((0 != (lvh.flags & LVHT_ONITEMSTATEICON)) && (0 == (lvh.flags & LVHT_ONITEMLABEL))) { // Make sure this item is selected ListView_SetItemState(m_hwndList, iSelected, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED); // Set the proper enable state _EnableRule(iSelected); } } } else { // We clicked outside the list // Disable the buttons _EnableButtons(pnmlv->iItem); } break; case NM_DBLCLK: // Did we click on an item? if (-1 != pnmlv->iItem) { ZeroMemory(&lvh, sizeof(lvh)); lvh.pt = pnmlv->ptAction; iSelected = ListView_HitTest(pnmlv->hdr.hwndFrom, &lvh); if (-1 != iSelected) { // Did we click on the rule name? if (0 != (lvh.flags & LVHT_ONITEMLABEL)) { // Edit the rule _EditRule(iSelected); } } } else { // We clicked outside the list // Disable the buttons _EnableButtons(pnmlv->iItem); } break; case LVN_ITEMCHANGED: // If an item's state changed to selected.. if ((-1 != pnmlv->iItem) && (0 != (pnmlv->uChanged & LVIF_STATE)) && (0 == (pnmlv->uOldState & LVIS_SELECTED)) && (0 != (pnmlv->uNewState & LVIS_SELECTED))) { // Enable the buttons _EnableButtons(pnmlv->iItem); } break; case LVN_ITEMCHANGING: // If an item's state changed to unselected.. if ((-1 != pnmlv->iItem) && (0 != (pnmlv->uChanged & LVIF_STATE)) && (0 != (pnmlv->uOldState & LVIS_SELECTED)) && (0 == (pnmlv->uNewState & LVIS_SELECTED))) { // Save off the rule changes _FSaveRule(pnmlv->iItem); } break; case LVN_KEYDOWN: pnmlvkd = (NMLVKEYDOWN *) pnmhdr; // The space key changes the enable state of a rule if (VK_SPACE == pnmlvkd->wVKey) { // Are we on a rule? iSelected = ListView_GetNextItem(m_hwndList, -1, LVNI_SELECTED); if (-1 != iSelected) { // Change the enable state of the rule _EnableRule(iSelected); } } // The delete key removes the rule from the list view else if (VK_DELETE == pnmlvkd->wVKey) { // Are we on a rule? iSelected = ListView_GetNextItem(m_hwndList, -1, LVNI_SELECTED); if (-1 != iSelected) { // Remove the rule from the list _RemoveRule(iSelected); } } break; case LVN_BEGINLABELEDIT: case LVN_ENDLABELEDIT: fRet = _FOnLabelEdit((LVN_BEGINLABELEDIT == pnmlv->hdr.code), (NMLVDISPINFO *) pnmhdr); break; case NM_RULE_CHANGED: fRet = _FOnRuleDescValid(); break; } exit: return fRet; } /////////////////////////////////////////////////////////////////////////////// // // FOnDestroy // // This handles the WM_DESTROY message for the mail rules UI dialog // // Returns: TRUE, if it was successfully destroyed // FALSE, otherwise // /////////////////////////////////////////////////////////////////////////////// BOOL COEMailRulesPageUI::FOnDestroy(VOID) { BOOL fRet = FALSE; UINT cRules = 0; UINT uiIndex = 0; LVITEM lvitem = {0}; UNALIGNED RULEINFO * pIRuleInfo = NULL; Assert(m_hwndList); // Get the number of rules in the list view cRules = ListView_GetItemCount(m_hwndList); // Initialize to get the rule interface from the list view lvitem.mask = LVIF_PARAM; // Release each of the rules from the list view for (uiIndex = 0; uiIndex < cRules; uiIndex++) { lvitem.iItem = uiIndex; // Get the rule interface if (FALSE != ListView_GetItem(m_hwndList, &lvitem)) { pIRuleInfo = (UNALIGNED RULEINFO *) (lvitem.lParam); if (NULL != pIRuleInfo) { // Release the rule if (NULL != pIRuleInfo->pIRule) { pIRuleInfo->pIRule->Release(); } delete pIRuleInfo; // MemFree(pIRuleInfo); } } } fRet = TRUE; return fRet; } /////////////////////////////////////////////////////////////////////////////// // // _FInitListCtrl // // This initializes the list view control in the mail rules dialog // // Returns: TRUE, on successful initialization // FALSE, otherwise. // /////////////////////////////////////////////////////////////////////////////// BOOL COEMailRulesPageUI::_FInitListCtrl(VOID) { BOOL fRet = FALSE; LVCOLUMN lvc; RECT rc; HIMAGELIST himl = NULL; Assert(NULL != m_hwndList); // Initialize the list view structure ZeroMemory(&lvc, sizeof(lvc)); lvc.mask = LVCF_WIDTH; // Calculate the size of the list view GetClientRect(m_hwndList, &rc); lvc.cx = rc.right - GetSystemMetrics(SM_CXVSCROLL); ListView_InsertColumn(m_hwndList, 0, &lvc); // Set the state image list himl = ImageList_LoadBitmap(g_hLocRes, MAKEINTRESOURCE(idb16x16st), 16, 0, RGB(255, 0, 255)); if (NULL != himl) { ListView_SetImageList(m_hwndList, himl, LVSIL_STATE); } // Full row selection on listview ListView_SetExtendedListViewStyle(m_hwndList, LVS_EX_FULLROWSELECT); // We worked fRet = TRUE; return fRet; } /////////////////////////////////////////////////////////////////////////////// // // _FLoadListCtrl // // This loads the list view with the current Mail rules // // Returns: TRUE, if it was successfully loaded // FALSE, otherwise // /////////////////////////////////////////////////////////////////////////////// BOOL COEMailRulesPageUI::_FLoadListCtrl(VOID) { BOOL fRet = FALSE; HRESULT hr = S_OK; DWORD dwListIndex = 0; RULEINFO * pinfoRules = NULL; ULONG cpinfoRules = 0; ULONG ulIndex = 0; IOERule * pIRule = NULL; Assert(NULL != m_hwndList); // Get the Rules enumerator Assert(NULL != g_pRulesMan); hr = g_pRulesMan->GetRules(GETF_EDIT, m_typeRule, &pinfoRules, &cpinfoRules); if (FAILED(hr)) { fRet = FALSE; goto exit; } // Remove all the items from the list control ListView_DeleteAllItems(m_hwndList); // Add each filter to the list dwListIndex = 0; for (ulIndex = 0; ulIndex < cpinfoRules; ulIndex++) { // Make a copy of the rule hr = pinfoRules[ulIndex].pIRule->Clone(&pIRule); if (FAILED(hr)) { continue; } // Add filter to the list if (FALSE != _FAddRuleToList(dwListIndex, pinfoRules[ulIndex].ridRule, pIRule)) { dwListIndex++; } SafeRelease(pIRule); } // Select the first item in the list if (0 != dwListIndex) { ListView_SetItemState(m_hwndList, 0, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED); } // Enable the dialog buttons. _EnableButtons((0 != dwListIndex) ? 0 : -1); fRet = TRUE; exit: SafeRelease(pIRule); if (NULL != pinfoRules) { for (ulIndex = 0; ulIndex < cpinfoRules; ulIndex++) { pinfoRules[ulIndex].pIRule->Release(); } MemFree(pinfoRules); } return fRet; } /////////////////////////////////////////////////////////////////////////////// // // _FAddRuleToList // // This adds the filter passed in to the list view // // dwIndex - the index on where to add the filter to into the list // rhdlTag - the rule handle for the new rule // pIRule - the actual rule // // Returns: TRUE, if it was successfully added // FALSE, otherwise // /////////////////////////////////////////////////////////////////////////////// BOOL COEMailRulesPageUI::_FAddRuleToList(DWORD dwIndex, RULEID ridRule, IOERule * pIRule) { BOOL fRet = FALSE; HRESULT hr = S_OK; PROPVARIANT propvar = {0}; LVITEM lvitem = {0}; BOOL fNotValid = FALSE; BOOL fDisabled = FALSE; RULEINFO * pinfoRule = NULL; Assert(NULL != m_hwndList); // If there's nothing to do... if (NULL == pIRule) { fRet = FALSE; goto exit; } // Is it disabled? hr = pIRule->GetProp(RULE_PROP_DISABLED, 0, &propvar); if (FAILED(hr)) { fRet = FALSE; goto exit; } fDisabled = !!propvar.boolVal; // Need to check if the rule is valid hr = pIRule->Validate(0); if (FAILED(hr)) { fRet = FALSE; goto exit; } fNotValid = (hr == S_FALSE); // Find out the name of the filter hr = pIRule->GetProp(RULE_PROP_NAME , 0, &propvar); if (FAILED(hr)) { fRet = FALSE; goto exit; } // Allocate space for the rule pinfoRule = new RULEINFO; if (NULL == pinfoRule) { fRet = FALSE; goto exit; } // Set up the value pinfoRule->ridRule = ridRule; pinfoRule->pIRule = pIRule; pinfoRule->pIRule->AddRef(); // Add in the image and rule interface lvitem.mask = LVIF_PARAM | LVIF_STATE | LVIF_TEXT; lvitem.iItem = dwIndex; // Need to change the state to mark the rule as invalid if (FALSE != fNotValid) { lvitem.state = INDEXTOSTATEIMAGEMASK(iiconStateInvalid + 1); } else { lvitem.state = fDisabled ? INDEXTOSTATEIMAGEMASK(iiconStateUnchecked + 1) : INDEXTOSTATEIMAGEMASK(iiconStateChecked + 1); } lvitem.stateMask = LVIS_STATEIMAGEMASK; lvitem.pszText = propvar.pszVal; lvitem.cchTextMax = lstrlen(propvar.pszVal) + 1; lvitem.lParam = (LPARAM) pinfoRule; if (-1 == ListView_InsertItem(m_hwndList, &lvitem)) { fRet = FALSE; goto exit; } fRet = TRUE; exit: PropVariantClear(&propvar); return fRet; } /////////////////////////////////////////////////////////////////////////////// // // _EnableButtons // // This enables or disables the buttons in the Mail rules UI dialog // depending on what is selected. // // iSelected - the item that was selected, // -1 means that nothing was selected // // Returns: NONE // /////////////////////////////////////////////////////////////////////////////// void COEMailRulesPageUI::_EnableButtons(INT iSelected) { int cRules = 0; BOOL fSelected = FALSE; BOOL fEnDisUp = FALSE; BOOL fEnDisDown = FALSE; LVITEM lvitem = {0}; IOERule * pIRule = NULL; Assert(NULL != m_hwndList); // Load the description field _LoadRule(iSelected); // Check the count of items in the list view cRules = ListView_GetItemCount(m_hwndList); fSelected = (-1 != iSelected); // If we have rules and the top rule isn't selected fEnDisUp = ((1 < cRules) && (0 != iSelected) && (FALSE != fSelected)); // If we have rules and the bottom rule ins't selected fEnDisDown = ((1 < cRules) && ((cRules - 1) != iSelected) && (FALSE != fSelected)); // Enable the up/down buttons RuleUtil_FEnDisDialogItem(m_hwndDlg, idbMoveDownRule, fEnDisDown); RuleUtil_FEnDisDialogItem(m_hwndDlg, idbMoveUpRule, fEnDisUp); // Enable the rule action buttons RuleUtil_FEnDisDialogItem(m_hwndDlg, idbDeleteRule, fSelected); RuleUtil_FEnDisDialogItem(m_hwndDlg, idbCopyRule, fSelected); RuleUtil_FEnDisDialogItem(m_hwndDlg, idbModifyRule, fSelected); return; } /////////////////////////////////////////////////////////////////////////////// // // _EnableRule // // This switches the current enabled state of the list view item // and updates the UI // // iSelected - index of the item in the listview to work on // // Returns: NONE // /////////////////////////////////////////////////////////////////////////////// VOID COEMailRulesPageUI::_EnableRule(int iSelected) { HRESULT hr = S_OK; LVITEM lvi = {0}; IOERule * pIRule = NULL; BOOL fEnabled = FALSE; PROPVARIANT propvar; // Grab the list view item lvi.mask = LVIF_PARAM | LVIF_STATE; lvi.stateMask = LVIS_STATEIMAGEMASK; lvi.iItem = iSelected; if (FALSE == ListView_GetItem(m_hwndList, &lvi)) { goto exit; } pIRule = ((RULEINFO *) (lvi.lParam))->pIRule; // Let's make sure we can enable this rule hr = m_pDescriptUI->HrVerifyRule(); if (S_OK != hr) { // Put up a message saying something is busted AthMessageBoxW(m_hwndDlg, MAKEINTRESOURCEW(idsAthenaMail), MAKEINTRESOURCEW(idsRulesErrorEnable), NULL, MB_OK | MB_ICONINFORMATION); goto exit; } // Get the new enabled value fEnabled = (lvi.state != INDEXTOSTATEIMAGEMASK(iiconStateChecked+1)); // Set the UI to the opposite enabled state ZeroMemory(&lvi, sizeof(lvi)); lvi.mask = LVIF_STATE; lvi.iItem = iSelected; lvi.state = fEnabled ? INDEXTOSTATEIMAGEMASK(iiconStateChecked+1) : INDEXTOSTATEIMAGEMASK(iiconStateUnchecked+1); lvi.stateMask = LVIS_STATEIMAGEMASK; ListView_SetItem(m_hwndList, &lvi); // Set the enabled property ZeroMemory(&propvar, sizeof(propvar)); propvar.vt = VT_BOOL; propvar.boolVal = !fEnabled; hr = pIRule->SetProp(RULE_PROP_DISABLED, 0, &propvar); if (FAILED(hr)) { goto exit; } // Tell the description field about it m_pDescriptUI->HrSetEnabled(fEnabled); // Redraw the string the new rule m_pDescriptUI->ShowDescriptionString(); // Mark the rule list as dirty m_dwState |= STATE_DIRTY; exit: return; } /////////////////////////////////////////////////////////////////////////////// // // _LoadRule // // This loads the selected rule into the description field. // If there isn't a selected rule, then the description field is cleared. // // iSelected - the item that was selected, // -1 means that nothing was selected // // Returns: NONE // /////////////////////////////////////////////////////////////////////////////// void COEMailRulesPageUI::_LoadRule(INT iSelected) { LVITEM lvi = {0}; IOERule * pIRule = NULL; Assert(NULL != m_hwndList); Assert(NULL != m_pDescriptUI); // Grab the rule from the list view if (-1 != iSelected) { lvi.iItem = iSelected; lvi.mask = LVIF_PARAM; if (FALSE != ListView_GetItem(m_hwndList, &lvi)) { pIRule = ((RULEINFO *) (lvi.lParam))->pIRule; } } // Have the description field load this rule m_pDescriptUI->HrSetRule(m_typeRule, pIRule); // Display the new rule m_pDescriptUI->ShowDescriptionString(); return; } /////////////////////////////////////////////////////////////////////////////// // // _FSaveRule // // This checks to see if the rule has been changed in the description // area and if it has, then it warns the user and changes the text // // iSelected - index of the item in the listview to work on // // Returns: TRUE, if the rule either didn't change or did change without problems // /////////////////////////////////////////////////////////////////////////////// BOOL COEMailRulesPageUI::_FSaveRule(int iSelected) { BOOL fRet = FALSE; HRESULT hr = S_OK; LVITEM lvi = {0}; IOERule * pIRule = NULL; PROPVARIANT propvar = {0}; CRIT_ITEM * pCritItem = NULL; ULONG cCritItem = 0; ACT_ITEM * pActItem = NULL; ULONG cActItem = 0; // If the rule didn't change, then we're done hr = m_pDescriptUI->HrIsDirty(); if (S_OK != hr) { fRet = (S_FALSE == hr); goto exit; } // Grab the list view item lvi.mask = LVIF_PARAM; lvi.iItem = iSelected; if (FALSE == ListView_GetItem(m_hwndList, &lvi)) { fRet = FALSE; goto exit; } pIRule = ((RULEINFO *) (lvi.lParam))->pIRule; // Get the criteria from the rule hr = m_pDescriptUI->HrGetCriteria(&pCritItem, &cCritItem); if (FAILED(hr)) { fRet = FALSE; goto exit; } // Get the actions for the rule hr = m_pDescriptUI->HrGetActions(&pActItem, &cActItem); if (FAILED(hr)) { fRet = FALSE; goto exit; } // Set the criteria from the rule PropVariantClear(&propvar); propvar.vt = VT_BLOB; propvar.blob.cbSize = cCritItem * sizeof(CRIT_ITEM); propvar.blob.pBlobData = (BYTE *) pCritItem; hr = pIRule->SetProp(RULE_PROP_CRITERIA, 0, &propvar); ZeroMemory(&propvar, sizeof(propvar)); if (FAILED(hr)) { fRet = FALSE; goto exit; } // Set the actions for the rule PropVariantClear(&propvar); propvar.vt = VT_BLOB; propvar.blob.cbSize = cActItem * sizeof(ACT_ITEM); propvar.blob.pBlobData = (BYTE *) pActItem; hr = pIRule->SetProp(RULE_PROP_ACTIONS, 0, &propvar); ZeroMemory(&propvar, sizeof(propvar)); if (FAILED(hr)) { fRet = FALSE; goto exit; } // Mark the rule list as dirty m_dwState |= STATE_DIRTY; // Make sure we clear out the fact that we saved the rule m_pDescriptUI->HrClearDirty(); // Set the proper return value fRet = TRUE; exit: RuleUtil_HrFreeCriteriaItem(pCritItem, cCritItem); SafeMemFree(pCritItem); RuleUtil_HrFreeActionsItem(pActItem, cActItem); SafeMemFree(pActItem); return fRet; } /////////////////////////////////////////////////////////////////////////////// // // _NewRule // // This brings up a fresh rules editor // // Returns: NONE // /////////////////////////////////////////////////////////////////////////////// void COEMailRulesPageUI::_NewRule(VOID) { HRESULT hr = S_OK; IOERule * pIRule = NULL; TCHAR szRes[CCHMAX_STRINGRES + 5]; ULONG cchRes = 0; ULONG ulIndex = 0; TCHAR szName[CCHMAX_STRINGRES + 5]; LVFINDINFO lvfinfo = {0}; PROPVARIANT propvar = {0}; CEditRuleUI * pEditRuleUI = NULL; LONG cRules = 0; UINT uiStrId = 0; // Create a new rule object if (FAILED(HrCreateRule(&pIRule))) { goto exit; } // Figure out the string Id if (RULE_TYPE_NEWS == m_typeRule) { uiStrId = idsRuleNewsDefaultName; } else { uiStrId = idsRuleMailDefaultName; } // Figure out the name of the new rule ... cchRes = LoadString(g_hLocRes, uiStrId, szRes, ARRAYSIZE(szRes)); if (0 == cchRes) { goto exit; } ulIndex = 1; wnsprintf(szName, ARRAYSIZE(szName), szRes, ulIndex); lvfinfo.flags = LVFI_STRING; lvfinfo.psz = szName; while (-1 != ListView_FindItem(m_hwndList, -1, &lvfinfo)) { ulIndex++; wnsprintf(szName, ARRAYSIZE(szName), szRes, ulIndex); } propvar.vt = VT_LPSTR; propvar.pszVal = szName; hr = pIRule->SetProp(RULE_PROP_NAME, 0, &propvar); if (FAILED(hr)) { goto exit; } // Create a rules editor object pEditRuleUI = new CEditRuleUI; if (NULL == pEditRuleUI) { goto exit; } // Initialize the editor object if (FAILED(pEditRuleUI->HrInit(m_hwndDlg, ERF_NEWRULE, m_typeRule, pIRule, NULL))) { goto exit; } // Bring up the rules editor UI hr = pEditRuleUI->HrShow(); if (FAILED(hr)) { goto exit; } if (S_OK == hr) { // Mark the rule list as dirty m_dwState |= STATE_DIRTY; // Add the rule to the manager UI cRules = ListView_GetItemCount(m_hwndList); _FAddRuleToList(cRules, RULEID_INVALID, pIRule); // Make sure the new item is selected ListView_SetItemState(m_hwndList, cRules, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED); // Make sure the new item is visible ListView_EnsureVisible(m_hwndList, cRules, FALSE); } exit: SafeRelease(pIRule); if (NULL != pEditRuleUI) { delete pEditRuleUI; } return; } /////////////////////////////////////////////////////////////////////////////// // // _EditRule // // This brings up the edit UI for the selected rule from the mail rules list // // iSelected - index of the item in the listview to work on // // Returns: NONE // /////////////////////////////////////////////////////////////////////////////// VOID COEMailRulesPageUI::_EditRule(int iSelected) { HRESULT hr = S_OK; LVITEM lvitem = {0}; IOERule * pIRule = NULL; CEditRuleUI * pEditRuleUI = NULL; PROPVARIANT propvar = {0}; BOOL fNotValid = FALSE; BOOL fDisabled = FALSE; Assert(NULL != m_hwndList); // Make sure we don't loose any changes _FSaveRule(iSelected); // Grab the rule from the list view lvitem.iItem = iSelected; lvitem.mask = LVIF_PARAM; if (FALSE == ListView_GetItem(m_hwndList, &lvitem)) { goto exit; } pIRule = ((RULEINFO *) (lvitem.lParam))->pIRule; if (NULL == pIRule) { goto exit; } // Create the rules editor pEditRuleUI = new CEditRuleUI; if (NULL == pEditRuleUI) { goto exit; } // Initialize the editor object if (FAILED(pEditRuleUI->HrInit(m_hwndDlg, 0, m_typeRule, pIRule, NULL))) { goto exit; } // Bring up the rules editor UI hr = pEditRuleUI->HrShow(); if (FAILED(hr)) { goto exit; } // If the rule changed, make sure we reload the description field if (S_OK == hr) { // Mark the rule list as dirty m_dwState |= STATE_DIRTY; ZeroMemory(&lvitem, sizeof(lvitem)); lvitem.mask = LVIF_STATE; lvitem.stateMask = LVIS_STATEIMAGEMASK; lvitem.iItem = iSelected; // Is it disabled? hr = pIRule->GetProp(RULE_PROP_DISABLED , 0, &propvar); if (FAILED(hr)) { goto exit; } fDisabled = !!propvar.boolVal; // Need to check if the rule is valid hr = pIRule->Validate(0); if (FAILED(hr)) { goto exit; } fNotValid = (hr == S_FALSE); // Grab the rule name PropVariantClear(&propvar); hr = pIRule->GetProp(RULE_PROP_NAME, 0, &propvar); if (FAILED(hr)) { goto exit; } if ((VT_LPSTR == propvar.vt) && (NULL != propvar.pszVal) && ('\0' != propvar.pszVal[0])) { lvitem.mask |= LVIF_TEXT; lvitem.pszText = propvar.pszVal; lvitem.cchTextMax = lstrlen(propvar.pszVal) + 1; } // Grab the rule state // Need to change the state to mark the rule as invalid if (FALSE != fNotValid) { lvitem.state = INDEXTOSTATEIMAGEMASK(iiconStateInvalid + 1); } else { lvitem.state = fDisabled ? INDEXTOSTATEIMAGEMASK(iiconStateUnchecked + 1) : INDEXTOSTATEIMAGEMASK(iiconStateChecked + 1); } if (-1 == ListView_SetItem(m_hwndList, &lvitem)) { goto exit; } _EnableButtons(iSelected); } exit: PropVariantClear(&propvar); if (NULL != pEditRuleUI) { delete pEditRuleUI; } return; } /////////////////////////////////////////////////////////////////////////////// // // _MoveRule // // This moves the selected rule in the desired direction // // iSelected - index of the item in the listview to work on // dir - the direction to move the item // // Returns: NONE // /////////////////////////////////////////////////////////////////////////////// void COEMailRulesPageUI::_MoveRule(INT iSelected, MOVE_DIR dir) { LVITEM lvitem = {0}; TCHAR szName[CCHMAX_STRINGRES]; IOERule * pIRule = NULL; int nIndexNew = 0; Assert(NULL != m_hwndList); // Grab the rule from the list view szName[0] = '\0'; lvitem.iItem = iSelected; lvitem.mask = LVIF_STATE | LVIF_PARAM | LVIF_TEXT; lvitem.stateMask = LVIS_SELECTED | LVIS_FOCUSED | LVIS_STATEIMAGEMASK; lvitem.pszText = szName; lvitem.cchTextMax = ARRAYSIZE(szName); if (FALSE == ListView_GetItem(m_hwndList, &lvitem)) { goto exit; } pIRule = ((RULEINFO *) (lvitem.lParam))->pIRule; // Update the item in the list view // Get the info for the new index nIndexNew = iSelected; nIndexNew += (MOVE_RULE_UP == dir) ? -1 : 2; // Insert the new index lvitem.iItem = nIndexNew; if (-1 == ListView_InsertItem(m_hwndList, &lvitem)) { goto exit; } // Ensure the new item is visible ListView_EnsureVisible(m_hwndList, nIndexNew, FALSE); ListView_RedrawItems(m_hwndList, nIndexNew, nIndexNew); // If we moved up, then the old item is now one lower than before if (MOVE_RULE_UP == dir) { iSelected++; } // Remove the old item if (FALSE == ListView_DeleteItem(m_hwndList, iSelected)) { goto exit; } // Mark the rule list as dirty m_dwState |= STATE_DIRTY; exit: return; } /////////////////////////////////////////////////////////////////////////////// // // _RemoveRule // // This removes the selected rule from the mail rules list // // iSelected - index of the item in the listview to work on // // Returns: NONE // /////////////////////////////////////////////////////////////////////////////// VOID COEMailRulesPageUI::_RemoveRule(int iSelected) { LVITEM lvitem = {0}; RULEINFO * pinfoRule = NULL; PROPVARIANT propvar = {0}; int cRules = 0; TCHAR szRes[CCHMAX_STRINGRES]; UINT cchRes = 0; LPTSTR pszMessage = NULL; Assert(NULL != m_hwndList); // Grab the rule from the list view lvitem.iItem = iSelected; lvitem.mask = LVIF_PARAM; if (FALSE == ListView_GetItem(m_hwndList, &lvitem)) { goto exit; } pinfoRule = (RULEINFO *) (lvitem.lParam); if ((NULL == pinfoRule) || (NULL == pinfoRule->pIRule)) { goto exit; } // Warn the user to make sure they know we are going to remove the rule if (FAILED(pinfoRule->pIRule->GetProp(RULE_PROP_NAME, 0, &propvar))) { goto exit; } // Get the string template to display cchRes = LoadString(g_hLocRes, idsRulesWarnDelete, szRes, ARRAYSIZE(szRes)); if (0 == cchRes) { goto exit; } // Allocate space to hold the final display string DWORD cchSize = (cchRes + lstrlen(propvar.pszVal) + 1); if (FAILED(HrAlloc((void ** ) &pszMessage, cchSize))) { goto exit; } // Build up the string and display it wnsprintf(pszMessage, cchSize, szRes, propvar.pszVal); if (IDNO == AthMessageBox(m_hwndDlg, MAKEINTRESOURCE(idsAthenaMail), pszMessage, NULL, MB_YESNO | MB_ICONINFORMATION)) { goto exit; } // Remove the item from the list ListView_DeleteItem(m_hwndList, iSelected); // Let's make sure we have a selection in the list cRules = ListView_GetItemCount(m_hwndList); if (cRules > 0) { // Did we delete the last item in the list if (iSelected >= cRules) { // Move the selection to the new last item in the list iSelected = cRules - 1; } // Set the new selection ListView_SetItemState(m_hwndList, iSelected, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED); // Let's make sure we can see this new item ListView_EnsureVisible(m_hwndList, iSelected, FALSE); } else { // Make sure we clear out all of the buttons _EnableButtons(-1); } // Release the rule SafeRelease(pinfoRule->pIRule); // Free up the memory delete pinfoRule; // SafeMemFree(pinfoRule); // Mark the rule list as dirty m_dwState |= STATE_DIRTY; exit: PropVariantClear(&propvar); SafeMemFree(pszMessage); return; } /////////////////////////////////////////////////////////////////////////////// // // CopyRule // // This copies the selected rule from the rules manager // // iSelected - index of the item in the listview to work on // // Returns: NONE // /////////////////////////////////////////////////////////////////////////////// VOID COEMailRulesPageUI::_CopyRule(INT iSelected) { LVITEM lvitem = {0}; IOERule * pIRule = NULL; HRESULT hr = S_OK; IOERule * pIRuleNew = NULL; PROPVARIANT propvar = {0}; UINT cRules = 0; TCHAR szRes[CCHMAX_STRINGRES]; UINT cchRes = 0; LPTSTR pszName = NULL; Assert(NULL != m_hwndList); // Make sure we don't loose any changes _FSaveRule(iSelected); // Grab the rule from the list view lvitem.iItem = iSelected; lvitem.mask = LVIF_PARAM; if (FALSE == ListView_GetItem(m_hwndList, &lvitem)) { goto exit; } pIRule = ((RULEINFO *) (lvitem.lParam))->pIRule; if (NULL == pIRule) { goto exit; } // Create a new rule object hr = pIRule->Clone(&pIRuleNew); if (FAILED(hr)) { goto exit; } // Let's set the name // Get the name from the source rule hr = pIRule->GetProp(RULE_PROP_NAME, 0, &propvar); if (FAILED(hr)) { goto exit; } // Get the string template to display cchRes = LoadString(g_hLocRes, idsRulesCopyName, szRes, ARRAYSIZE(szRes)); if (0 == cchRes) { goto exit; } // Allocate space to hold the final display string DWORD cchSize = (cchRes + lstrlen(propvar.pszVal) + 1); if (FAILED(HrAlloc((void ** ) &pszName, cchSize))) { goto exit; } // Build up the string and set it wnsprintf(pszName, cchSize, szRes, propvar.pszVal); PropVariantClear(&propvar); propvar.vt = VT_LPSTR; propvar.pszVal = pszName; pszName = NULL; // Set the name into the new rule Assert(VT_LPSTR == propvar.vt); Assert(NULL != propvar.pszVal); hr = pIRuleNew->SetProp(RULE_PROP_NAME, 0, &propvar); if (FAILED(hr)) { goto exit; } // Clear the version of the new rule PropVariantClear(&propvar); propvar.vt = VT_UI4; propvar.ulVal = 0; hr = pIRuleNew->SetProp(RULE_PROP_VERSION, 0, &propvar); if (FAILED(hr)) { goto exit; } // Add the rule to the rules list right below // the original rule iSelected++; _FAddRuleToList(iSelected, RULEID_INVALID, pIRuleNew); // Make sure the new item is selected ListView_SetItemState(m_hwndList, iSelected, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED); // Make sure the new item is visible ListView_EnsureVisible(m_hwndList, iSelected, FALSE); // Mark the rule list as dirty m_dwState |= STATE_DIRTY; exit: SafeMemFree(pszName); SafeRelease(pIRuleNew); PropVariantClear(&propvar); return; } /////////////////////////////////////////////////////////////////////////////// // // FOnApplyTo // // This applies the rules into a folder // // Returns: NONE // /////////////////////////////////////////////////////////////////////////////// VOID COEMailRulesPageUI::_OnApplyTo(INT iSelected) { COEApplyRulesUI * pApplyRulesUI = NULL; RULENODE * prnodeList = NULL; RULENODE * prnodeWalk = NULL; LVITEM lvitem = {0}; IOERule * pIRule = NULL; HRESULT hr = S_OK; // Create the rules UI object pApplyRulesUI = new COEApplyRulesUI; if (NULL == pApplyRulesUI) { goto exit; } // Get the rules from the page if (FALSE == SendMessage(m_hwndOwner, WM_OE_GET_RULES, (WPARAM) m_typeRule, (LPARAM) &prnodeList)) { goto exit; } if (NULL == prnodeList) { AthMessageBoxW(m_hwndDlg, MAKEINTRESOURCEW(idsAthenaMail), (RULE_TYPE_NEWS == m_typeRule) ? MAKEINTRESOURCEW(idsErrorApplyRulesNews) : MAKEINTRESOURCEW(idsErrorApplyRulesMail), NULL, MB_OK | MB_ICONERROR); goto exit; } // Get the rule associated with the item if (-1 != iSelected) { lvitem.iItem = iSelected; lvitem.mask = LVIF_PARAM; if (FALSE != ListView_GetItem(m_hwndList, &lvitem)) { pIRule = ((RULEINFO *) (lvitem.lParam))->pIRule; if (NULL != pIRule) { // Verify that it is valid hr = pIRule->Validate(0); if ((FAILED(hr)) || (S_FALSE == hr)) { pIRule = NULL; } } } } if (FAILED(pApplyRulesUI->HrInit(m_hwndDlg, 0, m_typeRule, prnodeList, pIRule))) { goto exit; } prnodeList = NULL; if (FAILED(pApplyRulesUI->HrShow())) { goto exit; } exit: while (NULL != prnodeList) { prnodeWalk = prnodeList; if (NULL != prnodeWalk->pIRule) { prnodeWalk->pIRule->Release(); } prnodeList = prnodeList->pNext; MemFree(prnodeWalk); } if (NULL != pApplyRulesUI) { delete pApplyRulesUI; } return; } /////////////////////////////////////////////////////////////////////////////// // // _FOnLabelEdit // // This brings up the edit UI for the selected rule from the mail rules list // // fBegin - is this for the LVN_BEGINLABELEDIT notification // pdi - the display info for the message // // Returns: TRUE, if the message was handled // FALSE, otherwise // /////////////////////////////////////////////////////////////////////////////// BOOL COEMailRulesPageUI::_FOnLabelEdit(BOOL fBegin, NMLVDISPINFO * pdi) { BOOL fRet = FALSE; HWND hwndEdit; ULONG cchName = 0; IOERule * pIRule = NULL; LVITEM lvitem; PROPVARIANT propvar; Assert(NULL != m_hwndList); if (NULL == pdi) { fRet = FALSE; goto exit; } Assert(m_hwndList == pdi->hdr.hwndFrom); if (FALSE != fBegin) { // Get the edit control hwndEdit = ListView_GetEditControl(m_hwndList); if (NULL == hwndEdit) { fRet = FALSE; goto exit; } // Limit the amount of text for the name SendMessage(hwndEdit, EM_LIMITTEXT, c_cchNameMax - 1, 0); // Tell the dialog it's aok to proceed SetDlgMsgResult(m_hwndDlg, WM_NOTIFY, FALSE); } else { // Did something change? if ((-1 != pdi->item.iItem) && (NULL != pdi->item.pszText)) { cchName = lstrlen(pdi->item.pszText); // Check to see if the rule name is valid if ((0 == cchName) || (0 == UlStripWhitespace(pdi->item.pszText, TRUE, TRUE, &cchName))) { // Put up a message saying something is busted AthMessageBoxW(m_hwndDlg, MAKEINTRESOURCEW(idsAthenaMail), MAKEINTRESOURCEW(idsRulesErrorNoName), NULL, MB_OK | MB_ICONINFORMATION); SetDlgMsgResult(m_hwndDlg, WM_NOTIFY, FALSE); fRet = TRUE; goto exit; } // Get the rule for the item ZeroMemory(&lvitem, sizeof(lvitem)); lvitem.iItem = pdi->item.iItem; lvitem.mask = LVIF_PARAM; if (FALSE == ListView_GetItem(m_hwndList, &lvitem)) { SetDlgMsgResult(m_hwndDlg, WM_NOTIFY, FALSE); fRet = TRUE; goto exit; } pIRule = ((RULEINFO *) (lvitem.lParam))->pIRule; if (NULL == pIRule) { SetDlgMsgResult(m_hwndDlg, WM_NOTIFY, FALSE); fRet = TRUE; goto exit; } // Set the new name into the rule ZeroMemory(&propvar, sizeof(propvar)); propvar.vt = VT_LPSTR; propvar.pszVal = pdi->item.pszText; SideAssert(S_OK == pIRule->SetProp(RULE_PROP_NAME, 0, &propvar)); // Mark the rule list as dirty m_dwState |= STATE_DIRTY; SetDlgMsgResult(m_hwndDlg, WM_NOTIFY, TRUE); } } fRet = TRUE; exit: return fRet; } /////////////////////////////////////////////////////////////////////////////// // // _FOnRuleDescValid // // This brings up the edit UI for the selected rule from the mail rules list // // Returns: TRUE, if the message was handled // FALSE, otherwise // /////////////////////////////////////////////////////////////////////////////// BOOL COEMailRulesPageUI::_FOnRuleDescValid(VOID) { BOOL fRet = FALSE; INT iSelected = 0; LVITEM lvitem; IOERule * pIRule = NULL; HRESULT hr = S_OK; PROPVARIANT propvar; Assert(NULL != m_hwndList); // Get the selected item iSelected = ListView_GetNextItem(m_hwndList, -1, LVNI_SELECTED); if (-1 == iSelected) { fRet = FALSE; goto exit; } // Get the current state of the rule ZeroMemory(&lvitem, sizeof(lvitem)); lvitem.mask = LVIF_PARAM | LVIF_STATE; lvitem.stateMask = LVIS_STATEIMAGEMASK; lvitem.iItem = iSelected; if (FALSE == ListView_GetItem(m_hwndList, &lvitem)) { fRet = FALSE; goto exit; } pIRule = ((RULEINFO *) (lvitem.lParam))->pIRule; // If the rule already valid, then bail if (lvitem.state != INDEXTOSTATEIMAGEMASK(iiconStateInvalid + 1)) { fRet = FALSE; goto exit; } // If we are still, invalid then bail hr = m_pDescriptUI->HrVerifyRule(); if (S_OK != hr) { fRet = FALSE; goto exit; } // Figure out the new enabled value hr = pIRule->GetProp(RULE_PROP_DISABLED, 0, &propvar); if (FAILED(hr)) { fRet = FALSE; goto exit; } // Set the UI to the proper enabled state ZeroMemory(&lvitem, sizeof(lvitem)); lvitem.mask = LVIF_STATE; lvitem.iItem = iSelected; lvitem.state = (!!propvar.boolVal) ? INDEXTOSTATEIMAGEMASK(iiconStateUnchecked + 1) : INDEXTOSTATEIMAGEMASK(iiconStateChecked + 1); lvitem.stateMask = LVIS_STATEIMAGEMASK; ListView_SetItem(m_hwndList, &lvitem); fRet = TRUE; exit: return fRet; }
27.766164
142
0.502503
[ "object" ]
3ff56b2c1667d58a2a10b899ad302369a2aeb73a
31,814
cpp
C++
third_party/WebKit/Source/platform/graphics/compositing/PaintArtifactCompositor.cpp
xzhan96/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-01-07T18:51:03.000Z
2021-01-07T18:51:03.000Z
third_party/WebKit/Source/platform/graphics/compositing/PaintArtifactCompositor.cpp
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/platform/graphics/compositing/PaintArtifactCompositor.cpp
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// 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 "platform/graphics/compositing/PaintArtifactCompositor.h" #include "cc/layers/content_layer_client.h" #include "cc/layers/layer.h" #include "cc/layers/picture_layer.h" #include "cc/playback/display_item_list.h" #include "cc/playback/display_item_list_settings.h" #include "cc/playback/drawing_display_item.h" #include "cc/playback/transform_display_item.h" #include "cc/trees/clip_node.h" #include "cc/trees/effect_node.h" #include "cc/trees/layer_tree_host.h" #include "cc/trees/property_tree.h" #include "cc/trees/scroll_node.h" #include "cc/trees/transform_node.h" #include "platform/RuntimeEnabledFeatures.h" #include "platform/graphics/paint/ClipPaintPropertyNode.h" #include "platform/graphics/paint/DisplayItem.h" #include "platform/graphics/paint/DrawingDisplayItem.h" #include "platform/graphics/paint/ForeignLayerDisplayItem.h" #include "platform/graphics/paint/PaintArtifact.h" #include "platform/graphics/paint/RasterInvalidationTracking.h" #include "platform/graphics/paint/ScrollPaintPropertyNode.h" #include "platform/graphics/paint/TransformPaintPropertyNode.h" #include "public/platform/Platform.h" #include "public/platform/WebCompositorSupport.h" #include "public/platform/WebLayer.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/point_f.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/rect_f.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/geometry/size_conversions.h" #include "ui/gfx/geometry/size_f.h" #include "ui/gfx/skia_util.h" #include "wtf/Allocator.h" #include "wtf/Noncopyable.h" #include "wtf/PtrUtil.h" #include <algorithm> #include <memory> #include <utility> namespace blink { template class RasterInvalidationTrackingMap<const cc::Layer>; static RasterInvalidationTrackingMap<const cc::Layer>& ccLayersRasterInvalidationTrackingMap() { DEFINE_STATIC_LOCAL(RasterInvalidationTrackingMap<const cc::Layer>, map, ()); return map; } template <typename T> static std::unique_ptr<JSONArray> sizeAsJSONArray(const T& size) { std::unique_ptr<JSONArray> array = JSONArray::create(); array->pushDouble(size.width()); array->pushDouble(size.height()); return array; } class PaintArtifactCompositor::ContentLayerClientImpl : public cc::ContentLayerClient { WTF_MAKE_NONCOPYABLE(ContentLayerClientImpl); USING_FAST_MALLOC(ContentLayerClientImpl); public: ContentLayerClientImpl(DisplayItem::Id paintChunkId) : m_id(paintChunkId), m_debugName(paintChunkId.client.debugName()), m_ccPictureLayer(cc::PictureLayer::Create(this)) {} void SetDisplayList(scoped_refptr<cc::DisplayItemList> ccDisplayItemList) { m_ccDisplayItemList = std::move(ccDisplayItemList); } void SetPaintableRegion(gfx::Rect region) { m_paintableRegion = region; } // cc::ContentLayerClient gfx::Rect PaintableRegion() override { return m_paintableRegion; } scoped_refptr<cc::DisplayItemList> PaintContentsToDisplayList( PaintingControlSetting) override { return m_ccDisplayItemList; } bool FillsBoundsCompletely() const override { return false; } size_t GetApproximateUnsharedMemoryUsage() const override { // TODO(jbroman): Actually calculate memory usage. return 0; } void resetTrackedRasterInvalidations() { RasterInvalidationTracking* tracking = ccLayersRasterInvalidationTrackingMap().find(m_ccPictureLayer.get()); if (!tracking) return; if (RuntimeEnabledFeatures::paintUnderInvalidationCheckingEnabled()) tracking->trackedRasterInvalidations.clear(); else ccLayersRasterInvalidationTrackingMap().remove(m_ccPictureLayer.get()); } bool hasTrackedRasterInvalidations() const { RasterInvalidationTracking* tracking = ccLayersRasterInvalidationTrackingMap().find(m_ccPictureLayer.get()); if (tracking) return !tracking->trackedRasterInvalidations.isEmpty(); return false; } void setNeedsDisplayRect(const gfx::Rect& rect, RasterInvalidationInfo* rasterInvalidationInfo) { m_ccPictureLayer->SetNeedsDisplayRect(rect); if (!rasterInvalidationInfo || rect.IsEmpty()) return; RasterInvalidationTracking& tracking = ccLayersRasterInvalidationTrackingMap().add(m_ccPictureLayer.get()); tracking.trackedRasterInvalidations.append(*rasterInvalidationInfo); if (RuntimeEnabledFeatures::paintUnderInvalidationCheckingEnabled()) { // TODO(crbug.com/496260): Some antialiasing effects overflow the paint // invalidation rect. IntRect r = rasterInvalidationInfo->rect; r.inflate(1); tracking.rasterInvalidationRegionSinceLastPaint.unite(r); } } std::unique_ptr<JSONObject> layerAsJSON() { std::unique_ptr<JSONObject> json = JSONObject::create(); json->setString("name", m_debugName); IntSize bounds(m_ccPictureLayer->bounds().width(), m_ccPictureLayer->bounds().height()); if (!bounds.isEmpty()) json->setArray("bounds", sizeAsJSONArray(bounds)); json->setBoolean("contentsOpaque", m_ccPictureLayer->contents_opaque()); json->setBoolean("drawsContent", m_ccPictureLayer->DrawsContent()); ccLayersRasterInvalidationTrackingMap().asJSON(m_ccPictureLayer.get(), json.get()); return json; } scoped_refptr<cc::PictureLayer> ccPictureLayer() { return m_ccPictureLayer; } bool matches(const PaintChunk& paintChunk) { return paintChunk.id && m_id == *paintChunk.id; } private: PaintChunk::Id m_id; String m_debugName; scoped_refptr<cc::PictureLayer> m_ccPictureLayer; scoped_refptr<cc::DisplayItemList> m_ccDisplayItemList; gfx::Rect m_paintableRegion; }; PaintArtifactCompositor::PaintArtifactCompositor() { if (!RuntimeEnabledFeatures::slimmingPaintV2Enabled()) return; m_rootLayer = cc::Layer::Create(); m_webLayer = Platform::current()->compositorSupport()->createLayerFromCCLayer( m_rootLayer.get()); m_isTrackingRasterInvalidations = false; } PaintArtifactCompositor::~PaintArtifactCompositor() {} void PaintArtifactCompositor::setTracksRasterInvalidations( bool tracksPaintInvalidations) { resetTrackedRasterInvalidations(); m_isTrackingRasterInvalidations = tracksPaintInvalidations; } void PaintArtifactCompositor::resetTrackedRasterInvalidations() { for (auto& client : m_contentLayerClients) client->resetTrackedRasterInvalidations(); } bool PaintArtifactCompositor::hasTrackedRasterInvalidations() const { for (auto& client : m_contentLayerClients) { if (client->hasTrackedRasterInvalidations()) return true; } return false; } std::unique_ptr<JSONObject> PaintArtifactCompositor::layersAsJSON( LayerTreeFlags flags) const { std::unique_ptr<JSONArray> layersJSON = JSONArray::create(); for (const auto& client : m_contentLayerClients) { layersJSON->pushObject(client->layerAsJSON()); } std::unique_ptr<JSONObject> json = JSONObject::create(); json->setArray("layers", std::move(layersJSON)); return json; } namespace { static gfx::Rect largeRect(-200000, -200000, 400000, 400000); static void appendDisplayItemToCcDisplayItemList(const DisplayItem& displayItem, cc::DisplayItemList* list) { if (DisplayItem::isDrawingType(displayItem.getType())) { const SkPicture* picture = static_cast<const DrawingDisplayItem&>(displayItem).picture(); if (!picture) return; // In theory we would pass the bounds of the picture, previously done as: // gfx::Rect bounds = gfx::SkIRectToRect(picture->cullRect().roundOut()); // or use the visual rect directly. However, clip content layers attempt // to raster in a different space than that of the visual rects. We'll be // reworking visual rects further for SPv2, so for now we just pass a // visual rect large enough to make sure items raster. list->CreateAndAppendDrawingItem<cc::DrawingDisplayItem>( largeRect, sk_ref_sp(picture)); } } static scoped_refptr<cc::DisplayItemList> recordPaintChunk( const PaintArtifact& artifact, const PaintChunk& chunk, const gfx::Rect& combinedBounds) { cc::DisplayItemListSettings settings; scoped_refptr<cc::DisplayItemList> list = cc::DisplayItemList::Create(settings); gfx::Transform translation; translation.Translate(-combinedBounds.x(), -combinedBounds.y()); // Passing combinedBounds as the visual rect for the begin/end transform item // would normally be the sensible thing to do, but see comment above re: // visual rects for drawing items and further rework in flight. list->CreateAndAppendPairedBeginItem<cc::TransformDisplayItem>(translation); const DisplayItemList& displayItems = artifact.getDisplayItemList(); for (const auto& displayItem : displayItems.itemsInPaintChunk(chunk)) appendDisplayItemToCcDisplayItemList(displayItem, list.get()); list->CreateAndAppendPairedEndItem<cc::EndTransformDisplayItem>(); list->Finalize(); return list; } scoped_refptr<cc::Layer> foreignLayerForPaintChunk( const PaintArtifact& paintArtifact, const PaintChunk& paintChunk, gfx::Vector2dF& layerOffset) { if (paintChunk.size() != 1) return nullptr; const auto& displayItem = paintArtifact.getDisplayItemList()[paintChunk.beginIndex]; if (!displayItem.isForeignLayer()) return nullptr; const auto& foreignLayerDisplayItem = static_cast<const ForeignLayerDisplayItem&>(displayItem); layerOffset = gfx::Vector2dF(foreignLayerDisplayItem.location().x(), foreignLayerDisplayItem.location().y()); scoped_refptr<cc::Layer> layer = foreignLayerDisplayItem.layer(); layer->SetBounds(foreignLayerDisplayItem.bounds()); layer->SetIsDrawable(true); return layer; } constexpr int kInvalidNodeId = -1; // cc's property trees use 0 for the root node (always non-null). constexpr int kRealRootNodeId = 0; // cc allocates special nodes for root effects such as the device scale. constexpr int kSecondaryRootNodeId = 1; constexpr int kPropertyTreeSequenceNumber = 1; } // namespace std::unique_ptr<PaintArtifactCompositor::ContentLayerClientImpl> PaintArtifactCompositor::clientForPaintChunk( const PaintChunk& paintChunk, const PaintArtifact& paintArtifact) { // TODO(chrishtr): for now, just using a linear walk. In the future we can // optimize this by using the same techniques used in PaintController for // display lists. for (auto& client : m_contentLayerClients) { if (client && client->matches(paintChunk)) return std::move(client); } return wrapUnique(new ContentLayerClientImpl( paintChunk.id ? *paintChunk.id : paintArtifact.getDisplayItemList()[paintChunk.beginIndex].getId())); } scoped_refptr<cc::Layer> PaintArtifactCompositor::layerForPaintChunk( const PaintArtifact& paintArtifact, const PaintChunk& paintChunk, gfx::Vector2dF& layerOffset, Vector<std::unique_ptr<ContentLayerClientImpl>>& newContentLayerClients, RasterInvalidationTracking* tracking) { DCHECK(paintChunk.size()); // If the paint chunk is a foreign layer, just return that layer. if (scoped_refptr<cc::Layer> foreignLayer = foreignLayerForPaintChunk(paintArtifact, paintChunk, layerOffset)) return foreignLayer; // The common case: create or reuse a PictureLayer for painted content. std::unique_ptr<ContentLayerClientImpl> contentLayerClient = clientForPaintChunk(paintChunk, paintArtifact); gfx::Rect combinedBounds = enclosingIntRect(paintChunk.bounds); scoped_refptr<cc::DisplayItemList> displayList = recordPaintChunk(paintArtifact, paintChunk, combinedBounds); contentLayerClient->SetDisplayList(std::move(displayList)); contentLayerClient->SetPaintableRegion(gfx::Rect(combinedBounds.size())); layerOffset = combinedBounds.OffsetFromOrigin(); scoped_refptr<cc::PictureLayer> ccPictureLayer = contentLayerClient->ccPictureLayer(); ccPictureLayer->SetBounds(combinedBounds.size()); ccPictureLayer->SetIsDrawable(true); if (paintChunk.knownToBeOpaque) ccPictureLayer->SetContentsOpaque(true); DCHECK(!tracking || tracking->trackedRasterInvalidations.size() == paintChunk.rasterInvalidationRects.size()); for (unsigned index = 0; index < paintChunk.rasterInvalidationRects.size(); ++index) { IntRect rect(enclosingIntRect(paintChunk.rasterInvalidationRects[index])); gfx::Rect ccInvalidationRect(rect.x(), rect.y(), std::max(0, rect.width()), std::max(0, rect.height())); // Raster paintChunk.rasterInvalidationRects is in the space of the // containing transform node, so need to subtract off the layer offset. ccInvalidationRect.Offset(-combinedBounds.OffsetFromOrigin()); contentLayerClient->setNeedsDisplayRect( ccInvalidationRect, tracking ? &tracking->trackedRasterInvalidations[index] : nullptr); } newContentLayerClients.append(std::move(contentLayerClient)); return ccPictureLayer; } namespace { class PropertyTreeManager { WTF_MAKE_NONCOPYABLE(PropertyTreeManager); public: PropertyTreeManager(cc::PropertyTrees& propertyTrees, cc::Layer* rootLayer) : m_propertyTrees(propertyTrees), m_rootLayer(rootLayer) { setupRootTransformNode(); setupRootClipNode(); setupRootEffectNode(); setupRootScrollNode(); } void setupRootTransformNode(); void setupRootClipNode(); void setupRootEffectNode(); void setupRootScrollNode(); int compositorIdForTransformNode(const TransformPaintPropertyNode*); int compositorIdForClipNode(const ClipPaintPropertyNode*); int switchToEffectNode(const EffectPaintPropertyNode& nextEffect); int compositorIdForCurrentEffectNode() const { return m_effectStack.last().id; } int compositorIdForScrollNode(const ScrollPaintPropertyNode*); // Scroll offset has special treatment in the transform and scroll trees. void updateScrollOffset(int layerId, int scrollId); private: void buildEffectNodesRecursively(const EffectPaintPropertyNode* nextEffect); cc::TransformTree& transformTree() { return m_propertyTrees.transform_tree; } cc::ClipTree& clipTree() { return m_propertyTrees.clip_tree; } cc::EffectTree& effectTree() { return m_propertyTrees.effect_tree; } cc::ScrollTree& scrollTree() { return m_propertyTrees.scroll_tree; } const EffectPaintPropertyNode* currentEffectNode() const { return m_effectStack.last().effect; } // Property trees which should be updated by the manager. cc::PropertyTrees& m_propertyTrees; // Layer to which transform "owner" layers should be added. These will not // have any actual children, but at present must exist in the tree. cc::Layer* m_rootLayer; // Maps from Blink-side property tree nodes to cc property node indices. HashMap<const TransformPaintPropertyNode*, int> m_transformNodeMap; HashMap<const ClipPaintPropertyNode*, int> m_clipNodeMap; HashMap<const ScrollPaintPropertyNode*, int> m_scrollNodeMap; struct BlinkEffectAndCcIdPair { const EffectPaintPropertyNode* effect; int id; }; Vector<BlinkEffectAndCcIdPair> m_effectStack; #if DCHECK_IS_ON() HashSet<const EffectPaintPropertyNode*> m_effectNodesConverted; #endif }; void PropertyTreeManager::setupRootTransformNode() { // cc is hardcoded to use transform node index 1 for device scale and // transform. cc::TransformTree& transformTree = m_propertyTrees.transform_tree; transformTree.clear(); cc::TransformNode& transformNode = *transformTree.Node( transformTree.Insert(cc::TransformNode(), kRealRootNodeId)); DCHECK_EQ(transformNode.id, kSecondaryRootNodeId); transformNode.source_node_id = transformNode.parent_id; transformTree.SetTargetId(transformNode.id, kRealRootNodeId); transformTree.SetContentTargetId(transformNode.id, kRealRootNodeId); // TODO(jaydasika): We shouldn't set ToScreeen and FromScreen of root // transform node here. They should be set while updating transform tree in // cc. float deviceScaleFactor = m_rootLayer->GetLayerTree()->device_scale_factor(); gfx::Transform toScreen; toScreen.Scale(deviceScaleFactor, deviceScaleFactor); transformTree.SetToScreen(kRealRootNodeId, toScreen); gfx::Transform fromScreen; bool invertible = toScreen.GetInverse(&fromScreen); DCHECK(invertible); transformTree.SetFromScreen(kRealRootNodeId, fromScreen); transformTree.set_needs_update(true); m_transformNodeMap.set(TransformPaintPropertyNode::root(), transformNode.id); m_rootLayer->SetTransformTreeIndex(transformNode.id); } void PropertyTreeManager::setupRootClipNode() { // cc is hardcoded to use clip node index 1 for viewport clip. cc::ClipTree& clipTree = m_propertyTrees.clip_tree; clipTree.clear(); cc::ClipNode& clipNode = *clipTree.Node(clipTree.Insert(cc::ClipNode(), kRealRootNodeId)); DCHECK_EQ(clipNode.id, kSecondaryRootNodeId); clipNode.resets_clip = true; clipNode.owner_id = m_rootLayer->id(); clipNode.clip_type = cc::ClipNode::ClipType::APPLIES_LOCAL_CLIP; clipNode.clip = gfx::RectF( gfx::SizeF(m_rootLayer->GetLayerTree()->device_viewport_size())); clipNode.transform_id = kRealRootNodeId; clipNode.target_transform_id = kRealRootNodeId; m_clipNodeMap.set(ClipPaintPropertyNode::root(), clipNode.id); m_rootLayer->SetClipTreeIndex(clipNode.id); } void PropertyTreeManager::setupRootEffectNode() { // cc is hardcoded to use effect node index 1 for root render surface. cc::EffectTree& effectTree = m_propertyTrees.effect_tree; effectTree.clear(); cc::EffectNode& effectNode = *effectTree.Node(effectTree.Insert(cc::EffectNode(), kInvalidNodeId)); DCHECK_EQ(effectNode.id, kSecondaryRootNodeId); effectNode.owner_id = m_rootLayer->id(); effectNode.transform_id = kRealRootNodeId; effectNode.clip_id = kSecondaryRootNodeId; effectNode.has_render_surface = true; m_effectStack.append( BlinkEffectAndCcIdPair{EffectPaintPropertyNode::root(), effectNode.id}); m_rootLayer->SetEffectTreeIndex(effectNode.id); } void PropertyTreeManager::setupRootScrollNode() { cc::ScrollTree& scrollTree = m_propertyTrees.scroll_tree; scrollTree.clear(); cc::ScrollNode& scrollNode = *scrollTree.Node(scrollTree.Insert(cc::ScrollNode(), kRealRootNodeId)); DCHECK_EQ(scrollNode.id, kSecondaryRootNodeId); scrollNode.owner_id = m_rootLayer->id(); scrollNode.transform_id = kSecondaryRootNodeId; m_scrollNodeMap.set(ScrollPaintPropertyNode::root(), scrollNode.id); m_rootLayer->SetScrollTreeIndex(scrollNode.id); } int PropertyTreeManager::compositorIdForTransformNode( const TransformPaintPropertyNode* transformNode) { DCHECK(transformNode); // TODO(crbug.com/645615): Remove the failsafe here. if (!transformNode) return kSecondaryRootNodeId; auto it = m_transformNodeMap.find(transformNode); if (it != m_transformNodeMap.end()) return it->value; scoped_refptr<cc::Layer> dummyLayer = cc::Layer::Create(); int parentId = compositorIdForTransformNode(transformNode->parent()); int id = transformTree().Insert(cc::TransformNode(), parentId); cc::TransformNode& compositorNode = *transformTree().Node(id); transformTree().SetTargetId(id, kRealRootNodeId); transformTree().SetContentTargetId(id, kRealRootNodeId); compositorNode.source_node_id = parentId; FloatPoint3D origin = transformNode->origin(); compositorNode.pre_local.matrix().setTranslate(-origin.x(), -origin.y(), -origin.z()); compositorNode.local.matrix() = TransformationMatrix::toSkMatrix44(transformNode->matrix()); compositorNode.post_local.matrix().setTranslate(origin.x(), origin.y(), origin.z()); compositorNode.needs_local_transform_update = true; compositorNode.flattens_inherited_transform = transformNode->flattensInheritedTransform(); compositorNode.sorting_context_id = transformNode->renderingContextID(); m_rootLayer->AddChild(dummyLayer); dummyLayer->SetTransformTreeIndex(id); dummyLayer->SetClipTreeIndex(kSecondaryRootNodeId); dummyLayer->SetEffectTreeIndex(kSecondaryRootNodeId); dummyLayer->SetScrollTreeIndex(kRealRootNodeId); dummyLayer->set_property_tree_sequence_number(kPropertyTreeSequenceNumber); auto result = m_transformNodeMap.set(transformNode, id); DCHECK(result.isNewEntry); transformTree().set_needs_update(true); return id; } int PropertyTreeManager::compositorIdForClipNode( const ClipPaintPropertyNode* clipNode) { DCHECK(clipNode); // TODO(crbug.com/645615): Remove the failsafe here. if (!clipNode) return kSecondaryRootNodeId; auto it = m_clipNodeMap.find(clipNode); if (it != m_clipNodeMap.end()) return it->value; scoped_refptr<cc::Layer> dummyLayer = cc::Layer::Create(); int parentId = compositorIdForClipNode(clipNode->parent()); int id = clipTree().Insert(cc::ClipNode(), parentId); cc::ClipNode& compositorNode = *clipTree().Node(id); compositorNode.owner_id = dummyLayer->id(); // TODO(jbroman): Don't discard rounded corners. compositorNode.clip = clipNode->clipRect().rect(); compositorNode.transform_id = compositorIdForTransformNode(clipNode->localTransformSpace()); compositorNode.target_transform_id = kRealRootNodeId; compositorNode.target_effect_id = kSecondaryRootNodeId; compositorNode.clip_type = cc::ClipNode::ClipType::APPLIES_LOCAL_CLIP; compositorNode.layers_are_clipped = true; compositorNode.layers_are_clipped_when_surfaces_disabled = true; m_rootLayer->AddChild(dummyLayer); dummyLayer->SetTransformTreeIndex(compositorNode.transform_id); dummyLayer->SetClipTreeIndex(id); dummyLayer->SetEffectTreeIndex(kSecondaryRootNodeId); dummyLayer->SetScrollTreeIndex(kRealRootNodeId); dummyLayer->set_property_tree_sequence_number(kPropertyTreeSequenceNumber); auto result = m_clipNodeMap.set(clipNode, id); DCHECK(result.isNewEntry); clipTree().set_needs_update(true); return id; } int PropertyTreeManager::compositorIdForScrollNode( const ScrollPaintPropertyNode* scrollNode) { DCHECK(scrollNode); // TODO(crbug.com/645615): Remove the failsafe here. if (!scrollNode) return kSecondaryRootNodeId; auto it = m_scrollNodeMap.find(scrollNode); if (it != m_scrollNodeMap.end()) return it->value; int parentId = compositorIdForScrollNode(scrollNode->parent()); int id = scrollTree().Insert(cc::ScrollNode(), parentId); cc::ScrollNode& compositorNode = *scrollTree().Node(id); compositorNode.owner_id = parentId; compositorNode.scrollable = true; compositorNode.scroll_clip_layer_bounds.SetSize(scrollNode->clip().width(), scrollNode->clip().height()); compositorNode.bounds.SetSize(scrollNode->bounds().width(), scrollNode->bounds().height()); compositorNode.user_scrollable_horizontal = scrollNode->userScrollableHorizontal(); compositorNode.user_scrollable_vertical = scrollNode->userScrollableVertical(); compositorNode.transform_id = compositorIdForTransformNode(scrollNode->scrollOffsetTranslation()); compositorNode.main_thread_scrolling_reasons = scrollNode->mainThreadScrollingReasons(); auto result = m_scrollNodeMap.set(scrollNode, id); DCHECK(result.isNewEntry); scrollTree().set_needs_update(true); return id; } void PropertyTreeManager::updateScrollOffset(int layerId, int scrollId) { cc::ScrollNode& scrollNode = *scrollTree().Node(scrollId); cc::TransformNode& transformNode = *transformTree().Node(scrollNode.transform_id); transformNode.scrolls = true; // Blink creates a 2d transform node just for scroll offset whereas cc's // transform node has a special scroll offset field. To handle this we // adjust cc's transform node to remove the 2d scroll translation and // let the cc scroll tree update the cc scroll offset. DCHECK(transformNode.local.IsIdentityOr2DTranslation()); auto offset = transformNode.local.To2dTranslation(); transformNode.local.MakeIdentity(); scrollTree().SetScrollOffset(layerId, gfx::ScrollOffset(-offset.x(), -offset.y())); scrollTree().set_needs_update(true); } unsigned depth(const EffectPaintPropertyNode* node) { unsigned result = 0; for (; node; node = node->parent()) result++; return result; } const EffectPaintPropertyNode* lowestCommonAncestor( const EffectPaintPropertyNode* nodeA, const EffectPaintPropertyNode* nodeB) { // Optimized common case. if (nodeA == nodeB) return nodeA; unsigned depthA = depth(nodeA), depthB = depth(nodeB); while (depthA > depthB) { nodeA = nodeA->parent(); depthA--; } while (depthB > depthA) { nodeB = nodeB->parent(); depthB--; } DCHECK_EQ(depthA, depthB); while (nodeA != nodeB) { nodeA = nodeA->parent(); nodeB = nodeB->parent(); } return nodeA; } int PropertyTreeManager::switchToEffectNode( const EffectPaintPropertyNode& nextEffect) { const EffectPaintPropertyNode* ancestor = lowestCommonAncestor(currentEffectNode(), &nextEffect); DCHECK(ancestor) << "Malformed effect tree. All nodes must be descendant of " "EffectPaintPropertyNode::root()."; while (currentEffectNode() != ancestor) m_effectStack.pop_back(); // Now the current effect is the lowest common ancestor of previous effect // and the next effect. That implies it is an existing node that already has // at least one paint chunk or child effect, and we are going to either attach // another paint chunk or child effect to it. We can no longer omit render // surface for it even for opacity-only nodes. // See comments in PropertyTreeManager::buildEffectNodesRecursively(). // TODO(crbug.com/504464): Remove premature optimization here. if (currentEffectNode() && currentEffectNode()->opacity() != 1.f) { effectTree().Node(compositorIdForCurrentEffectNode())->has_render_surface = true; } buildEffectNodesRecursively(&nextEffect); return compositorIdForCurrentEffectNode(); } void PropertyTreeManager::buildEffectNodesRecursively( const EffectPaintPropertyNode* nextEffect) { if (nextEffect == currentEffectNode()) return; DCHECK(nextEffect); buildEffectNodesRecursively(nextEffect->parent()); DCHECK_EQ(nextEffect->parent(), currentEffectNode()); #if DCHECK_IS_ON() DCHECK(!m_effectNodesConverted.contains(nextEffect)) << "Malformed paint artifact. Paint chunks under the same effect should " "be contiguous."; m_effectNodesConverted.add(nextEffect); #endif // We currently create dummy layers to host effect nodes and corresponding // render surfaces. This should be removed once cc implements better support // for freestanding property trees. scoped_refptr<cc::Layer> dummyLayer = nextEffect->ensureDummyLayer(); m_rootLayer->AddChild(dummyLayer); // Also cc assumes a clip node is always created by a layer that creates // render surface. cc::ClipNode& dummyClip = *clipTree().Node(clipTree().Insert(cc::ClipNode(), kSecondaryRootNodeId)); dummyClip.owner_id = dummyLayer->id(); dummyClip.transform_id = kRealRootNodeId; dummyClip.target_transform_id = kRealRootNodeId; dummyClip.target_effect_id = kSecondaryRootNodeId; cc::EffectNode& effectNode = *effectTree().Node(effectTree().Insert( cc::EffectNode(), compositorIdForCurrentEffectNode())); effectNode.owner_id = dummyLayer->id(); effectNode.clip_id = dummyClip.id; // Every effect is supposed to have render surface enabled for grouping, // but we can get away without one if the effect is opacity-only and has only // one compositing child. This is both for optimization and not introducing // sub-pixel differences in layout tests. // See PropertyTreeManager::switchToEffectNode() where we retrospectively // enable render surface when more than one compositing child is detected. // TODO(crbug.com/504464): There is ongoing work in cc to delay render surface // decision until later phase of the pipeline. Remove premature optimization // here once the work is ready. effectNode.opacity = nextEffect->opacity(); m_effectStack.append(BlinkEffectAndCcIdPair{nextEffect, effectNode.id}); dummyLayer->set_property_tree_sequence_number(kPropertyTreeSequenceNumber); dummyLayer->SetTransformTreeIndex(kSecondaryRootNodeId); dummyLayer->SetClipTreeIndex(dummyClip.id); dummyLayer->SetEffectTreeIndex(effectNode.id); dummyLayer->SetScrollTreeIndex(kRealRootNodeId); } } // namespace void PaintArtifactCompositor::update( const PaintArtifact& paintArtifact, RasterInvalidationTrackingMap<const PaintChunk>* rasterChunkInvalidations) { DCHECK(m_rootLayer); cc::LayerTree* layerTree = m_rootLayer->GetLayerTree(); // The tree will be null after detaching and this update can be ignored. // See: WebViewImpl::detachPaintArtifactCompositor(). if (!layerTree) return; if (m_extraDataForTestingEnabled) m_extraDataForTesting = wrapUnique(new ExtraDataForTesting); m_rootLayer->RemoveAllChildren(); m_rootLayer->set_property_tree_sequence_number(kPropertyTreeSequenceNumber); PropertyTreeManager propertyTreeManager(*layerTree->property_trees(), m_rootLayer.get()); Vector<std::unique_ptr<ContentLayerClientImpl>> newContentLayerClients; newContentLayerClients.reserveCapacity(paintArtifact.paintChunks().size()); for (const PaintChunk& paintChunk : paintArtifact.paintChunks()) { gfx::Vector2dF layerOffset; scoped_refptr<cc::Layer> layer = layerForPaintChunk( paintArtifact, paintChunk, layerOffset, newContentLayerClients, rasterChunkInvalidations ? rasterChunkInvalidations->find(&paintChunk) : nullptr); int transformId = propertyTreeManager.compositorIdForTransformNode( paintChunk.properties.transform.get()); int scrollId = propertyTreeManager.compositorIdForScrollNode( paintChunk.properties.scroll.get()); int clipId = propertyTreeManager.compositorIdForClipNode( paintChunk.properties.clip.get()); int effectId = propertyTreeManager.switchToEffectNode( *paintChunk.properties.effect.get()); propertyTreeManager.updateScrollOffset(layer->id(), scrollId); layer->set_offset_to_transform_parent(layerOffset); m_rootLayer->AddChild(layer); layer->set_property_tree_sequence_number(kPropertyTreeSequenceNumber); layer->SetTransformTreeIndex(transformId); layer->SetClipTreeIndex(clipId); layer->SetEffectTreeIndex(effectId); layer->SetScrollTreeIndex(scrollId); // TODO(jbroman): This probably shouldn't be necessary, but it is still // queried by RenderSurfaceImpl. layer->Set3dSortingContextId(layerTree->property_trees() ->transform_tree.Node(transformId) ->sorting_context_id); layer->SetShouldCheckBackfaceVisibility( paintChunk.properties.backfaceHidden); if (m_extraDataForTestingEnabled) m_extraDataForTesting->contentLayers.append(layer); } m_contentLayerClients.clear(); m_contentLayerClients.swap(newContentLayerClients); // Mark the property trees as having been rebuilt. layerTree->property_trees()->sequence_number = kPropertyTreeSequenceNumber; layerTree->property_trees()->needs_rebuild = false; layerTree->property_trees()->ResetCachedData(); } } // namespace blink
38.609223
80
0.748538
[ "geometry", "render", "vector", "transform" ]
b2025317255bec594bf3fddddcbab4ca87a076a1
6,863
cpp
C++
EmbUI/ui.cpp
vortigont/EmbUI
aeab49347794bdae292edc27df927459aad9645d
[ "MIT" ]
1
2022-03-27T21:40:46.000Z
2022-03-27T21:40:46.000Z
EmbUI/ui.cpp
vortigont/EmbUI
aeab49347794bdae292edc27df927459aad9645d
[ "MIT" ]
null
null
null
EmbUI/ui.cpp
vortigont/EmbUI
aeab49347794bdae292edc27df927459aad9645d
[ "MIT" ]
null
null
null
// This framework originaly based on JeeUI2 lib used under MIT License Copyright (c) 2019 Marsel Akhkamov // then re-written and named by (c) 2020 Anton Zolotarev (obliterator) (https://github.com/anton-zolotarev) // also many thanks to Vortigont (https://github.com/vortigont), kDn (https://github.com/DmytroKorniienko) // and others people #include "ui.h" void Interface::frame(const String &id, const String &value){ StaticJsonDocument<IFACE_STA_JSON_SIZE> obj; obj[FPSTR(P_html)] = F("iframe"); obj[FPSTR(P_type)] = F("frame"); obj[FPSTR(P_id)] = id; obj[FPSTR(P_value)] = value; frame_add_safe(obj.as<JsonObject>()); } void Interface::frame2(const String &id, const String &value){ StaticJsonDocument<IFACE_STA_JSON_SIZE> obj; obj[FPSTR(P_html)] = F("iframe2");; obj[FPSTR(P_type)] = F("frame"); obj[FPSTR(P_id)] = id; obj[FPSTR(P_value)] = value; frame_add_safe(obj.as<JsonObject>()); } void Interface::file(const String &name, const String &action, const String &label){ StaticJsonDocument<IFACE_STA_JSON_SIZE> obj; obj[FPSTR(P_html)] = FPSTR(P_file); obj[F("name")] = name; obj[F("action")] = action; obj[FPSTR(P_label)] = label; frame_add_safe(obj.as<JsonObject>()); } void Interface::spacer(const String &label){ StaticJsonDocument<IFACE_STA_JSON_SIZE> obj; obj[FPSTR(P_html)] = F("spacer"); if (label.length()) obj[FPSTR(P_label)] = label; frame_add_safe(obj.as<JsonObject>()); } void Interface::comment(const String &id, const String &label){ StaticJsonDocument<IFACE_STA_JSON_SIZE * 2> obj; // use a bit larger buffer for long texts obj[FPSTR(P_html)] = F("comment"); if (id.length()) obj[FPSTR(P_id)] = id; obj[FPSTR(P_label)] = label; frame_add_safe(obj.as<JsonObject>()); } /////////////////////////////////////// /** * @brief - begin UI secton of the specified <type> * generic frame creation method, used by other calls to create pther custom-typed frames */ void Interface::json_frame(const String &type){ json[F("pkg")] = type; json[FPSTR(P_final)] = false; json_section_begin("root" + String(micros())); } /** * @brief - begin Interface UI secton * used to construc WebUI html elements */ void Interface::json_frame_interface(const String &name){ json[F("app")] = name; json[F("mc")] = embui->mc; json[F("ver")] = F(EMBUI_VERSION_STRING); json_frame_interface(); } bool Interface::json_frame_add(const JsonObject &obj) { if (!obj.memoryUsage()) // пустышки не передаем return false; LOG(printf_P, PSTR("UI: Frame add obj %u b, mem:%d/%d"), obj.memoryUsage(), json.memoryUsage(), json.capacity()); if (json.capacity() - json.memoryUsage() > obj.memoryUsage() + 16 && section_stack.tail()->block.add(obj)) { LOG(printf_P, PSTR("...OK idx:%u\tMEM: %u\n"), section_stack.tail()->idx, ESP.getFreeHeap()); section_stack.tail()->idx++; // incr idx for next obj return true; } LOG(printf_P, PSTR(" - Frame full! Heap: %u\n"), ESP.getFreeHeap()); json_frame_send(); json_frame_next(); return false; } void Interface::json_frame_next(){ json.clear(); JsonObject obj = json.to<JsonObject>(); for (int i = 0; i < section_stack.size(); i++) { if (i) obj = section_stack[i - 1]->block.createNestedObject(); obj[FPSTR(P_section)] = section_stack[i]->name; obj[F("idx")] = section_stack[i]->idx; LOG(printf_P, PSTR("UI: section:'%s' [#%u] idx:%u\n"), section_stack[i]->name.c_str(), i, section_stack[i]->idx); section_stack[i]->block = obj.createNestedArray(FPSTR(P_block)); } LOG(printf_P, PSTR("json_frame_next: [#%u], mem:%u/%u\n"), section_stack.size()-1, obj.memoryUsage(), json.capacity()); // section index counts from 0 } void Interface::json_frame_clear(){ while(section_stack.size()) { section_stack_t *section = section_stack.shift(); delete section; } json.clear(); } void Interface::json_frame_flush(){ if (!section_stack.size()) return; LOG(println, F("UI: json_frame_flush")); json[FPSTR(P_final)] = true; json_section_end(); json_frame_send(); json_frame_clear(); } void Interface::json_section_line(const String &name){ json_section_begin(name, "", false, false, true); } void Interface::json_section_begin(const String &name, const String &label, bool main, bool hidden, bool line){ JsonObject obj; if (section_stack.size()) { obj = section_stack.tail()->block.createNestedObject(); } else { obj = json.as<JsonObject>(); } json_section_begin(name, label, main, hidden, line, obj); } void Interface::json_section_begin(const String &name, const String &label, bool main, bool hidden, bool line, JsonObject obj){ obj[FPSTR(P_section)] = name; if (!label.isEmpty()) obj[FPSTR(P_label)] = label; if (main) obj[F("main")] = true; if (hidden) obj[FPSTR(P_hidden)] = true; if (line) obj[F("line")] = true; section_stack_t *section = new section_stack_t; section->name = name; section->block = obj.createNestedArray(FPSTR(P_block)); section->idx = 0; section_stack.add(section); LOG(printf_P, PSTR("UI: section begin:'%s' [#%u] %u free\n"), name.c_str(), section_stack.size()-1, json.capacity() - json.memoryUsage()); // section index counts from 0 } void Interface::json_section_end(){ if (!section_stack.size()) return; section_stack_t *section = section_stack.pop(); if (section_stack.size()) { section_stack.tail()->idx++; } LOG(printf_P, PSTR("UI: section end:'%s' [#%u] MEM: %u\n"), section->name.c_str(), section_stack.size(), ESP.getFreeHeap()); // size() before pop() delete section; } /** * @brief - serialize and send json obj directly to the ws buffer */ void frameSendAll::send(const JsonObject& data){ size_t length = measureJson(data); AsyncWebSocketMessageBuffer * buffer = ws->makeBuffer(length); if (!buffer) return; serializeJson(data, (char*)buffer->get(), ++length); ws->textAll(buffer); }; /** * @brief - serialize and send json obj directly to the ws buffer */ void frameSendClient::send(const JsonObject& data){ size_t length = measureJson(data); AsyncWebSocketMessageBuffer * buffer = cl->server()->makeBuffer(length); if (!buffer) return; serializeJson(data, (char*)buffer->get(), ++length); cl->text(buffer); }; /** * @brief - add object to frame with mem overflow protection */ void Interface::frame_add_safe(const JsonObject &jobj){ size_t _cnt = FRAME_ADD_RETRY; do { --_cnt; #ifdef EMBUI_DEBUG if (!_cnt) LOG(println, FPSTR(P_ERR_obj2large)); #endif } while (!json_frame_add(jobj) && _cnt ); };
32.372642
175
0.646947
[ "object" ]
b203d0bdccdc2ef4022c5b795b784e30feca0809
11,864
cpp
C++
src/core/lib/core_data_model/reflection_proto/property_tree_model.cpp
wgsyd/wgtf
d8cacb43e2c5d40080d33c18a8c2f5bd27d21bed
[ "BSD-3-Clause" ]
28
2016-06-03T05:28:25.000Z
2019-02-14T12:04:31.000Z
src/core/lib/core_data_model/reflection_proto/property_tree_model.cpp
karajensen/wgtf
740397bcfdbc02bc574231579d57d7c9cd5cc26d
[ "BSD-3-Clause" ]
null
null
null
src/core/lib/core_data_model/reflection_proto/property_tree_model.cpp
karajensen/wgtf
740397bcfdbc02bc574231579d57d7c9cd5cc26d
[ "BSD-3-Clause" ]
14
2016-06-03T05:52:27.000Z
2019-03-21T09:56:03.000Z
#include "property_tree_model.hpp" #include "core_common/assert.hpp" #include "core_data_model/common_data_roles.hpp" #include "core_reflection/metadata/meta_utilities.hpp" #include "core_reflection/metadata/meta_impl.hpp" #include "core_reflection/interfaces/i_base_property.hpp" #include "core_reflection/interfaces/i_class_definition.hpp" #include "core_reflection/i_definition_manager.hpp" namespace wgt { ITEMROLE(indexPath) namespace proto { namespace { ObjectHandleT<MetaGroupObj> getGroupForProperty(const PropertyAccessor& accessor, const IDefinitionManager& defMgr) { auto groupObj = findFirstMetaData<MetaGroupObj>(accessor, defMgr); if (groupObj == nullptr) { return groupObj; } // Ignore empty label groups, collapse down to parent group const auto& object = accessor.getObject(); const auto groupName = groupObj->getGroupName(object); if (!groupName || *groupName == '\0') { return nullptr; } return groupObj; } } class PropertyGroupItem : public AbstractTreeItem { public: PropertyGroupItem(const MetaGroupObj& groupObj, const ObjectHandle& object, int currGroupLevel = MetaGroupObj::FULL_GROUP_LEVEL) : groupObj_(groupObj) , object_(object) , currGroupLevel_(currGroupLevel) { } virtual ~PropertyGroupItem() { } int getCurrLevelNormalized() const { int result = currGroupLevel_; if (result == (groupObj_.getNumSubGroups() - 1)) result = MetaGroupObj::FULL_GROUP_LEVEL; return result; } uint64_t getHash() const { int level = getCurrLevelNormalized(); uint64_t result = groupObj_.getGroupNameHash(object_, level); return result; } const MetaGroupObj& getGroupObj() const { return groupObj_; } const ObjectHandle& getObject() const { return object_; } // AbstractItem virtual Variant getData(int column, ItemRole::Id roleId) const override { if (roleId == ItemRole::displayId) { return groupObj_.getGroupName(object_, currGroupLevel_); } else if (roleId == ItemRole::indexPathId) { auto path = object_.path(); int level = getCurrLevelNormalized(); std::wstring groupNameW = groupObj_.getGroupName(object_, level); std::string groupName(groupNameW.begin(), groupNameW.end()); path += "{" + groupName + "}"; return path; } return Variant(); } virtual bool hasController() const override { return true; } private: const int currGroupLevel_; const MetaGroupObj& groupObj_; ObjectHandle object_; }; PropertyTreeModel::PropertyTreeModel(const ObjectHandle& object) : ReflectedTreeModel(object) { } PropertyTreeModel::~PropertyTreeModel() { } std::unique_ptr<ReflectedTreeModel::Children> PropertyTreeModel::mapChildren(const AbstractItem* item) { auto children = new Children(); std::pair<const ReflectedPropertyItem *, uint64_t> propertyItem = this->propertyItem(item); auto& newGroups = getGroups(propertyItem); const ReflectedPropertyItem *reflectedItem = propertyItem.first; auto& currGroupList = groups_[reflectedItem]; for (auto& group : newGroups) { children->push_back(group.get()); currGroupList.push_back(std::move(group)); } std::vector<PropertyItem> properties; collectProperties(propertyItem.first, properties); for (auto& property : properties) { uint64_t containerPropertyHash = propertyItem.second; uint64_t propertyHash = property.second; if (containerPropertyHash == propertyHash) { children->push_back(property.first); } } return std::unique_ptr<Children>(children); } void PropertyTreeModel::clearChildren(const AbstractItem* item) { const ReflectedPropertyItem* propertyItem = nullptr; for (auto& groups : groups_) { for (auto& groupItem : groups.second) { if (groupItem.get() == item) { propertyItem = groups.first; } } } if (propertyItem == nullptr) { propertyItem = static_cast<const ReflectedPropertyItem*>(item); } clearGroups(propertyItem); clearProperties(propertyItem); } const AbstractItem* PropertyTreeModel::mappedItem(const ReflectedPropertyItem* item) const { auto& object = getObject(); if (!object.isValid()) { return item; } auto definition = get<IDefinitionManager>()->getDefinition(object); while (item != nullptr && !isMapped(item)) { auto && path = item->getPath(); auto propertyAccessor = definition->bindProperty(path, object); auto parentItem = parentProperty(item); auto groupObj = getGroupForProperty(propertyAccessor, *get<IDefinitionManager>()); if (groupObj != nullptr) { auto groupsIt = groups_.find(parentItem); if(groupsIt != groups_.end()) { auto& groups = groupsIt->second; auto& propertyObject = propertyAccessor.getObject(); auto it = std::find_if(groups.begin(), groups.end(), [&](const PropertyGroupItemPtr& groupItem) { return groupItem->getHash() == groupObj->getGroupNameHash(propertyObject); }); TF_ASSERT(it != groups.end()); return it->get(); } } item = parentItem; } return item; } PropertyTreeModel::Groups PropertyTreeModel::getGroups(const PropertyItem propertyItem) { const ReflectedPropertyItem *item = propertyItem.first; std::vector<PropertyItem> properties; Groups newGroups; uint64_t groupHash = propertyItem.second; collectProperties(item, properties, &newGroups, groupHash); auto& currGroupList = groups_[propertyItem.first]; auto it = std::remove_if(newGroups.begin(), newGroups.end(), [&](const PropertyGroupItemPtr& groupItem) { // Remove group if no property references that group { auto propIt = std::find_if(properties.begin(), properties.end(), [&](const PropertyItem& property) { uint64_t propertyUsesGroupWithHash = property.second; const MetaGroupObj &groupObj = groupItem->getGroupObj(); const ObjectHandle &object = groupItem->getObject(); if (groupObj.getGroupNameHash(object, MetaGroupObj::FULL_GROUP_LEVEL) == propertyUsesGroupWithHash) return true; return false; }); if (propIt == properties.end()) return true; } // Remove group from list if it is already in the group list. { auto groupIt = std::find_if(currGroupList.begin(), currGroupList.end(), [&](const PropertyGroupItemPtr &existingGroup) { return (groupItem->getHash() == existingGroup->getHash()); }); return !(groupIt == currGroupList.end()); } }); newGroups.erase(it, newGroups.end()); return newGroups; } void PropertyTreeModel::clearGroups(const ReflectedPropertyItem* item) { auto groupsIt = groups_.find(item); if (groupsIt == groups_.end()) { return; } groups_.erase(groupsIt); } PropertyTreeModel::PropertyItem PropertyTreeModel::propertyItem(const AbstractItem* item) const { for (auto& groups : groups_) { for (auto& groupItem : groups.second) { if (groupItem.get() == item) { return PropertyItem(groups.first, groupItem->getHash()); } } } return PropertyItem(static_cast<const ReflectedPropertyItem*>(item), 0); } void PropertyTreeModel::collectProperties(const ReflectedPropertyItem* item, std::vector<PropertyItem>& o_Properties, Groups* groups, uint64_t groupHash) { auto makePropertyGroupIfUnique = [this](Groups *groups, ObjectHandleT<MetaGroupObj> groupObj, ObjectHandle propertyObject, uint64_t checkHash, int subGroupIndex) { auto found = std::find_if(groups->begin(), groups->end(), [&](const PropertyGroupItemPtr& group) { return group->getHash() == checkHash; }); if (found == groups->end()) { groups->emplace_back(std::make_unique<PropertyGroupItem>(*groupObj, propertyObject, subGroupIndex)); } }; auto& object = getObject(); if (!object.isValid()) { return; } auto definition = get<IDefinitionManager>()->getDefinition(object); auto& properties = getProperties(item); for (auto& property : properties) { auto propertyGroupHash = groupHash; auto && path = property->getPath(); auto propertyAccessor = definition->bindProperty(path, object); ObjectHandleT<MetaGroupObj> groupObj = getGroupForProperty(propertyAccessor, *get<IDefinitionManager>()); if (groupObj != nullptr) { auto& propertyObject = propertyAccessor.getObject(); bool subGroupDetected = (propertyGroupHash != 0); if (!subGroupDetected) { propertyGroupHash = groupObj->getGroupNameHash(propertyObject, MetaGroupObj::FULL_GROUP_LEVEL); } if (groups) { // NOTE: Level 0 contains the full group name if there are multiple sub groups. In the case // there is, we don't want to print the full name, but the sub-names, which are from index // 1 onwards in that case. int numSubGroups = groupObj->getNumSubGroups(); int subGroupStartIndex = (numSubGroups > 1) ? 1 : 0; if (subGroupDetected) { int lastSubGroupIndex = numSubGroups - 1; for (int subGroupIndex = subGroupStartIndex; subGroupIndex < numSubGroups; subGroupIndex++) { uint64_t checkHash = groupObj->getGroupNameHash(propertyObject, subGroupIndex); if (checkHash == propertyGroupHash) { // NOTE: If last subgroup, the group needs to use the full hash because the properties are // bound to the full name of the group hash. uint64_t subGroupHash; int nextIndex = subGroupIndex + 1; if (nextIndex == lastSubGroupIndex) { subGroupHash = groupObj->getGroupNameHash(propertyObject, MetaGroupObj::FULL_GROUP_LEVEL); makePropertyGroupIfUnique(groups, groupObj, propertyObject, subGroupHash, nextIndex); } else if (nextIndex > lastSubGroupIndex) { // do nothing } else { subGroupHash = groupObj->getGroupNameHash(propertyObject, nextIndex); makePropertyGroupIfUnique(groups, groupObj, propertyObject, subGroupHash, nextIndex); } propertyGroupHash = groupObj->getGroupNameHash(propertyObject, MetaGroupObj::FULL_GROUP_LEVEL); break; } } } else { uint64_t checkHash = groupObj->getGroupNameHash(propertyObject, subGroupStartIndex); makePropertyGroupIfUnique(groups, groupObj, propertyObject, checkHash, subGroupStartIndex); } } } auto filterResult = filterProperty(property.get()); switch (filterResult) { case FILTER_INCLUDE: o_Properties.push_back(PropertyItem(property.get(), propertyGroupHash)); break; case FILTER_INCLUDE_CHILDREN: collectProperties(property.get(), o_Properties, groups, propertyGroupHash); break; case FILTER_IGNORE: default: break; } } } PropertyTreeModel::FilterResult PropertyTreeModel::filterProperty(const ReflectedPropertyItem* item) const { auto& object = getObject(); auto& path = item->getPath(); auto& definitionManager = *get<IDefinitionManager>(); auto definition = definitionManager.getDefinition(object); if (definition == nullptr) { return FILTER_INCLUDE; } auto propertyAccessor = definition->bindProperty(path, object); if (!propertyAccessor.isValid() || !propertyAccessor.getProperty()->isValue()) { return FILTER_IGNORE; } // InPlace visibility can be dynamic, check for dynamic hidden properties (SpawnComponent - "Spawn Template") auto hidden = false; auto dynamicHidden = false; auto hiddenCallback = [&](const ObjectHandleT<MetaHiddenObj>& hiddenObj) { auto currentHidden = hiddenObj->isHidden(propertyAccessor.getObject());; hidden |= currentHidden; dynamicHidden |= currentHidden && hiddenObj->isDynamic(); }; forEachMetaData<MetaHiddenObj>(propertyAccessor, *get<IDefinitionManager>(), hiddenCallback); auto metaInPlaceObj = findFirstMetaData<MetaInPlaceObj>(propertyAccessor, *get<IDefinitionManager>()); if (metaInPlaceObj != nullptr) { return dynamicHidden ? FILTER_IGNORE : FILTER_INCLUDE_CHILDREN; } return hidden ? FILTER_IGNORE : FILTER_INCLUDE; } } }
28.450839
153
0.714009
[ "object", "vector" ]
b208d7261165b6a3b845765a28827cd6e2cce7fd
767
hpp
C++
src/util/logging_system.hpp
Entalpi/MeineKraft
62b037e05270cf19df5f11c8dacaa55a7414015f
[ "Unlicense", "MIT" ]
31
2016-07-01T21:25:11.000Z
2022-03-26T03:19:42.000Z
src/util/logging_system.hpp
Entalpi/MeineKraft
62b037e05270cf19df5f11c8dacaa55a7414015f
[ "Unlicense", "MIT" ]
1
2017-04-23T08:15:31.000Z
2017-04-23T08:15:31.000Z
src/util/logging_system.hpp
Entalpi/MeineKraft
62b037e05270cf19df5f11c8dacaa55a7414015f
[ "Unlicense", "MIT" ]
4
2017-01-26T18:13:11.000Z
2020-01-28T22:42:52.000Z
#ifndef MEINEKRAFT_LOGGING_SYSTEM_H_ #define MEINEKRAFT_LOGGING_SYSTEM_H_ #include <string> #include <array> #include <mutex> #include <vector> struct LogMsg { std::string msg; uint16_t filter_flags; }; struct LoggingSystem { std::mutex buffer_mutex; std::vector<LogMsg> buffer; uint16_t filter_flags; static LoggingSystem& instance() { static LoggingSystem instance; return instance; } void init() { } // Threadsafe callable on any thread - slow void add_msg(const std::string msg) { std::lock_guard<std::mutex> scoped(buffer_mutex); LogMsg logmsg; logmsg.msg = msg; buffer.push_back(logmsg); } // Callable only on main ImGui thread void draw_gui(bool* open); }; #endif // MEINEKRAFT_LOGGING_SYSTEM_H_
18.707317
53
0.710561
[ "vector" ]
b20ddae671fd07fdd224d8bc75986747976390a4
59
hpp
C++
src/boost_geometry_geometries_adapted_std_array.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_geometry_geometries_adapted_std_array.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_geometry_geometries_adapted_std_array.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/geometry/geometries/adapted/std_array.hpp>
29.5
58
0.830508
[ "geometry" ]
b21d79ddb94cac33bf24e8c8b233c0fa3b87534e
13,557
cc
C++
src/xapian/api/database.cc
Kronuz/Xapiand
a71570859dcfc9f48090d845053f359b07f4f78c
[ "MIT" ]
370
2016-03-14T12:19:08.000Z
2022-03-25T02:07:29.000Z
src/xapian/api/database.cc
YosefMac/Xapiand-1
a71570859dcfc9f48090d845053f359b07f4f78c
[ "MIT" ]
34
2015-11-30T19:06:40.000Z
2022-02-26T03:46:58.000Z
src/xapian/api/database.cc
YosefMac/Xapiand-1
a71570859dcfc9f48090d845053f359b07f4f78c
[ "MIT" ]
31
2015-02-13T22:27:34.000Z
2022-03-25T02:07:34.000Z
/** @file database.cc * @brief Database API class */ /* Copyright 2006,2007,2008,2009,2010,2011,2013,2014,2015,2016,2017,2019 Olly Betts * Copyright 2007,2008,2009 Lemur Consulting Ltd * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "xapian/database.h" #include "xapian/backends/databaseinternal.h" #include "xapian/backends/empty_database.h" #include "xapian/backends/multi/multi_database.h" #include "xapian/common/debuglog.h" #include "xapian/api/editdistance.h" #include "xapian/common/omassert.h" #include "xapian/api/postingiteratorinternal.h" #include "xapian/constants.h" #include "xapian/error.h" #include "xapian/positioniterator.h" #include "xapian/postingiterator.h" #include "xapian/termiterator.h" #include "xapian/unicode.h" #include <algorithm> #include <cstdlib> // For abs(). #include <memory> #include <string> #include <vector> using namespace std; [[noreturn]] static void docid_zero_invalid() { throw Xapian::InvalidArgumentError("Document ID 0 is invalid"); } [[noreturn]] static void empty_metadata_key() { throw Xapian::InvalidArgumentError("Empty metadata keys are invalid"); } [[noreturn]] static void empty_term_invalid() { throw Xapian::InvalidArgumentError("Empty terms are invalid"); } namespace Xapian { Database::Database(Database::Internal* internal_) : internal(internal_) { } Database::Database(const Database&) = default; Database& Database::operator=(const Database&) = default; Database::Database(Database&&) = default; Database& Database::operator=(Database&&) = default; Database::Database() : internal(new EmptyDatabase) { } Database::~Database() { } bool Database::reopen() { return internal->reopen(); } void Database::close() { internal->close(); } size_t Database::size() const { return internal->size(); } unsigned Database::refs() const { return internal->_refs; } void Database::add_database_(const Database& o, bool read_only) { if (this == &o) { const char* msg = read_only ? "Database::add_database(): Can't add a Database to itself" : "WritableDatabase::add_database(): Can't add a WritableDatabase " "to itself"; throw InvalidArgumentError(msg); } auto o_size = o.internal->size(); if (o_size == 0) { // Adding an empty database is a no-op. return; } auto my_size = internal->size(); if (my_size == 0 && o_size == 1) { // Just copy. internal = o.internal; return; } #if 0 // The check below doesn't work - for example: // // Database db; // db.add_database(WritableDatabase("one.db")); // db.add_database(WritableDatabase("two.db")); // // The first add_database() assigns the internal across, so at the second // call internal->is_read_only() returns false but read_only is true. // // I'm not entirely convinced the extra complexity required to make this // work is worthwhile. We catch static violations such as this at compile // time: // // WritableDatabase db; // db.add_database(Database("one.db")); // // The case we don't catch at compile time is: // // WritableDatabase db; // Database ro_db = db; // ro_db.add_database(Database("one.db")); // // But performing WritableDatabase actions using such a WritableDatabase // should now throw InvalidOperationError. if (!internal->is_read_only() && read_only) { throw InvalidArgumentError("Database::add_database(): Can't add a " "Database to a WritableDatabase"); } #endif // Make sure internal is a MultiDatabase with enough space reserved. auto new_size = my_size + o_size; MultiDatabase* multi_db; if (my_size <= 1) { multi_db = new MultiDatabase(new_size, read_only); if (my_size) multi_db->push_back(internal.get()); internal = multi_db; } else { // Must already be a MultiDatabase as everything else reports 1 for // size(). multi_db = static_cast<MultiDatabase*>(internal.get()); multi_db->reserve(new_size); } if (o_size == 1) { multi_db->push_back(o.internal.get()); } else { // Must be a MultiDatabase. auto o_multi = static_cast<MultiDatabase*>(o.internal.get()); // Add the shards from o to ourself. for (auto&& shard : o_multi->shards) { multi_db->push_back(shard); } } } PostingIterator Database::postlist_begin(const string& term) const { PostList* pl = internal->open_post_list(term); if (!pl) return PostingIterator(); return PostingIterator(new PostingIterator::Internal(pl, *this)); } TermIterator Database::termlist_begin(Xapian::docid did) const { if (did == 0) docid_zero_invalid(); return TermIterator(internal->open_term_list(did)); } TermIterator Database::allterms_begin(const string& prefix) const { return TermIterator(internal->open_allterms(prefix)); } bool Database::has_positions() const { return internal->has_positions(); } PositionIterator Database::positionlist_begin(Xapian::docid did, const string& term) const { if (did == 0) docid_zero_invalid(); if (term.empty()) empty_term_invalid(); return PositionIterator(internal->open_position_list(did, term)); } Xapian::doccount Database::get_doccount() const { return internal->get_doccount(); } Xapian::docid Database::get_lastdocid() const { return internal->get_lastdocid(); } double Database::get_average_length() const { Xapian::doccount doc_count = internal->get_doccount(); if (rare(doc_count == 0)) return 0.0; Xapian::totallength total_length = internal->get_total_length(); return total_length / double(doc_count); } Xapian::totallength Database::get_total_length() const { return internal->get_total_length(); } Xapian::doccount Database::get_termfreq(const string& term) const { if (term.empty()) return get_doccount(); Xapian::doccount result; internal->get_freqs(term, &result, NULL); return result; } Xapian::termcount Database::get_collection_freq(const string& term) const { if (term.empty()) return get_doccount(); Xapian::termcount result; internal->get_freqs(term, NULL, &result); return result; } Xapian::doccount Database::get_value_freq(Xapian::valueno slot) const { return internal->get_value_freq(slot); } string Database::get_value_lower_bound(Xapian::valueno slot) const { return internal->get_value_lower_bound(slot); } string Database::get_value_upper_bound(Xapian::valueno slot) const { return internal->get_value_upper_bound(slot); } Xapian::termcount Database::get_doclength_lower_bound() const { return internal->get_doclength_lower_bound(); } Xapian::termcount Database::get_doclength_upper_bound() const { return internal->get_doclength_upper_bound(); } Xapian::termcount Database::get_wdf_upper_bound(const string& term) const { if (term.empty()) return 0; return internal->get_wdf_upper_bound(term); } Xapian::termcount Database::get_unique_terms_lower_bound() const { return internal->get_unique_terms_lower_bound(); } Xapian::termcount Database::get_unique_terms_upper_bound() const { return internal->get_unique_terms_upper_bound(); } ValueIterator Database::valuestream_begin(Xapian::valueno slot) const { return ValueIterator(internal->open_value_list(slot)); } Xapian::termcount Database::get_doclength(Xapian::docid did) const { if (did == 0) docid_zero_invalid(); return internal->get_doclength(did); } Xapian::termcount Database::get_unique_terms(Xapian::docid did) const { if (did == 0) docid_zero_invalid(); return internal->get_unique_terms(did); } Document Database::get_document(Xapian::docid did, unsigned flags) const { if (rare(did == 0)) docid_zero_invalid(); bool assume_valid = flags & Xapian::DOC_ASSUME_VALID; return Document(internal->open_document(did, assume_valid)); } bool Database::term_exists(const string& term) const { // NB Internal::term_exists() handles term.empty(). return internal->term_exists(term); } void Database::keep_alive() { internal->keep_alive(); } string Database::get_description() const { string desc = "Database("; desc += internal->get_description(); desc += ')'; return desc; } // Word must have a trigram score at least this close to the best score seen // so far. #define TRIGRAM_SCORE_THRESHOLD 2 string Database::get_spelling_suggestion(const string& word, unsigned max_edit_distance) const { if (word.size() <= 1) return string(); unique_ptr<TermList> merger(internal->open_spelling_termlist(word)); if (!merger.get()) return string(); EditDistanceCalculator edcalc(word); Xapian::termcount best = 1; string result; int edist_best = max_edit_distance; Xapian::doccount freq_best = 0; Xapian::doccount freq_exact = 0; while (true) { TermList* ret = merger->next(); if (ret) merger.reset(ret); if (merger->at_end()) break; string term = merger->get_termname(); Xapian::termcount score = merger->get_wdf(); LOGVALUE(SPELLING, term); LOGVALUE(SPELLING, score); if (score + TRIGRAM_SCORE_THRESHOLD >= best) { if (score > best) best = score; int edist = edcalc(term, edist_best); LOGVALUE(SPELLING, edist); if (edist <= edist_best) { Xapian::doccount freq = internal->get_spelling_frequency(term); LOGVALUE(SPELLING, freq); LOGVALUE(SPELLING, freq_best); // Even if we have an exact match, there may be a much more // frequent potential correction which will still be // interesting. if (edist == 0) { freq_exact = freq; continue; } if (edist < edist_best || freq > freq_best) { LOGLINE(SPELLING, "Best so far: \"" << term << "\" edist " << edist << " freq " << freq); result = term; edist_best = edist; freq_best = freq; } } } } if (freq_best < freq_exact) return string(); return result; } TermIterator Database::spellings_begin() const { return TermIterator(internal->open_spelling_wordlist()); } TermIterator Database::synonyms_begin(const string& term) const { return TermIterator(internal->open_synonym_termlist(term)); } TermIterator Database::synonym_keys_begin(const string& prefix) const { return TermIterator(internal->open_synonym_keylist(prefix)); } string Database::get_metadata(const string& key) const { if (rare(key.empty())) empty_metadata_key(); return internal->get_metadata(key); } Xapian::TermIterator Database::metadata_keys_begin(const string& prefix) const { return TermIterator(internal->open_metadata_keylist(prefix)); } string Database::get_uuid() const { return internal->get_uuid(); } bool Database::locked() const { return internal->locked(); } Xapian::rev Database::get_revision() const { return internal->get_revision(); } void WritableDatabase::commit() { internal->commit(); } void WritableDatabase::begin_transaction(bool flushed) { internal->begin_transaction(flushed); } void WritableDatabase::end_transaction_(bool do_commit) { internal->end_transaction(do_commit); } Xapian::DocumentInfo WritableDatabase::add_document(const Document& doc) { return internal->add_document(doc); } void WritableDatabase::delete_document(Xapian::docid did) { internal->delete_document(did); } void WritableDatabase::delete_document(const string& term) { if (term.empty()) empty_term_invalid(); internal->delete_document(term); } Xapian::DocumentInfo WritableDatabase::replace_document(Xapian::docid did, const Document& doc) { if (rare(did == 0)) docid_zero_invalid(); return internal->replace_document(did, doc); } Xapian::DocumentInfo WritableDatabase::replace_document(const string& term, const Document& doc) { if (term.empty()) empty_term_invalid(); return internal->replace_document(term, doc); } void WritableDatabase::add_spelling(const string& word, Xapian::termcount freqinc) const { internal->add_spelling(word, freqinc); } Xapian::termcount WritableDatabase::remove_spelling(const string& word, Xapian::termcount freqdec) const { return internal->remove_spelling(word, freqdec); } void WritableDatabase::add_synonym(const string& term, const string& synonym) const { internal->add_synonym(term, synonym); } void WritableDatabase::remove_synonym(const string& term, const string& synonym) const { internal->remove_synonym(term, synonym); } void WritableDatabase::clear_synonyms(const string& term) const { internal->clear_synonyms(term); } void WritableDatabase::set_metadata(const string& key, const string& value) { if (rare(key.empty())) empty_metadata_key(); internal->set_metadata(key, value); } string WritableDatabase::get_description() const { string desc = "WritableDatabase("; desc += internal->get_description(); desc += ')'; return desc; } }
21.760835
83
0.709006
[ "vector" ]
b21fbed8ee24ad8e8ee317a686ede053f5c4861c
13,029
cpp
C++
src/MySQLConnector/MySQLConnector.cpp
jspark311/File-Librarian
0d4cddffe4e57c4feebd9ae62cbb9c82699e0a0b
[ "Apache-2.0" ]
null
null
null
src/MySQLConnector/MySQLConnector.cpp
jspark311/File-Librarian
0d4cddffe4e57c4feebd9ae62cbb9c82699e0a0b
[ "Apache-2.0" ]
null
null
null
src/MySQLConnector/MySQLConnector.cpp
jspark311/File-Librarian
0d4cddffe4e57c4feebd9ae62cbb9c82699e0a0b
[ "Apache-2.0" ]
null
null
null
#include <syslog.h> #include <mysql/errmsg.h> #include <mysql/mysql.h> #include "MySQLConnector.h" #include "StringBuilder.h" #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <ctype.h> #include <signal.h> #include <unistd.h> #include <sys/types.h> extern void fp_log(const char *fxn_name, int severity, const char *message, ...); extern int causeParentToReloadMysql(void); MySQLConnector::MySQLConnector() { this->db_connected = 0; this->port = 0; this->tag = nullptr; this->name = nullptr; this->host = nullptr; this->socket = nullptr; this->username = nullptr; this->password = nullptr; this->charset = nullptr; this->node_id = nullptr; this->mysql = nullptr; this->no_free_on_destructor = false; // This should only be true in the parent. } MySQLConnector::~MySQLConnector() { this->dbCleanup(); fp_log(__PRETTY_FUNCTION__, LOG_DEBUG, "MySQLConnector is beginning its free operation."); if (this->tag != nullptr) { free(this->tag); } if (this->name != nullptr) { free(this->name); } if (this->host != nullptr) { free(this->host); } if (this->socket != nullptr) { free(this->socket); } if (this->username != nullptr) { free(this->username); } if (this->password != nullptr) { free(this->password); } if (this->charset != nullptr) { free(this->charset); } if (this->node_id != nullptr) { free(this->node_id); } this->port = 0; this->tag = nullptr; this->name = nullptr; this->host = nullptr; this->socket = nullptr; this->username = nullptr; this->password = nullptr; this->charset = nullptr; this->mysql = nullptr; fp_log(__PRETTY_FUNCTION__, LOG_INFO, "MySQLConnector finished its free operation."); } // A debug function. Prints the database connection details. void MySQLConnector::print_db_conn_detail(){ fp_log(__PRETTY_FUNCTION__, LOG_INFO, "Database connection data follows:"); fp_log(__PRETTY_FUNCTION__, LOG_INFO, "=============================="); if (this->tag != nullptr) { fp_log(__PRETTY_FUNCTION__, LOG_INFO, "DB_TAG: %s", this->tag); } if (this->name != nullptr) { fp_log(__PRETTY_FUNCTION__, LOG_INFO, "DB_NAME: %s", this->name); } if (this->host != nullptr) { fp_log(__PRETTY_FUNCTION__, LOG_INFO, "HOST: %s", this->host); } if (this->port >= 0) { fp_log(__PRETTY_FUNCTION__, LOG_INFO, "PORT: %d", this->port); } if (this->socket != nullptr) { fp_log(__PRETTY_FUNCTION__, LOG_INFO, "SOCKET: %s", this->socket); } if (this->username != nullptr) { fp_log(__PRETTY_FUNCTION__, LOG_INFO, "USERNAME: %s", this->username); } if (this->password != nullptr) { fp_log(__PRETTY_FUNCTION__, LOG_INFO, "PASSWORD: %s", this->password); } if (this->charset != nullptr) { fp_log(__PRETTY_FUNCTION__, LOG_INFO, "CHARSET: %s", this->charset); } fp_log(__PRETTY_FUNCTION__, LOG_INFO, "=============================="); } /** * Wrapper for queries that will make all reasonable efforts to get the query executed. * Returns 1 on success and 0 on failure. */ int MySQLConnector::r_query(unsigned char *query) { return this->r_query((char *)query); } int MySQLConnector::r_query(const char *query) { return this->r_query((char *)query); } int MySQLConnector::r_query(char *query) { int return_value = 0; if (this->dbConnected()) { if (mysql_query(this->mysql, query) != 0) { unsigned int err_no = mysql_errno(this->mysql); switch (err_no) { case 0: this->result = mysql_store_result(this->mysql); fp_log(__PRETTY_FUNCTION__, LOG_WARNING, "in query 1\n"); return_value = 1; break; case 2006: // MySQL server has gone away. if (causeParentToReloadMysql()) { if (mysql_query(this->mysql, query)) { // Try to re-run the failed query. err_no = mysql_errno(this->mysql); fp_log(__PRETTY_FUNCTION__, LOG_WARNING, "The following query caused error code %d (%s) after being run for the second time. Dropping the query: %s", err_no, mysql_error(this->mysql), query); } } else fp_log(__PRETTY_FUNCTION__, LOG_WARNING, "DB failed a reload. The following query was permanently dropped: ", query); break; default: fp_log(__PRETTY_FUNCTION__, LOG_WARNING, "The following query caused error code %d (%s): %s", err_no, mysql_error(this->mysql), query); break; } } else { this->result = mysql_store_result(this->mysql); return_value = 1; } } return return_value; } long MySQLConnector::escape_string(char* src, StringBuilder* dest) { if ((nullptr != src) && (nullptr != dest)) { long escaped_len = 0; long src_len = strlen(src); if (src_len > 0) { char escaped[(src_len * 2) + 1]; escaped_len = mysql_real_escape_string(mysql, escaped, src, src_len); *(escaped + escaped_len) = '\0'; dest->concat(escaped); } return escaped_len; } return -1; } int MySQLConnector::last_insert_id() { int return_value = -1; if (this->dbConnected()) { if (mysql_query(this->mysql, "SELECT LAST_INSERT_ID();") == 0) { MYSQL_RES *last_id_res = mysql_store_result(this->mysql); MYSQL_ROW row = mysql_fetch_row(last_id_res); return_value = atoi(row[0]); mysql_free_result(last_id_res); } } return return_value; } // Pass a line from the DB conf file and it shall be parsed and placed into the appropriate slot. int MySQLConnector::parse_line_from_db_conf(char *line) { int return_value = -1; char* equal_pos = strchr(line, '='); char* line_end = strchr(line, '\n'); if (equal_pos != nullptr) { while ((*(equal_pos) == ' ') || (*(equal_pos) == '=' )) { equal_pos++; } // Trim if (strncmp("dbhost", line, 6) == 0) { this->host = (char *)(intptr_t) str_n_dup(equal_pos, (line_end-equal_pos)); return_value = 0; } else if (strncmp("dbname", line, 6) == 0) { this->name = (char *)(intptr_t) str_n_dup(equal_pos, (line_end-equal_pos)); return_value = 0; } else if (strncmp("dbuser", line, 6) == 0) { this->username = (char *)(intptr_t) str_n_dup(equal_pos, (line_end-equal_pos)); return_value = 0; } else if (strncmp("dbpass", line, 6) == 0) { this->password = (char *)(intptr_t) str_n_dup(equal_pos, (line_end-equal_pos)); return_value = 0; } else if (strncmp("dbport", line, 6) == 0) { // This one has to be an integer parse. char *temp_str = (char*) alloca((line_end-equal_pos)+1); memset(temp_str, 0, (line_end-equal_pos)+1); strncpy(temp_str, equal_pos, (line_end-equal_pos)); this->port = atoi(temp_str); return_value = 0; } else if (strncmp("dbsock", line, 6) == 0) { this->socket = (char *)(intptr_t) str_n_dup(equal_pos, (line_end-equal_pos)); return_value = 0; } else if (strncmp("dbcharset", line, 9) == 0) { this->charset = (char *)(intptr_t) str_n_dup(equal_pos, (line_end-equal_pos)); return_value = 0; } else if (strncmp("node_id", line, 7) == 0) { this->node_id = (char *)(intptr_t) str_n_dup(equal_pos, (line_end-equal_pos)); return_value = 0; } } return return_value; } // The root of the DB connection def parser. // Returns -1 on failure or the number of lines parsed on success int MySQLConnector::db_parse_root(char *feed){ int return_value = -1; if (feed == nullptr) { fp_log(__PRETTY_FUNCTION__, LOG_WARNING, "Couldn't parse tag: %s", feed); return return_value; } int feed_len = strlen(feed); this->tag = str_n_dup(feed, feed_len-1); char *line_delim = strchr(feed, '\n'); while ((line_delim != nullptr) && (strlen(line_delim) > 2)) { if (this->parse_line_from_db_conf((char *)(line_delim+1)) < 0) { fp_log(__PRETTY_FUNCTION__, LOG_WARNING, "Ignoring bad line in conf file: %s", ((char *)(line_delim+1))); } if (feed_len <= ((line_delim+1)-feed)) { line_delim = nullptr; } else { line_delim = strchr(line_delim+1, '\n'); } return_value++; } return_value++; // To make it a natural number. return return_value; } // Call this method to read the given filename and parse its contents into the // DB connection struct. int MySQLConnector::provisionConnectionDetails(char *filename) { int return_value = -1; char *ok_filename; if ((filename == nullptr) || (strlen(filename) <= 0)) { // If the provided filename is NULL, use the default. ok_filename = strdupa(DEFAULT_CONF_FILE); fp_log(__PRETTY_FUNCTION__, LOG_NOTICE, "Using default configuration file: %s", ok_filename); } else{ ok_filename = filename; } FILE *fp = fopen(ok_filename, "r"); if (fp == nullptr) { fp_log(__PRETTY_FUNCTION__, LOG_WARNING, "Could not open (%s) for read-only access.\n", ok_filename); return return_value; } size_t result, file_len; fseek(fp, 0, SEEK_END); file_len = ftell(fp); fseek(fp, 0, SEEK_SET); char *code = (char*) alloca((sizeof(char) * file_len) + 10); if (code == nullptr) { fp_log(__PRETTY_FUNCTION__, LOG_WARNING, "provisionConnectionDetails(): Failed to allocate %d bytes to read the DB connection data.", file_len); return return_value; } memset(code, 0x00, (sizeof(char) * file_len)+10); result = fread(code, 1, file_len, fp); if (result) { return_value = this->db_parse_root(code); } fclose(fp); return return_value; } // Returns 1 on success (ready to query) and 0 on failure. int MySQLConnector::dbConnected(){ if (this->mysql == nullptr) { this->mysql = mysql_init(nullptr); if (this->mysql == nullptr) { fp_log(__PRETTY_FUNCTION__, LOG_ERR, "Cannot connect to the MySQL server. This is a serious problem and will prevent us from running eventually."); this->db_connected = -1; return 0; } } if (this->db_connected != 1) { if (mysql_real_connect(this->mysql, this->host, this->username, this->password, this->name, this->port, nullptr, 0)) { StringBuilder temp_query((char *) "USE "); temp_query.concat(this->name); temp_query.concat(";"); if (mysql_query(this->mysql, (const char*)temp_query.string()) != 0) { fp_log(__PRETTY_FUNCTION__, LOG_NOTICE, "Failed to select %s as a database.", this->name); } else { mysql_autocommit(this->mysql, 1); this->db_connected = 1; fp_log(__PRETTY_FUNCTION__, LOG_NOTICE, "Connected to database %s.", this->name); } } else { this->db_connected = 0; char *tmp_str = (char *) mysql_error(this->mysql); fp_log(__PRETTY_FUNCTION__, LOG_ERR, "Failed to connect to MySQL: %s", tmp_str); this->print_db_conn_detail(); this->db_connected = -1; } } return this->db_connected; } // Call to wrap up any DB-related things so that we can exit clean. void MySQLConnector::dbCleanup() { if (this->mysql == nullptr) { fp_log(__PRETTY_FUNCTION__, LOG_WARNING, "We do not seem to have a MySQL server."); } else { if (!this->no_free_on_destructor) { fp_log(__PRETTY_FUNCTION__, LOG_INFO, "Closing connection to MySQL server."); mysql_close(this->mysql); } else { fp_log(__PRETTY_FUNCTION__, LOG_DEBUG, "This object was copied from a parent process. Declining to close the MySQL connection."); } this->db_connected = 0; this->mysql = nullptr; } } // Return a malloc'd copy of the trimmed input string. char* MySQLConnector::str_n_dup(const char *s, size_t n) { size_t i = 0; char *r = (char *) malloc(n+1); memset(r, 0, (n+1)); while (i < n) { *(r + i) = *(s + i); i++; } r[i] = '\0'; char *end = r + strlen(r) - 1; while (end > r && isspace(*end)) end--; *(end+1) = 0; return r; }
38.433628
218
0.578939
[ "object" ]
b2203c35d9fd11a2d97327312019f2b5bd3befd8
3,589
hpp
C++
src/SvgFontManager.hpp
StratifyLabs/fontutil
e8a7eab1fe0e851985a029abeb3e1acd848b6f10
[ "Apache-2.0" ]
null
null
null
src/SvgFontManager.hpp
StratifyLabs/fontutil
e8a7eab1fe0e851985a029abeb3e1acd848b6f10
[ "Apache-2.0" ]
null
null
null
src/SvgFontManager.hpp
StratifyLabs/fontutil
e8a7eab1fe0e851985a029abeb3e1acd848b6f10
[ "Apache-2.0" ]
null
null
null
/*! \file */ //Copyright 2011-2018 Tyler Gilbert; All Rights Reserved #ifndef SVGFONTMANAGER_HPP_ #define SVGFONTMANAGER_HPP_ #include "FontObject.hpp" #include "BmpFontGenerator.hpp" class FillPoint { public: FillPoint(const Point & point, sg_size_t spacing){ m_point = point; m_spacing = spacing; } Point point() const { return m_point; } sg_size_t spacing() const { return m_spacing; } bool operator < (const FillPoint & a) const { return spacing() < a.spacing(); } bool operator > (const FillPoint & a) const { return spacing() > a.spacing(); } private: sg_size_t m_spacing; sg_point_t m_point; }; class SvgFontManager : public FontObject { public: SvgFontManager(); int process_svg_font_file(const ConstString & path); int process_svg_icon_file(const ConstString & source, const ConstString & dest); void set_map_output_file(const ConstString & path){ m_bmp_font_generator.set_map_output_file(path); } void set_canvas_size(u16 size){ m_canvas_size = size; if( size == 0 ){ m_canvas_size = 128; } } void set_show_canvas(bool value = true){ m_is_show_canvas = value; } void set_pour_grid_size(u16 size){ m_pour_grid_size = size; if( size == 0 ){ m_pour_grid_size = 8; } } void set_downsample_factor(const Area & dim){ m_downsample = dim; } void set_flip_y(bool value = true){ if( value ){ m_scale_sign_y = -1; } else { m_scale_sign_y = 1; } } private: int process_svg_icon(const JsonObject & object); BmpFontGenerator m_bmp_font_generator; //used for exporting to bmp u16 m_canvas_size; Area m_downsample; Area m_canvas_dimensions; Point m_canvas_origin; u16 m_pour_grid_size; bool m_is_show_canvas; int parse_svg_path(const char * d); static const ConstString path_commands_sign(){ return "MmCcSsLlHhVvQqTtAaZz-"; } static const ConstString path_commands_space(){ return "MmCcSsLlHhVvQqTtAaZz \n\t"; } static const ConstString path_commands(){ return "MmCcSsLlHhVvQqTtAaZz"; } static bool is_command_char(char c); enum { NO_STATE, MOVETO_STATE, LINETO_STATE, TOTAL_STATE }; var::Vector<sg_vector_path_description_t> convert_svg_path(Bitmap & canvas, const var::ConstString & d, const Area & canvas_dimensions, sg_size_t grid_size, bool is_fit_icon); var::Vector<sg_vector_path_description_t> process_svg_path(const ConstString & path); Region parse_bounds(const ConstString & value); Area calculate_canvas_dimension(const Region & bounds, sg_size_t canvas_size); Point calculate_canvas_origin(const Region & bounds, const Area & canvas_dimensions); Point convert_svg_coord(float x, float y, bool is_absolute = true); void fit_icon_to_canvas(Bitmap & bitmap, VectorPath & vector_path, const VectorMap & map, bool recheck); enum { PATH_DESCRIPTION_MAX = 256, }; int m_state; Point m_current_point; Point m_control_point; char m_last_command_character; Region m_bounds; float m_scale; int m_scale_sign_y; u16 m_point_size; var::Vector<sg_vector_path_description_t> m_vector_path_icon_list; var::Vector<sg_font_char_t> m_font_character_list; static var::Vector<sg_point_t> calculate_pour_points(Bitmap & bitmap, const var::Vector<FillPoint> & fill_points); static var::Vector<FillPoint> find_all_fill_points(const Bitmap & bitmap, const Region & region, sg_size_t grid); static sg_size_t is_fill_point(const Bitmap & bitmap, sg_point_t point, const Region & region); int process_glyph(const JsonObject & glyph); int process_hkern(const JsonObject & kerning); sg_size_t map_svg_value_to_bitmap(u32 value); }; #endif /* SVGFONTMANAGER_HPP_ */
25.635714
176
0.758429
[ "object", "vector" ]
b2228db8349a136613da88006f205320ffc255df
3,716
cpp
C++
src/butterfly/private/fieldpath_huffman.cpp
ButterflyStats/butterfly
339e91a882cadc1a8f72446616f7d7f1480c3791
[ "Apache-2.0" ]
19
2017-04-13T07:46:59.000Z
2021-12-05T20:58:54.000Z
src/butterfly/private/fieldpath_huffman.cpp
ButterflyStats/butterfly
339e91a882cadc1a8f72446616f7d7f1480c3791
[ "Apache-2.0" ]
5
2018-03-21T17:06:23.000Z
2021-12-03T10:58:46.000Z
src/butterfly/private/fieldpath_huffman.cpp
ButterflyStats/butterfly
339e91a882cadc1a8f72446616f7d7f1480c3791
[ "Apache-2.0" ]
4
2018-03-11T12:12:07.000Z
2020-11-17T07:46:37.000Z
/** * @file fieldpath_huffman.cpp * @author Robin Dietrich <me (at) invokr (dot) org> * * @par License * Butterfly Replay Parser * Copyright 2014-2016 Robin Dietrich * * 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 <vector> #include "util_huffman.hpp" #include "fieldpath.hpp" #include "fieldpath_operations.hpp" #include "fieldpath_huffman.hpp" namespace butterfly { /* clang-format off */ std::vector<fieldop> fieldpath_operations = { {"PlusOne", fp_PlusOne, 36271}, // 0 {"PlusTwo", fp_PlusTwo, 10334}, {"PlusThree", fp_PlusThree, 1375}, {"PlusFour", fp_PlusFour, 646}, {"PlusN", fp_PlusN, 4128}, {"PushOneLeftDeltaZeroRightZero", fp_PushOneLeftDeltaZeroRightZero, 35}, // 5 {"PushOneLeftDeltaZeroRightNonZero", fp_PushOneLeftDeltaZeroRightNonZero, 3}, {"PushOneLeftDeltaOneRightZero", fp_PushOneLeftDeltaOneRightZero, 521}, {"PushOneLeftDeltaOneRightNonZero", fp_PushOneLeftDeltaOneRightNonZero, 2942}, {"PushOneLeftDeltaNRightZero", fp_PushOneLeftDeltaNRightZero, 560}, {"PushOneLeftDeltaNRightNonZero", fp_PushOneLeftDeltaNRightNonZero, 471}, // 10 {"PushOneLeftDeltaNRightNonZeroPack6Bits", fp_PushOneLeftDeltaNRightNonZeroPack6Bits, 10530}, {"PushOneLeftDeltaNRightNonZeroPack8Bits", fp_PushOneLeftDeltaNRightNonZeroPack8Bits, 251}, {"PushTwoLeftDeltaZero", fp_PushTwoLeftDeltaZero, 1}, {"PushTwoPack5LeftDeltaZero", fp_PushTwoPack5LeftDeltaZero, 1}, {"PushThreeLeftDeltaZero", fp_PushThreeLeftDeltaZero, 1}, // 15 {"PushThreePack5LeftDeltaZero", fp_PushThreePack5LeftDeltaZero, 1}, {"PushTwoLeftDeltaOne", fp_PushTwoLeftDeltaOne, 1}, {"PushTwoPack5LeftDeltaOne", fp_PushTwoPack5LeftDeltaOne, 1}, {"PushThreeLeftDeltaOne", fp_PushThreeLeftDeltaOne, 1}, {"PushThreePack5LeftDeltaOne", fp_PushThreePack5LeftDeltaOne, 1}, // 20 {"PushTwoLeftDeltaN", fp_PushTwoLeftDeltaN, 1}, {"PushTwoPack5LeftDeltaN", fp_PushTwoPack5LeftDeltaN, 1}, {"PushThreeLeftDeltaN", fp_PushThreeLeftDeltaN, 1}, {"PushThreePack5LeftDeltaN", fp_PushThreePack5LeftDeltaN, 1}, {"PushN", fp_PushN, 1}, // 25 {"PushNAndNonTopological", fp_PushNAndNonTopological, 310}, {"PopOnePlusOne", fp_PopOnePlusOne, 2}, {"PopOnePlusN", fp_PopOnePlusN, 1}, {"PopAllButOnePlusOne", fp_PopAllButOnePlusOne, 1837}, {"PopAllButOnePlusN", fp_PopAllButOnePlusN, 149}, // 30 {"PopAllButOnePlusNPack3Bits", fp_PopAllButOnePlusNPack3Bits, 300}, {"PopAllButOnePlusNPack6Bits", fp_PopAllButOnePlusNPack6Bits, 634}, {"PopNPlusOne", fp_PopNPlusOne, 1}, {"PopNPlusN", fp_PopNPlusN, 1}, {"PopNAndNonTopographical", fp_PopNAndNonTopographical, 1}, // 35 {"NonTopoComplex", fp_NonTopoComplex, 76}, {"NonTopoPenultimatePlusOne", fp_NonTopoPenultimatePlusOne, 271}, {"NonTopoComplexPack4Bits", fp_NonTopoComplexPack4Bits, 99}, {"FieldPathEncodeFinish", fp_FieldPathEncodeFinish, 25474} // 39 }; /* clang-format on */ /** Fieldop Huffman comparison function */ template <> int32_t huffman_compare<fieldop>( HuffmanNode* left, HuffmanNode* right ) { if ( left->weight == right->weight ) return left->num <= right->num; return left->weight > right->weight; } } /* butterfly */
44.238095
95
0.745694
[ "vector" ]
b2291f5d61cf62ebe7dd7d141d7bd97c89d36d89
329
hpp
C++
src/serialization/matrix.hpp
degarashi/frea
bb598245c2ab710cc816e98d7361e5863af5fd7e
[ "MIT" ]
null
null
null
src/serialization/matrix.hpp
degarashi/frea
bb598245c2ab710cc816e98d7361e5863af5fd7e
[ "MIT" ]
null
null
null
src/serialization/matrix.hpp
degarashi/frea
bb598245c2ab710cc816e98d7361e5863af5fd7e
[ "MIT" ]
null
null
null
#pragma once #include "../matrix.hpp" #include "vector.hpp" #include <cereal/cereal.hpp> namespace frea { template <class Ar, class V, int M> void serialize(Ar& ar, DataM<V,M>& d) { using Dm = DataM<V,M>; std::size_t sz = Dm::dim_m; ar(cereal::make_size_tag(sz)); for(std::size_t i=0 ; i<sz ; i++) ar(d.m[i]); } }
20.5625
40
0.6231
[ "vector" ]
b22b703aa66b4a71b0feb4e3fbf3bdbd6aaec990
7,225
cpp
C++
Engine/Dependences/Framework/Graphics/src/Types/Geometry/Mesh3D.cpp
GlebShikovec/SREngine
bb806c3e4da06ef6fddee5b46ed5d2fca231be43
[ "MIT" ]
null
null
null
Engine/Dependences/Framework/Graphics/src/Types/Geometry/Mesh3D.cpp
GlebShikovec/SREngine
bb806c3e4da06ef6fddee5b46ed5d2fca231be43
[ "MIT" ]
1
2022-03-07T14:42:22.000Z
2022-03-07T14:42:22.000Z
Engine/Dependences/Framework/Graphics/src/Types/Geometry/Mesh3D.cpp
GlebShikovec/SREngine
bb806c3e4da06ef6fddee5b46ed5d2fca231be43
[ "MIT" ]
null
null
null
// // Created by Nikita on 02.06.2021. // #include <Types/Geometry/Mesh3D.h> // TODO: UNSAFE SHIT! inline static std::map<unsigned int, unsigned long> VAO_usages = std::map<unsigned int, unsigned long>(); inline static std::map<std::string, unsigned int> VAO_names = std::map<std::string, unsigned int>(); inline static std::map<uint32_t, unsigned long> VBO_usages = std::map<unsigned int, unsigned long>(); inline static std::map<uint32_t, unsigned long> IBO_usages = std::map<unsigned int, unsigned long>(); inline static std::map<std::string, std::pair<uint32_t, uint32_t>> VBOandIBO_names = std::map<std::string, std::pair<uint32_t, uint32_t>>(); bool Framework::Graphics::Types::Mesh3D::Calculate() { if (!m_render){ Debug::Error("Mesh3D::Calculate() : mesh is not register in render!"); return false; } if (!m_shader){ if (!Shader::GetDefaultGeometryShader()) { Debug::Error("Mesh3D::Calculate() : mesh have not shader!"); return false; } } if (!m_material){ Debug::Error("Mesh3D::Calculate() : mesh have not material!"); return false; } //std::cout << Vertices::ToString(m_indices) << std::endl; //std::cout << Vertices::ToString(m_vertices) << std::endl; m_mutex.lock(); { /* Check exists pre-calculated meshes */ if (m_env->GetPipeLine() == PipeLine::OpenGL) { unsigned int exists = VAO_names[m_resource_id]; if (exists) { if (Debug::GetLevel() >= Debug::Level::High) Debug::Log("Mesh3D::Calculate() : copy VAO..."); m_VAO = (int) exists; VAO_usages[m_VAO]++; m_isCalculated = true; m_mutex.unlock(); return true; } } else { auto exists = VBOandIBO_names.find(m_resource_id); if (exists != VBOandIBO_names.end()) { if (Debug::GetLevel() >= Debug::Level::High) Debug::Log("Mesh3D::Calculate() : copy VBO and IBO..."); m_VBO = (int)exists->second.first; m_IBO = (int)exists->second.second; VBO_usages[m_VBO]++; IBO_usages[m_IBO]++; m_isCalculated = true; m_mutex.unlock(); return true; } } } if (Debug::GetLevel() >= Debug::Level::High) Debug::Log("Mesh3D::Calculate() : calculating \""+ m_geometry_name +"\"..."); if (m_env->GetPipeLine() == PipeLine::OpenGL) { if (!this->m_env->CalculateVAO(reinterpret_cast<unsigned int &>(m_VAO), m_vertices, m_countVertices)) { Debug::Error("Mesh3D::Calculate() : failed calculate \"" + m_geometry_name + "\" mesh!"); m_mutex.unlock(); return false; } VAO_usages[m_VAO]++; VAO_names[m_resource_id] = m_VAO; } else { if (!this->m_env->CalculateVBO(reinterpret_cast<unsigned int &>(m_VBO), m_vertices.data(), sizeof(Vertices::Mesh3DVertex), m_countVertices)) { Debug::Error("Mesh3D::Calculate() : failed calculate VBO \"" + m_geometry_name + "\" mesh!"); this->m_hasErrors = true; m_mutex.unlock(); return false; } if (!this->m_env->CalculateIBO(reinterpret_cast<unsigned int &>(m_IBO), m_indices.data(), sizeof(uint32_t), m_countIndices)) { Debug::Error("Mesh3D::Calculate() : failed calculate IBO \"" + m_geometry_name + "\" mesh!"); this->m_hasErrors = true; m_mutex.unlock(); return false; } VBOandIBO_names[m_resource_id] = std::pair((uint32_t)m_VBO, (uint32_t)m_IBO); int i = VBO_usages[m_VBO]; VBO_usages[(uint32_t)m_VBO]++; int i2 = VBO_usages[m_VBO]; IBO_usages[(uint32_t)m_IBO]++; } m_isCalculated = true; m_mutex.unlock(); return true; } Framework::Graphics::Types::Mesh *Framework::Graphics::Types::Mesh3D::Copy() { if (m_isDestroy) { Debug::Error("Mesh3D::Copy() : mesh already destroyed!"); return nullptr; } if (Debug::GetLevel() >= Debug::Level::High) Debug::Log("Mesh3D::Copy() : copy \""+m_resource_id+ "\" mesh..."); if (!m_material){ Debug::Error("Mesh3D::Copy() : material is nullptr! Something went wrong..."); return nullptr; } m_mutex.lock(); Material* mat = new Material( m_material->m_diffuse, m_material->m_normal, m_material->m_specular, m_material->m_glossiness ); Mesh3D* copy = new Mesh3D(this->m_shader, mat, this->m_geometry_name); { mat->m_mesh = copy; mat->m_bloom = m_material->m_bloom; mat->m_transparent = m_material->m_transparent; mat->m_color = m_material->m_color; } copy->m_countVertices = m_countVertices; copy->m_countIndices = m_countIndices; copy->m_useIndices = m_useIndices; copy->m_position = m_position; copy->m_rotation = m_rotation; copy->m_scale = m_scale; if (m_isCalculated) { if (m_VAO != -1) VAO_usages[m_VAO]++; if (m_VBO != -1) VBO_usages[m_VBO]++; if (m_IBO != -1) IBO_usages[m_IBO]++; copy->m_VAO = m_VAO; copy->m_VBO = m_VBO; copy->m_IBO = m_IBO; }else{ copy->m_vertices = m_vertices; copy->m_indices = m_indices; } copy->m_isCalculated = m_isCalculated; copy->m_autoRemove = m_autoRemove; copy->m_modelMat = m_modelMat; copy->m_resource_id = m_resource_id; m_mutex.unlock(); return copy; } bool Framework::Graphics::Types::Mesh3D::FreeVideoMemory() { if (m_env->GetPipeLine() == PipeLine::OpenGL) { if (m_VAO > 0) { VAO_usages[m_VAO]--; if (VAO_usages[m_VAO] == 0) m_env->FreeMesh(m_VAO); m_isCalculated = false; return true; } else { Debug::Error("Mesh:FreeVideoMemory() : VAO is zero! Something went wrong..."); return false; } } else { if (m_VBO >= 0) { int i = VBO_usages[m_VBO]; VBO_usages[m_VBO]--; if (VBO_usages[m_VBO] == 0) if (!m_env->FreeVBO(m_VBO)) { Debug::Error("Mesh:FreeVideoMemory() : failed free VBO! Something went wrong..."); return false; } } else { Debug::Error("Mesh:FreeVideoMemory() : VBO is not exists! Something went wrong..."); return false; } if (m_IBO >= 0) { IBO_usages[m_IBO]--; if (IBO_usages[m_IBO] == 0) if (!m_env->FreeIBO(m_IBO)) { Debug::Error("Mesh:FreeVideoMemory() : failed free IBO! Something went wrong..."); return false; } } else { Debug::Error("Mesh:FreeVideoMemory() : IBO is not exists! Something went wrong..."); return false; } this->m_isCalculated = false; return true; } }
31.969027
150
0.551419
[ "mesh", "geometry", "render" ]
b22c35ebce66e21fdc0867da81291691762b9041
3,837
cpp
C++
013/L7/Repository.cpp
atenie/programming-challenges
32c06284c87eb0559cfd7c23a11824cd3935a254
[ "BSD-2-Clause" ]
null
null
null
013/L7/Repository.cpp
atenie/programming-challenges
32c06284c87eb0559cfd7c23a11824cd3935a254
[ "BSD-2-Clause" ]
null
null
null
013/L7/Repository.cpp
atenie/programming-challenges
32c06284c87eb0559cfd7c23a11824cd3935a254
[ "BSD-2-Clause" ]
null
null
null
// // Created by alexandru on 03.06.2018. // #include <iostream> #include "Repository.h" void Repository::addMovie(std::shared_ptr<Movie> m) { m_List.push_back(m); } void Repository::addToWatchList(std::shared_ptr<Movie> m) { w_List.push_back(m); } std::vector<std::shared_ptr<Movie>> Repository::retWList() { std::vector<std::shared_ptr<Movie>> copy; copy.assign(w_List.begin(),w_List.end()); return copy; } std::vector<std::shared_ptr<Movie>> Repository::retMList() { std::vector<std::shared_ptr<Movie>> copy; copy.assign(m_List.begin(),m_List.end()); return copy; } void Repository::SaveToCSV(std::vector<std::shared_ptr<Movie>> someList) { std::ofstream f("/home/alexandru/CLionProjects/L7/mov.csv"); if(f.is_open()) { for (auto it : someList) { f << it->getM_Title() << ","; f << it->getM_Genre() << ","; f << it->getM_Year() << ","; f << it->getM_Likes() << ","; f << it->getM_Trailer() << std::endl; } } f.close(); } void Repository::SaveToHTML(std::vector<std::shared_ptr<Movie>> someList) { std::ofstream f("/home/alexandru/CLionProjects/L7/mov.html"); if(f.is_open()) { f << "<html>" <<std::endl; f << "<body>" <<std::endl; f << "<table style=\"width:100%\">" <<std::endl; f << "<tr>" <<std::endl; f << "<th>Title</th>" << std::endl; f << "<th>Genre</th>" << std::endl; f << "<th>Year</th>" << std::endl; f << "<th>Likes</th>" << std::endl; f << "<th>Trailer</th>" << std::endl; f << "</tr>" <<std::endl; for (auto it : someList) { f << "<tr>" <<std::endl; f << "<td>" << it->getM_Title() << "</td>" << std::endl; f << "<td>" << it->getM_Genre() << "</td>" << std::endl; f << "<td>" << it->getM_Year() << "</td>" << std::endl; f << "<td>" << it->getM_Likes() << "</td>" << std::endl; f << "<td>" << it->getM_Trailer()<< "</td>" << std::endl; f << "</tr>" <<std::endl; } f << "</table>" <<std::endl; f << "</body>" <<std::endl; f << "</html>" <<std::endl; } f.close(); } int Repository::findMoviePos(std::string Title) { for (int i = 0; i < m_List.size(); i++) { if ( m_List.at(i)->getM_Title()==Title ) { return i; } } return -1; } //Ditto. int Repository::findWLPos(std::string Title) { for (int i = 0; i < w_List.size(); i++) { if ( w_List.at(i)->getM_Title()==Title ) { return i; } } return -1; } std::vector<std::shared_ptr<Movie>> Repository::getMovie(std::string Genre) { if(Genre!="") for (int i = 0; i < m_List.size(); i++) { if (m_List.at(i)->getM_Genre() == Genre) found.push_back(m_List.at(i)); } else for (int i = 0; i < m_List.size(); i++) { found.push_back(m_List.at(i)); } return found; } int Repository::getLikes() { int likesSum=0; for(auto it : w_List) { likesSum+=it->getM_Likes(); } return likesSum; } void Repository::updMovie(std::shared_ptr<Movie> m, int pos) { if(pos<=m_List.size()) m_List.at(pos).swap(m); } void Repository::delMovie(int i) { if(i!=-1) { m_List.erase(m_List.begin() + i); m_List.shrink_to_fit(); } std::cout<<i<<std::endl; //testing purposes } void Repository::delWListMovie(int i) { if(i>-1) { w_List.at(i)->setM_Likes(w_List.at(i)->getM_Likes()-1); //scadem numarul de like-uri w_List.erase(w_List.begin() + i); w_List.shrink_to_fit(); } std::cout<<i<<std::endl; //testing purposes } void Repository::MovieToWL(int pos) { w_List.push_back(m_List[pos]); }
28.213235
92
0.513943
[ "vector" ]
b230c8fd4d0fdfaae4d65dc473dcbdc77a422941
2,039
hpp
C++
include/boost/gil/image_processing/filter.hpp
Sricharan16/gil
fbec8a3aa4b87245f840829cebfe722270e91f6e
[ "BSL-1.0" ]
1
2022-02-15T09:09:08.000Z
2022-02-15T09:09:08.000Z
include/boost/gil/image_processing/filter.hpp
Sricharan16/gil
fbec8a3aa4b87245f840829cebfe722270e91f6e
[ "BSL-1.0" ]
null
null
null
include/boost/gil/image_processing/filter.hpp
Sricharan16/gil
fbec8a3aa4b87245f840829cebfe722270e91f6e
[ "BSL-1.0" ]
null
null
null
// // Copyright 2019 Miral Shah <miralshah2211@gmail.com> // // Use, modification and distribution are subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_GIL_IMAGE_PROCESSING_FILTER_HPP #define BOOST_GIL_IMAGE_PROCESSING_FILTER_HPP #include <cstddef> #include <vector> #include <boost/gil/image.hpp> #include <boost/gil/image_view.hpp> #include <boost/gil/extension/numeric/kernel.hpp> #include <boost/gil/extension/numeric/convolve.hpp> namespace boost { namespace gil { template <typename SrcView, typename DstView> void box_filter( SrcView const& src_view, DstView const& dst_view, std::size_t kernel_size, long int anchor = -1, bool normalize=true, convolve_boundary_option option = convolve_option_extend_zero ) { gil_function_requires<ImageViewConcept<SrcView>>(); gil_function_requires<MutableImageViewConcept<DstView>>(); static_assert(color_spaces_are_compatible < typename color_space_type<SrcView>::type, typename color_space_type<DstView>::type >::value, "Source and destination views must have pixels with the same color space"); std::vector<float> kernel_values; if (normalize) { kernel_values.resize(kernel_size, 1.0f / float(kernel_size)); } else { kernel_values.resize(kernel_size, 1.0f); } if (anchor == -1) anchor = static_cast<int>(kernel_size / 2); kernel_1d<float> kernel(kernel_values.begin(), kernel_size, anchor); convolve_1d<pixel<float, typename SrcView::value_type::layout_t>>(src_view, kernel, dst_view, option); } template <typename SrcView, typename DstView> void blur( SrcView const& src_view, DstView const& dst_view, std::size_t kernel_size, long int anchor = -1, convolve_boundary_option option = convolve_option_extend_zero ) { box_filter(src_view, dst_view, kernel_size, anchor, true, option); } }} //namespace boost::gil #endif // !BOOST_GIL_IMAGE_PROCESSING_FILTER_HPP
31.369231
106
0.745463
[ "vector" ]
b23ab0c174eef35f649250d5fde87007d04d5997
52,790
cxx
C++
src/render.cxx
jtrulson/conquest
3dcb92ad6bf3b6a2eb64e457ce50b63c34110c96
[ "MIT" ]
13
2018-03-28T17:25:40.000Z
2022-03-10T14:13:23.000Z
src/render.cxx
jtrulson/conquest
3dcb92ad6bf3b6a2eb64e457ce50b63c34110c96
[ "MIT" ]
null
null
null
src/render.cxx
jtrulson/conquest
3dcb92ad6bf3b6a2eb64e457ce50b63c34110c96
[ "MIT" ]
1
2020-09-13T05:12:34.000Z
2020-09-13T05:12:34.000Z
// // Author: Jon Trulson <jon@radscan.com> // Copyright (c) 1994-2018 Jon Trulson // // The MIT License // // 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 "c_defs.h" #include "context.h" #include "global.h" #include "color.h" #include "conf.h" #include "cb.h" #include "conqlb.h" #include "conqutil.h" #include "gldisplay.h" #include "node.h" #include "client.h" #include "clientlb.h" #include "record.h" #include "ui.h" #include <GL/glut.h> #include "glmisc.h" #include "glfont.h" #include "render.h" #include "textures.h" #include "anim.h" #include "GL.h" #include "blinker.h" #include "hud.h" /* Cataboligne - 11.20.6 ack alert klaxon with <ESC> */ #include "cqsound.h" #define ALERT_OFF 0 #define ALERT_ON 1 #define ALERT_ACK 2 cqsHandle alertHandle = CQS_INVHANDLE; /* we store geometry here that should only need to be recomputed when the screen is resized, not every single frame :) */ // the number of torp pips we can display. #define NUM_TORP_PIPS 9 static struct { GLfloat x, y; /* stored x/y/w/h of game window */ GLfloat w, h; GLfloat xstatw; /* width of status area */ GLfloat sb_ih; /* statbox item height */ GLRect_t alertb; /* alert border */ GLRect_t head; GLRect_t headl; GLRect_t warp; GLRect_t warpl; GLRect_t sh; GLRect_t dam; GLRect_t fuel; GLRect_t etemp; GLRect_t wtemp; GLRect_t alloc; /* misc info (viewer) */ GLRect_t tow; GLRect_t arm; GLRect_t destruct; GLRect_t pbitem; /* planet/ship we are watching */ GLRect_t rectime; /* msg/prompt lines */ GLRect_t msg1; GLRect_t msg2; GLRect_t msgmsg; /* pulse messages (viewer) */ GLRect_t engfailpulse; /* wep/eng failure pulses */ GLRect_t wepfailpulse; GLRect_t fuelcritpulse; GLRect_t shcritpulse; GLRect_t hullcritpulse; GLRect_t magfac; /* mag factor */ /* iconhud decals */ /* decal1 */ GLRect_t decal1; /* decal 1 location */ GLRect_t d1shg; /* shield gauge */ GLRect_t d1shcharge; /* shield charge status */ GLRect_t d1shn; /* shield value (number) */ GLRect_t d1damg; /* damage */ GLRect_t d1damn; GLRect_t d1icon; /* the ship icon area */ GLRect_t d1icon_fa; /* the ship icon firing angle indicator */ GLRect_t d1icon_tad; /* last target, angle, dist indicator */ GLRect_t d1torps; /* location of the torp pip area */ GLRect_t d1torppips[NUM_TORP_PIPS]; /* the torp pips */ GLRect_t d1phcharge; /* phaser charge status */ GLRect_t d1atarg; /* ship causing alert */ /* decal2 */ GLRect_t decal2; /* decal 2 location */ GLRect_t d2fuelg; /* fuel gauge */ GLRect_t d2fueln; /* fuel value (number) */ GLRect_t d2engtg; /* etemp */ GLRect_t d2engtn; GLRect_t d2weptg; /* wtemp */ GLRect_t d2weptn; GLRect_t d2allocg; /* alloc */ GLRect_t d2allocn; GLRect_t d2killb; /* location of kills box */ } o = {}; /* FIXME - re-generate this... Pass the main rect (decal) as a rect and pass decal1/2 as rects.. ie: pass the proper decal_sz, and the 'hw' decal representation as args instead of 'global' tx,ty,tw,th - make it a friggin rect! */ /* a useful 'mapping' macros for the decals */ #define MAPAREAX(_decalw, _decalh, _rect) \ ( tx + (((_rect)->x / (_decalw) ) * tw) ) #define MAPAREAY(_decalw, _decalh, _rect) \ ( decaly + (((_rect)->y / (_decalh)) * th) ) #define MAPAREAW(_decalw, _decalh, _rect) \ ( (((_rect)->w / (_decalw)) * tw) ) #define MAPAREAH(_decalw, _decalh, _rect) \ ( (((_rect)->h / (_decalh)) * th) ) #define MAPAREA(_decalptr, _taptr, _optr) \ { \ (_optr)->x = MAPAREAX((_decalptr)->w, (_decalptr)->h, (_taptr)); \ (_optr)->y = MAPAREAY((_decalptr)->w, (_decalptr)->h, (_taptr)); \ (_optr)->w = MAPAREAW((_decalptr)->w, (_decalptr)->h, (_taptr)); \ (_optr)->h = MAPAREAH((_decalptr)->w, (_decalptr)->h, (_taptr)); \ } /* update icon hud geometry if stuff changes (resize). */ void updateIconHudGeo(int snum) { /* assumes context is current*/ GLfloat tx, ty, th, tw, decaly; int i; static int steam = -1; static bool firstTime = true; /* these two rects will just be used to store the texture size (in hw pixels) of each of the 2 decal areas (in w and h). */ static GLRect_t decal1_sz, decal2_sz; /* area pointers, decal1 */ static cqiTextureAreaPtr_t d1shg = NULL; /* d1 sh gauge */ static cqiTextureAreaPtr_t d1shchrg = NULL; /* d1 sh charge gauge */ static cqiTextureAreaPtr_t d1shn = NULL; /* d1 sh number */ static cqiTextureAreaPtr_t d1damg = NULL; /* d1 damage gauge */ static cqiTextureAreaPtr_t d1damn = NULL; /* d1 damage number */ static cqiTextureAreaPtr_t d1torps = NULL; /* d1 torp icon area */ static cqiTextureAreaPtr_t d1phaserchrg = NULL; /* d1 phaser charge */ static cqiTextureAreaPtr_t d1icon = NULL; /* d1 ship icon area */ static cqiTextureAreaPtr_t d1icon_fa = NULL; /* d1 ship icon firing ang */ static cqiTextureAreaPtr_t d1icon_tad = NULL; /* d1 ship icon target data */ /* area pointers, decal2 */ static cqiTextureAreaPtr_t d2fuelg = NULL; /* d2 fuel */ static cqiTextureAreaPtr_t d2fueln = NULL; /* d2 number */ static cqiTextureAreaPtr_t d2engtg = NULL; /* d2 engine temp */ static cqiTextureAreaPtr_t d2engtn = NULL; /* d2 engine number */ static cqiTextureAreaPtr_t d2weptg = NULL; /* d2 weapon temp */ static cqiTextureAreaPtr_t d2weptn = NULL; /* d2 weapon number */ static cqiTextureAreaPtr_t d2allocg = NULL; /* d2 alloc */ static cqiTextureAreaPtr_t d2allocn = NULL; /* d2 alloc number */ static cqiTextureAreaPtr_t d2killb = NULL; /* d2 kills box */ /* default texarea if we couldn't find the right one (1 pixel size) */ static cqiTextureAreaRec_t defaultTA = { "NULL", 0.0, 0.0, 1.0, 1.0 }; char buffer[CQI_NAMELEN]; if (cbShips[snum].team != steam || firstTime) { // we switched teams, or this is our first time though here. // reload/remap the decal texareas // The firstTime check here is a little superfluous, but a // static analyzer can't know that a valid team will never be // -1, so... firstTime = false; int ndx; steam = cbShips[snum].team; /* decal 1 */ snprintf(buffer, CQI_NAMELEN, "ship%c-ico-decal1", cbTeams[steam].teamchar); /* get decal1 size */ memset((void*)&decal1_sz, 0, sizeof(GLRect_t)); if ((ndx = findGLTexture(buffer)) >= 0 ) { /* this is the decal's texture size in pixels */ decal1_sz.w = (GLfloat)GLTextures[ndx].w; decal1_sz.h = (GLfloat)GLTextures[ndx].h; } /* look up the texareas, and clamp to the texture size */ d1shg = cqiFindTexArea(buffer, "shieldg", &defaultTA); CLAMPRECT(decal1_sz.w, decal1_sz.h, d1shg); d1shchrg = cqiFindTexArea(buffer, "shchargeg", &defaultTA); CLAMPRECT(decal1_sz.w, decal1_sz.h, d1shchrg); d1shn = cqiFindTexArea(buffer, "shieldn", &defaultTA); CLAMPRECT(decal1_sz.w, decal1_sz.h, d1shn); d1damg = cqiFindTexArea(buffer, "damageg", &defaultTA); CLAMPRECT(decal1_sz.w, decal1_sz.h, d1damg); d1damn = cqiFindTexArea(buffer, "damagen", &defaultTA); CLAMPRECT(decal1_sz.w, decal1_sz.h, d1damn); d1icon = cqiFindTexArea(buffer, "icon", &defaultTA); CLAMPRECT(decal1_sz.w, decal1_sz.h, d1icon); d1icon_fa = cqiFindTexArea(buffer, "icon-fangle", &defaultTA); CLAMPRECT(decal1_sz.w, decal1_sz.h, d1icon_fa); d1icon_tad = cqiFindTexArea(buffer, "icon-tad", &defaultTA); CLAMPRECT(decal1_sz.w, decal1_sz.h, d1icon_tad); d1torps = cqiFindTexArea(buffer, "torps", &defaultTA); CLAMPRECT(decal1_sz.w, decal1_sz.h, d1torps); d1phaserchrg = cqiFindTexArea(buffer, "phaserchrg", &defaultTA); CLAMPRECT(decal1_sz.w, decal1_sz.h, d1phaserchrg); /* decal 2 */ snprintf(buffer, CQI_NAMELEN, "ship%c-ico-decal2", cbTeams[steam].teamchar); /* get decal2 size */ memset((void*)&decal2_sz, 0, sizeof(GLRect_t)); if ((ndx = findGLTexture(buffer)) >= 0 ) { decal2_sz.w = (GLfloat)GLTextures[ndx].w; decal2_sz.h = (GLfloat)GLTextures[ndx].h; } d2fuelg = cqiFindTexArea(buffer, "fuelg", &defaultTA); CLAMPRECT(decal2_sz.w, decal2_sz.h, d2fuelg); d2fueln = cqiFindTexArea(buffer, "fueln", &defaultTA); CLAMPRECT(decal2_sz.w, decal2_sz.h, d2fueln); d2engtg = cqiFindTexArea(buffer, "etempg", &defaultTA); CLAMPRECT(decal2_sz.w, decal2_sz.h, d2engtg); d2engtn = cqiFindTexArea(buffer, "etempn", &defaultTA); CLAMPRECT(decal2_sz.w, decal2_sz.h, d2engtn); d2weptg = cqiFindTexArea(buffer, "wtempg", &defaultTA); CLAMPRECT(decal2_sz.w, decal2_sz.h, d2weptg); d2weptn = cqiFindTexArea(buffer, "wtempn", &defaultTA); CLAMPRECT(decal2_sz.w, decal2_sz.h, d2weptn); d2allocg = cqiFindTexArea(buffer, "allocg", &defaultTA); CLAMPRECT(decal2_sz.w, decal2_sz.h, d2allocg); d2allocn = cqiFindTexArea(buffer, "allocn", &defaultTA); CLAMPRECT(decal2_sz.w, decal2_sz.h, d2allocn); d2killb = cqiFindTexArea(buffer, "killsbox", &defaultTA); CLAMPRECT(decal2_sz.w, decal2_sz.h, d2killb); } o.x = dConf.wX; o.y = dConf.wY; o.w = dConf.wW; o.h = dConf.wH; /* the width of the entire hud info drawing area */ o.xstatw = dConf.vX - (dConf.wBorderW * 2.0); ty = dConf.vY + dConf.vH; /* icon height */ o.sb_ih = (dConf.wH - (dConf.wBorderW * 2.0) - ty) / 4.0; /* alert border */ o.alertb.x = dConf.vX - 3.0; o.alertb.y = dConf.vY - 3.0; o.alertb.w = dConf.vW + (3.0 * 2.0); o.alertb.h = dConf.vH + (3.0 * 2.0); tx = dConf.wBorderW; ty = dConf.wBorderW; /* the real fun begins. */ /* figure out hud dimensions and decal sizes/locations * * we divide the hud area of the screen into 10 parts vertically * 2 parts for warp/head, 4 for decal 1, 4 for decal 2 * * we calculate the pixel positions by dividing the drawing area * into sections, and then refering to offsets in these sections by * a percentage. For example, assuming a region with a length of * 1.0, 0.2 would refer to 20% of of the total size. This is then * used to locate a specific position in the drawing areas, which * will always be correct regardless of the true pixel dimensions * and size of the area. Ie, the calculations are used to compute * 'real' pixel positions based on percentages of total area. Never * use absolute screen pixel x/y positions in computing these * values or scaling/resizing will be broken. * * The decal texture sizes and the texareas specified in their * texture definitions are used to compute the right x/y/w/h values * for items that are going to be mapped into them (like a fuel * gauge). The actual texture pixel values were determined by * loading the tex into gimp, positioning the cursor on the area of * interest, and recording the texture pixel start X, Y, width, and * height of the area of interest (like the fuel gauge in decal2). * These coordinates are specified as 'texareas' in the decal's * texture definition. No more hardcoding! :) */ /* heading tex and label * we divide the section horizontally into 6 parts * the heading icon occupies 2 parts, and the warp 3, then * centered within the 6-part area. */ /* we should probably re-do heading/warp as a single texture (decal0?) with texarea's describing the right location to draw things (like decal1 and 2 are handled). */ o.head.x = tx + 2.0; o.head.y = ty; o.head.w = ((o.xstatw / 6.0) * 2.0); o.head.h = (dConf.vH / 10.0) * 1.5; o.headl.x = o.head.x; o.headl.y = o.head.y + o.head.h; o.headl.w = ((o.xstatw / 6.0) * 1.5); o.headl.h = (o.head.h / 10.0) * 2.0; /* warp tex and label, used for warp backgraound as well */ o.warp.x = (o.xstatw / 6.0) * 3.0; o.warp.y = ty; o.warp.w = (o.xstatw / 6.0) * 3.0; o.warp.h = (dConf.vH / 10.0) * 2.0; o.warpl.x = o.warp.x; o.warpl.y = o.headl.y + (o.headl.h * 0.7); o.warpl.w = ((o.xstatw / 6.0) * 1.5); o.warpl.h = o.headl.h * 0.9; /* pixel height of decal 1 & 2 */ th = (dConf.vH / 10.0) * 4.0; /* pixel width of decal 1 & 2 */ tw = o.xstatw; /* decal 1 */ o.decal1.x = tx; o.decal1.y = ty + ((dConf.vH / 10.0) * 2.0); o.decal1.w = tw; o.decal1.h = (dConf.vH / 10.0) * 4.0; decaly = o.decal1.y; /* save this for mapping macros */ /* shield gauge */ MAPAREA(&decal1_sz, d1shg, &o.d1shg); /* shield number (value) */ MAPAREA(&decal1_sz, d1shn, &o.d1shn); /* shield charge level (this is just a line) */ MAPAREA(&decal1_sz, d1shchrg, &o.d1shcharge); /* damage */ MAPAREA(&decal1_sz, d1damg, &o.d1damg); MAPAREA(&decal1_sz, d1damn, &o.d1damn); /* position the ship icon area within decal 1 */ MAPAREA(&decal1_sz, d1icon, &o.d1icon); /* position the 'firing angle' and 'target, ang, distance' indicators */ MAPAREA(&decal1_sz, d1icon_fa, &o.d1icon_fa); MAPAREA(&decal1_sz, d1icon_tad, &o.d1icon_tad); /* torp pips */ MAPAREA(&decal1_sz, d1torps, &o.d1torps); for (i=0; i < NUM_TORP_PIPS; i++) { o.d1torppips[i].x = o.d1torps.x; o.d1torppips[i].y = o.d1torps.y + (o.d1torps.h / (real)NUM_TORP_PIPS * (real)i); o.d1torppips[i].w = o.d1torps.w; o.d1torppips[i].h = o.d1torps.h / (real)NUM_TORP_PIPS; } /* phaser recharge status */ MAPAREA(&decal1_sz, d1phaserchrg, &o.d1phcharge); /* decal 2 */ o.decal2.x = tx; o.decal2.y = o.decal1.y + o.decal1.h; o.decal2.w = tw; o.decal2.h = (dConf.vH / 10.0) * 4.0; decaly = o.decal2.y; /* save this for mapping */ /* fuel */ MAPAREA(&decal2_sz, d2fuelg, &o.d2fuelg); MAPAREA(&decal2_sz, d2fueln, &o.d2fueln); /* etemp */ MAPAREA(&decal2_sz, d2engtg, &o.d2engtg); MAPAREA(&decal2_sz, d2engtn, &o.d2engtn); /* wtemp */ MAPAREA(&decal2_sz, d2weptg, &o.d2weptg); MAPAREA(&decal2_sz, d2weptn, &o.d2weptn); /* allocations */ MAPAREA(&decal2_sz, d2allocg, &o.d2allocg); MAPAREA(&decal2_sz, d2allocn, &o.d2allocn); /* kills box */ MAPAREA(&decal2_sz, d2killb, &o.d2killb); /* END of the DECALS! */ /* Cat 'gridscale'. Now, magfac. */ o.magfac.x = dConf.vX + ((dConf.vW / 180.0) * 1.0); o.magfac.y = dConf.vY + (dConf.vH - ((dConf.vH / 20.0) * 1.35)); o.magfac.w = (dConf.vW / 12.0) * 1.0; o.magfac.h = (dConf.vH / 38.0) * 1.0; /* For tow, armies, and wep/eng pulses, we divide the viewer into 8 * horizontal, and 20 vertical segments and confine these items to * one of those segments. */ /* tow is located at the bottom left of the viewer area. */ o.tow.x = dConf.vX + ((dConf.vW / 8.0) * 1.0); o.tow.y = dConf.vY + (dConf.vH - ((dConf.vH / 20.0) * 2.0)); o.tow.w = (dConf.vW / 8.0) * 1.0; o.tow.h = (dConf.vH / 20.0) * 1.0; /* armies in lower right of the viewer area */ o.arm.x = dConf.vX + ((dConf.vW / 8.0) * 6.0); o.arm.y = o.tow.y; o.arm.w = o.tow.w; o.arm.h = o.tow.h; /* for the eng/wep/fuel failure/crit 'pulse' messages, lined up on * the left of the viewer next to the item in trouble. */ o.fuelcritpulse.x = dConf.vX + 2.0; o.fuelcritpulse.y = o.d2fueln.y; o.fuelcritpulse.w = dConf.vW; o.fuelcritpulse.h = o.d2fueln.h; o.wepfailpulse.x = dConf.vX + 2.0; o.wepfailpulse.y = o.d2weptn.y; o.wepfailpulse.w = dConf.vW; o.wepfailpulse.h = o.d2weptn.h; o.hullcritpulse.x = dConf.vX + 2.0; o.hullcritpulse.y = o.d1damn.y; o.hullcritpulse.w = dConf.vW; o.hullcritpulse.h = o.d1damn.h; o.shcritpulse.x = dConf.vX + 2.0; o.shcritpulse.y = o.d1shn.y; o.shcritpulse.w = dConf.vW; o.shcritpulse.h = o.d1shn.h; o.engfailpulse.x = dConf.vX + 2.0; o.engfailpulse.y = o.d2engtn.y; o.engfailpulse.w = dConf.vW; o.engfailpulse.h = o.d2engtn.h; /* alert target - bottom of viewer */ o.d1atarg.x = dConf.vX + ((dConf.vW / 8.0) * 1.5); o.d1atarg.y = dConf.vY + (dConf.vH - ((dConf.vH / 20.0) * 1.0)); o.d1atarg.w = ((dConf.vW / 8.0) * 5.0); o.d1atarg.h = (dConf.vH / 20.0) * 1.0; /* destructing message. try to center within viewer. */ o.destruct.x = dConf.vX + ((dConf.vW / 6.0) * 1.0); o.destruct.y = dConf.vY + (dConf.vH / 2.0) - ((dConf.vH / 6.0) / 2.0); o.destruct.w = ((dConf.vW / 6.0) * 4.0); o.destruct.h = (dConf.vH / 6.0); /* playback item (ship/planet, name, team, etc) */ tx = dConf.vX; ty = dConf.vY + dConf.vH; o.pbitem.x = tx; o.pbitem.y = ty + (o.sb_ih * 0.2); o.pbitem.w = ((dConf.vX + dConf.vW) - tx); o.pbitem.h = (o.sb_ih * 0.7); /* rectime or stats info */ tx = dConf.wBorderW; o.rectime.x = tx; o.rectime.y = (ty + (o.sb_ih * 0.2)); o.rectime.w = o.xstatw; o.rectime.h = (o.sb_ih * 0.7); /* the 3 prompt/msg lines */ o.msg1.x = tx; o.msg1.y = ty + (o.sb_ih * 1.0); o.msg1.w = (dConf.wW - (dConf.wBorderW * 2.0)); o.msg1.h = o.sb_ih; o.msg2.x = tx; o.msg2.y = ty + (o.sb_ih * 2.0); o.msg2.w = (dConf.wW - (dConf.wBorderW * 2.0)); o.msg2.h = o.sb_ih; o.msgmsg.x = tx; o.msgmsg.y = ty + (o.sb_ih * 3.0); o.msgmsg.w = (dConf.wW - (dConf.wBorderW * 2.0)); o.msgmsg.h = o.sb_ih; return; } static void renderScale(GLfloat x, GLfloat y, GLfloat w, GLfloat h, int min, int max, int val, int scalecolor) { val = CLAMP(min, max, val); uiPutColor(scalecolor); /* gauge */ drawQuad(x, y, w * (GLfloat)((GLfloat)val / ((GLfloat)max - (GLfloat)min)), h, 0.0); return; } /* like renderScale, but more specific */ static void renderAlloc(GLfloat x, GLfloat y, GLfloat w, GLfloat h, struct _alloc *a) { int walloc = 0; /* bg */ if (a->ealloc > 0) uiPutColor(BlueColor); else uiPutColor(RedLevelColor); drawQuad(x, y, w, h, 0.0); /* fg */ if (!a->ealloc) walloc = a->walloc; /* e overload */ else walloc = 100 - a->ealloc; if (a->walloc > 0) uiPutColor(NoColor); else uiPutColor(RedLevelColor); drawQuad(x, y, w * (GLfloat)((GLfloat)walloc / 100.0), h, 0.0); return; } /* draw overload/critical messages using a 'pulse' effect in the viewer. Use a slower pulse for 'critical' levels, except for hull critical. */ static void renderPulseMsgs(void) { static animStateRec_t engfail = {}; /* animdef states */ static animStateRec_t wepfail = {}; static animStateRec_t wepcrit = {}; static animStateRec_t engcrit = {}; static animStateRec_t fuelcrit = {}; static animStateRec_t shcrit = {}; static animStateRec_t hullcrit = {}; static bool firsttime = true; static const bool testlamps = false; // set to non-zero to see // them all at once (for // testing) scrNode_t *curnode = getTopNode(); int drawing = false; if (firsttime) { if (!curnode->animVec) return; /* maybe we'll get one next time */ firsttime = false; /* init the anims */ if (animInitState("overload-pulse", &engfail, NULL)) { curnode->animVec->push_back(&engfail); } if (animInitState("overload-pulse", &wepfail, NULL)) { curnode->animVec->push_back(&wepfail); } if (animInitState("critical-pulse", &engcrit, NULL)) { curnode->animVec->push_back(&engcrit); } if (animInitState("critical-pulse", &wepcrit, NULL)) { curnode->animVec->push_back(&wepcrit); } if (animInitState("overload-pulse", &fuelcrit, NULL)) { curnode->animVec->push_back(&fuelcrit); } if (animInitState("overload-pulse", &shcrit, NULL)) { curnode->animVec->push_back(&shcrit); } if (animInitState("overload-pulse", &hullcrit, NULL)) { curnode->animVec->push_back(&hullcrit); } } if (testlamps || hudData.alloc.ealloc <= 0 || hudData.alloc.walloc <= 0 || hudData.etemp.temp > HUD_E_CRIT || hudData.wtemp.temp > HUD_W_CRIT || hudData.fuel.fuel < HUD_F_CRIT || (hudData.sh.shields <= HUD_SH_CRIT && SSHUP(Context.snum) && !SREPAIR(Context.snum)) || hudData.dam.damage >= HUD_HULL_CRIT) drawing = true; if (!drawing) return; glBlendFunc(GL_SRC_ALPHA, GL_ONE); glEnable(GL_BLEND); if (testlamps || hudData.fuel.fuel < HUD_F_CRIT) { if (ANIM_EXPIRED(&fuelcrit)) { animResetState(&fuelcrit, frameTime); curnode->animVec->push_back(&fuelcrit); } glfRenderFont(o.fuelcritpulse.x, o.fuelcritpulse.y, 0.0, o.fuelcritpulse.w, o.fuelcritpulse.h, glfFontLarge, "Fuel Critical", 0, &fuelcrit.state.col, GLF_FONT_F_ORTHO); } if (hudData.alloc.ealloc <= 0) { if (ANIM_EXPIRED(&engfail)) { animResetState(&engfail, frameTime); curnode->animVec->push_back(&engfail); } glfRenderFont(o.engfailpulse.x, o.engfailpulse.y, 0.0, o.engfailpulse.w, o.engfailpulse.h, glfFontLarge, "Engines Overloaded", 0, &engfail.state.col, GLF_FONT_F_ORTHO); } else if (testlamps || hudData.etemp.temp > HUD_E_CRIT) { if (ANIM_EXPIRED(&engcrit)) { animResetState(&engcrit, frameTime); curnode->animVec->push_back(&engcrit); } glfRenderFont(o.engfailpulse.x, o.engfailpulse.y, 0.0, o.engfailpulse.w, o.engfailpulse.h, glfFontLarge, "Engines Critical", 0, &engcrit.state.col, GLF_FONT_F_ORTHO); } if (testlamps ||hudData.alloc.walloc <= 0) { if (ANIM_EXPIRED(&wepfail)) { animResetState(&wepfail, frameTime); curnode->animVec->push_back(&wepfail); } glfRenderFont(o.wepfailpulse.x, o.wepfailpulse.y, 0.0, o.wepfailpulse.w, o.wepfailpulse.h, glfFontLarge, "Weapons Overloaded", 0, &wepfail.state.col, GLF_FONT_F_ORTHO); } else if (hudData.wtemp.temp > HUD_W_CRIT) { if (ANIM_EXPIRED(&wepcrit)) { animResetState(&wepcrit, frameTime); curnode->animVec->push_back(&wepcrit); } glfRenderFont(o.wepfailpulse.x, o.wepfailpulse.y, 0.0, o.wepfailpulse.w, o.wepfailpulse.h, glfFontLarge, "Weapons Critical", 0, &wepcrit.state.col, GLF_FONT_F_ORTHO); } if (testlamps || (hudData.sh.shields < HUD_SH_CRIT && SSHUP(Context.snum) && !SREPAIR(Context.snum))) { if (ANIM_EXPIRED(&shcrit)) { animResetState(&shcrit, frameTime); curnode->animVec->push_back(&shcrit); } glfRenderFont(o.shcritpulse.x, o.shcritpulse.y, 0.0, o.shcritpulse.w, o.shcritpulse.h, glfFontLarge, "Shields Critical", 0, &shcrit.state.col, GLF_FONT_F_ORTHO); } if (testlamps || hudData.dam.damage >= HUD_HULL_CRIT) { if (ANIM_EXPIRED(&hullcrit)) { animResetState(&hullcrit, frameTime); curnode->animVec->push_back(&hullcrit); } glfRenderFont(o.hullcritpulse.x, o.hullcritpulse.y, 0.0, o.hullcritpulse.w, o.hullcritpulse.h, glfFontLarge, "Hull Critical", 0, &hullcrit.state.col, GLF_FONT_F_ORTHO); } glDisable(GL_BLEND); return; } /* render the shield's current strength when down */ static void renderShieldCharge(void) { real val; val = CLAMP(0.0, 100.0, cbShips[Context.snum].shields); if (!val) return; uiPutColor(hudData.sh.color); /* gauge */ drawLine(o.d1shcharge.x, o.d1shcharge.y, o.d1shcharge.w * (GLfloat)((GLfloat)val / 100.0), o.d1shcharge.h); return; } /* This is Cat's icon hud */ void renderHud(bool dostats) { /* assumes context is current*/ const int bufSize = 128; // make the same as the size of sbuf, // ibuf, and fbuf. static char sbuf[128]; static char ibuf[128]; /* fps, stats, etc */ static char fbuf[128]; int FPS = (int)getFPS(); cqColor icl; real warp = cbShips[Context.snum].warp; real maxwarp = cbShipTypes[cbShips[Context.snum].shiptype].warpMax; int steam = cbShips[Context.snum].team; int stype = cbShips[Context.snum].shiptype; int snum = Context.snum; static int oldteam = -1; static int rxtime = 0; static int oldrx = 0; static int rxdiff = 0; int i; static int ack_alert = 0; static struct { real oldFPS; uint32_t oldPingAvg; real oldRxdiff; } oldData = {}; int magFac; extern int ncpLRMagFactor; /* from nCP */ extern int ncpSRMagFactor; if (!GLTextures.size()) return; /* don't render until we actually can */ if ((frameTime - rxtime) > 1000) { rxdiff = pktStats.rxBytes - oldrx; oldrx = pktStats.rxBytes; rxtime = frameTime; } /* update stats data, if needed */ if (FPS != oldData.oldFPS || pktStats.pingAvg != oldData.oldPingAvg || rxdiff != oldData.oldRxdiff) { oldData.oldFPS = FPS; oldData.oldPingAvg = pktStats.pingAvg; oldData.oldRxdiff = rxdiff; snprintf(fbuf, bufSize, "FPS: %03d", FPS); snprintf(ibuf, bufSize, "%4dms %3.1fKB/s %s", pktStats.pingAvg, ((float)rxdiff / 1000.0), fbuf); } if (o.x != dConf.wX || o.y != dConf.wY || o.w != dConf.wW || o.h != dConf.wH || oldteam != steam) { updateIconHudGeo(snum); oldteam = steam; } /* draw alert border */ drawLineBox(o.alertb.x, o.alertb.y, 0.0, o.alertb.w, o.alertb.h, hudData.aStat.color, 2.0); /* The Icon Hud (TM) in all it's glory... */ /* heading val */ glfRenderFont(o.headl.x, o.headl.y, 0.0, o.headl.w, o.headl.h, glfFontLarge, hudData.heading.str.c_str(), hudData.heading.color, NULL, GLF_FONT_F_SCALEX | GLF_FONT_F_ORTHO); /* warp background */ /* kindof sucky to do this here, but since we are drawing a quad sandwiched between two textures... */ glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); drawIconHUDDecal(o.warp.x, o.warp.y, o.warp.w, o.warp.h, TEX_HUD_WARP2, 0xffffffff); glDisable(GL_BLEND); glDisable(GL_TEXTURE_2D); /* warp val */ glfRenderFont(o.warpl.x, o.warpl.y, 0.0, o.warpl.w, o.warpl.h, glfFontLarge, hudData.warp.str.c_str(), hudData.warp.color, NULL, GLF_FONT_F_SCALEX | GLF_FONT_F_ORTHO); /* warp quad indicator color */ glColor4fv(GLTEX_COLOR(GLShips[steam][stype].warpq_col).vec); /* warp indicator quad */ if (warp >= 0.1) drawQuad(o.warp.x, o.warp.y, (o.warp.w * (warp / maxwarp)), o.warp.h * 0.79 /*empirical. ick.*/, 0.0); /* shields gauge */ if (hudData.sh.shields > 0.0) renderScale(o.d1shg.x, o.d1shg.y, o.d1shg.w, o.d1shg.h, 0, 100, hudData.sh.shields, hudData.sh.color); /* shields num */ glfRenderFont(o.d1shn.x, o.d1shn.y, 0.0, o.d1shn.w, o.d1shn.h, glfFontFixed, hudData.sh.str.c_str(), hudData.sh.color, NULL, GLF_FONT_F_SCALEX | GLF_FONT_F_ORTHO); /* shield charging status */ if (!SSHUP(snum) || SREPAIR(snum)) renderShieldCharge(); /* damage gauge */ renderScale(o.d1damg.x, o.d1damg.y, o.d1damg.w, o.d1damg.h, 0, 100, hudData.dam.damage, hudData.dam.color); /* damage num */ glfRenderFont(o.d1damn.x, o.d1damn.y, 0.0, o.d1damn.w, o.d1damn.h, glfFontFixed, hudData.dam.str.c_str(), hudData.dam.color, NULL, GLF_FONT_F_SCALEX | GLF_FONT_F_ORTHO); /* fuel guage */ renderScale(o.d2fuelg.x, o.d2fuelg.y, o.d2fuelg.w, o.d2fuelg.h, 0, 999, hudData.fuel.fuel, hudData.fuel.color); /* fuel value */ glfRenderFont(o.d2fueln.x, o.d2fueln.y, 0.0, o.d2fueln.w, o.d2fueln.h, glfFontFixed, hudData.fuel.str.c_str(), hudData.fuel.color, NULL, GLF_FONT_F_SCALEX | GLF_FONT_F_ORTHO); /* etemp guage */ renderScale(o.d2engtg.x, o.d2engtg.y, o.d2engtg.w, o.d2engtg.h, 0, 100, hudData.etemp.temp, hudData.etemp.color); /* etemp value */ glfRenderFont(o.d2engtn.x, o.d2engtn.y, 0.0, o.d2engtn.w, o.d2engtn.h, glfFontFixed, hudData.etemp.str.c_str(), hudData.etemp.color, NULL, GLF_FONT_F_SCALEX | GLF_FONT_F_ORTHO); /* wtemp gauge */ renderScale(o.d2weptg.x, o.d2weptg.y, o.d2weptg.w, o.d2weptg.h, 0, 100, hudData.wtemp.temp, hudData.wtemp.color); /* wtemp value*/ glfRenderFont(o.d2weptn.x, o.d2weptn.y, 0.0, o.d2weptn.w, o.d2weptn.h, glfFontFixed, hudData.wtemp.str.c_str(), hudData.wtemp.color, NULL, GLF_FONT_F_SCALEX | GLF_FONT_F_ORTHO); /* alloc */ renderAlloc(o.d2allocg.x, o.d2allocg.y, o.d2allocg.w, o.d2allocg.h, &hudData.alloc); /* alloc value */ glfRenderFont(o.d2allocn.x, o.d2allocn.y, 0.0, o.d2allocn.w, o.d2allocn.h, glfFontFixed, hudData.alloc.str.c_str(), hudData.alloc.color, NULL, GLF_FONT_F_SCALEX | GLF_FONT_F_ORTHO); /* BEGIN "stat" box - kills, towing/towed by, x armies, CLOAKED/destruct */ /* kills */ glfRenderFont(o.d2killb.x, o.d2killb.y, 0.0, o.d2killb.w, o.d2killb.h, glfFontFixed, hudData.kills.str.c_str(), hudData.kills.color, NULL, GLF_FONT_F_SCALEX | GLF_FONT_F_ORTHO); magFac = (!SMAP(snum)) ? ncpSRMagFactor : ncpLRMagFactor; /* towed-towing/armies/destruct/alert - blended text displayed in viewer */ if (magFac || hudData.tow.towstat || hudData.armies.armies || hudData.destruct.fuse || hudData.aStat.alertLevel) { /* we want to use blending for these */ glBlendFunc(GL_ONE_MINUS_SRC_ALPHA, GL_ONE); glEnable(GL_BLEND); if (hudData.tow.towstat) glfRenderFont(o.tow.x, o.tow.y, 0.0, o.tow.w, o.tow.h, glfFontFixed, hudData.tow.str.c_str(), hudData.tow.color | 0x50000000, NULL, GLF_FONT_F_ORTHO); /* army count or robot action - we position the robot action * at the same location as the army count... */ if (SROBOT(snum)) glfRenderFont(o.arm.x, o.arm.y, 0.0, o.arm.w, o.arm.h, glfFontFixed, hudData.raction.str.c_str(), hudData.raction.color | 0x50000000, NULL, GLF_FONT_F_SCALEX | GLF_FONT_F_ORTHO); else if (hudData.armies.armies) glfRenderFont(o.arm.x, o.arm.y, 0.0, o.arm.w, o.arm.h, glfFontFixed, hudData.armies.str.c_str(), hudData.armies.color | 0x50000000, NULL, GLF_FONT_F_SCALEX | GLF_FONT_F_ORTHO); /* Destruct msg, centered in the viewer */ if (hudData.destruct.fuse) /* destructing */ { glfRenderFont(o.destruct.x, o.destruct.y, 0.0, o.destruct.w, o.destruct.h, glfFontMsg, hudData.destruct.str.c_str(), (BLINK_ONESEC) ? hudData.destruct.color | CQC_A_BOLD | 0x50000000: (hudData.destruct.color | 0x50000000) & ~CQC_A_BOLD, NULL, GLF_FONT_F_SCALEX | GLF_FONT_F_ORTHO); } /* alert target */ if (hudData.aStat.alertLevel != GREEN_ALERT) { switch(hudData.aStat.alertLevel) /* define alert decal */ { /* need to blink these */ case PHASER_ALERT: /* red alert (not Alert) */ case YELLOW_ALERT: /* yellow alert (not Prox) */ icl = (BLINK_HALFSEC) ? hudData.aStat.color & ~CQC_A_BOLD : hudData.aStat.color | CQC_A_BOLD; break; default: icl = hudData.aStat.color; break; } glfRenderFont(o.d1atarg.x, o.d1atarg.y, 0.0, o.d1atarg.w, o.d1atarg.h, glfFontLarge, hudData.aStat.str.c_str(), icl | 0x50000000, NULL, GLF_FONT_F_SCALEX | GLF_FONT_F_ORTHO); } /* magnification factor */ if (magFac) { if (magFac > 0) sprintf(sbuf, "MAG +%1d", magFac); else sprintf(sbuf, "MAG %1d", magFac); glfRenderFont(o.magfac.x, o.magfac.y, 0.0, o.magfac.w, o.magfac.h, glfFontFixed, sbuf, SpecialColor | 0x50000000, NULL, GLF_FONT_F_SCALEX | GLF_FONT_F_ORTHO); } glDisable(GL_BLEND); } /* Cataboligne - sound code to handle red alert klaxon logic - ack_alert inits 0 when in red range - if handle is INV meaning sound is off - if ack is OFF play snd, set ack ON if ack is ON - klaxon was turned off with ESC - set ack to ACK when out of red range - set ack to OFF stop sound if playing another idea - play sound whenever near a cloaked ship and (CLOAKED) displays if info gotten */ if (hudData.aStat.alertLevel == PHASER_ALERT || hudData.aStat.alertLevel == RED_ALERT) { /* alert condition red - check klaxon state */ if (alertHandle == CQS_INVHANDLE) /* not playing now */ { if (ack_alert == ALERT_OFF) /* was off */ { ack_alert = ALERT_ON; cqsEffectPlay(cqsTeamEffects[steam].alert, &alertHandle, 0.0, 0.0, 0.0); } else if (ack_alert == ALERT_ON) /* was on - turned off */ { ack_alert = ALERT_ACK; /* been ack'ed in nCP.c with <ESC> */ } } } else { /* Cataboligne - idea time out the alert if going beyond the red range? (or just plain stop it here...hmm) */ if (alertHandle != CQS_INVHANDLE) { cqsEffectStop(alertHandle, false); alertHandle = CQS_INVHANDLE; } ack_alert = ALERT_OFF; } /* GL */ glBlendFunc(GL_SRC_ALPHA, GL_ONE); glEnable(GL_BLEND); glEnable(GL_TEXTURE_2D); /* icon shield decal */ if (hudData.sh.shields > 0.0) { if (SCLOAKED(snum)) icl = hudData.sh.color | 0x80000000; /* set some alpha if cloaked */ else icl = hudData.sh.color; drawIconHUDDecal(o.d1icon.x, o.d1icon.y, o.d1icon.w, o.d1icon.h, TEX_HUD_SHI, icl); } /* ship icon decal */ if (SCLOAKED(snum)) icl = hudData.dam.color | 0x80000000; /* set some alpha if cloaked */ else icl = hudData.dam.color; drawIconHUDDecal(o.d1icon.x, o.d1icon.y, o.d1icon.w, o.d1icon.h, TEX_HUD_ICO, icl); icl = 0xFFFFFFFF; /* heading decal */ drawIconHUDDecal(o.head.x, o.head.y, o.head.w, o.head.h, TEX_HUD_HEAD, icl); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); /* draw the heading pointer (dialp) */ /* GL */ glPushMatrix(); glTranslatef(o.head.x + (o.head.w / 2.0), o.head.y + (o.head.h / 2.0), 0.0); glRotatef(cbShips[snum].head, 0.0, 0.0, -1.0); drawIconHUDDecal(-(o.head.w / 2.0), -(o.head.h / 2.0), o.head.w, o.head.h, TEX_HUD_HDP, icl); glPopMatrix(); /* regular conq stuff - tractor beam, armies, cloak */ /* Cataboligne + display critical alerts decals critical levels - display decal shields < 20 eng temp > 80 or overloaded wep temp > 80 or overloaded hull dmg >= 70 */ /* draw warp and decals */ drawIconHUDDecal(o.warp.x, o.warp.y, o.warp.w, o.warp.h, TEX_HUD_WARP, icl); drawIconHUDDecal(o.decal1.x, o.decal1.y, o.decal1.w, o.decal1.h, TEX_HUD_DECAL1, icl); drawIconHUDDecal(o.decal2.x, o.decal2.y, o.decal2.w, o.decal2.h, TEX_HUD_DECAL2, icl); /* ico lamps */ /* shields * during repair, if your shields are up, this will blink green. Just so * you know :) */ icl = 0; if (SSHUP(snum)) { if (hudData.sh.shields <= HUD_SH_CRIT) icl = (BLINK_QTRSEC) ? hudData.sh.color : 0; else icl = hudData.sh.color; } drawIconHUDDecal(o.decal1.x, o.decal1.y, o.decal1.w, o.decal1.h, TEX_HUD_DECAL1_LAMP_SH, icl); /* hull */ icl = 0; if (hudData.dam.damage > HUD_HULL_ALRT) { if (hudData.dam.damage > HUD_HULL_CRIT) icl = (BLINK_QTRSEC) ? hudData.dam.color : 0; else icl = hudData.dam.color; } drawIconHUDDecal(o.decal1.x, o.decal1.y, o.decal1.w, o.decal1.h, TEX_HUD_DECAL1_LAMP_HULL, icl); /* fuel */ icl = 0; if (hudData.fuel.fuel < HUD_F_ALRT) { if (hudData.fuel.fuel < HUD_F_CRIT) icl = (BLINK_QTRSEC) ? hudData.fuel.color : 0; else icl = hudData.fuel.color; } drawIconHUDDecal(o.decal1.x, o.decal1.y, o.decal1.w, o.decal1.h, TEX_HUD_DECAL1_LAMP_FUEL, icl); /* engines */ icl = 0; if (hudData.etemp.overl || hudData.etemp.temp > HUD_E_ALRT) { if (hudData.etemp.overl) icl = (BLINK_QTRSEC) ? hudData.etemp.color : 0; else if (hudData.etemp.temp > HUD_E_CRIT) icl = (BLINK_HALFSEC) ? hudData.etemp.color : 0; else icl = hudData.etemp.color; } drawIconHUDDecal(o.decal1.x, o.decal1.y, o.decal1.w, o.decal1.h, TEX_HUD_DECAL1_LAMP_ENG, icl); /* weapons */ icl = 0; if (hudData.wtemp.overl || hudData.wtemp.temp > HUD_W_ALRT) { if (hudData.wtemp.overl) icl = (BLINK_QTRSEC) ? hudData.wtemp.color : 0; else if (hudData.wtemp.temp > HUD_W_CRIT) icl = (BLINK_HALFSEC) ? hudData.wtemp.color : 0; else icl = hudData.wtemp.color; } drawIconHUDDecal(o.decal1.x, o.decal1.y, o.decal1.w, o.decal1.h, TEX_HUD_DECAL1_LAMP_WEP, icl); /* cloaking */ icl = 0; if (SCLOAKED(snum)) icl = (BLINK_ONESEC) ? MagentaColor : MagentaColor | CQC_A_DIM; drawIconHUDDecal(o.decal1.x, o.decal1.y, o.decal1.w, o.decal1.h, TEX_HUD_DECAL1_LAMP_CLOAK, icl); /* repairing */ icl = 0; if (SREPAIR(snum)) icl = (BLINK_ONESEC) ? CyanColor : CyanColor | CQC_A_DIM; drawIconHUDDecal(o.decal1.x, o.decal1.y, o.decal1.w, o.decal1.h, TEX_HUD_DECAL1_LAMP_REP, icl); /* towing/towedby */ icl = 0; if (hudData.tow.towstat) icl = (BLINK_ONESEC) ? CyanColor : CyanColor | CQC_A_DIM; drawIconHUDDecal(o.decal1.x, o.decal1.y, o.decal1.w, o.decal1.h, TEX_HUD_DECAL1_LAMP_TOW, icl); /* torp pips */ if (snum >= 0 && snum < cbLimits.maxShips()) { glBindTexture(GL_TEXTURE_2D, GLTEX_ID(GLShips[steam][stype].ico_torp)); for (i=0; i < cbLimits.maxTorps(); i++) { switch (cbShips[snum].torps[i].status) { case TS_OFF: uiPutColor(GreenColor); break; case TS_FIREBALL: uiPutColor(RedColor); break; default: uiPutColor(NoColor); break; } // If we ever allow more than 9 torps per ships, then this // logic should be changed to do something sensible. For // now we will only care about the first 9 torps. if (i < NUM_TORP_PIPS) drawTexQuad(o.d1torppips[i].x, o.d1torppips[i].y, 0.0, o.d1torppips[i].w, o.d1torppips[i].h, true, false); } } /* phaser recharge status */ if (snum >= 0 && snum < cbLimits.maxShips()) { GLfloat phasH; /* draw the ship's phaser */ glBindTexture(GL_TEXTURE_2D, GLTEX_ID(GLShips[steam][stype].phas)); glColor4fv(GLTEX_COLOR(GLShips[steam][stype].phas).vec); phasH = (cbShips[snum].pfuse <= 0) ? o.d1phcharge.h : (o.d1phcharge.h - (o.d1phcharge.h / 10.0) * (real)cbShips[snum].pfuse); drawTexQuad(o.d1phcharge.x, o.d1phcharge.y, 0.0, o.d1phcharge.w, phasH, true, true); } /* GL */ glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); /* if phasers are recharging, draw a box around the recharge indicator */ if (snum >= 0 && snum < cbLimits.maxShips()) { if (cbShips[snum].pfuse > 0) drawLineBox(o.d1phcharge.x, o.d1phcharge.y, 0.0, o.d1phcharge.w, o.d1phcharge.h, RedColor, 1.0); } /* END stat box */ /* last firing angle, target angle and distance icon indicators */ /* first update the data if neccessary */ if (snum >= 0) hudSetInfoFiringAngle(cbShips[snum].lastblast); hudSetInfoTargetAngle(Context.lasttang); hudSetInfoTargetDist(Context.lasttdist); if (UserConf.hudInfo) { /* render fa */ glfRenderFont(o.d1icon_fa.x, o.d1icon_fa.y, 0.0, o.d1icon_fa.w, o.d1icon_fa.h, glfFontFixed, hudData.info.lastblaststr.c_str(), NoColor, NULL, GLF_FONT_F_SCALEX | GLF_FONT_F_DOCOLOR | GLF_FONT_F_ORTHO); /* render tad */ if (hudData.info.lasttadstr.size()) glfRenderFont(o.d1icon_tad.x, o.d1icon_tad.y, 0.0, o.d1icon_tad.w, o.d1icon_tad.h, glfFontFixed, hudData.info.lasttadstr.c_str(), NoColor, NULL, GLF_FONT_F_SCALEX | GLF_FONT_F_DOCOLOR | GLF_FONT_F_ORTHO); } if ((Context.recmode != RECMODE_PLAYING) && (Context.recmode != RECMODE_PAUSED)) { if (dostats) { glfRenderFont(o.rectime.x, o.rectime.y, 0.0, o.rectime.w, o.rectime.h, glfFontFixed, ibuf, NoColor | CQC_A_DIM, NULL, GLF_FONT_F_SCALEX | GLF_FONT_F_DOCOLOR | GLF_FONT_F_ORTHO); } } else { /* for playback, the ship/item we are watching */ glfRenderFont(o.pbitem.x, o.pbitem.y, 0.0, o.pbitem.w, o.pbitem.h, glfFontFixed, hudData.recId.str.c_str(), MagentaColor | CQC_A_BOLD, NULL, GLF_FONT_F_SCALEX | GLF_FONT_F_DOCOLOR | GLF_FONT_F_ORTHO); glfRenderFont(o.rectime.x, o.rectime.y, 0.0, o.rectime.w, o.rectime.h, glfFontFixed, hudData.recTime.str.c_str(), NoColor, NULL, GLF_FONT_F_SCALEX | GLF_FONT_F_DOCOLOR | GLF_FONT_F_ORTHO); } /* the 3 prompt/msg lines */ /* MSG_LIN1 */ if (hudData.p1.str.size()) glfRenderFont(o.msg1.x, o.msg1.y, 0.0, o.msg1.w, o.msg1.h, glfFontFixed, hudData.p1.str.c_str(), InfoColor, NULL, GLF_FONT_F_SCALEX | GLF_FONT_F_DOCOLOR | GLF_FONT_F_ORTHO); /* MSG_LIN2 */ if (hudData.p2.str.size()) glfRenderFont(o.msg2.x, o.msg2.y, 0.0, o.msg2.w, o.msg2.h, glfFontFixed, hudData.p2.str.c_str(), InfoColor, NULL, GLF_FONT_F_SCALEX | GLF_FONT_F_DOCOLOR | GLF_FONT_F_ORTHO); /* MSG_MSG */ if (hudData.msg.str.size()) glfRenderFont(o.msgmsg.x, o.msgmsg.y, 0.0, o.msgmsg.w, o.msgmsg.h, glfFontMsg, hudData.msg.str.c_str(), InfoColor, NULL, GLF_FONT_F_SCALEX | GLF_FONT_F_DOCOLOR | GLF_FONT_F_ORTHO); /* critical/overload indicators */ renderPulseMsgs(); return; } void renderViewer(bool dovbg) { /* setup the proper viewport and projection matrix for the viewer */ glViewport(dConf.vX, dConf.vY + (dConf.wH - dConf.vH - (dConf.wBorderW * 2.0)), dConf.vW, dConf.vH); glMatrixMode(GL_PROJECTION); glLoadMatrixf(dConf.viewerProjection); glMatrixMode(GL_MODELVIEW); drawViewerBG(Context.snum, dovbg); // draw the tactical grid if desired (beneath everything else // after the background), but only if the GLShips array has been // initialized (which is when these colors are initialized)... if (UserConf.DoTacBkg && GLShips[0][0].ship) { // draw 10 circles at 1000 CU spaced intervals around your // ship (tactical grid) float alpha = float(UserConf.DoTacShade) / 100.0; glLineWidth(2.0); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); for (int i=1; i<=10; i++) { switch(i) { case 1: // red alert/phaser range, 1000 CU's glColor4f(GLTEX_COLOR(tacRing1K).r, GLTEX_COLOR(tacRing1K).g, GLTEX_COLOR(tacRing1K).b, alpha); break; case 2: // yellow, 2000 CU's glColor4f(GLTEX_COLOR(tacRing2K).r, GLTEX_COLOR(tacRing2K).g, GLTEX_COLOR(tacRing2K).b, alpha); break; case 3: // green, 3000 CU's glColor4f(GLTEX_COLOR(tacRing3K).r, GLTEX_COLOR(tacRing3K).g, GLTEX_COLOR(tacRing3K).b, alpha); break; case 10: // cyan - last ring, 10000 CU's glColor4f(GLTEX_COLOR(tacRing10K).r, GLTEX_COLOR(tacRing10K).g, GLTEX_COLOR(tacRing10K).b, alpha); break; default: // grey for rest, every 1000 CU's afterward up to 10000 glColor4f(GLTEX_COLOR(tacRingXK).r, GLTEX_COLOR(tacRingXK).g, GLTEX_COLOR(tacRingXK).b, alpha); break; } drawCircle(0, 0, cu2GLSize(1000 * i, (SMAP(Context.snum) ? MAP_LR_FAC : MAP_SR_FAC)), 100); } glDisable(GL_BLEND); } // negative energy barrier drawNEB(Context.snum); // the universe display( Context.snum ); #if 0 /* TEST GRID */ { int i; static const int nlines = 10; /* 30 lines, each side of 0 */ GLfloat gx, gy; glColor4f(0.1, 0.1, 0.1, 0.3); for (i = 0; i < nlines; i++) { if (!i) gx = gy = 0.0; else GLcvtcoords(0.0, 0.0, i * 1000.0, i * 1000.0, (SMAP(Context.snum) ? MAP_LR_FAC : MAP_SR_FAC), &gx, &gy); glBegin(GL_LINES); /* x */ glVertex3f(gx, -VIEWANGLE, TRANZ); /* left */ glVertex3f(gx, VIEWANGLE, TRANZ); /* right */ glVertex3f(-gx, -VIEWANGLE, TRANZ); /* left */ glVertex3f(-gx, VIEWANGLE, TRANZ); /* right */ /* y */ glVertex3f(-VIEWANGLE, gy, TRANZ); /* top */ glVertex3f(VIEWANGLE, gy, TRANZ); /* bottom */ glVertex3f(-VIEWANGLE, -gy, TRANZ); /* top */ glVertex3f(VIEWANGLE, -gy, TRANZ); /* bottom */ glEnd(); } } #endif /* reset for everything else */ glViewport(0, 0, dConf.wW, dConf.wH); glMatrixMode(GL_PROJECTION); glLoadMatrixf(dConf.hudProjection); glMatrixMode(GL_MODELVIEW); return; }
32.829602
85
0.547376
[ "geometry", "render" ]
b2428d7a705752b7c168d630701b836dc48cffaa
932
hpp
C++
NDD_VR_Viewer/include/videosynchronizer.hpp
Ezrit/VR_TCMPODS
bc114a4c98bf7af6a348825671fcea49004e22b5
[ "Unlicense" ]
null
null
null
NDD_VR_Viewer/include/videosynchronizer.hpp
Ezrit/VR_TCMPODS
bc114a4c98bf7af6a348825671fcea49004e22b5
[ "Unlicense" ]
null
null
null
NDD_VR_Viewer/include/videosynchronizer.hpp
Ezrit/VR_TCMPODS
bc114a4c98bf7af6a348825671fcea49004e22b5
[ "Unlicense" ]
null
null
null
#ifndef __MSI_VR__VIDEOSYNCHRONIZER_HPP__ #define __MSI_VR__VIDEOSYNCHRONIZER_HPP__ #include <vector> #include <chrono> #include "videotexture.hpp" namespace msi_vr { class VideoSynchronizer { public: bool repeat = true; VideoSynchronizer(); ~VideoSynchronizer(); void start(); void play(); void pause(); void stop(); void seek(std::chrono::nanoseconds time); void update(); int addVideo(VideoTexture* video); void removeVideo(VideoTexture* video); std::vector<VideoTexture*> videos; bool changeBuffer = true; private: GstElement *pipeline=NULL; GMainLoop* loop; // cant have unique_ptr for some reason std::thread videothread; static gboolean bus_callback(GstBus *bus, GstMessage *message, VideoSynchronizer *videosyncer); }; } // namespace msi_vr #endif
21.181818
103
0.636266
[ "vector" ]
b2484a75242d0721c361c9a00b00e7898a4e0238
1,163
cpp
C++
test/container/grid/fill.cpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
test/container/grid/fill.cpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
test/container/grid/fill.cpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2018. // 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 <fcppt/cast/size.hpp> #include <fcppt/cast/to_signed.hpp> #include <fcppt/container/grid/fill.hpp> #include <fcppt/container/grid/object.hpp> #include <fcppt/container/grid/output.hpp> #include <fcppt/container/grid/static_row.hpp> #include <fcppt/config/external_begin.hpp> #include <catch2/catch.hpp> #include <fcppt/config/external_end.hpp> TEST_CASE( "container::grid::fill", "[container],[grid]" ) { typedef fcppt::container::grid::object< int, 2 > int2_grid; int2_grid test( int2_grid::dim( 2u, 2u ), 0 ); typedef int2_grid::pos pos; fcppt::container::grid::fill( test, []( pos const _pos ) { return fcppt::cast::size< int >( fcppt::cast::to_signed( _pos.x() + _pos.y() ) ); } ); CHECK( test == int2_grid{ fcppt::container::grid::static_row( 0, 1 ), fcppt::container::grid::static_row( 1, 2 ) } ); }
15.716216
61
0.625967
[ "object" ]
b24c30a46c34da02779f5beb21e96e605fdc467c
36,530
cpp
C++
src/slam/LinearSolver_CholMod.cpp
meitiever/SLAM-BA
57ee2af8508300e818feb67f7adbe026eee3ada7
[ "MIT" ]
null
null
null
src/slam/LinearSolver_CholMod.cpp
meitiever/SLAM-BA
57ee2af8508300e818feb67f7adbe026eee3ada7
[ "MIT" ]
null
null
null
src/slam/LinearSolver_CholMod.cpp
meitiever/SLAM-BA
57ee2af8508300e818feb67f7adbe026eee3ada7
[ "MIT" ]
null
null
null
/* +-----------------------------------+ | | | *** CHOLMOD linear solver *** | | | | Copyright (c) -tHE SWINe- 2012 | | | | LinearSolver_CholMod.cpp | | | +-----------------------------------+ */ /** * @file src/slam/LinearSolver_CholMod.cpp * @brief linear solver model based on CHOLMOD * @author -tHE SWINe- * @date 2012-09-03 * * @note This is faster than CSparse in x86, but slower in x64 * (possibly due to DLONG; would have to somehow use int). * @note Using __CHOLMOD_SHORT, this is faster in x64 on windows, * but actually slower on linux. Tried using raw arrays * for workspace instead of std::vectors, but still nowhere * near csparse. * */ #include "slam/LinearSolver_CholMod.h" #include "slam/Timer.h" /* * === CLinearSolver_CholMod === */ CLinearSolver_CholMod::CLinearSolver_CholMod() :m_p_lambda(0), m_p_factor(0), m_p_block_structure(0) #ifdef __LINEAR_SOLVER_CHOLMOD_CSPARSE_INPLACE_SOLVE , m_n_workspace_size(0), m_p_workspace_double(0) #endif // __LINEAR_SOLVER_CHOLMOD_CSPARSE_INPLACE_SOLVE { #ifdef __CHOLMOD_x64 cholmod_l_start(&m_t_cholmod_common); #else // __CHOLMOD_x64 cholmod_start(&m_t_cholmod_common); #endif // __CHOLMOD_x64 // initialize cholmod! m_t_cholmod_common.nmethods = 1; m_t_cholmod_common.method[0].ordering = default_ordering_Method; m_t_cholmod_common.method[1].ordering = m_t_cholmod_common.method[0].ordering; m_t_cholmod_common.postorder = 1; //m_t_cholmod_common.postorder = 0; m_t_cholmod_common.supernodal = default_analysis_Type; // setup ordering strategy memset(&m_t_lambda, 0, sizeof(cholmod_sparse)); m_t_lambda.stype = 1; // upper triangular block only (values in lower part are ignore, may ommit their calculation) m_t_lambda.itype = CHOLMOD_INT; m_t_lambda.xtype = CHOLMOD_REAL; m_t_lambda.dtype = CHOLMOD_DOUBLE; m_t_lambda.sorted = 1; m_t_lambda.packed = 1; // sets cholmod structure #ifdef __CHOLMOD_BLOCKY_LINEAR_SOLVER memset(&m_t_block_structure, 0, sizeof(cholmod_sparse)); m_t_block_structure.nz = 0; m_t_block_structure.x = 0; m_t_block_structure.z = 0; m_t_block_structure.stype = 1; m_t_block_structure.xtype = CHOLMOD_PATTERN; m_t_block_structure.itype = CHOLMOD_INT; m_t_block_structure.dtype = CHOLMOD_DOUBLE; m_t_block_structure.sorted = 1; m_t_block_structure.packed = 1; // sets cholmod structure #endif // __CHOLMOD_BLOCKY_LINEAR_SOLVER /*m_f_tosparse_time = 0; m_f_analysis_time = 0; m_f_factor_time = 0; m_f_solve_time = 0;*/ } CLinearSolver_CholMod::CLinearSolver_CholMod(int n_analysis_type /*= default_analysis_Type*/, int n_ordering_method /*= default_ordering_Method*/) :m_p_lambda(0), m_p_factor(0), m_p_block_structure(0) #ifdef __LINEAR_SOLVER_CHOLMOD_CSPARSE_INPLACE_SOLVE , m_n_workspace_size(0), m_p_workspace_double(0) #endif // __LINEAR_SOLVER_CHOLMOD_CSPARSE_INPLACE_SOLVE { #ifdef __CHOLMOD_x64 cholmod_l_start(&m_t_cholmod_common); #else // __CHOLMOD_x64 cholmod_start(&m_t_cholmod_common); #endif // __CHOLMOD_x64 // initialize cholmod! m_t_cholmod_common.nmethods = 1; m_t_cholmod_common.method[0].ordering = n_ordering_method; m_t_cholmod_common.method[1].ordering = m_t_cholmod_common.method[0].ordering; m_t_cholmod_common.postorder = 1; //m_t_cholmod_common.postorder = 0; m_t_cholmod_common.supernodal = n_analysis_type; // setup ordering strategy memset(&m_t_lambda, 0, sizeof(cholmod_sparse)); m_t_lambda.stype = 1; // upper triangular block only (values in lower part are ignore, may ommit their calculation) m_t_lambda.itype = CHOLMOD_INT; m_t_lambda.xtype = CHOLMOD_REAL; m_t_lambda.dtype = CHOLMOD_DOUBLE; m_t_lambda.sorted = 1; m_t_lambda.packed = 1; // sets cholmod structure #ifdef __CHOLMOD_BLOCKY_LINEAR_SOLVER memset(&m_t_block_structure, 0, sizeof(cholmod_sparse)); m_t_block_structure.nz = 0; m_t_block_structure.x = 0; m_t_block_structure.z = 0; m_t_block_structure.stype = 1; m_t_block_structure.xtype = CHOLMOD_PATTERN; m_t_block_structure.itype = CHOLMOD_INT; m_t_block_structure.dtype = CHOLMOD_DOUBLE; m_t_block_structure.sorted = 1; m_t_block_structure.packed = 1; // sets cholmod structure #endif // __CHOLMOD_BLOCKY_LINEAR_SOLVER /*m_f_tosparse_time = 0; m_f_analysis_time = 0; m_f_factor_time = 0; m_f_solve_time = 0;*/ } CLinearSolver_CholMod::CLinearSolver_CholMod(const CLinearSolver_CholMod &r_other) :m_p_lambda(0), m_p_factor(0), m_p_block_structure(0) #ifdef __LINEAR_SOLVER_CHOLMOD_CSPARSE_INPLACE_SOLVE , m_n_workspace_size(0), m_p_workspace_double(0) #endif // __LINEAR_SOLVER_CHOLMOD_CSPARSE_INPLACE_SOLVE { #ifdef __CHOLMOD_x64 cholmod_l_start(&m_t_cholmod_common); #else // __CHOLMOD_x64 cholmod_start(&m_t_cholmod_common); #endif // __CHOLMOD_x64 // initialize cholmod! m_t_cholmod_common.nmethods = 1; m_t_cholmod_common.method[0].ordering = r_other.m_t_cholmod_common.method[0].ordering; m_t_cholmod_common.method[1].ordering = m_t_cholmod_common.method[0].ordering; // backup m_t_cholmod_common.postorder = 1; m_t_cholmod_common.supernodal = m_t_cholmod_common.supernodal; // setup ordering strategy (copy config from r_other) memset(&m_t_lambda, 0, sizeof(cholmod_sparse)); m_t_lambda.stype = 1; // upper triangular block only (values in lower part are ignore, may ommit their calculation) #ifdef __CHOLMOD_x64 m_t_lambda.itype = CHOLMOD_LONG; #else // __CHOLMOD_x64 m_t_lambda.itype = CHOLMOD_INT; #endif // __CHOLMOD_x64 m_t_lambda.xtype = CHOLMOD_REAL; m_t_lambda.dtype = CHOLMOD_DOUBLE; m_t_lambda.sorted = 1; m_t_lambda.packed = 1; // sets cholmod structure #ifdef __CHOLMOD_BLOCKY_LINEAR_SOLVER memset(&m_t_block_structure, 0, sizeof(cholmod_sparse)); m_t_block_structure.nz = 0; m_t_block_structure.x = 0; m_t_block_structure.z = 0; m_t_block_structure.stype = 1; m_t_block_structure.xtype = CHOLMOD_PATTERN; #ifdef __CHOLMOD_x64 m_t_block_structure.itype = CHOLMOD_LONG; #else // __CHOLMOD_x64 m_t_block_structure.itype = CHOLMOD_INT; #endif // __CHOLMOD_x64 m_t_block_structure.dtype = CHOLMOD_DOUBLE; m_t_block_structure.sorted = 1; m_t_block_structure.packed = 1; // sets cholmod structure #endif // __CHOLMOD_BLOCKY_LINEAR_SOLVER /*m_f_tosparse_time = 0; m_f_analysis_time = 0; m_f_factor_time = 0; m_f_solve_time = 0;*/ } void CLinearSolver_CholMod::Free_Memory() { { std::vector<_TyPerm> empty; m_p_scalar_permutation.swap(empty); } { std::vector<_TyPerm> empty; m_p_block_permutation.swap(empty); } #ifdef __CHOLMOD_BLOCKY_LINEAR_SOLVER if(m_p_block_structure) { cs_spfree(m_p_block_structure); m_p_block_structure = 0; } if(m_p_factor) { #ifdef __CHOLMOD_x64 cholmod_l_free_factor(&m_p_factor, &m_t_cholmod_common); // t_odo - dispose of m_p_factor #else // __CHOLMOD_x64 cholmod_free_factor(&m_p_factor, &m_t_cholmod_common); // t_odo - dispose of m_p_factor #endif // __CHOLMOD_x64 m_p_factor = 0; } #ifdef __LINEAR_SOLVER_CHOLMOD_CSPARSE_INPLACE_SOLVE { std::vector<_TyPerm> empty; m_p_inverse_scalar_permutation.swap(empty); } if(m_p_workspace_double) { delete[] m_p_workspace_double; m_p_workspace_double = 0; } m_n_workspace_size = 0; #endif // __LINEAR_SOLVER_CHOLMOD_CSPARSE_INPLACE_SOLVE #endif // __CHOLMOD_BLOCKY_LINEAR_SOLVER if(m_p_lambda) { cs_spfree(m_p_lambda); m_p_lambda = 0; } } CLinearSolver_CholMod::~CLinearSolver_CholMod() { Free_Memory(); // delete all aux matrices and buffers #ifdef __CHOLMOD_x64 cholmod_l_finish(&m_t_cholmod_common); // shutdown cholmod! #else // __CHOLMOD_x64 cholmod_finish(&m_t_cholmod_common); // shutdown cholmod! #endif // __CHOLMOD_x64 /*if(m_f_tosparse_time > 0) { printf("cholmod to-sparse time: %.2f sec\n", m_f_tosparse_time); printf("cholmod analysis time: %.2f sec\n", m_f_analysis_time); printf("cholmod factor time: %.2f sec\n", m_f_factor_time); printf("cholmod solve time: %.2f sec\n", m_f_solve_time); }*/ // dump timing stats } CLinearSolver_CholMod &CLinearSolver_CholMod::operator =(const CLinearSolver_CholMod &r_other) { m_t_cholmod_common.method[0].ordering = r_other.m_t_cholmod_common.method[0].ordering; m_t_cholmod_common.method[1].ordering = m_t_cholmod_common.method[0].ordering; // backup m_t_cholmod_common.supernodal = m_t_cholmod_common.supernodal; // copy settings return *this; } bool CLinearSolver_CholMod::Solve_PosDef(const CUberBlockMatrix &r_lambda, Eigen::VectorXd &r_eta) // throw(std::bad_alloc) { //double f_to_sparse_start = m_timer.f_Time(); _ASSERTE(r_lambda.b_SymmetricLayout()); // pos-def is supposed to be symmetric _ASSERTE(r_eta.rows() == r_lambda.n_Row_Num()); // make sure the vector has correct dimension #ifdef __CHOLMOD_x64_BUT_SHORT if(!(m_p_lambda = r_lambda.p_Convert_to_Sparse32(m_p_lambda))) #else // __CHOLMOD_x64_BUT_SHORT if(!(m_p_lambda = r_lambda.p_Convert_to_Sparse(m_p_lambda))) #endif // __CHOLMOD_x64_BUT_SHORT throw std::bad_alloc(); // convert to csparse matrix m_t_lambda.p = m_p_lambda->p; m_t_lambda.nzmax = m_p_lambda->nzmax; m_t_lambda.nrow = m_p_lambda->m; m_t_lambda.ncol = m_p_lambda->n; m_t_lambda.i = m_p_lambda->i; m_t_lambda.x = m_p_lambda->x; // fills cholsol matrix (just reref arrays) m_t_cholmod_common.nmethods = 1; m_t_cholmod_common.method[0].ordering = m_t_cholmod_common.method[1].ordering; // get from backup m_t_cholmod_common.postorder = 1; // set ordering up (blocky solver rewrites it) //double f_analyze_start = m_timer.f_Time(); cholmod_factor *p_cholmod_factor; #ifdef __CHOLMOD_x64 if(!(p_cholmod_factor = cholmod_l_analyze(&m_t_lambda, &m_t_cholmod_common))) #else // __CHOLMOD_x64 if(!(p_cholmod_factor = cholmod_analyze(&m_t_lambda, &m_t_cholmod_common))) #endif // __CHOLMOD_x64 return false; // symbolic factorization //double f_factorize_start = m_timer.f_Time(); #ifdef __CHOLMOD_x64 cholmod_l_factorize(&m_t_lambda, p_cholmod_factor, &m_t_cholmod_common); #else // __CHOLMOD_x64 cholmod_factorize(&m_t_lambda, p_cholmod_factor, &m_t_cholmod_common); #endif // __CHOLMOD_x64 if(m_t_cholmod_common.status == CHOLMOD_NOT_POSDEF) { #ifdef __CHOLMOD_x64 cholmod_l_free_factor(&p_cholmod_factor, &m_t_cholmod_common); #else // __CHOLMOD_x64 cholmod_free_factor(&p_cholmod_factor, &m_t_cholmod_common); #endif // __CHOLMOD_x64 return false; // not positive definite } // factorize //double f_solve_start = m_timer.f_Time(); cholmod_dense t_b_cholmod; t_b_cholmod.nrow = t_b_cholmod.d = m_t_lambda.nrow; t_b_cholmod.ncol = 1; t_b_cholmod.x = &r_eta(0); t_b_cholmod.xtype = CHOLMOD_REAL; t_b_cholmod.dtype = CHOLMOD_DOUBLE; // set up dense vector with eta for calling cholmod #ifdef __CHOLMOD_x64 cholmod_dense *p_x_cholmod = cholmod_l_solve(CHOLMOD_A, p_cholmod_factor, &t_b_cholmod, &m_t_cholmod_common); #else // __CHOLMOD_x64 cholmod_dense *p_x_cholmod = cholmod_solve(CHOLMOD_A, p_cholmod_factor, &t_b_cholmod, &m_t_cholmod_common); #endif // __CHOLMOD_x64 _ASSERTE(r_eta.rows() == t_b_cholmod.nrow); // it's symmetric, dimension of solution equals dimension of right side // call cholesky memcpy(&r_eta(0), p_x_cholmod->x, sizeof(double) * t_b_cholmod.nrow); // copy back to src array #ifdef __CHOLMOD_x64 cholmod_l_free_dense(&p_x_cholmod, &m_t_cholmod_common); cholmod_l_free_factor(&p_cholmod_factor, &m_t_cholmod_common); #else // __CHOLMOD_x64 cholmod_free_dense(&p_x_cholmod, &m_t_cholmod_common); cholmod_free_factor(&p_cholmod_factor, &m_t_cholmod_common); #endif // __CHOLMOD_x64 // cleanup /*double f_solve_end = m_timer.f_Time(); m_f_tosparse_time += f_analyze_start - f_to_sparse_start; m_f_analysis_time += f_factorize_start - f_analyze_start; m_f_factor_time += f_solve_start - f_factorize_start; m_f_solve_time += f_solve_end - f_solve_start;*/ return true; } #ifdef __CHOLMOD_BLOCKY_LINEAR_SOLVER bool CLinearSolver_CholMod::Factorize_PosDef_Blocky(CUberBlockMatrix &r_factor, const CUberBlockMatrix &r_lambda, std::vector<size_t> &r_workspace, size_t n_dest_row_id /*= 0*/, size_t n_dest_column_id /*= 0*/, bool b_upper_factor /*= true*/) // throw(std::bad_alloc) { /*return CLinearSolver_CSparse().Factorize_PosDef_Blocky(r_factor, r_lambda, r_workspace, n_dest_row_id, n_dest_column_id, b_upper_factor);*/ // debug - reference solution _ASSERTE(r_lambda.b_SymmetricLayout()); // pos-def is supposed to be symmetric #ifdef __CHOLMOD_x64_BUT_SHORT if(!(m_p_lambda = r_lambda.p_Convert_to_Sparse32(m_p_lambda))) #else // __CHOLMOD_x64_BUT_SHORT if(!(m_p_lambda = r_lambda.p_Convert_to_Sparse(m_p_lambda))) #endif // __CHOLMOD_x64_BUT_SHORT throw std::bad_alloc(); // convert to csparse matrix m_t_lambda.p = m_p_lambda->p; m_t_lambda.nzmax = m_p_lambda->nzmax; m_t_lambda.nrow = m_p_lambda->m; m_t_lambda.ncol = m_p_lambda->n; m_t_lambda.i = m_p_lambda->i; m_t_lambda.x = m_p_lambda->x; // fills cholsol matrix (just reref arrays) m_t_cholmod_common.prefer_upper = b_upper_factor; #if 1 m_t_cholmod_common.nmethods = 1; m_t_cholmod_common.method[0].ordering = CHOLMOD_NATURAL; // no ordering m_t_cholmod_common.postorder = 0; // !! // set ordering up (blocky solver rewrites it) cholmod_factor *p_cholmod_factor; #ifdef __CHOLMOD_x64 if(!(p_cholmod_factor = cholmod_l_analyze(&m_t_lambda, &m_t_cholmod_common))) #else // __CHOLMOD_x64 if(!(p_cholmod_factor = cholmod_analyze(&m_t_lambda, &m_t_cholmod_common))) #endif // __CHOLMOD_x64 return false; #else // 1 m_t_cholmod_common.nmethods = 1; m_t_cholmod_common.method[0].ordering = CHOLMOD_GIVEN;//CHOLMOD_NATURAL; // no ordering m_t_cholmod_common.postorder = 0; // set ordering up (blocky solver rewrites it) { const size_t n = r_lambda.n_Column_Num(); if(m_p_scalar_permutation.size() < n) { m_p_scalar_permutation.clear(); m_p_scalar_permutation.resize(std::max(n, 2 * m_p_scalar_permutation.capacity())); } for(size_t i = 0; i < n; ++ i) m_p_scalar_permutation[i] = i; } // make identity permutation cholmod_factor *p_cholmod_factor; #ifdef __CHOLMOD_x64 if(!(p_cholmod_factor = cholmod_l_analyze_p(&m_t_lambda, &m_p_scalar_permutation[0], NULL, 0, &m_t_cholmod_common))) #else // __CHOLMOD_x64 if(!(p_cholmod_factor = cholmod_analyze_p(&m_t_lambda, &m_p_scalar_permutation[0], NULL, 0, &m_t_cholmod_common))) #endif // __CHOLMOD_x64 return false; #endif // 1 // symbolic factorization #ifdef __CHOLMOD_x64 cholmod_l_factorize(&m_t_lambda, p_cholmod_factor, &m_t_cholmod_common); #else // __CHOLMOD_x64 cholmod_factorize(&m_t_lambda, p_cholmod_factor, &m_t_cholmod_common); #endif // __CHOLMOD_x64 if(m_t_cholmod_common.status == CHOLMOD_NOT_POSDEF) { #ifdef __CHOLMOD_x64 cholmod_l_free_factor(&p_cholmod_factor, &m_t_cholmod_common); #else // __CHOLMOD_x64 cholmod_free_factor(&p_cholmod_factor, &m_t_cholmod_common); #endif // __CHOLMOD_x64 return false; // not positive definite } // factorize #ifdef __CHOLMOD_x64 if(!cholmod_l_change_factor(CHOLMOD_REAL, 1, 0/*p_cholmod_factor->is_super*/, 1/*0*/, 1/*p_cholmod_factor->is_monotonic*/, p_cholmod_factor, &m_t_cholmod_common)) #else // __CHOLMOD_x64 if(!cholmod_change_factor(CHOLMOD_REAL, 1, 0/*p_cholmod_factor->is_super*/, 1/*0*/, 1/*p_cholmod_factor->is_monotonic*/, p_cholmod_factor, &m_t_cholmod_common)) #endif // __CHOLMOD_x64 return false; _ASSERTE(p_cholmod_factor->is_ll && !p_cholmod_factor->is_super && p_cholmod_factor->is_monotonic); // makes sure it comes in correct format // convert the factorization to LL, simplical, packed/*or not*/, monotonic cs L; L.nzmax = p_cholmod_factor->nzmax; L.nz = -1; L.p = (csi*)p_cholmod_factor->p; L.i = (csi*)p_cholmod_factor->i; L.x = (double*)p_cholmod_factor->x; L.m = p_cholmod_factor->n; L.n = p_cholmod_factor->n; // get L matrix from the factor #if 0 _ASSERTE(p_cholmod_factor->ordering == CHOLMOD_NATURAL || p_cholmod_factor->ordering == CHOLMOD_GIVEN); cs *p_L; { const cs *A = m_p_lambda; css *S; if(!(S = cs_schol(0, A))) // do use symbolic something! (keeps L sparse) return false; // ordering and symbolic analysis for a Cholesky factorization csn *N; if(!(N = cs_chol(A, S))) {// @todo - use CLinearSolver_CSparse to do that, it caches workspace and stuff ... cs_sfree(S); return false; } p_L = N->L;//cs_symperm(N->L, N->pinv, 1); cs_sfree(S); cs_spfree(N->U); // t_odo - remove if possible cs_free(N->pinv); cs_free(N->B); //cs_free(N->L); // note that the above pointers are most likely null (not used for Cholesky, only by QR or LU) } cs *p_diff = cs_add(p_L, &L, -1, 1); double f_diff = cs_norm(p_diff); if(f_diff > 1e-5) { CDebug::Dump_SparseMatrix("L_csparse.tga", p_L); CDebug::Dump_SparseMatrix("L_cholmod.tga", &L); CDebug::Dump_SparseMatrix("L_diff.tga", p_diff); } cs_spfree(p_L); cs_spfree(p_diff); #endif // 0 // debug code to make sure no ordering is used _ASSERTE(sizeof(_TyCSIntType) == sizeof(_TyPerm)); bool b_result; if(b_upper_factor) { _ASSERTE(L.n >= 0 && L.n <= SIZE_MAX); if(m_p_scalar_permutation.size() < size_t(L.m)) { m_p_scalar_permutation.clear(); m_p_scalar_permutation.resize(std::max(size_t(L.m), 2 * m_p_scalar_permutation.capacity())); } // reuse storage cs *p_transpose = fast_transpose(&L, (_TyCSIntType*)&m_p_scalar_permutation[0]); // this calculates transpose with 32 or 64bit integers, based on target machine and __CHOLMOD_x64_BUT_SHORT #ifdef __CHOLMOD_x64_BUT_SHORT b_result = r_factor.From_Sparse32(n_dest_row_id, n_dest_column_id, p_transpose, false, r_workspace); #else // __CHOLMOD_x64_BUT_SHORT b_result = r_factor.From_Sparse(n_dest_row_id, n_dest_column_id, p_transpose, false, r_workspace); #endif // __CHOLMOD_x64_BUT_SHORT cs_spfree(p_transpose); } else { #ifdef __CHOLMOD_x64_BUT_SHORT b_result = r_factor.From_Sparse32(n_dest_row_id, n_dest_column_id, &L, false, r_workspace); #else // __CHOLMOD_x64_BUT_SHORT b_result = r_factor.From_Sparse(n_dest_row_id, n_dest_column_id, &L, false, r_workspace); #endif // __CHOLMOD_x64_BUT_SHORT } #ifdef __CHOLMOD_x64 cholmod_l_free_factor(&p_cholmod_factor, &m_t_cholmod_common); #else // __CHOLMOD_x64 cholmod_free_factor(&p_cholmod_factor, &m_t_cholmod_common); #endif // __CHOLMOD_x64 // cleanup return b_result; } bool CLinearSolver_CholMod::Factorize_PosDef_Blocky_Benchmark(double &r_f_time, CUberBlockMatrix &r_factor, const CUberBlockMatrix &r_lambda, std::vector<size_t> &r_workspace, size_t n_dest_row_id /*= 0*/, size_t n_dest_column_id /*= 0*/, bool b_upper_factor /*= true*/) // throw(std::bad_alloc) { /*return CLinearSolver_CSparse().Factorize_PosDef_Blocky(r_factor, r_lambda, r_workspace, n_dest_row_id, n_dest_column_id, b_upper_factor);*/ // debug - reference solution CDeltaTimer dt; _ASSERTE(r_lambda.b_SymmetricLayout()); // pos-def is supposed to be symmetric #ifdef __CHOLMOD_x64_BUT_SHORT if(!(m_p_lambda = r_lambda.p_Convert_to_Sparse32(m_p_lambda))) #else // __CHOLMOD_x64_BUT_SHORT if(!(m_p_lambda = r_lambda.p_Convert_to_Sparse(m_p_lambda))) #endif // __CHOLMOD_x64_BUT_SHORT throw std::bad_alloc(); // convert to csparse matrix m_t_lambda.p = m_p_lambda->p; m_t_lambda.nzmax = m_p_lambda->nzmax; m_t_lambda.nrow = m_p_lambda->m; m_t_lambda.ncol = m_p_lambda->n; m_t_lambda.i = m_p_lambda->i; m_t_lambda.x = m_p_lambda->x; // fills cholsol matrix (just reref arrays) dt.Reset(); // reset the timer m_t_cholmod_common.prefer_upper = b_upper_factor; #if 1 m_t_cholmod_common.nmethods = 1; m_t_cholmod_common.method[0].ordering = CHOLMOD_NATURAL; // no ordering m_t_cholmod_common.postorder = 0; // !! // set ordering up (blocky solver rewrites it) cholmod_factor *p_cholmod_factor; #ifdef __CHOLMOD_x64 if(!(p_cholmod_factor = cholmod_l_analyze(&m_t_lambda, &m_t_cholmod_common))) #else // __CHOLMOD_x64 if(!(p_cholmod_factor = cholmod_analyze(&m_t_lambda, &m_t_cholmod_common))) #endif // __CHOLMOD_x64 return false; #else // 1 m_t_cholmod_common.nmethods = 1; m_t_cholmod_common.method[0].ordering = CHOLMOD_GIVEN;//CHOLMOD_NATURAL; // no ordering m_t_cholmod_common.postorder = 0; // set ordering up (blocky solver rewrites it) { const size_t n = r_lambda.n_Column_Num(); if(m_p_scalar_permutation.size() < n) { m_p_scalar_permutation.clear(); m_p_scalar_permutation.resize(std::max(n, 2 * m_p_scalar_permutation.capacity())); } for(size_t i = 0; i < n; ++ i) m_p_scalar_permutation[i] = i; } // make identity permutation cholmod_factor *p_cholmod_factor; #ifdef __CHOLMOD_x64 if(!(p_cholmod_factor = cholmod_l_analyze_p(&m_t_lambda, &m_p_scalar_permutation[0], NULL, 0, &m_t_cholmod_common))) #else // __CHOLMOD_x64 if(!(p_cholmod_factor = cholmod_analyze_p(&m_t_lambda, &m_p_scalar_permutation[0], NULL, 0, &m_t_cholmod_common))) #endif // __CHOLMOD_x64 return false; #endif // 1 // symbolic factorization #ifdef __CHOLMOD_x64 cholmod_l_factorize(&m_t_lambda, p_cholmod_factor, &m_t_cholmod_common); #else // __CHOLMOD_x64 cholmod_factorize(&m_t_lambda, p_cholmod_factor, &m_t_cholmod_common); #endif // __CHOLMOD_x64 if(m_t_cholmod_common.status == CHOLMOD_NOT_POSDEF) { #ifdef __CHOLMOD_x64 cholmod_l_free_factor(&p_cholmod_factor, &m_t_cholmod_common); #else // __CHOLMOD_x64 cholmod_free_factor(&p_cholmod_factor, &m_t_cholmod_common); #endif // __CHOLMOD_x64 return false; // not positive definite } // factorize #ifdef __CHOLMOD_x64 if(!cholmod_l_change_factor(CHOLMOD_REAL, 1, 0/*p_cholmod_factor->is_super*/, 1/*0*/, 1/*p_cholmod_factor->is_monotonic*/, p_cholmod_factor, &m_t_cholmod_common)) #else // __CHOLMOD_x64 if(!cholmod_change_factor(CHOLMOD_REAL, 1, 0/*p_cholmod_factor->is_super*/, 1/*0*/, 1/*p_cholmod_factor->is_monotonic*/, p_cholmod_factor, &m_t_cholmod_common)) #endif // __CHOLMOD_x64 return false; _ASSERTE(p_cholmod_factor->is_ll && !p_cholmod_factor->is_super && p_cholmod_factor->is_monotonic); // makes sure it comes in correct format // convert the factorization to LL, simplical, packed/*or not*/, monotonic cs L; L.nzmax = p_cholmod_factor->nzmax; L.nz = -1; L.p = (csi*)p_cholmod_factor->p; L.i = (csi*)p_cholmod_factor->i; L.x = (double*)p_cholmod_factor->x; L.m = p_cholmod_factor->n; L.n = p_cholmod_factor->n; // get L matrix from the factor r_f_time = dt.f_Time(); // sample the timer #if 0 _ASSERTE(p_cholmod_factor->ordering == CHOLMOD_NATURAL || p_cholmod_factor->ordering == CHOLMOD_GIVEN); cs *p_L; { const cs *A = m_p_lambda; css *S; if(!(S = cs_schol(0, A))) // do use symbolic something! (keeps L sparse) return false; // ordering and symbolic analysis for a Cholesky factorization csn *N; if(!(N = cs_chol(A, S))) {// @todo - use CLinearSolver_CSparse to do that, it caches workspace and stuff ... cs_sfree(S); return false; } p_L = N->L;//cs_symperm(N->L, N->pinv, 1); cs_sfree(S); cs_spfree(N->U); // t_odo - remove if possible cs_free(N->pinv); cs_free(N->B); //cs_free(N->L); // note that the above pointers are most likely null (not used for Cholesky, only by QR or LU) } cs *p_diff = cs_add(p_L, &L, -1, 1); double f_diff = cs_norm(p_diff); if(f_diff > 1e-5) { CDebug::Dump_SparseMatrix("L_csparse.tga", p_L); CDebug::Dump_SparseMatrix("L_cholmod.tga", &L); CDebug::Dump_SparseMatrix("L_diff.tga", p_diff); } cs_spfree(p_L); cs_spfree(p_diff); #endif // 0 // debug code to make sure no ordering is used _ASSERTE(sizeof(_TyCSIntType) == sizeof(_TyPerm)); bool b_result; if(b_upper_factor) { _ASSERTE(L.n >= 0 && L.n <= SIZE_MAX); if(m_p_scalar_permutation.size() < size_t(L.m)) { m_p_scalar_permutation.clear(); m_p_scalar_permutation.resize(std::max(size_t(L.m), 2 * m_p_scalar_permutation.capacity())); } // reuse storage cs *p_transpose = fast_transpose(&L, (_TyCSIntType*)&m_p_scalar_permutation[0]); // this calculates transpose with 32 or 64bit integers, based on target machine and __CHOLMOD_x64_BUT_SHORT #ifdef __CHOLMOD_x64_BUT_SHORT b_result = r_factor.From_Sparse32(n_dest_row_id, n_dest_column_id, p_transpose, false, r_workspace); #else // __CHOLMOD_x64_BUT_SHORT b_result = r_factor.From_Sparse(n_dest_row_id, n_dest_column_id, p_transpose, false, r_workspace); #endif // __CHOLMOD_x64_BUT_SHORT cs_spfree(p_transpose); } else { #ifdef __CHOLMOD_x64_BUT_SHORT b_result = r_factor.From_Sparse32(n_dest_row_id, n_dest_column_id, &L, false, r_workspace); #else // __CHOLMOD_x64_BUT_SHORT b_result = r_factor.From_Sparse(n_dest_row_id, n_dest_column_id, &L, false, r_workspace); #endif // __CHOLMOD_x64_BUT_SHORT } #ifdef __CHOLMOD_x64 cholmod_l_free_factor(&p_cholmod_factor, &m_t_cholmod_common); #else // __CHOLMOD_x64 cholmod_free_factor(&p_cholmod_factor, &m_t_cholmod_common); #endif // __CHOLMOD_x64 // cleanup return b_result; } bool CLinearSolver_CholMod::Solve_PosDef_Blocky(const CUberBlockMatrix &r_lambda, Eigen::VectorXd &r_eta) // throw(std::bad_alloc) { //double f_to_sparse_start = m_timer.f_Time(), f_to_sparse_end; _ASSERTE(r_lambda.b_SymmetricLayout()); // pos-def is supposed to be symmetric _ASSERTE(r_eta.rows() == r_lambda.n_Row_Num()); // make sure the vector has correct dimension if(!m_p_factor) { if(!SymbolicDecomposition_Blocky(r_lambda)) return false; _ASSERTE(m_p_factor); //f_to_sparse_end = f_to_sparse_start; } else { #ifdef __CHOLMOD_x64_BUT_SHORT if(!(m_p_lambda = r_lambda.p_Convert_to_Sparse32(m_p_lambda))) #else // __CHOLMOD_x64_BUT_SHORT if(!(m_p_lambda = r_lambda.p_Convert_to_Sparse(m_p_lambda))) #endif // __CHOLMOD_x64_BUT_SHORT throw std::bad_alloc(); // otherwise it's done in SymbolicDecomposition_Blocky(), can save the conversion here m_t_lambda.p = m_p_lambda->p; m_t_lambda.nzmax = m_p_lambda->nzmax; m_t_lambda.nrow = m_p_lambda->m; m_t_lambda.ncol = m_p_lambda->n; m_t_lambda.i = m_p_lambda->i; m_t_lambda.x = m_p_lambda->x; // fills cholsol matrix (just reref arrays) //f_to_sparse_end = m_timer.f_Time(); } #ifdef __CHOLMOD_x64 cholmod_l_factorize(&m_t_lambda, m_p_factor, &m_t_cholmod_common); #else // __CHOLMOD_x64 cholmod_factorize(&m_t_lambda, m_p_factor, &m_t_cholmod_common); #endif // __CHOLMOD_x64 if(m_t_cholmod_common.status == CHOLMOD_NOT_POSDEF) return false; // calculate cholesky // t_odo this is only using GPU in special cases (supernodal). investigate. #ifdef __CHOLMOD_x64 if(!cholmod_l_change_factor(CHOLMOD_REAL, 1, 0, 1, 1, m_p_factor, &m_t_cholmod_common)) #else // __CHOLMOD_x64 if(!cholmod_change_factor(CHOLMOD_REAL, 1, 0, 1, 1, m_p_factor, &m_t_cholmod_common)) #endif // __CHOLMOD_x64 return false; _ASSERTE(m_p_factor->is_ll && !m_p_factor->is_super && m_p_factor->is_monotonic); // makes sure it comes in correct format // convert the factorization to LL, simplical, packed, monotonic // @todo see if this is ever called and if it is, see what exactly it does ... //double f_solve_start = m_timer.f_Time(); #ifdef __LINEAR_SOLVER_CHOLMOD_CSPARSE_INPLACE_SOLVE { const _TyPerm *p = (const _TyPerm*)m_p_factor->Perm; if(m_p_inverse_scalar_permutation.size() < m_t_lambda.ncol) { m_p_inverse_scalar_permutation.clear(); // avoids copying the data m_p_inverse_scalar_permutation.resize(m_t_lambda.ncol); } for(size_t i = 0, n = m_t_lambda.ncol; i < n; ++ i, ++ p) m_p_inverse_scalar_permutation[*p] = _TyPerm(i); } // invert the permutation cs L; L.nzmax = m_p_factor->nzmax; L.nz = -1; L.p = (csi*)m_p_factor->p; L.i = (csi*)m_p_factor->i; L.x = (double*)m_p_factor->x; L.m = m_p_factor->n; L.n = m_p_factor->n; // get L matrix from the factor if(m_n_workspace_size < size_t(m_p_lambda->n)) { m_n_workspace_size = std::max(2 * m_n_workspace_size, size_t(2 * m_p_lambda->n)); if(m_p_workspace_double) delete[] m_p_workspace_double; m_p_workspace_double = new double[m_n_workspace_size]; } // get some workspace double *p_b = &r_eta(0), *p_x = m_p_workspace_double; const csi n_col_num = m_p_lambda->n; cs_ipvec(&m_p_inverse_scalar_permutation[0], p_b, p_x, n_col_num); // x = P*b cs_lsolve(&L, p_x); // x = L\x cs_ltsolve(&L, p_x); // x = L'\x cs_pvec(&m_p_inverse_scalar_permutation[0], p_x, p_b, n_col_num); // b = P'*x // don't forget to solve, btw #else // __LINEAR_SOLVER_CHOLMOD_CSPARSE_INPLACE_SOLVE cholmod_dense t_b_cholmod; t_b_cholmod.nrow = t_b_cholmod.d = m_t_lambda.nrow; t_b_cholmod.ncol = 1; t_b_cholmod.x = &r_eta(0); t_b_cholmod.xtype = CHOLMOD_REAL; t_b_cholmod.dtype = CHOLMOD_DOUBLE; // set up dense vector with eta for calling cholmod #ifdef __CHOLMOD_x64 cholmod_dense *p_x_cholmod = cholmod_l_solve(CHOLMOD_A, m_p_factor, &t_b_cholmod, &m_t_cholmod_common); #else // __CHOLMOD_x64 cholmod_dense *p_x_cholmod = cholmod_solve(CHOLMOD_A, m_p_factor, &t_b_cholmod, &m_t_cholmod_common); #endif // __CHOLMOD_x64 _ASSERTE(r_eta.rows() == t_b_cholmod.nrow); // it's symmetric, dimension of solution equals dimension of right side // call cholesky memcpy(&r_eta(0), p_x_cholmod->x, sizeof(double) * t_b_cholmod.nrow); // copy back to src array #ifdef __CHOLMOD_x64 cholmod_l_free_dense(&p_x_cholmod, &m_t_cholmod_common); #else // __CHOLMOD_x64 cholmod_free_dense(&p_x_cholmod, &m_t_cholmod_common); #endif // __CHOLMOD_x64 //cholmod_free_factor(&m_p_factor, &m_t_cholmod_common); // not the factor! will reuse it. // cleanup #endif // __LINEAR_SOLVER_CHOLMOD_CSPARSE_INPLACE_SOLVE /*double f_solve_end = m_timer.f_Time(); m_f_tosparse_time += f_to_sparse_end - f_to_sparse_start; m_f_factor_time += f_solve_start - f_to_sparse_end; m_f_solve_time += f_solve_end - f_solve_start;*/ return true; } bool CLinearSolver_CholMod::SymbolicDecomposition_Blocky(const CUberBlockMatrix &r_lambda) // throw(std::bad_alloc) { //double f_to_sparse_start = m_timer.f_Time(); _ASSERTE(r_lambda.b_SymmetricLayout()); // pos-def is supposed to be symmetric #ifdef __CHOLMOD_x64_BUT_SHORT if(!(m_p_lambda = r_lambda.p_Convert_to_Sparse32(m_p_lambda))) #else // __CHOLMOD_x64_BUT_SHORT if(!(m_p_lambda = r_lambda.p_Convert_to_Sparse(m_p_lambda))) #endif // __CHOLMOD_x64_BUT_SHORT throw std::bad_alloc(); // convert to csparse matrix m_t_lambda.p = m_p_lambda->p; m_t_lambda.nzmax = m_p_lambda->nzmax; m_t_lambda.nrow = m_p_lambda->m; m_t_lambda.ncol = m_p_lambda->n; m_t_lambda.i = m_p_lambda->i; m_t_lambda.x = m_p_lambda->x; // fills cholsol matrix (just reref arrays) #ifdef __CHOLMOD_x64_BUT_SHORT if(!(m_p_block_structure = r_lambda.p_BlockStructure_to_Sparse32(m_p_block_structure))) #else // __CHOLMOD_x64_BUT_SHORT if(!(m_p_block_structure = r_lambda.p_BlockStructure_to_Sparse(m_p_block_structure))) #endif // __CHOLMOD_x64_BUT_SHORT throw std::bad_alloc(); // convert block layout to csparse matrix const size_t n_column_block_num = r_lambda.n_BlockColumn_Num(); if(m_p_block_permutation.size() < n_column_block_num) { m_p_block_permutation.clear(); // avoids copying data if resizing m_p_block_permutation.resize(std::max(n_column_block_num, 2 * m_p_block_permutation.capacity())); } // double space if resizing //double f_analyze_start = m_timer.f_Time(); m_t_block_structure.nzmax = m_p_block_structure->nzmax; m_t_block_structure.nrow = m_t_block_structure.ncol = n_column_block_num; m_t_block_structure.p = m_p_block_structure->p; m_t_block_structure.i = m_p_block_structure->i; #ifdef __CHOLMOD_x64 if(!cholmod_l_amd(&m_t_block_structure, NULL, 0, &m_p_block_permutation[0], &m_t_cholmod_common)) #else // __CHOLMOD_x64 if(!cholmod_amd(&m_t_block_structure, NULL, 0, &m_p_block_permutation[0], &m_t_cholmod_common)) #endif // __CHOLMOD_x64 return false; // prepare AMD call via CHOLMOD const size_t n_column_num = r_lambda.n_Column_Num(); if(m_p_scalar_permutation.size() < n_column_num) { m_p_scalar_permutation.clear(); m_p_scalar_permutation.resize(std::max(n_column_num, 2 * m_p_scalar_permutation.capacity())); } size_t n_scalar_offset = 0; const _TyPerm *p_order_ptr = &m_p_block_permutation[0]; for(size_t i = 0; i < n_column_block_num; ++ i, ++ p_order_ptr) { const size_t n_order = *p_order_ptr; size_t n_block_base = r_lambda.n_BlockColumn_Base(n_order); size_t n_block_width = r_lambda.n_BlockColumn_Column_Num(n_order); for(size_t j = 0; j < n_block_width; ++ j, ++ n_scalar_offset, ++ n_block_base) m_p_scalar_permutation[n_scalar_offset] = _TyPerm(n_block_base); } _ASSERTE(n_scalar_offset == n_column_num); // blow up the permutation to the scalar matrix m_t_cholmod_common.nmethods = 1; m_t_cholmod_common.method[0].ordering = CHOLMOD_GIVEN; m_t_cholmod_common.postorder = 1; #ifdef __CHOLMOD_x64 m_p_factor = cholmod_l_analyze_p(&m_t_lambda, &m_p_scalar_permutation[0], NULL, 0, &m_t_cholmod_common); #else // __CHOLMOD_x64 m_p_factor = cholmod_analyze_p(&m_t_lambda, &m_p_scalar_permutation[0], NULL, 0, &m_t_cholmod_common); #endif // __CHOLMOD_x64 // apply the ordering /*double f_analyze_end = m_timer.f_Time(); m_f_tosparse_time += f_analyze_start - f_to_sparse_start; m_f_analysis_time += f_analyze_end - f_analyze_start;*/ return true; } #endif // __CHOLMOD_BLOCKY_LINEAR_SOLVER #ifdef __CHOLMOD_x64_BUT_SHORT cs *CLinearSolver_CholMod::cs_spalloc32(csi m, csi n, csi nzmax, csi values, csi triplet) { cs *A = (cs*)cs_calloc (1, sizeof (cs)) ; /* allocate the cs struct */ if (!A) return (NULL) ; /* out of memory */ A->m = m ; /* define dimensions and nzmax */ A->n = n ; A->nzmax = nzmax = CS_MAX (nzmax, 1) ; A->nz = triplet ? 0 : -1 ; /* allocate triplet or comp.col */ A->p = (csi*)cs_malloc (triplet ? nzmax : n+1, sizeof (int)) ; A->i = (csi*)cs_malloc (nzmax, sizeof (int)) ; A->x = (double*)(values ? cs_malloc (nzmax, sizeof (double)) : NULL) ; return ((!A->p || !A->i || (values && !A->x)) ? cs_spfree (A) : A) ; } #endif // __CHOLMOD_x64_BUT_SHORT void CLinearSolver_CholMod::fast_cumsum2(_TyCSIntType *p, _TyCSIntType *c, size_t n) { size_t nz = 0; for(_TyCSIntType *e = p + n; p != e; ++ p, ++ c) { _ASSERTE(nz <= CMaxIntValue<_TyCSIntType>::result()); *p = _TyCSIntType(nz); nz += *c; *c = *p; } _ASSERTE(nz <= CMaxIntValue<_TyCSIntType>::result()); *p = _TyCSIntType(nz); } cs *CLinearSolver_CholMod::fast_transpose(const cs *A, _TyCSIntType *p_workspace) { csi m, n; _TyCSIntType *Cp, *Ci, *Ap, *Ai, *w; double *Cx, *Ax; _ASSERTE(CS_CSC(A) && A->x && p_workspace); /* check inputs */ m = A->m; n = A->n; Ap = (_TyCSIntType*)A->p; Ai = (_TyCSIntType*)A->i; Ax = A->x; cs *C; #ifdef __CHOLMOD_x64_BUT_SHORT if(!(C = cs_spalloc32(n, m, Ap[n], 1, 0))) #else // __CHOLMOD_x64_BUT_SHORT if(!(C = cs_spalloc(n, m, Ap[n], 1, 0))) #endif // __CHOLMOD_x64_BUT_SHORT return 0; /* allocate result */ w = p_workspace; memset(w, 0, m * sizeof(_TyCSIntType)); /* get workspace */ Cp = (_TyCSIntType*)C->p; Ci = (_TyCSIntType*)C->i; Cx = C->x; for(_TyCSIntType p = 0; p < Ap[n]; ++ p) ++ w[Ai[p]]; /* row counts */ fast_cumsum2(Cp, w, m); // cant use fast cumsum, need copy of the array /* row pointers */ for(_TyCSIntType j = 0; j < n; ++ j) { for(_TyCSIntType p = Ap[j]; p < Ap[j + 1]; ++ p) { _TyCSIntType q = w[Ai[p]]; ++ w[Ai[p]]; Ci[q] = j; /* place A(i,j) as entry C(j,i) */ Cx[q] = Ax[p]; } } return C; /* success; do not free w, just return C */ } /* * === ~CLinearSolver_CholMod === */
35.813725
164
0.721872
[ "vector", "model" ]
b24f31bcd5ea87bae282eb209d7fe9f4168bda09
3,176
cpp
C++
CH19/HULL/hull.cpp
acastellanos95/AppCompPhys
920a7ba707e92f1ef92fba9d97323863994f0b1a
[ "MIT" ]
null
null
null
CH19/HULL/hull.cpp
acastellanos95/AppCompPhys
920a7ba707e92f1ef92fba9d97323863994f0b1a
[ "MIT" ]
null
null
null
CH19/HULL/hull.cpp
acastellanos95/AppCompPhys
920a7ba707e92f1ef92fba9d97323863994f0b1a
[ "MIT" ]
null
null
null
/* hull.cpp Jarvis March algorithm for the convex hull */ #include <iostream> #include <fstream> #include <cmath> #include <random> #include <vector> using namespace std; class TwoVect { public: double x; double y; TwoVect () { x=0.0; y=0.0; }; TwoVect (double x0, double y0) { x=x0; y=y0; }; void setV(double x0, double y0) { x=x0; y=y0; } double mag() { return sqrt(x*x + y*y); } double operator*(const TwoVect & other); TwoVect operator+(const TwoVect & other); TwoVect operator-(const TwoVect & other); friend std::ostream &operator<<(std::ostream &out, TwoVect v0) { out << v0.x << " " << v0.y; return out; } }; // end of class TwoVect TwoVect TwoVect::operator-(const TwoVect & other) { return TwoVect(x-other.x,y-other.y); } TwoVect TwoVect::operator+(const TwoVect & other) { return TwoVect(x+other.x,y+other.y); } double TwoVect::operator*(const TwoVect & other) { // dot product return x*other.x + y*other.y; } TwoVect operator*(const double & lhs, const TwoVect & rhs) { TwoVect v0 = TwoVect(lhs*rhs.x,lhs*rhs.y); return v0; } TwoVect operator*(const TwoVect & lhs, const double & rhs) { TwoVect v0 = TwoVect(rhs*lhs.x,rhs*lhs.y); return v0; } TwoVect operator/(const TwoVect & lhs, const double & rhs) { TwoVect v0 = TwoVect(lhs.x/rhs,lhs.y/rhs); return v0; } // -------------------------------------------------------------------- typedef int node; typedef int element; TwoVect *rNode = NULL; // vector of node coordinates bool left(node n1, node n2, node n) { // return true if p is left of the line from p1 to p2 if ( (rNode[n].x - rNode[n1].x)*(rNode[n2].y - rNode[n1].y) < (rNode[n].y - rNode[n1].y)*(rNode[n2].x - rNode[n1].x) ) return true; return false; } int main(void) { int seed; node N; ofstream ofs,ofs2; ofs.open("hull.dat"); ofs2.open("hull2.dat"); cout << " input number of nodes, seed " << endl; cin >> N >> seed; mt19937_64 mt(seed); uniform_real_distribution<double> dist(-1.0,1.0); vector<node> nHull; // set up nodes and determine the leftmost point. // probably best track the hull node numbers rather than the coords rNode = new TwoVect[N]; node hullStart; vector<node> hullPoints; double hPt = 1000.0; for (node n=0;n<N;n++) { double x = dist(mt); double y = dist(mt); rNode[n].setV(x,y); ofs << rNode[n] << endl; if (x < hPt) { hPt = x; hullStart = n; } } cout << " leftmost point: " << rNode[hullStart] << " " << hullStart << endl; // Jarvis March node endPoint; node hullPt = hullStart; ofs2 << rNode[hullStart] << endl; node n=0; do { hullPoints.push_back (hullPt); endPoint = 0; for (node m=1;m<N;m++) { if ( (endPoint == hullPt) || left(hullPoints[n],endPoint,m) ) { endPoint = m; } } n++; hullPt = endPoint; ofs2 << rNode[hullPt] << endl; } while (endPoint != hullStart); cout << n << " hull points found " << endl; delete [] rNode; ofs.close(); ofs2.close(); cout << " node coords in hull.dat " << endl; cout << " convex hull coords in hull2.dat " << endl; return 0; }
21.033113
133
0.596662
[ "vector" ]
b2571273881376fd5b96cfa81c7a846096fa2e6f
1,240
cpp
C++
volume_I/acm_1024.cpp
raidenluikang/acm.timus.ru
9b7c99eb03959acff9dd96326eec642a2c31ed04
[ "MIT" ]
null
null
null
volume_I/acm_1024.cpp
raidenluikang/acm.timus.ru
9b7c99eb03959acff9dd96326eec642a2c31ed04
[ "MIT" ]
null
null
null
volume_I/acm_1024.cpp
raidenluikang/acm.timus.ru
9b7c99eb03959acff9dd96326eec642a2c31ed04
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <set> #include <map> #include <stack> #include <utility> #include <functional> #include <algorithm> #include <list> #include <queue> #include <iomanip> #include <cstddef> #include <cstdio> #include <cstdlib> #include <cstring> #include <string> typedef long long i64; typedef unsigned long long u64; typedef std::vector<int> vi; typedef std::pair<int,int> ii; static const std::size_t N = 100005; template< typename T > T gcd(T a, T b){ while(b){ T m = a % b; a = b; b = m; } return a; } int solve() { unsigned p[1024] = {}; unsigned n = 0; std::cin >> n; for(unsigned i = 1; i <= n ; ++i) std::cin >> p[i]; unsigned res = 1; for(unsigned i = 1; i<=n; ++i) { if (p[i] == 0)continue; unsigned rn = 0; unsigned j = i; while(p[j] != 0) { unsigned p_j = p[j]; ++rn; p[j] = 0; j = p_j; } unsigned d = gcd(res, rn); rn /= d; res *= rn; } std::cout << res << '\n'; return 0; } int main() { #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif ::std::ios::sync_with_stdio(false); ::std::cin.tie(0); ::std::cout.tie(0); solve(); return 0; }
19.68254
90
0.566129
[ "vector" ]
b2588d535d7fbac8f2b72e6d88fb21b016510d29
2,764
hpp
C++
src/common/types.hpp
farleyknight/PotatoDB
cf8e39a76caf8a66a0182310509756737c624cfa
[ "MIT" ]
3
2021-06-24T01:05:42.000Z
2021-07-23T07:24:16.000Z
src/common/types.hpp
farleyknight/PotatoDB
cf8e39a76caf8a66a0182310509756737c624cfa
[ "MIT" ]
5
2021-06-25T00:13:51.000Z
2021-07-23T14:26:01.000Z
src/common/types.hpp
farleyknight/PotatoDB
cf8e39a76caf8a66a0182310509756737c624cfa
[ "MIT" ]
null
null
null
#pragma once #include <deque> #include <future> #include <memory> #include <mutex> #include <limits> #include <list> #include <string> #include <map> #include <unordered_map> #include <unordered_set> #include <vector> /************************************************ * Macros ************************************************/ #define UNUSED __attribute__ ((unused)) /************************************************ * Types we will be using w/o the `std::` prefix ************************************************/ using std::int32_t; using std::uint32_t; using timestamp_t = std::uint64_t; using std::fstream; using std::deque; using std::make_optional; using std::make_pair; using std::make_shared; using std::make_tuple; using std::make_unique; using std::max; using std::move; using std::pair; using std::chrono::milliseconds; using std::nullopt; using std::nullptr_t; using std::numeric_limits; using std::pair; using std::shared_ptr; using std::string; using std::stringstream; using std::tuple; using std::unique_ptr; using std::unique_lock; template<typename K, typename V> using map = std::unordered_map<K, V>; template<typename K, typename V> using ordered_map = std::map<K, V>; namespace fs = std::filesystem; // ptr is shorter than unique_ptr template<class T> using ptr = unique_ptr<T>; // sptr is shorter than shared_ptr template<class T> using sptr = shared_ptr<T>; // NOTE: File descriptors are integers and are pointers to // file objects elsewhere in the system. // // No need to know more details than that. They are used // mostly in the server code. using file_desc_t = int; using byte_t = std::uint8_t; using std::mutex; using std::thread; using std::weak_ptr; using std::function; using std::vector; using std::list; using std::future; using std::condition_variable; using std::atomic; using std::optional; using std::unordered_set; using std::deque; /************************************************ * References and Pointers ************************************************/ template<typename T> using Move = T&&; template<class K, class V> using Map = const std::unordered_map<K, V>; template<class K, class V> using MutMap = std::unordered_map<K, V>; // NOTE: SPtr means shared_ptr template<class T> using SPtr = const std::shared_ptr<T>; template<class T> using MutSPtr = std::shared_ptr<T>; using std::list; using std::future; using task = future<void>; using cond_var = condition_variable; template<class T> using ref_wrap = std::reference_wrapper<T>; template<class T> using opt_ref = std::optional<std::reference_wrapper<T>>; template<class T> using option = optional<T>; template<class T> using set = unordered_set<T>; using std::deque;
19.602837
58
0.640738
[ "vector" ]
b263fb30b5853df3744bfeda0b77c726cef36f52
241
inl
C++
include/inline/com.inl
vn-os/Vutils
e8c4cbc9ff5eebc6f3cc0114f5239f23ee696ad9
[ "MIT" ]
15
2018-05-17T12:15:45.000Z
2022-03-18T03:22:42.000Z
include/inline/com.inl
vn-os/Vutils
e8c4cbc9ff5eebc6f3cc0114f5239f23ee696ad9
[ "MIT" ]
null
null
null
include/inline/com.inl
vn-os/Vutils
e8c4cbc9ff5eebc6f3cc0114f5239f23ee696ad9
[ "MIT" ]
14
2018-05-17T12:58:32.000Z
2022-03-18T03:22:46.000Z
/** * @file com.inl * @author Vic P. * @brief Inline for Component Object Model */ #if defined(VU_WMI_ENABLED) struct IWbemLocator; struct IWbemServices; struct IWbemClassObject; struct IEnumWbemClassObject; #endif // VU_WMI_ENABLED
18.538462
44
0.751037
[ "object", "model" ]
b265420a14886318dcc20650f443bc101d7fe7dd
1,275
cc
C++
runtime/vm/instructions.cc
TheRakeshPurohit/sdk
2885ecc42664e4972343addeb73beb892f4737ea
[ "BSD-3-Clause" ]
null
null
null
runtime/vm/instructions.cc
TheRakeshPurohit/sdk
2885ecc42664e4972343addeb73beb892f4737ea
[ "BSD-3-Clause" ]
null
null
null
runtime/vm/instructions.cc
TheRakeshPurohit/sdk
2885ecc42664e4972343addeb73beb892f4737ea
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/instructions.h" #include "vm/object.h" #if defined(DART_PRECOMPILER) #include "vm/compiler/aot/precompiler.h" #endif namespace dart { bool ObjectAtPoolIndex(const Code& code, intptr_t index, Object* obj) { #if defined(DART_PRECOMPILER) if (FLAG_precompiled_mode) { Precompiler* precompiler = Precompiler::Instance(); if (precompiler != nullptr) { compiler::ObjectPoolBuilder* pool = precompiler->global_object_pool_builder(); if (index < pool->CurrentLength()) { compiler::ObjectPoolBuilderEntry& entry = pool->EntryAt(index); if (entry.type() == compiler::ObjectPoolBuilderEntry::kTaggedObject) { *obj = entry.obj_->ptr(); return true; } } } return false; } #endif const ObjectPool& pool = ObjectPool::Handle(code.GetObjectPool()); if (!pool.IsNull() && (index < pool.Length()) && (pool.TypeAt(index) == ObjectPool::EntryType::kTaggedObject)) { *obj = pool.ObjectAt(index); return true; } return false; } } // namespace dart
30.357143
78
0.671373
[ "object" ]
b26788cfe5a04b414da12109f7744872a212157b
828
cc
C++
2nQuatri/InsertionSort/main_insertion.cc
ulidev/UPC2015
8b3b44ce204fcb0faced227d32ba85f882a510d7
[ "MIT" ]
null
null
null
2nQuatri/InsertionSort/main_insertion.cc
ulidev/UPC2015
8b3b44ce204fcb0faced227d32ba85f882a510d7
[ "MIT" ]
null
null
null
2nQuatri/InsertionSort/main_insertion.cc
ulidev/UPC2015
8b3b44ce204fcb0faced227d32ba85f882a510d7
[ "MIT" ]
null
null
null
#import <iostream> #import <vector> using namespace std; void insertion_sort(vector<double>& v) { if (v.size() < 2) return; for (int i = 1; i < v.size(); i++){ int j = i; while (j > 0 && v[j] < v[j-1]){ int aux = v[j]; v[j] = v[j-1]; v[j-1] = aux; j--; } } } // for (int i = 1; i < v.size(); i++){ // int j = i; // double k = v[i]; // while (j > 0 && v[j-1] > k){ // v[j] = v[j-1]; // --j; // } // v[j] = k; // } // } void mostrat_vector(vector<double> v) { for (int i = 0; i < v.size(); i++) { cout<<v[i]<<" "; } cout<<endl; } int main() { int size = 15; vector<double> vector(size); srand (time(NULL)); for(int i = 0; i < size-1; i++) { vector[i] = rand() % size + 1; } insertion_sort(vector); mostrat_vector(vector); }
15.622642
40
0.448068
[ "vector" ]
b267dc5efea58bb1f461c59f91c7b27d1637af3d
4,866
cpp
C++
src/chroma/cpp/Disk.cpp
bensteinert/chromarenderer
d29b1b080e7f7e4e8650eaa74f03752a07afdab8
[ "MIT" ]
null
null
null
src/chroma/cpp/Disk.cpp
bensteinert/chromarenderer
d29b1b080e7f7e4e8650eaa74f03752a07afdab8
[ "MIT" ]
null
null
null
src/chroma/cpp/Disk.cpp
bensteinert/chromarenderer
d29b1b080e7f7e4e8650eaa74f03752a07afdab8
[ "MIT" ]
1
2018-03-06T03:31:08.000Z
2018-03-06T03:31:08.000Z
#include "Defines.h" #include "BoundingBox.h" #include "Disk.h" #include "Chroma.h" #include "Hitpoint.h" Disk::Disk() { } Disk::Disk(const Vector3 &center_in, const Vector3 &normal_in, const float &radius_in, Material *insideMat_in, Material *outsideMat_in) : Primitive(insideMat_in, false, outsideMat_in), center(center_in), normal(normal_in), radius(radius_in), radiusSquared(radius_in * radius_in) { area = getArea(); } Disk::Disk(const Disk &in) : Primitive(in.insideMat, false, in.outsideMat), center(in.center), normal(in.normal), radius(in.radius), radiusSquared(in.radiusSquared) { area = getArea(); } Disk::~Disk() { } void Disk::getBoundingBox(BoundingBox &bb) const { // Monte Carlo approx.... static const int numSamples = 512; Vector3 *samples = 0; bb.infinitify(); //WARNING! usage of globalsampler is not multithread-safe! // TODO: Needed for thin lens camera!!! //getunifdistrSamples(*globalSampler, numSamples, samples); for (int i = 0; i < numSamples; i++) bb.insertVertex(samples[i]); delete[] samples; } float Disk::getArea() const { return PI_f * radius * radius; } float planeRayIntersection(const Ray& ray, const Vector3& normal, const Vector3& center){ //general ray equation placed into plane equation: //0 = (H-P) * n //H = O + t*d //0 = (O+t*d-P)*n float OminusPmultN = (ray.origin - center)*normal; float DmultN = ray.direction*normal; if(DmultN!=0.0f){ //ray and plane are not parallel float t = OminusPmultN/DmultN; return -t; } return 0.0f; } float Disk::intersectRay(const Ray *ray, float &u, float &v) const { const float t = planeRayIntersection(*ray, normal, center); if (t > 0.0f) { Vector3 tmpHit = ray->at(t); float distSq = (tmpHit - center).lengthSquared(); if (distSq < radiusSquared) return t; } return 0.0f; } int Disk::intersectRay(const Ray *ray, Hitpoint &hit) const { const float t = planeRayIntersection(*ray, normal, center); if (t > 0.0f) { Vector3 tmpHit = ray->at(t); float distSq = (tmpHit - center).lengthSquared(); if (distSq < radiusSquared) { hit.hit = true; hit.index = this; hit.dist = t; hit.u = 0.0f; hit.v = 0.0f; hit.p = tmpHit; getNormal(-ray->direction, hit); return 1; } else { return 0; } } return 0; } float Disk::getunifdistrSamples(Sampler &s, const int nrSamples, Vector3 *&samples) const { //write samples to global SamplerArray Vector3 t1, t2; getCoordSystem(normal, t1, t2); samples = new Vector3[nrSamples]; for (int i = 0; i < nrSamples; i++) { Vector3 sample = (s.get_unifdistr_DiskSample() * radius); samples[i] = (sample[0] * t1 + sample[1] * t2 + sample[2] * normal) + center; } return area; } float Disk::getunifdistrSample(Sampler &s, Vector3 &position, Vector3 &n) const { n = normal; return getunifdistrSample(s, position); } Vector3 Disk::getNormal(const Vector3 &pos, const Vector3 &dir) const { return ieeeSignWOif(normal * dir) * normal; } void Disk::getNormal(const Vector3 &dir, Hitpoint &hit) const { // dir is reversed ray direction in general! if (normal * dir > 0.0f) { hit.n = normal; hit.flipped = false; } else { hit.n = -normal; hit.flipped = true; } } void Disk::transform(const Vector3 &translation, const float &scale, const Matrix3x3 &rotation) { center = (rotation * (scale * center)) + translation; normal = rotation * normal; radius = radius * scale; radiusSquared = radius * radius; area = getArea(); } void Disk::out(std::ostream &os) const { os << "c=" << center << " | " << "n=" << normal << " | " << "r=" << radius << std::endl; } void Disk::shift(const Vector3 &v) { center += v; } void Disk::scaleRel(float scale) { center *= scale; radius *= scale; radiusSquared = radius * radius; area = getArea(); } void Disk::scaleAbs(float val) { float scale = val / radius; scaleRel(scale); } void Disk::stopUp() { scaleToRadius(radius / SQRT2); } void Disk::stopDown() { scaleToRadius(radius * SQRT2); } float Disk::getunifdistrSample(Sampler &s, Vector3 &position) const { Vector3 sample = (s.get_unifdistr_DiskSample() * radius); // assert(sample.length()<radius); Vector3 t1, t2; getCoordSystem(normal, t1, t2); position = (sample[0] * t1 + sample[1] * t2 + sample[2] * normal) + center; return area; } void Disk::scaleToRadius(const float rad_in) { radius = rad_in; radiusSquared = rad_in * rad_in; area = getArea(); }
23.852941
111
0.606658
[ "transform" ]
05da5f61aed36d9784c120f81219ac996ddc2eff
6,759
hpp
C++
redfish-core/lib/cable.hpp
cjcain/bmcweb
80badf7ceff486ef2bcb912309563919fc5326ea
[ "Apache-2.0" ]
null
null
null
redfish-core/lib/cable.hpp
cjcain/bmcweb
80badf7ceff486ef2bcb912309563919fc5326ea
[ "Apache-2.0" ]
null
null
null
redfish-core/lib/cable.hpp
cjcain/bmcweb
80badf7ceff486ef2bcb912309563919fc5326ea
[ "Apache-2.0" ]
null
null
null
#pragma once #include <boost/container/flat_map.hpp> #include <utils/json_utils.hpp> namespace redfish { /** * @brief Fill cable specific properties. * @param[in,out] resp HTTP response. * @param[in] ec Error code corresponding to Async method call. * @param[in] properties List of Cable Properties key/value pairs. */ inline void fillCableProperties(crow::Response& resp, const boost::system::error_code ec, const dbus::utility::DBusPropertiesMap& properties) { if (ec) { BMCWEB_LOG_DEBUG << "DBUS response error " << ec; messages::internalError(resp); return; } for (const auto& [propKey, propVariant] : properties) { if (propKey == "CableTypeDescription") { const std::string* cableTypeDescription = std::get_if<std::string>(&propVariant); if (cableTypeDescription == nullptr) { messages::internalError(resp); return; } resp.jsonValue["CableType"] = *cableTypeDescription; } else if (propKey == "Length") { const double* cableLength = std::get_if<double>(&propVariant); if (cableLength == nullptr) { messages::internalError(resp); return; } if (!std::isfinite(*cableLength)) { if (std::isnan(*cableLength)) { continue; } messages::internalError(resp); return; } resp.jsonValue["LengthMeters"] = *cableLength; } } } /** * @brief Api to get Cable properties. * @param[in,out] asyncResp Async HTTP response. * @param[in] cableObjectPath Object path of the Cable. * @param[in] serviceMap A map to hold Service and corresponding * interface list for the given cable id. */ inline void getCableProperties(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, const std::string& cableObjectPath, const dbus::utility::MapperServiceMap& serviceMap) { BMCWEB_LOG_DEBUG << "Get Properties for cable " << cableObjectPath; for (const auto& [service, interfaces] : serviceMap) { for (const auto& interface : interfaces) { if (interface != "xyz.openbmc_project.Inventory.Item.Cable") { continue; } crow::connections::systemBus->async_method_call( [asyncResp]( const boost::system::error_code ec, const dbus::utility::DBusPropertiesMap& properties) { fillCableProperties(asyncResp->res, ec, properties); }, service, cableObjectPath, "org.freedesktop.DBus.Properties", "GetAll", interface); } } } /** * The Cable schema */ inline void requestRoutesCable(App& app) { BMCWEB_ROUTE(app, "/redfish/v1/Cables/<str>/") .privileges(redfish::privileges::getCable) .methods(boost::beast::http::verb::get)( [](const crow::Request&, const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, const std::string& cableId) { BMCWEB_LOG_DEBUG << "Cable Id: " << cableId; auto respHandler = [asyncResp, cableId](const boost::system::error_code ec, const dbus::utility::MapperGetSubTreeResponse& subtree) { if (ec.value() == EBADR) { messages::resourceNotFound( asyncResp->res, "#Cable.v1_0_0.Cable", cableId); return; } if (ec) { BMCWEB_LOG_ERROR << "DBUS response error " << ec; messages::internalError(asyncResp->res); return; } for (const auto& [objectPath, serviceMap] : subtree) { sdbusplus::message::object_path path(objectPath); if (path.filename() != cableId) { continue; } asyncResp->res.jsonValue["@odata.type"] = "#Cable.v1_0_0.Cable"; asyncResp->res.jsonValue["@odata.id"] = "/redfish/v1/Cables/" + cableId; asyncResp->res.jsonValue["Id"] = cableId; asyncResp->res.jsonValue["Name"] = "Cable"; getCableProperties(asyncResp, objectPath, serviceMap); return; } messages::resourceNotFound(asyncResp->res, "Cable", cableId); }; crow::connections::systemBus->async_method_call( respHandler, "xyz.openbmc_project.ObjectMapper", "/xyz/openbmc_project/object_mapper", "xyz.openbmc_project.ObjectMapper", "GetSubTree", "/xyz/openbmc_project/inventory", 0, std::array<const char*, 1>{ "xyz.openbmc_project.Inventory.Item.Cable"}); }); } /** * Collection of Cable resource instances */ inline void requestRoutesCableCollection(App& app) { BMCWEB_ROUTE(app, "/redfish/v1/Cables/") .privileges(redfish::privileges::getCableCollection) .methods(boost::beast::http::verb::get)( [](const crow::Request&, const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { asyncResp->res.jsonValue["@odata.type"] = "#CableCollection.CableCollection"; asyncResp->res.jsonValue["@odata.id"] = "/redfish/v1/Cables"; asyncResp->res.jsonValue["Name"] = "Cable Collection"; asyncResp->res.jsonValue["Description"] = "Collection of Cable Entries"; collection_util::getCollectionMembers( asyncResp, "/redfish/v1/Cables", {"xyz.openbmc_project.Inventory.Item.Cable"}); }); } } // namespace redfish
36.535135
80
0.487942
[ "object" ]
05ddd8f4928772a24ca4e4cdfbb5cda40809b345
15,632
cc
C++
src/nnet3/nnet-cctc-example.cc
roscisz/kaldi-mpi
2176d0810da77defb382fd8da7066ed583b7fe73
[ "Apache-2.0" ]
2
2018-08-09T14:11:48.000Z
2020-04-27T02:46:00.000Z
src/nnet3/nnet-cctc-example.cc
roscisz/kaldi-mpi
2176d0810da77defb382fd8da7066ed583b7fe73
[ "Apache-2.0" ]
null
null
null
src/nnet3/nnet-cctc-example.cc
roscisz/kaldi-mpi
2176d0810da77defb382fd8da7066ed583b7fe73
[ "Apache-2.0" ]
null
null
null
// nnet3/nnet-ctcexample.cc // Copyright 2015 Johns Hopkins University (author: Daniel Povey) // See ../../COPYING for clarification regarding multiple 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include <cmath> #include "nnet3/nnet-cctc-example.h" #include "nnet3/nnet-example-utils.h" namespace kaldi { namespace nnet3 { void NnetCctcSupervision::Write(std::ostream &os, bool binary) const { CheckDim(); WriteToken(os, binary, "<NnetCctcSup>"); WriteToken(os, binary, name); WriteIndexVector(os, binary, indexes); WriteToken(os, binary, "<NumSups>"); int32 size = supervision.size(); KALDI_ASSERT(size > 0 && "Attempting to write empty NnetCctcSupervision."); WriteBasicType(os, binary, size); if (!binary) os << "\n"; for (int32 i = 0; i < size; i++) { supervision[i].Write(os, binary); if (!binary) os << "\n"; } WriteToken(os, binary, "</NnetCctcSup>"); } bool NnetCctcSupervision::operator == (const NnetCctcSupervision &other) const { return name == other.name && indexes == other.indexes && supervision == other.supervision; } void NnetCctcSupervision::Read(std::istream &is, bool binary) { ExpectToken(is, binary, "<NnetCctcSup>"); ReadToken(is, binary, &name); ReadIndexVector(is, binary, &indexes); { // temp. to delete soon. std::string s; ReadToken(is, binary, &s); } // will be replaced with: ExpectToken(is, binary, "<NumSups>"); int32 size; ReadBasicType(is, binary, &size); KALDI_ASSERT(size > 0 && size < 1000000); supervision.resize(size); for (int32 i = 0; i < size; i++) supervision[i].Read(is, binary); ExpectToken(is, binary, "</NnetCctcSup>"); CheckDim(); } void NnetCctcSupervision::ComputeObjfAndDerivs( const ctc::CctcTrainingOptions &opts, const ctc::CctcTransitionModel &cctc_trans_model, const CuMatrix<BaseFloat> &cu_weights, const CuMatrixBase<BaseFloat> &nnet_output, BaseFloat *tot_weight_out, BaseFloat *tot_objf_out, CuMatrixBase<BaseFloat> *nnet_out_deriv) const { static int32 num_warnings = 50; int32 num_output_indexes = cctc_trans_model.NumOutputIndexes(); KALDI_ASSERT(nnet_output.NumCols() == num_output_indexes); int32 cur_offset = 0; const BaseFloat error_logprob_per_frame = -10.0; BaseFloat tot_weight = 0.0, tot_objf = 0.0; std::vector<ctc::CctcSupervision>::const_iterator iter = supervision.begin(), end = supervision.end(); if (nnet_out_deriv) nnet_out_deriv->SetZero(); for (; iter != end; cur_offset += iter->num_frames,++iter) { const ctc::CctcSupervision &supervision = *iter; const CuSubMatrix<BaseFloat> nnet_output_part(nnet_output, cur_offset, supervision.num_frames, 0, num_output_indexes); ctc::CctcComputation computation(opts, cctc_trans_model, cu_weights, supervision, nnet_output_part); tot_weight += supervision.num_frames * supervision.weight; BaseFloat tot_log_prob = computation.Forward(); if (tot_log_prob == tot_log_prob && tot_log_prob - tot_log_prob == 0.0) { tot_objf += supervision.weight * tot_log_prob; } else { // NaN or inf tot_objf += supervision.num_frames * supervision.weight * error_logprob_per_frame; if (num_warnings > 0) { num_warnings--; KALDI_WARN << "Bad forward prob " << tot_log_prob << " encountered in CTC computation"; } continue; // Don't do the backprop. } if (nnet_out_deriv == NULL) continue; // Now do the backward phase, if requested. CuSubMatrix<BaseFloat> out_deriv_part(*nnet_out_deriv, cur_offset, supervision.num_frames, 0, num_output_indexes); if (!computation.Backward(&out_deriv_part)) { nnet_out_deriv->Range(cur_offset, supervision.num_frames, 0, num_output_indexes).SetZero(); if (num_warnings > 0) { num_warnings--; KALDI_WARN << "NaN's or inf's encountered in CTC backprop"; } } } KALDI_ASSERT(cur_offset == nnet_output.NumRows()); *tot_weight_out = tot_weight; *tot_objf_out = tot_objf; } void NnetCctcSupervision::CheckDim() const { int32 num_indexes = indexes.size(), num_indexes_check = 0, label_dim = -1; std::vector<ctc::CctcSupervision>::const_iterator iter = supervision.begin(), end = supervision.end(); for (; iter != end; ++iter) { num_indexes_check += iter->num_frames; if (label_dim == -1) { label_dim = iter->label_dim; } else { KALDI_ASSERT(label_dim == iter->label_dim); } } KALDI_ASSERT(num_indexes == num_indexes_check); } NnetCctcSupervision::NnetCctcSupervision(const NnetCctcSupervision &other): name(other.name), indexes(other.indexes), supervision(other.supervision) { CheckDim(); } void NnetCctcSupervision::Swap(NnetCctcSupervision *other) { name.swap(other->name); indexes.swap(other->indexes); supervision.swap(other->supervision); CheckDim(); } NnetCctcSupervision::NnetCctcSupervision( const ctc::CctcSupervision &ctc_supervision, const std::string &name, int32 first_frame, int32 frame_skip): name(name) { supervision.resize(1); supervision[0] = ctc_supervision; int32 num_frames = ctc_supervision.num_frames; KALDI_ASSERT(num_frames > 0 && frame_skip > 0); indexes.resize(num_frames); // leave n and x in the indexes at zero at this point. for (int32 i = 0; i < num_frames; i++) indexes[i].t = first_frame + i * frame_skip; CheckDim(); } void NnetCctcExample::Write(std::ostream &os, bool binary) const { // Note: weight, label, input_frames and spk_info are members. This is a // struct. WriteToken(os, binary, "<Nnet3CctcEg>"); WriteToken(os, binary, "<NumInputs>"); int32 size = inputs.size(); WriteBasicType(os, binary, size); KALDI_ASSERT(size > 0 && "Attempting to write NnetCctcExample with no inputs"); if (!binary) os << '\n'; for (int32 i = 0; i < size; i++) { inputs[i].Write(os, binary); if (!binary) os << '\n'; } WriteToken(os, binary, "<NumOutputs>"); size = outputs.size(); WriteBasicType(os, binary, size); KALDI_ASSERT(size > 0 && "Attempting to write NnetCctcExample with no outputs"); if (!binary) os << '\n'; for (int32 i = 0; i < size; i++) { outputs[i].Write(os, binary); if (!binary) os << '\n'; } WriteToken(os, binary, "</Nnet3CctcEg>"); } void NnetCctcExample::Read(std::istream &is, bool binary) { ExpectToken(is, binary, "<Nnet3CctcEg>"); ExpectToken(is, binary, "<NumInputs>"); int32 size; ReadBasicType(is, binary, &size); if (size < 1 || size > 1000000) KALDI_ERR << "Invalid size " << size; inputs.resize(size); for (int32 i = 0; i < size; i++) inputs[i].Read(is, binary); ExpectToken(is, binary, "<NumOutputs>"); ReadBasicType(is, binary, &size); if (size < 1 || size > 1000000) KALDI_ERR << "Invalid size " << size; outputs.resize(size); for (int32 i = 0; i < size; i++) outputs[i].Read(is, binary); ExpectToken(is, binary, "</Nnet3CctcEg>"); } void NnetCctcExample::Swap(NnetCctcExample *other) { inputs.swap(other->inputs); outputs.swap(other->outputs); } void NnetCctcExample::Compress() { std::vector<NnetIo>::iterator iter = inputs.begin(), end = inputs.end(); // calling features.Compress() will do nothing if they are sparse or already // compressed. for (; iter != end; ++iter) iter->features.Compress(); } NnetCctcExample::NnetCctcExample(const NnetCctcExample &other): inputs(other.inputs), outputs(other.outputs) { } // called from MergeCctcExamplesInternal, this function merges the CctcSupervision // objects into one. Requires (and checks) that they all have the same name. static void MergeCctcSupervision( const std::vector<const NnetCctcSupervision*> &inputs, bool compactify, NnetCctcSupervision *output) { int32 num_inputs = inputs.size(), num_indexes = 0; for (int32 n = 0; n < num_inputs; n++) { KALDI_ASSERT(inputs[n]->name == inputs[0]->name); num_indexes += inputs[n]->indexes.size(); } output->name = inputs[0]->name; std::vector<const ctc::CctcSupervision*> input_supervision; input_supervision.reserve(inputs.size()); for (int32 n = 0; n < num_inputs; n++) { std::vector<ctc::CctcSupervision>::const_iterator iter = inputs[n]->supervision.begin(), end = inputs[n]->supervision.end(); for (; iter != end; ++iter) input_supervision.push_back(&(*iter)); } AppendCctcSupervision(input_supervision, compactify, &(output->supervision)); output->indexes.clear(); output->indexes.reserve(num_indexes); for (int32 n = 0; n < num_inputs; n++) { const std::vector<Index> &src_indexes = inputs[n]->indexes; int32 cur_size = output->indexes.size(); output->indexes.insert(output->indexes.end(), src_indexes.begin(), src_indexes.end()); std::vector<Index>::iterator iter = output->indexes.begin() + cur_size, end = output->indexes.end(); // change the 'n' index to correspond to the index into 'input'. // Each example gets a different 'n' value, starting from 0. for (; iter != end; ++iter) { KALDI_ASSERT(iter->n == 0 && "Merging already-merged CTC egs"); iter->n = n; } } KALDI_ASSERT(output->indexes.size() == num_indexes); } void MergeCctcExamples(bool compress, bool compactify, std::vector<NnetCctcExample> *input, NnetCctcExample *output) { int32 num_examples = input->size(); KALDI_ASSERT(num_examples > 0); // we temporarily make the input-features in 'input' look like regular NnetExamples, // so that we can recycle the MergeExamples() function. std::vector<NnetExample> eg_inputs(num_examples); for (int32 i = 0; i < num_examples; i++) eg_inputs[i].io.swap((*input)[i].inputs); NnetExample eg_output; MergeExamples(eg_inputs, compress, &eg_output); // swap the inputs back so that they are not really changed. for (int32 i = 0; i < num_examples; i++) eg_inputs[i].io.swap((*input)[i].inputs); // write to 'output->inputs' eg_output.io.swap(output->inputs); // Now deal with the CTC-supervision 'outputs'. There will // normally be just one of these, with name "output", but we // handle the more general case. int32 num_output_names = (*input)[0].outputs.size(); output->outputs.resize(num_output_names); for (int32 i = 0; i < num_output_names; i++) { std::vector<const NnetCctcSupervision*> to_merge(num_examples); for (int32 j = 0; j < num_examples; j++) { KALDI_ASSERT((*input)[j].outputs.size() == num_output_names); to_merge[j] = &((*input)[j].outputs[i]); } MergeCctcSupervision(to_merge, compactify, &(output->outputs[i])); } } void GetCctcComputationRequest(const Nnet &nnet, const NnetCctcExample &eg, bool need_model_derivative, bool store_component_stats, ComputationRequest *request) { request->inputs.clear(); request->inputs.reserve(eg.inputs.size()); request->outputs.clear(); request->outputs.reserve(eg.outputs.size()); request->need_model_derivative = need_model_derivative; request->store_component_stats = store_component_stats; for (size_t i = 0; i < eg.inputs.size(); i++) { const NnetIo &io = eg.inputs[i]; const std::string &name = io.name; int32 node_index = nnet.GetNodeIndex(name); if (node_index == -1 && !nnet.IsInputNode(node_index)) KALDI_ERR << "Nnet example has input named '" << name << "', but no such input node is in the network."; request->inputs.resize(request->inputs.size() + 1); IoSpecification &io_spec = request->inputs.back(); io_spec.name = name; io_spec.indexes = io.indexes; io_spec.has_deriv = false; } for (size_t i = 0; i < eg.outputs.size(); i++) { // there will normally be exactly one output , named "output" const NnetCctcSupervision &sup = eg.outputs[i]; const std::string &name = sup.name; int32 node_index = nnet.GetNodeIndex(name); if (node_index == -1 && !nnet.IsOutputNode(node_index)) KALDI_ERR << "Nnet example has output named '" << name << "', but no such output node is in the network."; request->outputs.resize(request->outputs.size() + 1); IoSpecification &io_spec = request->outputs.back(); io_spec.name = name; io_spec.indexes = sup.indexes; io_spec.has_deriv = need_model_derivative; } // check to see if something went wrong. if (request->inputs.empty()) KALDI_ERR << "No inputs in computation request."; if (request->outputs.empty()) KALDI_ERR << "No outputs in computation request."; } void ShiftCctcExampleTimes(int32 frame_shift, const std::vector<std::string> &exclude_names, NnetCctcExample *eg) { std::vector<NnetIo>::iterator input_iter = eg->inputs.begin(), input_end = eg->inputs.end(); for (; input_iter != input_end; ++input_iter) { bool must_exclude = false; std::vector<string>::const_iterator exclude_iter = exclude_names.begin(), exclude_end = exclude_names.end(); for (; exclude_iter != exclude_end; ++exclude_iter) if (input_iter->name == *exclude_iter) must_exclude = true; if (!must_exclude) { std::vector<Index>::iterator indexes_iter = input_iter->indexes.begin(), indexes_end = input_iter->indexes.end(); for (; indexes_iter != indexes_end; ++indexes_iter) indexes_iter->t += frame_shift; } } // note: we'll normally choose a small enough shift that the output-data // shift will be zero. std::vector<NnetCctcSupervision>::iterator sup_iter = eg->outputs.begin(), sup_end = eg->outputs.end(); for (; sup_iter != sup_end; ++sup_iter) { std::vector<Index> &indexes = sup_iter->indexes; KALDI_ASSERT(indexes.size() >= 2 && indexes[0].n == indexes[1].n && indexes[0].x == indexes[1].x); int32 frame_subsampling_factor = indexes[1].t - indexes[0].t; KALDI_ASSERT(frame_subsampling_factor > 0); // We need to shift by a multiple of frame_subsampling_factor. // Round to the closest multiple. int32 supervision_frame_shift = frame_subsampling_factor * std::floor(0.5 + (frame_shift * 1.0 / frame_subsampling_factor)); if (supervision_frame_shift == 0) continue; std::vector<Index>::iterator indexes_iter = indexes.begin(), indexes_end = indexes.end(); for (; indexes_iter != indexes_end; ++indexes_iter) indexes_iter->t += supervision_frame_shift; } } } // namespace nnet3 } // namespace kaldi
38.034063
86
0.651164
[ "vector" ]
05df7ea6a25403ef274ca645a20ec70c4f7e35ce
1,939
cpp
C++
scsdk/c++/scsdk_test/standard_cyborg/io/json/PolylineFileIOTests.cpp
StandardCyborg/scsdk
92f80bf2a580ebaafa6b0d1052d90d5c8f6682f7
[ "Apache-2.0" ]
7
2020-11-26T01:07:26.000Z
2021-12-14T07:45:19.000Z
scsdk/c++/scsdk_test/standard_cyborg/io/json/PolylineFileIOTests.cpp
StandardCyborg/scsdk
92f80bf2a580ebaafa6b0d1052d90d5c8f6682f7
[ "Apache-2.0" ]
null
null
null
scsdk/c++/scsdk_test/standard_cyborg/io/json/PolylineFileIOTests.cpp
StandardCyborg/scsdk
92f80bf2a580ebaafa6b0d1052d90d5c8f6682f7
[ "Apache-2.0" ]
null
null
null
/* Copyright 2020 Standard Cyborg Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <gtest/gtest.h> #include <sstream> #include "standard_cyborg/sc3d/Polyline.hpp" #include "standard_cyborg/io/json/PolylineFileIO_JSON.hpp" using standard_cyborg::math::Vec3; TEST(PolylineFileIOTests, testPolylineReadWrite) { standard_cyborg::sc3d::Polyline originalPolyline({{1.0, 2.0, 3.0}, {2.0, 3.0, 4.0}}); std::stringstream buf; standard_cyborg::io::json::WritePolylineToJSONStream(buf, originalPolyline); standard_cyborg::sc3d::Polyline readPolyline; EXPECT_TRUE(standard_cyborg::io::json::ReadPolylineFromJSONStream(readPolyline, buf)); EXPECT_EQ(originalPolyline.getPositions(), readPolyline.getPositions()); } TEST(PolylineFileIOTests, testPolylineWithNaN) { standard_cyborg::sc3d::Polyline originalPolyline({{1.0, NAN, 3.0}, {2.0, 3.0, 4.0}}); std::stringstream buf; standard_cyborg::io::json::WritePolylineToJSONStream(buf, originalPolyline); standard_cyborg::sc3d::Polyline readPolyline; EXPECT_TRUE(standard_cyborg::io::json::ReadPolylineFromJSONStream(readPolyline, buf)); std::vector<Vec3> positions = readPolyline.getPositions(); EXPECT_EQ(positions[0].x, 1.0); EXPECT_TRUE(isnan(positions[0].y)); EXPECT_EQ(positions[0].z, 3.0); EXPECT_EQ(positions[1].x, 2.0); EXPECT_EQ(positions[1].y, 3.0); EXPECT_EQ(positions[1].z, 4.0); }
32.864407
90
0.732852
[ "vector" ]
05e2f61f7fcc213e160d096745c3384ea6b478ef
6,140
cpp
C++
kr_quadrotor_simulator/src/quadrotor_simulator_trpy.cpp
fcladera/kr_mav_control
3e4a80f9af469df59628537876fb4e9a8f2fcd14
[ "BSD-3-Clause" ]
29
2021-02-08T17:04:13.000Z
2022-03-29T10:43:50.000Z
kr_quadrotor_simulator/src/quadrotor_simulator_trpy.cpp
fcladera/kr_mav_control
3e4a80f9af469df59628537876fb4e9a8f2fcd14
[ "BSD-3-Clause" ]
6
2021-02-08T20:28:40.000Z
2021-09-29T16:51:24.000Z
kr_quadrotor_simulator/src/quadrotor_simulator_trpy.cpp
fcladera/kr_mav_control
3e4a80f9af469df59628537876fb4e9a8f2fcd14
[ "BSD-3-Clause" ]
16
2021-02-10T09:38:10.000Z
2022-03-30T15:55:59.000Z
#include <kr_mav_msgs/TRPYCommand.h> #include <Eigen/Geometry> #include "quadrotor_simulator_base.hpp" namespace QuadrotorSimulator { typedef struct _TRPYCommand { float thrust; float roll, pitch, yaw; float angular_velocity[3]; float kR[3]; float kOm[3]; bool enable_motors; } TRPYCommand; class QuadrotorSimulatorTRPY : public QuadrotorSimulatorBase<kr_mav_msgs::TRPYCommand, TRPYCommand> { public: QuadrotorSimulatorTRPY(ros::NodeHandle &nh) : QuadrotorSimulatorBase(nh) {} private: virtual void cmd_callback(const kr_mav_msgs::TRPYCommand::ConstPtr &cmd); virtual ControlInput getControl(const Quadrotor &quad, const TRPYCommand &cmd) const; }; void QuadrotorSimulatorTRPY::cmd_callback(const kr_mav_msgs::TRPYCommand::ConstPtr &cmd) { command_.thrust = cmd->thrust; command_.roll = cmd->roll; command_.pitch = cmd->pitch; command_.yaw = cmd->yaw; command_.angular_velocity[0] = cmd->angular_velocity.x; command_.angular_velocity[1] = cmd->angular_velocity.y; command_.angular_velocity[2] = cmd->angular_velocity.z; command_.kR[0] = cmd->kR[0]; command_.kR[1] = cmd->kR[1]; command_.kR[2] = cmd->kR[2]; command_.kOm[0] = cmd->kOm[0]; command_.kOm[1] = cmd->kOm[1]; command_.kOm[2] = cmd->kOm[2]; command_.enable_motors = cmd->aux.enable_motors; } QuadrotorSimulatorTRPY::ControlInput QuadrotorSimulatorTRPY::getControl(const Quadrotor &quad, const TRPYCommand &cmd) const { const double _kf = quad.getPropellerThrustCoefficient(); const double _km = quad.getPropellerMomentCoefficient(); const double kf = _kf; const double km = _km / _kf * kf; const double d = quad.getArmLength(); const Eigen::Matrix3f J = quad.getInertia().cast<float>(); const float I[3][3] = {{J(0, 0), J(0, 1), J(0, 2)}, {J(1, 0), J(1, 1), J(1, 2)}, {J(2, 0), J(2, 1), J(2, 2)}}; const Quadrotor::State &state = quad.getState(); float R11 = state.R(0, 0); float R12 = state.R(0, 1); float R13 = state.R(0, 2); float R21 = state.R(1, 0); float R22 = state.R(1, 1); float R23 = state.R(1, 2); float R31 = state.R(2, 0); float R32 = state.R(2, 1); float R33 = state.R(2, 2); float Om1 = state.omega(0); float Om2 = state.omega(1); float Om3 = state.omega(2); float Rd11 = cos(cmd.yaw) * cos(cmd.pitch); float Rd12 = cos(cmd.yaw) * sin(cmd.pitch) * sin(cmd.roll) - cos(cmd.roll) * sin(cmd.yaw); float Rd13 = sin(cmd.yaw) * sin(cmd.roll) + cos(cmd.yaw) * cos(cmd.roll) * sin(cmd.pitch); float Rd21 = cos(cmd.pitch) * sin(cmd.yaw); float Rd22 = cos(cmd.yaw) * cos(cmd.roll) + sin(cmd.yaw) * sin(cmd.pitch) * sin(cmd.roll); float Rd23 = cos(cmd.roll) * sin(cmd.yaw) * sin(cmd.pitch) - cos(cmd.yaw) * sin(cmd.roll); float Rd31 = -sin(cmd.pitch); float Rd32 = cos(cmd.pitch) * sin(cmd.roll); float Rd33 = cos(cmd.pitch) * cos(cmd.roll); float Psi = 0.5f * (3.0f - (Rd11 * R11 + Rd21 * R21 + Rd31 * R31 + Rd12 * R12 + Rd22 * R22 + Rd32 * R32 + Rd13 * R13 + Rd23 * R23 + Rd33 * R33)); float force = 0; if(Psi < 1.0f) // Position control stability guaranteed only when Psi < 1 force = cmd.thrust; float eR1 = 0.5f * (R12 * Rd13 - R13 * Rd12 + R22 * Rd23 - R23 * Rd22 + R32 * Rd33 - R33 * Rd32); float eR2 = 0.5f * (R13 * Rd11 - R11 * Rd13 - R21 * Rd23 + R23 * Rd21 - R31 * Rd33 + R33 * Rd31); float eR3 = 0.5f * (R11 * Rd12 - R12 * Rd11 + R21 * Rd22 - R22 * Rd21 + R31 * Rd32 - R32 * Rd31); float Omd1 = cmd.angular_velocity[0] * (R11 * Rd11 + R21 * Rd21 + R31 * Rd31) + cmd.angular_velocity[1] * (R11 * Rd12 + R21 * Rd22 + R31 * Rd32) + cmd.angular_velocity[2] * (R11 * Rd13 + R21 * Rd23 + R31 * Rd33); float Omd2 = cmd.angular_velocity[0] * (R12 * Rd11 + R22 * Rd21 + R32 * Rd31) + cmd.angular_velocity[1] * (R12 * Rd12 + R22 * Rd22 + R32 * Rd32) + cmd.angular_velocity[2] * (R12 * Rd13 + R22 * Rd23 + R32 * Rd33); float Omd3 = cmd.angular_velocity[0] * (R13 * Rd11 + R23 * Rd21 + R33 * Rd31) + cmd.angular_velocity[1] * (R13 * Rd12 + R23 * Rd22 + R33 * Rd32) + cmd.angular_velocity[2] * (R13 * Rd13 + R23 * Rd23 + R33 * Rd33); float eOm1 = Om1 - Omd1; float eOm2 = Om2 - Omd2; float eOm3 = Om3 - Omd3; #if 0 float in1 = Om2 * (I[2][0] * Om1 + I[2][1] * Om2 + I[2][2] * Om3) - Om3 * (I[1][0] * Om1 + I[1][1] * Om2 + I[1][2] * Om3); float in2 = Om3 * (I[0][0] * Om1 + I[0][1] * Om2 + I[0][2] * Om3) - Om1 * (I[2][0] * Om1 + I[2][1] * Om2 + I[2][2] * Om3); float in3 = Om1 * (I[1][0] * Om1 + I[1][1] * Om2 + I[1][2] * Om3) - Om2 * (I[0][0] * Om1 + I[0][1] * Om2 + I[0][2] * Om3); #else float in1 = Omd2 * (I[2][0] * Omd1 + I[2][1] * Omd2 + I[2][2] * Omd3) - Omd3 * (I[1][0] * Omd1 + I[1][1] * Omd2 + I[1][2] * Omd3); float in2 = Omd3 * (I[0][0] * Omd1 + I[0][1] * Omd2 + I[0][2] * Omd3) - Omd1 * (I[2][0] * Omd1 + I[2][1] * Omd2 + I[2][2] * Omd3); float in3 = Omd1 * (I[1][0] * Omd1 + I[1][1] * Omd2 + I[1][2] * Omd3) - Omd2 * (I[0][0] * Omd1 + I[0][1] * Omd2 + I[0][2] * Omd3); #endif float M1 = -cmd.kR[0] * eR1 - cmd.kOm[0] * eOm1 + in1; float M2 = -cmd.kR[1] * eR2 - cmd.kOm[1] * eOm2 + in2; float M3 = -cmd.kR[2] * eR3 - cmd.kOm[2] * eOm3 + in3; float w_sq[4]; w_sq[0] = force / (4 * kf) - M2 / (2 * d * kf) + M3 / (4 * km); w_sq[1] = force / (4 * kf) + M2 / (2 * d * kf) + M3 / (4 * km); w_sq[2] = force / (4 * kf) + M1 / (2 * d * kf) - M3 / (4 * km); w_sq[3] = force / (4 * kf) - M1 / (2 * d * kf) - M3 / (4 * km); ControlInput control; for(int i = 0; i < 4; i++) { if(cmd.enable_motors) { if(w_sq[i] < 0) w_sq[i] = 0; control.rpm[i] = sqrtf(w_sq[i]); } else { control.rpm[i] = 0; } } return control; } } // namespace QuadrotorSimulator int main(int argc, char **argv) { ros::init(argc, argv, "kr_quadrotor_simulator_trpy"); ros::NodeHandle n("~"); QuadrotorSimulator::QuadrotorSimulatorTRPY quad_sim(n); quad_sim.run(); return 0; }
37.212121
120
0.569218
[ "geometry" ]
af0349797c126669531e76755d4be313cf8a7554
16,362
cc
C++
chrome/browser/extensions/extension_browser_event_router.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
11
2015-03-20T04:08:08.000Z
2021-11-15T15:51:36.000Z
chrome/browser/extensions/extension_browser_event_router.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/extensions/extension_browser_event_router.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2009 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/extensions/extension_browser_event_router.h" #include "base/json/json_writer.h" #include "base/values.h" #include "chrome/browser/browser.h" #include "chrome/browser/profile.h" #include "chrome/browser/extensions/extension_event_names.h" #include "chrome/browser/extensions/extension_message_service.h" #include "chrome/browser/extensions/extension_tabs_module_constants.h" #include "chrome/browser/extensions/extension_page_actions_module_constants.h" #include "chrome/browser/tab_contents/navigation_entry.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/notification_service.h" namespace events = extension_event_names; namespace tab_keys = extension_tabs_module_constants; namespace page_action_keys = extension_page_actions_module_constants; ExtensionBrowserEventRouter::TabEntry::TabEntry() : state_(ExtensionTabUtil::TAB_COMPLETE), pending_navigate_(false), url_() { } ExtensionBrowserEventRouter::TabEntry::TabEntry(const TabContents* contents) : state_(ExtensionTabUtil::TAB_COMPLETE), pending_navigate_(false), url_(contents->GetURL()) { UpdateLoadState(contents); } DictionaryValue* ExtensionBrowserEventRouter::TabEntry::UpdateLoadState( const TabContents* contents) { ExtensionTabUtil::TabStatus old_state = state_; state_ = ExtensionTabUtil::GetTabStatus(contents); if (old_state == state_) return false; if (state_ == ExtensionTabUtil::TAB_LOADING) { // Do not send "loading" state changed now. Wait for navigate so the new // url is available. pending_navigate_ = true; return NULL; } else if (state_ == ExtensionTabUtil::TAB_COMPLETE) { // Send "complete" state change. DictionaryValue* changed_properties = new DictionaryValue(); changed_properties->SetString(tab_keys::kStatusKey, tab_keys::kStatusValueComplete); return changed_properties; } else { NOTREACHED(); return NULL; } } DictionaryValue* ExtensionBrowserEventRouter::TabEntry::DidNavigate( const TabContents* contents) { if (!pending_navigate_) return NULL; DictionaryValue* changed_properties = new DictionaryValue(); changed_properties->SetString(tab_keys::kStatusKey, tab_keys::kStatusValueLoading); GURL new_url = contents->GetURL(); if (new_url != url_) { url_ = new_url; changed_properties->SetString(tab_keys::kUrlKey, url_.spec()); } pending_navigate_ = false; return changed_properties; } ExtensionBrowserEventRouter* ExtensionBrowserEventRouter::GetInstance() { return Singleton<ExtensionBrowserEventRouter>::get(); } static void DispatchEvent(Profile* profile, const char* event_name, const std::string json_args) { if (profile->GetExtensionMessageService()) { profile->GetExtensionMessageService()-> DispatchEventToRenderers(event_name, json_args); } } static void DispatchEventWithTab(Profile* profile, const char* event_name, const TabContents* tab_contents) { ListValue args; args.Append(ExtensionTabUtil::CreateTabValue(tab_contents)); std::string json_args; base::JSONWriter::Write(&args, false, &json_args); DispatchEvent(profile, event_name, json_args); } static void DispatchSimpleBrowserEvent(Profile* profile, const int window_id, const char* event_name) { ListValue args; args.Append(Value::CreateIntegerValue(window_id)); std::string json_args; base::JSONWriter::Write(&args, false, &json_args); DispatchEvent(profile, event_name, json_args); } void ExtensionBrowserEventRouter::Init() { if (initialized_) return; BrowserList::AddObserver(this); // Init() can happen after the browser is running, so catch up with any // windows that already exist. for (BrowserList::const_iterator iter = BrowserList::begin(); iter != BrowserList::end(); ++iter) { RegisterForBrowserNotifications(*iter); // Also catch up our internal bookkeeping of tab entries. Browser* browser = *iter; if (browser->tabstrip_model()) { for (int i = 0; i < browser->tabstrip_model()->count(); ++i) { TabContents* contents = browser->tabstrip_model()->GetTabContentsAt(i); int tab_id = ExtensionTabUtil::GetTabId(contents); tab_entries_[tab_id] = TabEntry(contents); } } } initialized_ = true; } ExtensionBrowserEventRouter::ExtensionBrowserEventRouter() : initialized_(false) { } void ExtensionBrowserEventRouter::OnBrowserAdded(const Browser* browser) { RegisterForBrowserNotifications(browser); } void ExtensionBrowserEventRouter::RegisterForBrowserNotifications( const Browser* browser) { // Start listening to TabStripModel events for this browser. browser->tabstrip_model()->AddObserver(this); // If this is a new window, it isn't ready at this point, so we register to be // notified when it is. If this is an existing window, this is a no-op that we // just do to reduce code complexity. registrar_.Add(this, NotificationType::BROWSER_WINDOW_READY, Source<const Browser>(browser)); if (browser->tabstrip_model()) { for (int i = 0; i < browser->tabstrip_model()->count(); ++i) RegisterForTabNotifications( browser->tabstrip_model()->GetTabContentsAt(i)); } } void ExtensionBrowserEventRouter::RegisterForTabNotifications( TabContents* contents) { registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED, Source<NavigationController>(&contents->controller())); // Observing TAB_CONTENTS_DESTROYED is necessary because it's // possible for tabs to be created, detached and then destroyed without // ever having been re-attached and closed. This happens in the case of // a devtools TabContents that is opened in window, docked, then closed. registrar_.Add(this, NotificationType::TAB_CONTENTS_DESTROYED, Source<TabContents>(contents)); } void ExtensionBrowserEventRouter::OnBrowserWindowReady(const Browser* browser) { ListValue args; DictionaryValue* window_dictionary = ExtensionTabUtil::CreateWindowValue( browser, false); args.Append(window_dictionary); std::string json_args; base::JSONWriter::Write(&args, false, &json_args); DispatchEvent(browser->profile(), events::kOnWindowCreated, json_args); } void ExtensionBrowserEventRouter::OnBrowserRemoving(const Browser* browser) { // Stop listening to TabStripModel events for this browser. browser->tabstrip_model()->RemoveObserver(this); registrar_.Remove(this, NotificationType::BROWSER_WINDOW_READY, Source<const Browser>(browser)); DispatchSimpleBrowserEvent(browser->profile(), ExtensionTabUtil::GetWindowId(browser), events::kOnWindowRemoved); } void ExtensionBrowserEventRouter::OnBrowserSetLastActive( const Browser* browser) { DispatchSimpleBrowserEvent(browser->profile(), ExtensionTabUtil::GetWindowId(browser), events::kOnWindowFocusedChanged); } void ExtensionBrowserEventRouter::TabCreatedAt(TabContents* contents, int index, bool foreground) { DispatchEventWithTab(contents->profile(), events::kOnTabCreated, contents); RegisterForTabNotifications(contents); } void ExtensionBrowserEventRouter::TabInsertedAt(TabContents* contents, int index, bool foreground) { // If tab is new, send created event. int tab_id = ExtensionTabUtil::GetTabId(contents); if (tab_entries_.find(tab_id) == tab_entries_.end()) { tab_entries_[tab_id] = TabEntry(contents); TabCreatedAt(contents, index, foreground); return; } ListValue args; args.Append(Value::CreateIntegerValue(tab_id)); DictionaryValue* object_args = new DictionaryValue(); object_args->Set(tab_keys::kNewWindowIdKey, Value::CreateIntegerValue( ExtensionTabUtil::GetWindowIdOfTab(contents))); object_args->Set(tab_keys::kNewPositionKey, Value::CreateIntegerValue( index)); args.Append(object_args); std::string json_args; base::JSONWriter::Write(&args, false, &json_args); DispatchEvent(contents->profile(), events::kOnTabAttached, json_args); } void ExtensionBrowserEventRouter::TabDetachedAt(TabContents* contents, int index) { int tab_id = ExtensionTabUtil::GetTabId(contents); if (tab_entries_.find(tab_id) == tab_entries_.end()) { // The tab was removed. Don't send detach event. return; } ListValue args; args.Append(Value::CreateIntegerValue(tab_id)); DictionaryValue* object_args = new DictionaryValue(); object_args->Set(tab_keys::kOldWindowIdKey, Value::CreateIntegerValue( ExtensionTabUtil::GetWindowIdOfTab(contents))); object_args->Set(tab_keys::kOldPositionKey, Value::CreateIntegerValue( index)); args.Append(object_args); std::string json_args; base::JSONWriter::Write(&args, false, &json_args); DispatchEvent(contents->profile(), events::kOnTabDetached, json_args); } void ExtensionBrowserEventRouter::TabClosingAt(TabContents* contents, int index) { int tab_id = ExtensionTabUtil::GetTabId(contents); ListValue args; args.Append(Value::CreateIntegerValue(tab_id)); std::string json_args; base::JSONWriter::Write(&args, false, &json_args); DispatchEvent(contents->profile(), events::kOnTabRemoved, json_args); int removed_count = tab_entries_.erase(tab_id); DCHECK_GT(removed_count, 0); registrar_.Remove(this, NotificationType::NAV_ENTRY_COMMITTED, Source<NavigationController>(&contents->controller())); registrar_.Remove(this, NotificationType::TAB_CONTENTS_DESTROYED, Source<TabContents>(contents)); } void ExtensionBrowserEventRouter::TabSelectedAt(TabContents* old_contents, TabContents* new_contents, int index, bool user_gesture) { ListValue args; args.Append(Value::CreateIntegerValue( ExtensionTabUtil::GetTabId(new_contents))); DictionaryValue* object_args = new DictionaryValue(); object_args->Set(tab_keys::kWindowIdKey, Value::CreateIntegerValue( ExtensionTabUtil::GetWindowIdOfTab(new_contents))); args.Append(object_args); std::string json_args; base::JSONWriter::Write(&args, false, &json_args); DispatchEvent(new_contents->profile(), events::kOnTabSelectionChanged, json_args); } void ExtensionBrowserEventRouter::TabMoved(TabContents* contents, int from_index, int to_index, bool pinned_state_changed) { ListValue args; args.Append(Value::CreateIntegerValue(ExtensionTabUtil::GetTabId(contents))); DictionaryValue* object_args = new DictionaryValue(); object_args->Set(tab_keys::kWindowIdKey, Value::CreateIntegerValue( ExtensionTabUtil::GetWindowIdOfTab(contents))); object_args->Set(tab_keys::kFromIndexKey, Value::CreateIntegerValue( from_index)); object_args->Set(tab_keys::kToIndexKey, Value::CreateIntegerValue( to_index)); args.Append(object_args); std::string json_args; base::JSONWriter::Write(&args, false, &json_args); DispatchEvent(contents->profile(), events::kOnTabMoved, json_args); } void ExtensionBrowserEventRouter::TabUpdated(TabContents* contents, bool did_navigate) { int tab_id = ExtensionTabUtil::GetTabId(contents); std::map<int, TabEntry>::iterator i = tab_entries_.find(tab_id); DCHECK(tab_entries_.end() != i); TabEntry& entry = i->second; DictionaryValue* changed_properties = NULL; if (did_navigate) changed_properties = entry.DidNavigate(contents); else changed_properties = entry.UpdateLoadState(contents); if (changed_properties) { // The state of the tab (as seen from the extension point of view) has // changed. Send a notification to the extension. ListValue args; // First arg: The id of the tab that changed. args.Append(Value::CreateIntegerValue(tab_id)); // Second arg: An object containing the changes to the tab state. args.Append(changed_properties); // Third arg: An object containing the state of the tab. args.Append(ExtensionTabUtil::CreateTabValue(contents)); std::string json_args; base::JSONWriter::Write(&args, false, &json_args); DispatchEvent(contents->profile(), events::kOnTabUpdated, json_args); } } void ExtensionBrowserEventRouter::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { if (type == NotificationType::NAV_ENTRY_COMMITTED) { NavigationController* source_controller = Source<NavigationController>(source).ptr(); TabUpdated(source_controller->tab_contents(), true); } else if (type == NotificationType::TAB_CONTENTS_DESTROYED) { // Tab was destroyed after being detached (without being re-attached). TabContents* contents = Source<TabContents>(source).ptr(); registrar_.Remove(this, NotificationType::NAV_ENTRY_COMMITTED, Source<NavigationController>(&contents->controller())); registrar_.Remove(this, NotificationType::TAB_CONTENTS_DESTROYED, Source<TabContents>(contents)); } else if (type == NotificationType::BROWSER_WINDOW_READY) { const Browser* browser = Source<const Browser>(source).ptr(); OnBrowserWindowReady(browser); } else { NOTREACHED(); } } void ExtensionBrowserEventRouter::TabChangedAt(TabContents* contents, int index, TabChangeType change_type) { TabUpdated(contents, false); } void ExtensionBrowserEventRouter::TabStripEmpty() { } void ExtensionBrowserEventRouter::DispatchOldPageActionEvent( Profile* profile, const std::string& extension_id, const std::string& page_action_id, int tab_id, const std::string& url, int button) { ListValue args; args.Append(Value::CreateStringValue(page_action_id)); DictionaryValue* data = new DictionaryValue(); data->Set(tab_keys::kTabIdKey, Value::CreateIntegerValue(tab_id)); data->Set(tab_keys::kTabUrlKey, Value::CreateStringValue(url)); data->Set(page_action_keys::kButtonKey, Value::CreateIntegerValue(button)); args.Append(data); std::string json_args; base::JSONWriter::Write(&args, false, &json_args); std::string event_name = std::string("pageActions/") + extension_id; DispatchEvent(profile, event_name.c_str(), json_args); } void ExtensionBrowserEventRouter::PageActionExecuted( Profile* profile, const std::string& extension_id, const std::string& page_action_id, int tab_id, const std::string& url, int button) { DispatchOldPageActionEvent(profile, extension_id, page_action_id, tab_id, url, button); TabContents* tab_contents = NULL; if (!ExtensionTabUtil::GetTabById(tab_id, profile, NULL, NULL, &tab_contents, NULL)) { return; } std::string event_name = std::string("pageAction/") + extension_id; DispatchEventWithTab(profile, event_name.c_str(), tab_contents); } void ExtensionBrowserEventRouter::BrowserActionExecuted( Profile* profile, const std::string& extension_id, Browser* browser) { TabContents* tab_contents = NULL; int tab_id = 0; if (!ExtensionTabUtil::GetDefaultTab(browser, &tab_contents, &tab_id)) return; std::string event_name = std::string("browserAction/") + extension_id; DispatchEventWithTab(profile, event_name.c_str(), tab_contents); }
36.279379
80
0.697225
[ "object" ]
af0b8732d4af8ba49a766eb73581505eddf906e7
27,300
cpp
C++
EngineLayer/FdrAnalysis/FdrAnalysisEngine.cpp
edgargabriel/HPCMetaMorpheus
160cc269464b8e563fa2f62f6843690b6a2533ee
[ "MIT" ]
2
2020-09-10T19:14:20.000Z
2021-09-11T16:36:56.000Z
EngineLayer/FdrAnalysis/FdrAnalysisEngine.cpp
edgargabriel/HPCMetaMorpheus
160cc269464b8e563fa2f62f6843690b6a2533ee
[ "MIT" ]
null
null
null
EngineLayer/FdrAnalysis/FdrAnalysisEngine.cpp
edgargabriel/HPCMetaMorpheus
160cc269464b8e563fa2f62f6843690b6a2533ee
[ "MIT" ]
3
2020-09-11T01:19:47.000Z
2021-09-02T02:05:01.000Z
#include "FdrAnalysisEngine.h" #include "../PeptideSpectralMatch.h" #include "../CommonParameters.h" #include "../MetaMorpheusEngineResults.h" #include "FdrAnalysisResults.h" #include "../GlobalVariables.h" #include <boost/math/special_functions/gamma.hpp> #include <numeric> #include <math.h> #include "Group.h" namespace EngineLayer { namespace FdrAnalysis { FdrAnalysisEngine::FdrAnalysisEngine(std::vector<PeptideSpectralMatch*> &psms, int massDiffAcceptorNumNotches, CommonParameters *commonParameters, std::vector<std::string> nestedIds, int verbosityLevel ) : MetaMorpheusEngine(commonParameters, nestedIds, verbosityLevel), MassDiffAcceptorNumNotches(massDiffAcceptorNumNotches), UseDeltaScore(commonParameters->getUseDeltaScore()), CalculateEValue(commonParameters->getCalculateEValue()), ScoreCutoff(commonParameters->getScoreCutoff()), AllPsms(psms) { } MetaMorpheusEngineResults *FdrAnalysisEngine::RunSpecific() { FdrAnalysisResults *myAnalysisResults = new FdrAnalysisResults(this); Status("Running FDR analysis..."); DoFalseDiscoveryRateAnalysis(myAnalysisResults); std::vector<PeptideSpectralMatch *> tmp; for ( auto b: AllPsms ) { if (b->getFdrInfo()->getQValue() < 0.01 ) { tmp.push_back(b); } } myAnalysisResults->setPsmsWithin1PercentFdr(tmp.size() ); return myAnalysisResults; } void FdrAnalysisEngine::DoFalseDiscoveryRateAnalysis(FdrAnalysisResults *myAnalysisResults) { // Stop if canceled if (GlobalVariables::getStopLoops()) { return; } // calculate FDR on a per-protease basis (targets and decoys for a specific protease) #ifdef ORIG auto psmsGroupedByProtease = AllPsms.GroupBy([&] (std::any p){ p::DigestionParams::Protease; }); #endif std::function<bool(PeptideSpectralMatch*,PeptideSpectralMatch*)> f1 = [&] (PeptideSpectralMatch *l, PeptideSpectralMatch *r) { return l->digestionParams->getProtease() < r->digestionParams->getProtease(); } ; std::function<bool(PeptideSpectralMatch*,PeptideSpectralMatch*)> f2 = [&] (PeptideSpectralMatch *l, PeptideSpectralMatch *r) { return l->digestionParams->getProtease() != r->digestionParams->getProtease(); } ; std::vector<std::vector<PeptideSpectralMatch *>> psmsGroupedByProtease = Group::GroupBy( AllPsms, f1, f2 ); for (auto psms : psmsGroupedByProtease) { // generate the null distribution for e-value calculations double globalMeanScore = 0; int globalMeanCount = 0; #ifdef ORIG //if (CalculateEValue && psms.Any()) #endif if (CalculateEValue && !psms.empty()) { std::vector<double> combinedScores; for (auto psm : psms) { auto allscores = psm->getAllScores(); std::sort(allscores.begin(), allscores.end()); combinedScores.insert(combinedScores.end(), allscores.begin(), allscores.end()); //remove top scoring peptide #ifdef ORIG //if (combinedScores.Any()) #endif if ( !combinedScores.empty() ) { combinedScores.pop_back(); } } #ifdef ORIG //if (combinedScores.Any()) #endif if ( !combinedScores.empty() ) { //globalMeanScore = combinedScores.Average(); globalMeanScore = std::accumulate(combinedScores.begin(),combinedScores.end(), 0.0)/combinedScores.size(); globalMeanCount = static_cast<int>(static_cast<double>(combinedScores.size()) / psms.size()); } else { // should be a very rare case... if there are PSMs but each PSM only has one hit globalMeanScore = 0; globalMeanCount = 0; } } //Calculate delta scores for the psms (regardless of if we are using them) for (auto psm : psms) { if (psm != nullptr) { psm->CalculateDeltaScore(ScoreCutoff); } } //determine if Score or DeltaScore performs better if (UseDeltaScore) { constexpr double qValueCutoff = 0.01; //optimize to get the most PSMs at a 1% FDR #ifdef ORIG std::vector<PeptideSpectralMatch*> scoreSorted = psms.OrderByDescending([&] (std::any b) { b::Score; }).ThenBy([&] (std::any b) { b::PeptideMonisotopicMass.HasValue ? std::abs(b::ScanPrecursorMass-b::PeptideMonisotopicMass->Value) : std::numeric_limits<double>::max(); }).GroupBy([&] (std::any b) { return std::tuple <std::string, int, std::optional<double>>(b::FullFilePath, b::ScanNumber, b::PeptideMonisotopicMass)} )->Select([&] (std::any b) { b::First(); }).ToList(); #endif //OrderByDescending and ThenBy std::stable_sort (psms.begin(), psms.end(), [&] (PeptideSpectralMatch *r, PeptideSpectralMatch *l) { if ( r->getScore() > l->getScore() ) return true; if ( r->getScore() < l->getScore() ) return false; double lval= std::numeric_limits<double>::max(), rval=std::numeric_limits<double>::max(); if ( l->getPeptideMonisotopicMass().has_value() ) { lval = std::abs(l->getScanPrecursorMass() - l->getPeptideMonisotopicMass().value()); } if ( r->getPeptideMonisotopicMass().has_value() ) { rval = std::abs(r->getScanPrecursorMass() - r->getPeptideMonisotopicMass().value()); } return rval < lval; }); //GroupBy tuple std::function<bool(PeptideSpectralMatch*,PeptideSpectralMatch*)> f3 = [&] (PeptideSpectralMatch *l, PeptideSpectralMatch *r) { return l->getFullFilePath() != r->getFullFilePath() && l->getScanNumber() != r->getScanNumber() && l->getPeptideMonisotopicMass() != r->getPeptideMonisotopicMass(); } ; std::vector<std::vector<PeptideSpectralMatch *>>tvec; //Edgar: Note: cannot use the Group::GroupBy functionality here because of the custom sorting. for ( auto p : psms ) { bool found = false; for ( auto q: tvec ) { if ( f3 ( p, q[0] ) ) { found = true; q.push_back(p); break; } } if ( !found ) { auto vec = new std::vector<PeptideSpectralMatch *>(); vec->push_back(p); tvec.push_back(*vec); } } // Select first std::vector<PeptideSpectralMatch*> scoreSorted; for ( auto t: tvec ) { scoreSorted.push_back(t[0]); } int ScorePSMs = GetNumPSMsAtqValueCutoff(scoreSorted, qValueCutoff); #ifdef ORIG scoreSorted = psms.OrderByDescending([&] (std::any b) { b::DeltaScore; }).ThenBy([&] (std::any b){ b::PeptideMonisotopicMass.HasValue ? std::abs(b::ScanPrecursorMass - b::PeptideMonisotopicMass->Value) : std::numeric_limits<double>::max(); }).GroupBy([&] (std::any b) { return std::tuple < std::string>; }, int, std::optional<double>>(b::FullFilePath, b::ScanNumber, b::PeptideMonisotopicMass))->Select([&] (std::any b) { b::First(); }).ToList(); #endif //OrderByDescending and ThenBy std::stable_sort (psms.begin(), psms.end(), [&] (PeptideSpectralMatch *r, PeptideSpectralMatch *l) { if ( r->getDeltaScore() > l->getDeltaScore() ) return true; if ( r->getDeltaScore() < l->getDeltaScore() ) return false; double lval= std::numeric_limits<double>::max(), rval=std::numeric_limits<double>::max(); if ( l->getPeptideMonisotopicMass().has_value() ) { lval = std::abs(l->getScanPrecursorMass() - l->getPeptideMonisotopicMass().value()); } if ( r->getPeptideMonisotopicMass().has_value() ) { rval = std::abs(r->getScanPrecursorMass() - r->getPeptideMonisotopicMass().value()); } return rval < lval; }); //GroupBy tuple tvec.clear(); for ( auto p : psms ) { bool found = false; for ( auto q: tvec ) { if ( f3 ( p, q[0] ) ) { found = true; q.push_back(p); break; } } if ( !found ) { auto vec = new std::vector<PeptideSpectralMatch *>(); vec->push_back(p); tvec.push_back(*vec); } } // Select first scoreSorted.clear(); for ( auto t: tvec ) { scoreSorted.push_back(t[0]); } int DeltaScorePSMs = GetNumPSMsAtqValueCutoff(scoreSorted, qValueCutoff); //sort by best method myAnalysisResults->setDeltaScoreImprovement(DeltaScorePSMs > ScorePSMs); #ifdef ORIG psms = myAnalysisResults->getDeltaScoreImprovement() ? psms.OrderByDescending([&] (std::any b) { b::DeltaScore; }).ThenBy([&] (std::any b) { b::PeptideMonisotopicMass.HasValue ? std::abs(b::ScanPrecursorMass - b::PeptideMonisotopicMass->Value) : std::numeric_limits<double>::max(); }).ToList() : psms.OrderByDescending([&] (std::any b) { b::Score; }).ThenBy([&] (std::any b){ b::PeptideMonisotopicMass.HasValue ? std::abs(b::ScanPrecursorMass - b::PeptideMonisotopicMass->Value) : std::numeric_limits<double>::max(); }).ToList(); #endif if ( myAnalysisResults->getDeltaScoreImprovement() ) { //OrderByDescending and ThenBy std::stable_sort (psms.begin(), psms.end(), [&] (PeptideSpectralMatch *r, PeptideSpectralMatch *l) { if ( r->getDeltaScore() > l->getDeltaScore() ) return true; if ( r->getDeltaScore() < l->getDeltaScore() ) return false; double lval= std::numeric_limits<double>::max(), rval=std::numeric_limits<double>::max(); if ( l->getPeptideMonisotopicMass().has_value() ) { lval = std::abs(l->getScanPrecursorMass() - l->getPeptideMonisotopicMass().value()); } if ( r->getPeptideMonisotopicMass().has_value() ) { rval = std::abs(r->getScanPrecursorMass() - r->getPeptideMonisotopicMass().value()); } return rval < lval; }); } else { //OrderByDescending and ThenBy std::stable_sort (psms.begin(), psms.end(), [&] (PeptideSpectralMatch *r, PeptideSpectralMatch *l) { if ( r->getScore() > l->getScore() ) return true; if ( r->getScore() < l->getScore() ) return false; double lval= std::numeric_limits<double>::max(), rval=std::numeric_limits<double>::max(); if ( l->getPeptideMonisotopicMass().has_value() ) { lval = std::abs(l->getScanPrecursorMass() - l->getPeptideMonisotopicMass().value()); } if ( r->getPeptideMonisotopicMass().has_value() ) { rval = std::abs(r->getScanPrecursorMass() - r->getPeptideMonisotopicMass().value()); } return rval < lval; }); } } else //sort by score { #ifdef ORIG psms = psms.OrderByDescending([&] (std::any b) { b::Score; }).ThenBy([&] (std::any b) { b::PeptideMonisotopicMass.HasValue ? std::abs(b::ScanPrecursorMass - b::PeptideMonisotopicMass->Value) : std::numeric_limits<double>::max(); }).ToList(); #endif //OrderByDescending and ThenBy std::stable_sort (psms.begin(), psms.end(), [&] (PeptideSpectralMatch *r, PeptideSpectralMatch *l) { if ( r->getScore() > l->getScore() ) return true; if ( r->getScore() < l->getScore() ) return false; double lval= std::numeric_limits<double>::max(), rval=std::numeric_limits<double>::max(); if ( l->getPeptideMonisotopicMass().has_value() ) { lval = std::abs(l->getScanPrecursorMass() - l->getPeptideMonisotopicMass().value()); } if ( r->getPeptideMonisotopicMass().has_value() ) { rval = std::abs(r->getScanPrecursorMass() - r->getPeptideMonisotopicMass().value()); } return rval < lval; }); } double cumulativeTarget = 0; double cumulativeDecoy = 0; //set up arrays for local FDRs std::vector<double> cumulativeTargetPerNotch(MassDiffAcceptorNumNotches + 1); std::vector<double> cumulativeDecoyPerNotch(MassDiffAcceptorNumNotches + 1); //Assign FDR values to PSMs for (int i = 0; i < (int)psms.size(); i++) { // Stop if canceled if (GlobalVariables::getStopLoops()) { break; } PeptideSpectralMatch *psm = psms[i]; std::optional<int> tempVar = psm->getNotch(); int notch = tempVar.has_value() ? tempVar.value() : MassDiffAcceptorNumNotches; if (psm->getIsDecoy()) { // the PSM can be ambiguous between a target and a decoy sequence // in that case, count it as the fraction of decoy hits // e.g. if the PSM matched to 1 target and 2 decoys, it counts as 2/3 decoy double decoyHits = 0; double totalHits = 0; #ifdef ORIG auto hits = psm->BestMatchingPeptides.GroupBy([&] (std::any p) { p::Peptide::FullSequence; }); #endif std::vector<std::vector<std::tuple<int, PeptideWithSetModifications *>>>hits; int current =0; std::string currFullSequence, prevFullSequence; auto tmpsms = psm->getBestMatchingPeptides(); for ( auto p = tmpsms.begin(); p != tmpsms.end(); p++ ) { if ( p == tmpsms.begin() ) { std::vector<std::tuple<int, PeptideWithSetModifications *>> *v = new std::vector<std::tuple<int, PeptideWithSetModifications *>>; hits.push_back(*v); prevFullSequence = std::get<1>(*p)->getFullSequence(); } else { auto q = p - 1; currFullSequence = std::get<1>(*p)->getFullSequence(); if ( currFullSequence != prevFullSequence ) { std::vector<std::tuple<int, PeptideWithSetModifications *>> *v = new std::vector<std::tuple<int, PeptideWithSetModifications *>>; hits.push_back(*v); current++; prevFullSequence = currFullSequence; } } hits[current].push_back(*p); } for (auto hit : hits) { #ifdef ORIG if (hit->First().Peptide.Protein.IsDecoy) #endif if (std::get<1>(hit.front())->getProtein()->getIsDecoy()) { decoyHits++; } totalHits++; } cumulativeDecoy += decoyHits / totalHits; cumulativeDecoyPerNotch[notch] += decoyHits / totalHits; } else { cumulativeTarget++; cumulativeTargetPerNotch[notch]++; } double qValue = std::min(1.0, cumulativeDecoy / cumulativeTarget); double qValueNotch = std::min(1.0, cumulativeDecoyPerNotch[notch] / cumulativeTargetPerNotch[notch]); double maximumLikelihood = 0; double eValue = 0; double eScore = 0; if (CalculateEValue) { eValue = GetEValue(psm, globalMeanCount, globalMeanScore, maximumLikelihood); //eScore = -Math::Log(eValue, 10); eScore = -log10(eValue); } psm->SetFdrValues(cumulativeTarget, cumulativeDecoy, qValue, cumulativeTargetPerNotch[notch], cumulativeDecoyPerNotch[notch], qValueNotch, maximumLikelihood, eValue, eScore, CalculateEValue); } // set q-value thresholds such that a lower scoring PSM can't have // a higher confidence than a higher scoring PSM //Populate min qValues double qValueThreshold = 1.0; std::vector<double> qValueNotchThreshold(MassDiffAcceptorNumNotches + 1); for (int i = 0; i < (int)qValueNotchThreshold.size(); i++) { qValueNotchThreshold[i] = 1.0; } for (int i = (int)psms.size() - 1; i >= 0; i--) { PeptideSpectralMatch *psm = psms[i]; // threshold q-values if (psm->getFdrInfo()->getQValue() > qValueThreshold) { psm->getFdrInfo()->setQValue(qValueThreshold); } else if (psm->getFdrInfo()->getQValue() < qValueThreshold) { qValueThreshold = psm->getFdrInfo()->getQValue(); } // threshold notch q-values std::optional<int> tempVar2 = psm->getNotch(); int notch = tempVar2.has_value() ? tempVar2.value() : MassDiffAcceptorNumNotches; if (psm->getFdrInfo()->getQValueNotch() > qValueNotchThreshold[notch]) { psm->getFdrInfo()->setQValueNotch(qValueNotchThreshold[notch]); } else if (psm->getFdrInfo()->getQValueNotch() < qValueNotchThreshold[notch]) { qValueNotchThreshold[notch] = psm->getFdrInfo()->getQValueNotch(); } } } } double FdrAnalysisEngine::GetEValue(PeptideSpectralMatch *psm, int globalMeanCount, double globalMeanScore, double &maximumLikelihood) { // get all of the PSM's scores for all hits, sort them, then remove the last value (the best score) std::vector<double> scoresWithoutBestHit; scoresWithoutBestHit.insert(scoresWithoutBestHit.end(), psm->getAllScores().begin(), psm->getAllScores().end()); std::sort(scoresWithoutBestHit.begin(), scoresWithoutBestHit.end()); #ifdef ORIG if (scoresWithoutBestHit.Any()) #endif if (!scoresWithoutBestHit.empty()) { scoresWithoutBestHit.pop_back(); } // this is the "default" case for when there are no scores except the best hit // it uses a global mean score (all scores across all PSMs) to generate the null Poisson distribution // this will be overriden by the next few lines if there are enough scores in this PSM to estimate a null distribution //double preValue = SpecialFunctions::GammaLowerRegularized(globalMeanScore, psm->getScore()); //Edgar Note: the boost gamma lower regularized function gamma_p does not accept the first argument to be 0. // I verified with the C# version that the result returned by SpecialFunctions::GammaLowerRegularized // is in that case 1, independent of the second argument. Mimicking the same here. double preValue = 1; if ( globalMeanScore > 0 ) { preValue = boost::math::gamma_p (globalMeanScore, psm->getScore()); } maximumLikelihood = globalMeanScore; // calculate single-spectrum evalue if there are enough hits besides the best scoring peptide if (psm->getScore() == 0) { preValue = 1; maximumLikelihood = 0; } #ifdef ORIG else if (scoresWithoutBestHit.Any()) #endif else if (!scoresWithoutBestHit.empty()) { //maximumLikelihood = scoresWithoutBestHit.Average(); maximumLikelihood = std::accumulate(scoresWithoutBestHit.begin(), scoresWithoutBestHit.end(), 0.0)/scoresWithoutBestHit.size(); // this is the cumulative distribution for the poisson at each score up to but not including the score of the winner. // This is the probability that the winner has of getting that score at random by matching against a SINGLE spectrum if (maximumLikelihood > 0) { //preValue = SpecialFunctions::GammaLowerRegularized(maximumLikelihood, psm->getScore()); //preValue = Math::GammaLowerRegularized(maximumLikelihood, psm->getScore()); preValue = boost::math::gamma_p ( maximumLikelihood, psm->getScore()); } } // Now the probability of getting the winner's score goes up for each spectrum match. // We multiply the preValue by the number of theoretical spectrum within the tolerance to get this new probability. int count = scoresWithoutBestHit.size(); if (count == 0) { count = globalMeanCount; } double probabilityOfScore = 1 - std::pow(preValue, count); return count * probabilityOfScore; } int FdrAnalysisEngine::GetNumPSMsAtqValueCutoff(std::vector<PeptideSpectralMatch*> &psms, double qValueCutoff) { int cumulative_target = 0; int cumulative_decoy = 0; for (auto psm : psms) { if (psm->getIsDecoy()) { cumulative_decoy++; if (static_cast<double>(cumulative_decoy) / cumulative_target >= qValueCutoff) { return cumulative_target; } } else { cumulative_target++; } } return cumulative_target; } } }
51.028037
176
0.458828
[ "vector" ]
af0eaf321df04eee1b8d22af442db69f44d429d3
12,511
cpp
C++
logos/bootstrap/connection.cpp
LogosNetwork/logos-core
6b155539a734efefb8f649a761d044b5f267a51a
[ "BSD-2-Clause" ]
3
2020-01-17T18:05:19.000Z
2021-12-29T04:21:59.000Z
logos/bootstrap/connection.cpp
LogosNetwork/logos-core
6b155539a734efefb8f649a761d044b5f267a51a
[ "BSD-2-Clause" ]
null
null
null
logos/bootstrap/connection.cpp
LogosNetwork/logos-core
6b155539a734efefb8f649a761d044b5f267a51a
[ "BSD-2-Clause" ]
2
2020-12-22T05:51:53.000Z
2021-06-08T00:27:46.000Z
#include <logos/bootstrap/bootstrap_messages.hpp> #include <logos/bootstrap/connection.hpp> #include <logos/bootstrap/pull_connection.hpp> #include <logos/bootstrap/tip_connection.hpp> #include <logos/bootstrap/attempt.hpp> #include <boost/asio/buffer.hpp> namespace Bootstrap { SocketTimeout::SocketTimeout (Socket & socket) : ticket (0) , socket (socket) {} void SocketTimeout::start (std::chrono::steady_clock::time_point timeout_a) { auto ticket_l (++ticket); std::weak_ptr<Socket> socket_w (socket.shared ()); socket.alarm.add (timeout_a, [socket_w, ticket_l]() { // NOTE: If we timeout, we disconnect. if (auto socket_l = socket_w.lock ()) { if (socket_l->timeout.ticket == ticket_l) { socket_l->OnNetworkError(); LOG_DEBUG(socket_l->log) << "timeout: " <<"remote_endpoint " << socket_l->peer; } } }); } void SocketTimeout::stop () { LOG_DEBUG(socket.log) << "socket_timeout::stop:"; ++ticket; } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// using BoostError = boost::system::error_code; Socket::Socket(logos::tcp_endpoint & endpoint, logos::alarm & alarm) : peer(endpoint) , alarm(alarm) , socket(alarm.service) , timeout (*this) , disconnected(true) { LOG_TRACE(log) << "bootstrap_socket::"<<__func__ << " client side"; } Socket::Socket(boost::asio::ip::tcp::socket &socket_a, logos::alarm & alarm) : peer(socket_a.remote_endpoint()) , alarm(alarm) , socket(std::move(socket_a)) , timeout (*this) , disconnected(true) { LOG_TRACE(log) << "bootstrap_socket::"<<__func__ << " server side"; } Socket::~Socket() { LOG_TRACE(log) << "bootstrap_socket::"<<__func__; Disconnect(); } void Socket::Connect (std::function<void(bool)> ConnectComplete) { LOG_TRACE(log) << "bootstrap_socket::"<<__func__ << " this: " << this << " timeout_ms: " << CONNECT_TIMEOUT_MS; timeout.start (std::chrono::steady_clock::now () + std::chrono::milliseconds(CONNECT_TIMEOUT_MS)); auto this_l = shared(); socket.async_connect (peer, [this, this_l, ConnectComplete](BoostError const & ec) { timeout.stop(); if (!ec) { LOG_TRACE(log) << "Socket::connect: connected"; { std::lock_guard<std::mutex> lock(mtx); disconnected = false; } ConnectComplete(true); } else { LOG_ERROR(log) << "Socket::connect: network error: ec.message: " << ec.message(); ConnectComplete(false); } }); } void Socket::Disconnect() { /* * From boost doc: * Note that, even if the function indicates an error, the underlying descriptor is closed. * To graceful closure of a connected socket, call shutdown() before closing the socket. */ std::lock_guard<std::mutex> lock(mtx); if(!disconnected) { LOG_TRACE(log) << "Socket::Disconnect " << this; disconnected = true; BoostError ec; socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); socket.close (ec); } } void Socket::AsyncSend(std::shared_ptr<std::vector<uint8_t>> buf, SendComplete cb, uint32_t timeout_ms) { LOG_TRACE(log) << "Socket::"<<__func__ << " this: " << this << " timeout_ms: " << timeout_ms; if(timeout_ms > timeout_disabled) { timeout.start (std::chrono::steady_clock::now () + std::chrono::milliseconds(timeout_ms)); } boost::asio::async_write (socket, boost::asio::buffer(buf->data(), buf->size()), [this, cb, timeout_ms](BoostError const & ec, size_t size_a) { if(timeout_ms > timeout_disabled) { timeout.stop(); } if (!ec) { LOG_TRACE(log) << "Socket::AsyncSend: sent data, size=" << size_a; cb(true); }else{ LOG_ERROR(log) << "Socket::AsyncSend: Network error " << ec.message (); cb(false); } }); } void Socket::AsyncReceive(ReceiveComplete cb, uint32_t timeout_ms) { LOG_TRACE(log) << "Socket::"<<__func__ << " this: " << this << " timeout_ms: " << timeout_ms; if(timeout_ms > timeout_disabled) { timeout.start (std::chrono::steady_clock::now () + std::chrono::milliseconds(timeout_ms)); } boost::asio::async_read (socket, boost::asio::buffer(header_buf.data (), MessageHeader::WireSize), [this, cb, timeout_ms](BoostError const & ec, size_t size_a) { if (!ec) { LOG_TRACE(log) << "Socket::AsyncReceive received header data"; assert (size_a == MessageHeader::WireSize); logos::bufferstream stream (header_buf.data (), size_a); bool error = false; MessageHeader header(error, stream); if(error || ! header.Validate()) { LOG_ERROR(log) << "Socket::AsyncReceive Header error"; cb(false, header, nullptr); return; } boost::asio::async_read (socket, boost::asio::buffer(receive_buf.data(), header.payload_size), [this, cb, timeout_ms, header](BoostError const & ec, size_t size_a) { if(timeout_ms > timeout_disabled) { timeout.stop(); } if (!ec) { LOG_TRACE(log) << "Socket::AsyncReceive received data"; assert (size_a == header.payload_size); cb(true, header, receive_buf.data()); }else{ LOG_ERROR(log) << "Socket::AsyncReceive Network error " << ec.message (); cb(false, header, nullptr); return; } }); }else{ LOG_ERROR(log) << "Socket::AsyncReceive Network error " << ec.message (); MessageHeader header; cb(false, header, nullptr); return; } }); } std::shared_ptr<Socket> Socket::shared () { auto x = shared_from_this(); return x; } boost::asio::ip::address Socket::PeerAddress() const { return peer.address(); } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// BootstrapClient::BootstrapClient (BootstrapAttempt & attempt_a, logos::tcp_endpoint & endpoint_a) : Socket (endpoint_a, attempt_a.alarm) , attempt (attempt_a) { LOG_TRACE(log) << "bootstrap_client::"<<__func__; } BootstrapClient::~BootstrapClient () { LOG_TRACE(log) << "bootstrap_client::"<<__func__; } void BootstrapClient::OnNetworkError(bool black_list) { LOG_TRACE(log) << "bootstrap_client::"<<__func__<< " this=" <<this; Socket::Disconnect(); attempt.remove_connection(shared(), black_list); } void BootstrapClient::Release() { LOG_TRACE(log) << "bootstrap_client::"<<__func__<< " this=" <<this; attempt.pool_connection(shared()); } std::shared_ptr<BootstrapClient> BootstrapClient::shared () { //LOG_TRACE(log) << "bootstrap_client::"<<__func__; return shared_from_base<BootstrapClient>(); } //////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// BootstrapServer::BootstrapServer (BootstrapListener & listener, BoostSocket & socket_a, Store & store) : Socket (socket_a, listener.alarm) , listener(listener) , store (store) { LOG_TRACE(log) << "bootstrap_server::"<<__func__; } BootstrapServer::~BootstrapServer () { LOG_TRACE(log) << "bootstrap_server::"<<__func__; } void BootstrapServer::receive_request () { LOG_TRACE(log) << "bootstrap_server::"<<__func__; auto this_l = shared(); AsyncReceive([this, this_l](bool good, MessageHeader header, uint8_t * buf) { dispatch(good, header, buf); }); } void BootstrapServer::OnNetworkError(bool black_list) { LOG_TRACE(log) << "bootstrap_server::"<<__func__<< " this=" <<this; Socket::Disconnect(); listener.remove_connection(shared());//server does not black list } void BootstrapServer::Release() { LOG_TRACE(log) << "bootstrap_server::"<<__func__<< " this=" <<this; receive_request (); } void BootstrapServer::dispatch (bool good, MessageHeader header, uint8_t * buf) { LOG_TRACE(log) << "bootstrap_server::"<<__func__ <<" good=" << good; bool error = false; if (good) { #ifdef DUMP_BLOCK_DATA //TODO delete after integration tests { std::stringstream stream; for(size_t i = 0; i < header.payload_size; ++i) { stream << std::hex << std::noshowbase << std::setw (2) << std::setfill ('0') << (unsigned int)(buf[i]); } LOG_TRACE(log) << "bootstrap_server::"<<__func__ <<" data:" << stream.str (); } #endif logos::bufferstream stream (buf, header.payload_size); switch (header.type) { case MessageType::TipRequest: { TipSet request(error, stream); if(!error) { LOG_TRACE(log) << "bootstrap_server::"<<__func__ <<" tip request parsed"; auto tip_server( std::make_shared<TipServer>(shared_from_this(), request, store)); tip_server->send_tips(); } else LOG_TRACE(log) << "bootstrap_server::"<<__func__ <<" tip request parse error"; break; } case MessageType::PullRequest: { PullRequest pull(error, stream); if(!error) { LOG_TRACE(log) << "bootstrap_server::"<<__func__ <<" pull request parsed"; auto pull_server( std::make_shared<PullServer>(shared_from_this(), pull, store)); pull_server->send_block(); } else LOG_TRACE(log) << "bootstrap_server::"<<__func__ <<" pull request parse error"; break; } default: error = true; break; } } else error = true; if(error) OnNetworkError(); } std::shared_ptr<BootstrapServer> BootstrapServer::shared () { return shared_from_base<BootstrapServer>(); } }
36.369186
123
0.468548
[ "vector" ]
af1439520f729756ba81d2d3b87f4d4f825b5f9b
30,449
cc
C++
android/art/tools/hiddenapi/hiddenapi_test.cc
Solotov/deoptfuscator
8a54119e81517bcef73d2d6dfefba910ae2446e7
[ "MIT" ]
206
2020-04-13T03:19:33.000Z
2022-03-27T13:52:25.000Z
android/art/tools/hiddenapi/hiddenapi_test.cc
Solotov/deoptfuscator
8a54119e81517bcef73d2d6dfefba910ae2446e7
[ "MIT" ]
9
2020-06-07T12:51:09.000Z
2022-03-28T23:55:09.000Z
android/art/tools/hiddenapi/hiddenapi_test.cc
Solotov/deoptfuscator
8a54119e81517bcef73d2d6dfefba910ae2446e7
[ "MIT" ]
42
2020-04-13T03:37:58.000Z
2022-03-23T15:08:12.000Z
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <fstream> #include "base/unix_file/fd_file.h" #include "common_runtime_test.h" #include "dex/art_dex_file_loader.h" #include "dex/dex_file-inl.h" #include "exec_utils.h" #include "zip_archive.h" namespace art { class HiddenApiTest : public CommonRuntimeTest { protected: std::string GetHiddenApiCmd() { std::string file_path = GetTestAndroidRoot(); file_path += "/bin/hiddenapi"; if (kIsDebugBuild) { file_path += "d"; } if (!OS::FileExists(file_path.c_str())) { LOG(FATAL) << "Could not find binary " << file_path; UNREACHABLE(); } return file_path; } std::unique_ptr<const DexFile> RunHiddenApi(const ScratchFile& light_greylist, const ScratchFile& dark_greylist, const ScratchFile& blacklist, const std::vector<std::string>& extra_args, ScratchFile* out_dex) { std::string error; std::unique_ptr<ZipArchive> jar( ZipArchive::Open(GetTestDexFileName("HiddenApi").c_str(), &error)); if (jar == nullptr) { LOG(FATAL) << "Could not open test file " << GetTestDexFileName("HiddenApi") << ": " << error; UNREACHABLE(); } std::unique_ptr<ZipEntry> jar_classes_dex(jar->Find("classes.dex", &error)); if (jar_classes_dex == nullptr) { LOG(FATAL) << "Could not find classes.dex in test file " << GetTestDexFileName("HiddenApi") << ": " << error; UNREACHABLE(); } else if (!jar_classes_dex->ExtractToFile(*out_dex->GetFile(), &error)) { LOG(FATAL) << "Could not extract classes.dex from test file " << GetTestDexFileName("HiddenApi") << ": " << error; UNREACHABLE(); } std::vector<std::string> argv_str; argv_str.push_back(GetHiddenApiCmd()); argv_str.insert(argv_str.end(), extra_args.begin(), extra_args.end()); argv_str.push_back("--dex=" + out_dex->GetFilename()); argv_str.push_back("--light-greylist=" + light_greylist.GetFilename()); argv_str.push_back("--dark-greylist=" + dark_greylist.GetFilename()); argv_str.push_back("--blacklist=" + blacklist.GetFilename()); int return_code = ExecAndReturnCode(argv_str, &error); if (return_code != 0) { LOG(FATAL) << "HiddenApi binary exited with unexpected return code " << return_code; } return OpenDex(*out_dex); } std::unique_ptr<const DexFile> OpenDex(const ScratchFile& file) { ArtDexFileLoader dex_loader; std::string error_msg; File fd(file.GetFilename(), O_RDONLY, /* check_usage */ false); if (fd.Fd() == -1) { LOG(FATAL) << "Unable to open file '" << file.GetFilename() << "': " << strerror(errno); UNREACHABLE(); } std::unique_ptr<const DexFile> dex_file(dex_loader.OpenDex( fd.Release(), /* location */ file.GetFilename(), /* verify */ false, /* verify_checksum */ true, /* mmap_shared */ false, &error_msg)); if (dex_file.get() == nullptr) { LOG(FATAL) << "Open failed for '" << file.GetFilename() << "' " << error_msg; UNREACHABLE(); } else if (!dex_file->IsStandardDexFile()) { LOG(FATAL) << "Expected a standard dex file '" << file.GetFilename() << "'"; UNREACHABLE(); } return dex_file; } std::ofstream OpenStream(const ScratchFile& file) { std::ofstream ofs(file.GetFilename(), std::ofstream::out); if (ofs.fail()) { LOG(FATAL) << "Open failed for '" << file.GetFilename() << "' " << strerror(errno); UNREACHABLE(); } return ofs; } const DexFile::ClassDef& FindClass(const char* desc, const DexFile& dex_file) { for (uint32_t i = 0; i < dex_file.NumClassDefs(); ++i) { const DexFile::ClassDef& class_def = dex_file.GetClassDef(i); if (strcmp(desc, dex_file.GetClassDescriptor(class_def)) == 0) { return class_def; } } LOG(FATAL) << "Could not find class " << desc; UNREACHABLE(); } HiddenApiAccessFlags::ApiList GetFieldHiddenFlags(const char* name, uint32_t expected_visibility, const DexFile::ClassDef& class_def, const DexFile& dex_file) { const uint8_t* class_data = dex_file.GetClassData(class_def); if (class_data == nullptr) { LOG(FATAL) << "Class " << dex_file.GetClassDescriptor(class_def) << " has no data"; UNREACHABLE(); } for (ClassDataItemIterator it(dex_file, class_data); it.HasNext(); it.Next()) { if (it.IsAtMethod()) { break; } const DexFile::FieldId& fid = dex_file.GetFieldId(it.GetMemberIndex()); if (strcmp(name, dex_file.GetFieldName(fid)) == 0) { uint32_t actual_visibility = it.GetFieldAccessFlags() & kAccVisibilityFlags; if (actual_visibility != expected_visibility) { LOG(FATAL) << "Field " << name << " in class " << dex_file.GetClassDescriptor(class_def) << " does not have the expected visibility flags (" << expected_visibility << " != " << actual_visibility << ")"; UNREACHABLE(); } return it.DecodeHiddenAccessFlags(); } } LOG(FATAL) << "Could not find field " << name << " in class " << dex_file.GetClassDescriptor(class_def); UNREACHABLE(); } HiddenApiAccessFlags::ApiList GetMethodHiddenFlags(const char* name, uint32_t expected_visibility, bool expected_native, const DexFile::ClassDef& class_def, const DexFile& dex_file) { const uint8_t* class_data = dex_file.GetClassData(class_def); if (class_data == nullptr) { LOG(FATAL) << "Class " << dex_file.GetClassDescriptor(class_def) << " has no data"; UNREACHABLE(); } for (ClassDataItemIterator it(dex_file, class_data); it.HasNext(); it.Next()) { if (!it.IsAtMethod()) { continue; } const DexFile::MethodId& mid = dex_file.GetMethodId(it.GetMemberIndex()); if (strcmp(name, dex_file.GetMethodName(mid)) == 0) { if (expected_native != it.MemberIsNative()) { LOG(FATAL) << "Expected native=" << expected_native << " for method " << name << " in class " << dex_file.GetClassDescriptor(class_def); UNREACHABLE(); } uint32_t actual_visibility = it.GetMethodAccessFlags() & kAccVisibilityFlags; if (actual_visibility != expected_visibility) { LOG(FATAL) << "Method " << name << " in class " << dex_file.GetClassDescriptor(class_def) << " does not have the expected visibility flags (" << expected_visibility << " != " << actual_visibility << ")"; UNREACHABLE(); } return it.DecodeHiddenAccessFlags(); } } LOG(FATAL) << "Could not find method " << name << " in class " << dex_file.GetClassDescriptor(class_def); UNREACHABLE(); } HiddenApiAccessFlags::ApiList GetIFieldHiddenFlags(const DexFile& dex_file) { return GetFieldHiddenFlags("ifield", kAccPublic, FindClass("LMain;", dex_file), dex_file); } HiddenApiAccessFlags::ApiList GetSFieldHiddenFlags(const DexFile& dex_file) { return GetFieldHiddenFlags("sfield", kAccPrivate, FindClass("LMain;", dex_file), dex_file); } HiddenApiAccessFlags::ApiList GetIMethodHiddenFlags(const DexFile& dex_file) { return GetMethodHiddenFlags( "imethod", 0, /* native */ false, FindClass("LMain;", dex_file), dex_file); } HiddenApiAccessFlags::ApiList GetSMethodHiddenFlags(const DexFile& dex_file) { return GetMethodHiddenFlags( "smethod", kAccPublic, /* native */ false, FindClass("LMain;", dex_file), dex_file); } HiddenApiAccessFlags::ApiList GetINMethodHiddenFlags(const DexFile& dex_file) { return GetMethodHiddenFlags( "inmethod", kAccPublic, /* native */ true, FindClass("LMain;", dex_file), dex_file); } HiddenApiAccessFlags::ApiList GetSNMethodHiddenFlags(const DexFile& dex_file) { return GetMethodHiddenFlags( "snmethod", kAccProtected, /* native */ true, FindClass("LMain;", dex_file), dex_file); } }; TEST_F(HiddenApiTest, InstanceFieldNoMatch) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->ifield:LBadType1;" << std::endl; OpenStream(dark_greylist) << "LMain;->ifield:LBadType2;" << std::endl; OpenStream(blacklist) << "LMain;->ifield:LBadType3;" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kWhitelist, GetIFieldHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, InstanceFieldLightGreylistMatch) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->ifield:I" << std::endl; OpenStream(dark_greylist) << "LMain;->ifield:LBadType2;" << std::endl; OpenStream(blacklist) << "LMain;->ifield:LBadType3;" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kLightGreylist, GetIFieldHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, InstanceFieldDarkGreylistMatch) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->ifield:LBadType1;" << std::endl; OpenStream(dark_greylist) << "LMain;->ifield:I" << std::endl; OpenStream(blacklist) << "LMain;->ifield:LBadType3;" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kDarkGreylist, GetIFieldHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, InstanceFieldBlacklistMatch) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->ifield:LBadType1;" << std::endl; OpenStream(dark_greylist) << "LMain;->ifield:LBadType2;" << std::endl; OpenStream(blacklist) << "LMain;->ifield:I" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kBlacklist, GetIFieldHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, InstanceFieldTwoListsMatch1) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->ifield:LBadType1;" << std::endl; OpenStream(dark_greylist) << "LMain;->ifield:I" << std::endl; OpenStream(blacklist) << "LMain;->ifield:I" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kBlacklist, GetIFieldHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, InstanceFieldTwoListsMatch2) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->ifield:I" << std::endl; OpenStream(dark_greylist) << "LMain;->ifield:LBadType2;" << std::endl; OpenStream(blacklist) << "LMain;->ifield:I" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kBlacklist, GetIFieldHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, InstanceFieldTwoListsMatch3) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->ifield:I" << std::endl; OpenStream(dark_greylist) << "LMain;->ifield:I" << std::endl; OpenStream(blacklist) << "LMain;->ifield:LBadType3;" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kDarkGreylist, GetIFieldHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, StaticFieldNoMatch) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->sfield:LBadType1;" << std::endl; OpenStream(dark_greylist) << "LMain;->sfield:LBadType2;" << std::endl; OpenStream(blacklist) << "LMain;->sfield:LBadType3;" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kWhitelist, GetSFieldHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, StaticFieldLightGreylistMatch) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->sfield:Ljava/lang/Object;" << std::endl; OpenStream(dark_greylist) << "LMain;->sfield:LBadType2;" << std::endl; OpenStream(blacklist) << "LMain;->sfield:LBadType3;" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kLightGreylist, GetSFieldHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, StaticFieldDarkGreylistMatch) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->sfield:LBadType1;" << std::endl; OpenStream(dark_greylist) << "LMain;->sfield:Ljava/lang/Object;" << std::endl; OpenStream(blacklist) << "LMain;->sfield:LBadType3;" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kDarkGreylist, GetSFieldHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, StaticFieldBlacklistMatch) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->sfield:LBadType1;" << std::endl; OpenStream(dark_greylist) << "LMain;->sfield:LBadType2;" << std::endl; OpenStream(blacklist) << "LMain;->sfield:Ljava/lang/Object;" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kBlacklist, GetSFieldHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, StaticFieldTwoListsMatch1) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->sfield:LBadType1;" << std::endl; OpenStream(dark_greylist) << "LMain;->sfield:Ljava/lang/Object;" << std::endl; OpenStream(blacklist) << "LMain;->sfield:Ljava/lang/Object;" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kBlacklist, GetSFieldHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, StaticFieldTwoListsMatch2) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->sfield:Ljava/lang/Object;" << std::endl; OpenStream(dark_greylist) << "LMain;->sfield:LBadType2;" << std::endl; OpenStream(blacklist) << "LMain;->sfield:Ljava/lang/Object;" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kBlacklist, GetSFieldHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, StaticFieldTwoListsMatch3) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->sfield:Ljava/lang/Object;" << std::endl; OpenStream(dark_greylist) << "LMain;->sfield:Ljava/lang/Object;" << std::endl; OpenStream(blacklist) << "LMain;->sfield:LBadType3;" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kDarkGreylist, GetSFieldHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, InstanceMethodNoMatch) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->imethod(LBadType1;)V" << std::endl; OpenStream(dark_greylist) << "LMain;->imethod(LBadType2;)V" << std::endl; OpenStream(blacklist) << "LMain;->imethod(LBadType3;)V" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kWhitelist, GetIMethodHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, InstanceMethodLightGreylistMatch) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->imethod(J)V" << std::endl; OpenStream(dark_greylist) << "LMain;->imethod(LBadType2;)V" << std::endl; OpenStream(blacklist) << "LMain;->imethod(LBadType3;)V" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kLightGreylist, GetIMethodHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, InstanceMethodDarkGreylistMatch) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->imethod(LBadType1;)V" << std::endl; OpenStream(dark_greylist) << "LMain;->imethod(J)V" << std::endl; OpenStream(blacklist) << "LMain;->imethod(LBadType3;)V" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kDarkGreylist, GetIMethodHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, InstanceMethodBlacklistMatch) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->imethod(LBadType1;)V" << std::endl; OpenStream(dark_greylist) << "LMain;->imethod(LBadType2;)V" << std::endl; OpenStream(blacklist) << "LMain;->imethod(J)V" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kBlacklist, GetIMethodHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, InstanceMethodTwoListsMatch1) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->imethod(LBadType1;)V" << std::endl; OpenStream(dark_greylist) << "LMain;->imethod(J)V" << std::endl; OpenStream(blacklist) << "LMain;->imethod(J)V" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kBlacklist, GetIMethodHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, InstanceMethodTwoListsMatch2) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->imethod(J)V" << std::endl; OpenStream(dark_greylist) << "LMain;->imethod(LBadType2;)V" << std::endl; OpenStream(blacklist) << "LMain;->imethod(J)V" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kBlacklist, GetIMethodHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, InstanceMethodTwoListsMatch3) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->imethod(J)V" << std::endl; OpenStream(dark_greylist) << "LMain;->imethod(J)V" << std::endl; OpenStream(blacklist) << "LMain;->imethod(LBadType3;)V" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kDarkGreylist, GetIMethodHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, StaticMethodNoMatch) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->smethod(LBadType1;)V" << std::endl; OpenStream(dark_greylist) << "LMain;->smethod(LBadType2;)V" << std::endl; OpenStream(blacklist) << "LMain;->smethod(LBadType3;)V" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kWhitelist, GetSMethodHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, StaticMethodLightGreylistMatch) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->smethod(Ljava/lang/Object;)V" << std::endl; OpenStream(dark_greylist) << "LMain;->smethod(LBadType2;)V" << std::endl; OpenStream(blacklist) << "LMain;->smethod(LBadType3;)V" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kLightGreylist, GetSMethodHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, StaticMethodDarkGreylistMatch) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->smethod(LBadType1;)V" << std::endl; OpenStream(dark_greylist) << "LMain;->smethod(Ljava/lang/Object;)V" << std::endl; OpenStream(blacklist) << "LMain;->smethod(LBadType3;)V" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kDarkGreylist, GetSMethodHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, StaticMethodBlacklistMatch) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->smethod(LBadType1;)V" << std::endl; OpenStream(dark_greylist) << "LMain;->smethod(LBadType2;)V" << std::endl; OpenStream(blacklist) << "LMain;->smethod(Ljava/lang/Object;)V" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kBlacklist, GetSMethodHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, StaticMethodTwoListsMatch1) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->smethod(LBadType1;)V" << std::endl; OpenStream(dark_greylist) << "LMain;->smethod(Ljava/lang/Object;)V" << std::endl; OpenStream(blacklist) << "LMain;->smethod(Ljava/lang/Object;)V" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kBlacklist, GetSMethodHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, StaticMethodTwoListsMatch2) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->smethod(Ljava/lang/Object;)V" << std::endl; OpenStream(dark_greylist) << "LMain;->smethod(LBadType2;)V" << std::endl; OpenStream(blacklist) << "LMain;->smethod(Ljava/lang/Object;)V" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kBlacklist, GetSMethodHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, StaticMethodTwoListsMatch3) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->smethod(Ljava/lang/Object;)V" << std::endl; OpenStream(dark_greylist) << "LMain;->smethod(Ljava/lang/Object;)V" << std::endl; OpenStream(blacklist) << "LMain;->smethod(LBadType3;)V" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kDarkGreylist, GetSMethodHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, InstanceNativeMethodNoMatch) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->inmethod(LBadType1;)V" << std::endl; OpenStream(dark_greylist) << "LMain;->inmethod(LBadType2;)V" << std::endl; OpenStream(blacklist) << "LMain;->inmethod(LBadType3;)V" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kWhitelist, GetINMethodHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, InstanceNativeMethodLightGreylistMatch) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->inmethod(C)V" << std::endl; OpenStream(dark_greylist) << "LMain;->inmethod(LBadType2;)V" << std::endl; OpenStream(blacklist) << "LMain;->inmethod(LBadType3;)V" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kLightGreylist, GetINMethodHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, InstanceNativeMethodDarkGreylistMatch) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->inmethod(LBadType1;)V" << std::endl; OpenStream(dark_greylist) << "LMain;->inmethod(C)V" << std::endl; OpenStream(blacklist) << "LMain;->inmethod(LBadType3;)V" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kDarkGreylist, GetINMethodHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, InstanceNativeMethodBlacklistMatch) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->inmethod(LBadType1;)V" << std::endl; OpenStream(dark_greylist) << "LMain;->inmethod(LBadType2;)V" << std::endl; OpenStream(blacklist) << "LMain;->inmethod(C)V" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kBlacklist, GetINMethodHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, InstanceNativeMethodTwoListsMatch1) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->inmethod(LBadType1;)V" << std::endl; OpenStream(dark_greylist) << "LMain;->inmethod(C)V" << std::endl; OpenStream(blacklist) << "LMain;->inmethod(C)V" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kBlacklist, GetINMethodHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, InstanceNativeMethodTwoListsMatch2) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->inmethod(C)V" << std::endl; OpenStream(dark_greylist) << "LMain;->inmethod(LBadType2;)V" << std::endl; OpenStream(blacklist) << "LMain;->inmethod(C)V" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kBlacklist, GetINMethodHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, InstanceNativeMethodTwoListsMatch3) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->inmethod(C)V" << std::endl; OpenStream(dark_greylist) << "LMain;->inmethod(C)V" << std::endl; OpenStream(blacklist) << "LMain;->inmethod(LBadType3;)V" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kDarkGreylist, GetINMethodHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, StaticNativeMethodNoMatch) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->snmethod(LBadType1;)V" << std::endl; OpenStream(dark_greylist) << "LMain;->snmethod(LBadType2;)V" << std::endl; OpenStream(blacklist) << "LMain;->snmethod(LBadType3;)V" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kWhitelist, GetSNMethodHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, StaticNativeMethodLightGreylistMatch) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->snmethod(Ljava/lang/Integer;)V" << std::endl; OpenStream(dark_greylist) << "LMain;->snmethod(LBadType2;)V" << std::endl; OpenStream(blacklist) << "LMain;->snmethod(LBadType3;)V" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kLightGreylist, GetSNMethodHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, StaticNativeMethodDarkGreylistMatch) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->snmethod(LBadType1;)V" << std::endl; OpenStream(dark_greylist) << "LMain;->snmethod(Ljava/lang/Integer;)V" << std::endl; OpenStream(blacklist) << "LMain;->snmethod(LBadType3;)V" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kDarkGreylist, GetSNMethodHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, StaticNativeMethodBlacklistMatch) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->snmethod(LBadType1;)V" << std::endl; OpenStream(dark_greylist) << "LMain;->snmethod(LBadType2;)V" << std::endl; OpenStream(blacklist) << "LMain;->snmethod(Ljava/lang/Integer;)V" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kBlacklist, GetSNMethodHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, StaticNativeMethodTwoListsMatch1) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->snmethod(LBadType1;)V" << std::endl; OpenStream(dark_greylist) << "LMain;->snmethod(Ljava/lang/Integer;)V" << std::endl; OpenStream(blacklist) << "LMain;->snmethod(Ljava/lang/Integer;)V" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kBlacklist, GetSNMethodHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, StaticNativeMethodTwoListsMatch2) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->snmethod(Ljava/lang/Integer;)V" << std::endl; OpenStream(dark_greylist) << "LMain;->snmethod(LBadType2;)V" << std::endl; OpenStream(blacklist) << "LMain;->snmethod(Ljava/lang/Integer;)V" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kBlacklist, GetSNMethodHiddenFlags(*dex_file)); } TEST_F(HiddenApiTest, StaticNativeMethodTwoListsMatch3) { ScratchFile dex, light_greylist, dark_greylist, blacklist; OpenStream(light_greylist) << "LMain;->snmethod(Ljava/lang/Integer;)V" << std::endl; OpenStream(dark_greylist) << "LMain;->snmethod(Ljava/lang/Integer;)V" << std::endl; OpenStream(blacklist) << "LMain;->snmethod(LBadType3;)V" << std::endl; auto dex_file = RunHiddenApi(light_greylist, dark_greylist, blacklist, {}, &dex); ASSERT_EQ(HiddenApiAccessFlags::kDarkGreylist, GetSNMethodHiddenFlags(*dex_file)); } } // namespace art
50.579734
100
0.708463
[ "object", "vector" ]
af1ae2bba3d655b1ffc8051dacdaef4a760f682a
4,620
cc
C++
second/align.cc
Enigmatisms/DIP
f8dcbfc60bcb7be3d79d52e23c689e214f79630b
[ "MIT" ]
1
2021-03-28T09:03:39.000Z
2021-03-28T09:03:39.000Z
second/align.cc
Enigmatisms/DIP
f8dcbfc60bcb7be3d79d52e23c689e214f79630b
[ "MIT" ]
null
null
null
second/align.cc
Enigmatisms/DIP
f8dcbfc60bcb7be3d79d52e23c689e214f79630b
[ "MIT" ]
null
null
null
/** * @brief 2D配准 闭式解算法 * @author hqy * @date 2021.3.15 */ #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/calib3d.hpp> #include <opencv2/features2d.hpp> #include <Eigen/Core> #include <Eigen/Geometry> #include <iostream> template<typename T> void printMat(const T& mat, int size){ for (int i = 0; i < size; i++){ for (int j = 0; j < size - 1; j++){ std::cout << mat(i, j) << ", "; } std::cout << mat(i, size - 1) << std::endl; } } void hMatrixSolver( const std::vector<cv::DMatch>& matches, const std::vector<cv::KeyPoint>& pts1, const std::vector<cv::KeyPoint>& pts2, Eigen::Matrix3d& H ) { int size = matches.size(); Eigen::Matrix3Xd P(3, size); Eigen::Matrix3Xd Q(3, size); P.setZero(); Q.setZero(); #pragma omp parallel for num_threads(8) for (size_t i = 0; i < matches.size(); i++) { const cv::Point2f& _p1 = pts1[matches[i].queryIdx].pt; const cv::Point2f& _p2 = pts2[matches[i].trainIdx].pt; P.block<3, 1>(0, i) = Eigen::Vector3d(_p1.x, _p1.y, 1); Q.block<3, 1>(0, i) = Eigen::Vector3d(_p2.x, _p2.y, 1); } Eigen::Matrix3d PPT = P * P.transpose(); Eigen::Matrix3d inv = (PPT).ldlt().solve(Eigen::Matrix3d::Identity()); // LDLT分解求逆矩阵 (PP^T) Eigen::Matrix3d res = PPT * inv; H = Q * P.transpose() * inv; } void featureExtract( const cv::Mat& src1, const cv::Mat& src2, cv::Mat& dst, Eigen::Matrix3d& H ){ std::vector<cv::DMatch> matches; std::vector<cv::KeyPoint> pts1, pts2; #define POINT_NUM 64 cv::Mat dscp1, dscp2; #pragma omp parallel sections { #pragma omp section { cv::Ptr<cv::FeatureDetector> det1 = cv::ORB::create(POINT_NUM); cv::Ptr<cv::DescriptorExtractor> des1 = cv::ORB::create(POINT_NUM); det1->detectAndCompute(src1, cv::noArray(), pts1, dscp1); } #pragma omp section { cv::Ptr<cv::FeatureDetector> det2 = cv::ORB::create(POINT_NUM); cv::Ptr<cv::DescriptorExtractor> des2 = cv::ORB::create(POINT_NUM); det2->detectAndCompute(src2, cv::noArray(), pts2, dscp2); } } std::cout << "Parallel ORB descriptors found.\n"; cv::Ptr<cv::DescriptorMatcher> match = cv::DescriptorMatcher::create(cv::DescriptorMatcher::BRUTEFORCE_HAMMINGLUT); match->match(dscp1, dscp2, matches); std::cout << "ORB descriptors matched.\n"; std::vector<cv::Point2f> crn1, crn2; for (const cv::DMatch& mt: matches){ crn1.push_back(pts1[mt.queryIdx].pt); crn2.push_back(pts2[mt.trainIdx].pt); } cv::Mat mask; cv::Mat cvH = cv::findHomography(crn1, crn2, mask, cv::RANSAC, 16); printf("Homography found. mask is %d, %d, %d, %d\n", mask.cols, mask.rows, mask.type(), CV_8UC1); printf("The original match num is %lu.\n", matches.size()); std::vector<cv::DMatch> truth; for (size_t i = 0; i < matches.size(); i++){ if (mask.at<uchar>(i) == 1){ truth.push_back(matches[i]); } } cv::drawMatches(src1, pts1, src2, pts2, truth, dst); hMatrixSolver(truth, pts1, pts2, H); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { printf("%lf, ", cvH.at<double>(i, j)); } printf("\n"); } } /// 可视化 void alignmentVisualize(const cv::Mat& src, cv::Mat&dst, Eigen::Matrix3d H) { dst.create(src.rows, src.cols, CV_8UC3); #pragma for num_threads(8); for (int i = 0; i < src.rows; i++) { for (int j = 0; j < src.cols; j++) { Eigen::Vector3d now(j, i, 1.0); Eigen::Vector3d trans = H * now; int px = trans[0], py = trans[1]; if (px >= 0 && px < dst.cols && py >= 0 && py < dst.rows) { dst.at<cv::Vec3b>(py, px) = src.at<cv::Vec3b>(i, j); } } } } int main() { cv::Mat src1 = cv::imread("../data/ImageA.jpg"); cv::Mat src2 = cv::imread("../data/ImageB.jpg"); cv::Mat gray1, gray2; cv::cvtColor(src1, gray1, cv::COLOR_BGR2GRAY); cv::cvtColor(src2, gray2, cv::COLOR_BGR2GRAY); cv::equalizeHist(gray1, gray1); cv::equalizeHist(gray2, gray2); cv::Mat aligned; cv::Mat feats; Eigen::Matrix3d H; featureExtract(gray1, gray2, feats, H); std::cout << "H matrix is:\n"; printMat<Eigen::Matrix3d>(H, 3); cv::imwrite("../data/features.jpg", feats); alignmentVisualize(src1, aligned, H); cv::imwrite("../data/result.jpg", aligned); return 0; }
32.307692
119
0.568182
[ "geometry", "vector" ]
af1b24055dd4e890c0803f853b240a81006ecde4
385
cpp
C++
Algorithms/reverseStrRecursive.cpp
Alex0Blackwell/c-projects
eb5a4507603b8510abc18223fd99c454e8effc38
[ "MIT" ]
1
2020-12-07T03:00:52.000Z
2020-12-07T03:00:52.000Z
Algorithms/reverseStrRecursive.cpp
Alex0Blackwell/c-projects
eb5a4507603b8510abc18223fd99c454e8effc38
[ "MIT" ]
1
2020-10-02T06:27:48.000Z
2020-10-02T06:27:48.000Z
Algorithms/reverseStrRecursive.cpp
Alex0Blackwell/c-projects
eb5a4507603b8510abc18223fd99c454e8effc38
[ "MIT" ]
2
2020-10-02T06:16:11.000Z
2020-10-27T15:05:25.000Z
class Solution { void swap(char & a, char & b) { char _tmp = a; a = b; b = _tmp; } void help(vector<char> & s, int left, int right) { if(left >= right) return; swap(s[left], s[right]); help(s, ++left, --right); } public: void reverseString(vector<char>& s) { help(s, 0, s.size()-1); } };
16.73913
54
0.449351
[ "vector" ]
af225bb6750d7f8386d10cd221f48bbe5a92420b
73,604
cpp
C++
tests/unit/fem/test_get_value.cpp
stefanhenneking/mfem
dc4715e03d177233ea0d891f2875324cadb06dc4
[ "BSD-3-Clause" ]
1
2021-05-02T23:05:53.000Z
2021-05-02T23:05:53.000Z
tests/unit/fem/test_get_value.cpp
stefanhenneking/mfem
dc4715e03d177233ea0d891f2875324cadb06dc4
[ "BSD-3-Clause" ]
null
null
null
tests/unit/fem/test_get_value.cpp
stefanhenneking/mfem
dc4715e03d177233ea0d891f2875324cadb06dc4
[ "BSD-3-Clause" ]
1
2021-09-15T14:14:29.000Z
2021-09-15T14:14:29.000Z
// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "mfem.hpp" #include "catch.hpp" using namespace mfem; namespace get_value { double func_1D_lin(const Vector &x) { return x[0]; } double func_2D_lin(const Vector &x) { return x[0] + 2.0 * x[1]; } double func_3D_lin(const Vector &x) { return x[0] + 2.0 * x[1] + 3.0 * x[2]; } void Func_2D_lin(const Vector &x, Vector &v) { v.SetSize(2); v[0] = 1.234 * x[0] - 2.357 * x[1]; v[1] = 2.537 * x[0] + 4.321 * x[1]; } void Func_3D_lin(const Vector &x, Vector &v) { v.SetSize(3); v[0] = 1.234 * x[0] - 2.357 * x[1] + 3.572 * x[2]; v[1] = 2.537 * x[0] + 4.321 * x[1] - 1.234 * x[2]; v[2] = -2.572 * x[0] + 1.321 * x[1] + 3.234 * x[2]; } TEST_CASE("1D GetValue", "[GridFunction]" "[GridFunctionCoefficient]") { int log = 1; int n = 1; int dim = 1; int order = 1; int npts = 0; double tol = 1e-6; for (int type = (int)Element::SEGMENT; type <= (int)Element::SEGMENT; type++) { Mesh mesh(n, 2.0); FunctionCoefficient linCoef(func_1D_lin); SECTION("1D GetValue tests for element type " + std::to_string(type)) { H1_FECollection h1_fec(order, dim); DG_FECollection dgv_fec(order, dim, BasisType::GaussLegendre, FiniteElement::VALUE); DG_FECollection dgi_fec(order, dim, BasisType::GaussLegendre, FiniteElement::INTEGRAL); FiniteElementSpace h1_fespace(&mesh, &h1_fec); FiniteElementSpace dgv_fespace(&mesh, &dgv_fec); FiniteElementSpace dgi_fespace(&mesh, &dgi_fec); GridFunction h1_x(&h1_fespace); GridFunction dgv_x(&dgv_fespace); GridFunction dgi_x(&dgi_fespace); GridFunctionCoefficient h1_xCoef(&h1_x); GridFunctionCoefficient dgv_xCoef(&dgv_x); GridFunctionCoefficient dgi_xCoef(&dgi_x); h1_x.ProjectCoefficient(linCoef); dgv_x.ProjectCoefficient(linCoef); dgi_x.ProjectCoefficient(linCoef); SECTION("Domain Evaluation 1D") { std::cout << "Domain Evaluation 1D" << std::endl; for (int e = 0; e < mesh.GetNE(); e++) { ElementTransformation *T = mesh.GetElementTransformation(e); const FiniteElement *fe = h1_fespace.GetFE(e); const IntegrationRule &ir = IntRules.Get(fe->GetGeomType(), 2*order + 2); double h1_err = 0.0; double dgv_err = 0.0; double dgi_err = 0.0; double tip_data[1]; Vector tip(tip_data, 1); for (int j=0; j<ir.GetNPoints(); j++) { npts++; const IntegrationPoint &ip = ir.IntPoint(j); T->SetIntPoint(&ip); T->Transform(ip, tip); double f_val = func_1D_lin(tip); double h1_gf_val = h1_xCoef.Eval(*T, ip); double dgv_gf_val = dgv_xCoef.Eval(*T, ip); double dgi_gf_val = dgi_xCoef.Eval(*T, ip); h1_err += fabs(f_val - h1_gf_val); dgv_err += fabs(f_val - dgv_gf_val); dgi_err += fabs(f_val - dgi_gf_val); if (log > 0 && fabs(f_val - h1_gf_val) > tol) { std::cout << e << ":" << j << " h1 " << f_val << " " << h1_gf_val << " " << fabs(f_val - h1_gf_val) << std::endl; } if (log > 0 && fabs(f_val - dgv_gf_val) > tol) { std::cout << e << ":" << j << " dgv " << f_val << " " << dgv_gf_val << " " << fabs(f_val - dgv_gf_val) << std::endl; } if (log > 0 && fabs(f_val - dgi_gf_val) > tol) { std::cout << e << ":" << j << " dgi " << f_val << " " << dgi_gf_val << " " << fabs(f_val - dgi_gf_val) << std::endl; } } h1_err /= ir.GetNPoints(); dgv_err /= ir.GetNPoints(); dgi_err /= ir.GetNPoints(); REQUIRE(h1_err == Approx(0.0)); REQUIRE(dgv_err == Approx(0.0)); REQUIRE(dgi_err == Approx(0.0)); } } SECTION("Boundary Evaluation 1D (H1 Context)") { std::cout << "Boundary Evaluation 1D (H1 Context)" << std::endl; for (int be = 0; be < mesh.GetNBE(); be++) { ElementTransformation *T = mesh.GetBdrElementTransformation(be); const FiniteElement *fe = h1_fespace.GetBE(be); const IntegrationRule &ir = IntRules.Get(fe->GetGeomType(), 2*order + 2); double h1_err = 0.0; double dgv_err = 0.0; double dgi_err = 0.0; double tip_data[1]; Vector tip(tip_data, 1); for (int j=0; j<ir.GetNPoints(); j++) { npts++; const IntegrationPoint &ip = ir.IntPoint(j); T->SetIntPoint(&ip); T->Transform(ip, tip); double f_val = func_1D_lin(tip); double h1_gf_val = h1_xCoef.Eval(*T, ip); double dgv_gf_val = dgv_xCoef.Eval(*T, ip); double dgi_gf_val = dgi_xCoef.Eval(*T, ip); h1_err += fabs(f_val - h1_gf_val); dgv_err += fabs(f_val - dgv_gf_val); dgi_err += fabs(f_val - dgi_gf_val); if (log > 0 && fabs(f_val - h1_gf_val) > tol) { std::cout << be << ":" << j << " h1 " << f_val << " " << h1_gf_val << " " << fabs(f_val - h1_gf_val) << std::endl; } if (log > 0 && fabs(f_val - dgv_gf_val) > tol) { std::cout << be << ":" << j << " dgv " << f_val << " " << dgv_gf_val << " " << fabs(f_val - dgv_gf_val) << std::endl; } if (log > 0 && fabs(f_val - dgi_gf_val) > tol) { std::cout << be << ":" << j << " dgi " << f_val << " " << dgi_gf_val << " " << fabs(f_val - dgi_gf_val) << std::endl; } } h1_err /= ir.GetNPoints(); dgv_err /= ir.GetNPoints(); dgi_err /= ir.GetNPoints(); REQUIRE(h1_err == Approx(0.0)); REQUIRE(dgv_err == Approx(0.0)); REQUIRE(dgi_err == Approx(0.0)); } } SECTION("Boundary Evaluation 1D (DG Context)") { std::cout << "Boundary Evaluation 1D (DG Context)" << std::endl; for (int be = 0; be < mesh.GetNBE(); be++) { FaceElementTransformations *T = mesh.GetBdrFaceTransformations(be); const IntegrationRule &ir = IntRules.Get(T->GetGeometryType(), 2*order + 2); double h1_err = 0.0; double dgv_err = 0.0; double dgi_err = 0.0; double tip_data[1]; Vector tip(tip_data, 1); for (int j=0; j<ir.GetNPoints(); j++) { npts++; const IntegrationPoint &ip = ir.IntPoint(j); T->SetIntPoint(&ip); T->Transform(ip, tip); double f_val = func_1D_lin(tip); double h1_gf_val = h1_xCoef.Eval(*T, ip); double dgv_gf_val = dgv_xCoef.Eval(*T, ip); double dgi_gf_val = dgi_xCoef.Eval(*T, ip); h1_err += fabs(f_val - h1_gf_val); dgv_err += fabs(f_val - dgv_gf_val); dgi_err += fabs(f_val - dgi_gf_val); if (log > 0 && fabs(f_val - h1_gf_val) > tol) { std::cout << be << ":" << j << " h1 " << f_val << " " << h1_gf_val << " " << fabs(f_val - h1_gf_val) << std::endl; } if (log > 0 && fabs(f_val - dgv_gf_val) > tol) { std::cout << be << ":" << j << " dgv " << f_val << " " << dgv_gf_val << " " << fabs(f_val - dgv_gf_val) << std::endl; } if (log > 0 && fabs(f_val - dgi_gf_val) > tol) { std::cout << be << ":" << j << " dgi " << f_val << " " << dgi_gf_val << " " << fabs(f_val - dgi_gf_val) << std::endl; } } h1_err /= ir.GetNPoints(); dgv_err /= ir.GetNPoints(); dgi_err /= ir.GetNPoints(); REQUIRE(h1_err == Approx(0.0)); REQUIRE(dgv_err == Approx(0.0)); REQUIRE(dgi_err == Approx(0.0)); } } } } std::cout << "Checked GridFunction::GetValue at " << npts << " 1D points" << std::endl; } TEST_CASE("2D GetValue", "[GridFunction]" "[GridFunctionCoefficient]") { int log = 1; int n = 1; int dim = 2; int order = 1; int npts = 0; double tol = 1e-6; for (int type = (int)Element::TRIANGLE; type <= (int)Element::QUADRILATERAL; type++) { Mesh mesh(n, n, (Element::Type)type, 1, 2.0, 3.0); FunctionCoefficient linCoef(func_2D_lin); SECTION("2D GetValue tests for element type " + std::to_string(type)) { H1_FECollection h1_fec(order, dim); DG_FECollection dgv_fec(order, dim, BasisType::GaussLegendre, FiniteElement::VALUE); DG_FECollection dgi_fec(order, dim, BasisType::GaussLegendre, FiniteElement::INTEGRAL); FiniteElementSpace h1_fespace(&mesh, &h1_fec); FiniteElementSpace dgv_fespace(&mesh, &dgv_fec); FiniteElementSpace dgi_fespace(&mesh, &dgi_fec); GridFunction h1_x(&h1_fespace); GridFunction dgv_x(&dgv_fespace); GridFunction dgi_x(&dgi_fespace); GridFunctionCoefficient h1_xCoef(&h1_x); GridFunctionCoefficient dgv_xCoef(&dgv_x); GridFunctionCoefficient dgi_xCoef(&dgi_x); h1_x.ProjectCoefficient(linCoef); dgv_x.ProjectCoefficient(linCoef); dgi_x.ProjectCoefficient(linCoef); SECTION("Domain Evaluation 2D") { std::cout << "Domain Evaluation 2D" << std::endl; for (int e = 0; e < mesh.GetNE(); e++) { ElementTransformation *T = mesh.GetElementTransformation(e); const FiniteElement *fe = h1_fespace.GetFE(e); const IntegrationRule &ir = IntRules.Get(fe->GetGeomType(), 2*order + 2); double h1_err = 0.0; double dgv_err = 0.0; double dgi_err = 0.0; double tip_data[dim]; Vector tip(tip_data, dim); for (int j=0; j<ir.GetNPoints(); j++) { npts++; const IntegrationPoint &ip = ir.IntPoint(j); T->SetIntPoint(&ip); T->Transform(ip, tip); double f_val = func_2D_lin(tip); double h1_gf_val = h1_xCoef.Eval(*T, ip); double dgv_gf_val = dgv_xCoef.Eval(*T, ip); double dgi_gf_val = dgi_xCoef.Eval(*T, ip); h1_err += fabs(f_val - h1_gf_val); dgv_err += fabs(f_val - dgv_gf_val); dgi_err += fabs(f_val - dgi_gf_val); if (log > 0 && fabs(f_val - h1_gf_val) > tol) { std::cout << e << ":" << j << " h1 " << f_val << " " << h1_gf_val << " " << fabs(f_val - h1_gf_val) << std::endl; } if (log > 0 && fabs(f_val - dgv_gf_val) > tol) { std::cout << e << ":" << j << " dgv " << f_val << " " << dgv_gf_val << " " << fabs(f_val - dgv_gf_val) << std::endl; } if (log > 0 && fabs(f_val - dgi_gf_val) > tol) { std::cout << e << ":" << j << " dgi " << f_val << " " << dgi_gf_val << " " << fabs(f_val - dgi_gf_val) << std::endl; } } h1_err /= ir.GetNPoints(); dgv_err /= ir.GetNPoints(); dgi_err /= ir.GetNPoints(); REQUIRE(h1_err == Approx(0.0)); REQUIRE(dgv_err == Approx(0.0)); REQUIRE(dgi_err == Approx(0.0)); } } SECTION("Boundary Evaluation 2D (H1 Context)") { std::cout << "Boundary Evaluation 2D (H1 Context)" << std::endl; for (int be = 0; be < mesh.GetNBE(); be++) { ElementTransformation *T = mesh.GetBdrElementTransformation(be); const FiniteElement *fe = h1_fespace.GetBE(be); const IntegrationRule &ir = IntRules.Get(fe->GetGeomType(), 2*order + 2); double h1_err = 0.0; double dgv_err = 0.0; double dgi_err = 0.0; double tip_data[dim]; Vector tip(tip_data, dim); for (int j=0; j<ir.GetNPoints(); j++) { npts++; const IntegrationPoint &ip = ir.IntPoint(j); T->SetIntPoint(&ip); T->Transform(ip, tip); double f_val = func_2D_lin(tip); double h1_gf_val = h1_xCoef.Eval(*T, ip); double dgv_gf_val = dgv_xCoef.Eval(*T, ip); double dgi_gf_val = dgi_xCoef.Eval(*T, ip); h1_err += fabs(f_val - h1_gf_val); dgv_err += fabs(f_val - dgv_gf_val); dgi_err += fabs(f_val - dgi_gf_val); if (log > 0 && fabs(f_val - h1_gf_val) > tol) { std::cout << be << ":" << j << " h1 " << f_val << " " << h1_gf_val << " " << fabs(f_val - h1_gf_val) << std::endl; } if (log > 0 && fabs(f_val - dgv_gf_val) > tol) { std::cout << be << ":" << j << " dgv " << f_val << " " << dgv_gf_val << " " << fabs(f_val - dgv_gf_val) << std::endl; } if (log > 0 && fabs(f_val - dgi_gf_val) > tol) { std::cout << be << ":" << j << " dgi " << f_val << " " << dgi_gf_val << " " << fabs(f_val - dgi_gf_val) << std::endl; } } h1_err /= ir.GetNPoints(); dgv_err /= ir.GetNPoints(); dgi_err /= ir.GetNPoints(); REQUIRE(h1_err == Approx(0.0)); REQUIRE(dgv_err == Approx(0.0)); REQUIRE(dgi_err == Approx(0.0)); } } SECTION("Boundary Evaluation 2D (DG Context)") { std::cout << "Boundary Evaluation 2D (DG Context)" << std::endl; for (int be = 0; be < mesh.GetNBE(); be++) { FaceElementTransformations *T = mesh.GetBdrFaceTransformations(be); const IntegrationRule &ir = IntRules.Get(T->GetGeometryType(), 2*order + 2); double h1_err = 0.0; double dgv_err = 0.0; double dgi_err = 0.0; double tip_data[dim]; Vector tip(tip_data, dim); for (int j=0; j<ir.GetNPoints(); j++) { npts++; const IntegrationPoint &ip = ir.IntPoint(j); T->SetIntPoint(&ip); T->Transform(ip, tip); double f_val = func_2D_lin(tip); double h1_gf_val = h1_xCoef.Eval(*T, ip); double dgv_gf_val = dgv_xCoef.Eval(*T, ip); double dgi_gf_val = dgi_xCoef.Eval(*T, ip); h1_err += fabs(f_val - h1_gf_val); dgv_err += fabs(f_val - dgv_gf_val); dgi_err += fabs(f_val - dgi_gf_val); if (log > 0 && fabs(f_val - h1_gf_val) > tol) { std::cout << be << ":" << j << " h1 " << f_val << " " << h1_gf_val << " " << fabs(f_val - h1_gf_val) << std::endl; } if (log > 0 && fabs(f_val - dgv_gf_val) > tol) { std::cout << be << ":" << j << " dgv " << f_val << " " << dgv_gf_val << " " << fabs(f_val - dgv_gf_val) << std::endl; } if (log > 0 && fabs(f_val - dgi_gf_val) > tol) { std::cout << be << ":" << j << " dgi " << f_val << " " << dgi_gf_val << " " << fabs(f_val - dgi_gf_val) << std::endl; } } h1_err /= ir.GetNPoints(); dgv_err /= ir.GetNPoints(); dgi_err /= ir.GetNPoints(); REQUIRE(h1_err == Approx(0.0)); REQUIRE(dgv_err == Approx(0.0)); REQUIRE(dgi_err == Approx(0.0)); } } SECTION("Edge Evaluation 2D (H1 Context)") { std::cout << "Edge Evaluation 2D (H1 Context)" << std::endl; for (int e = 0; e < mesh.GetNEdges(); e++) { ElementTransformation *T = mesh.GetEdgeTransformation(e); const FiniteElement *fe = h1_fespace.GetEdgeElement(e); const IntegrationRule &ir = IntRules.Get(fe->GetGeomType(), 2*order + 2); double h1_err = 0.0; double tip_data[dim]; Vector tip(tip_data, dim); for (int j=0; j<ir.GetNPoints(); j++) { npts++; const IntegrationPoint &ip = ir.IntPoint(j); T->SetIntPoint(&ip); T->Transform(ip, tip); double f_val = func_3D_lin(tip); double h1_gf_val = h1_xCoef.Eval(*T, ip); h1_err += fabs(f_val - h1_gf_val); if (log > 0 && fabs(f_val - h1_gf_val) > tol) { std::cout << e << ":" << j << " h1 " << f_val << " " << h1_gf_val << " " << fabs(f_val - h1_gf_val) << std::endl; } } h1_err /= ir.GetNPoints(); REQUIRE(h1_err == Approx(0.0)); } } } } std::cout << "Checked GridFunction::GetValue at " << npts << " 2D points" << std::endl; } TEST_CASE("3D GetValue", "[GridFunction]" "[GridFunctionCoefficient]") { int log = 1; int n = 1; int dim = 3; int order = 1; int npts = 0; double tol = 1e-6; for (int type = (int)Element::TETRAHEDRON; type <= (int)Element::WEDGE; type++) { Mesh mesh(n, n, n, (Element::Type)type, 1, 2.0, 3.0, 5.0); FunctionCoefficient linCoef(func_3D_lin); SECTION("3D GetValue tests for element type " + std::to_string(type)) { H1_FECollection h1_fec(order, dim); DG_FECollection dgv_fec(order, dim, BasisType::GaussLegendre, FiniteElement::VALUE); DG_FECollection dgi_fec(order, dim, BasisType::GaussLegendre, FiniteElement::INTEGRAL); FiniteElementSpace h1_fespace(&mesh, &h1_fec); FiniteElementSpace dgv_fespace(&mesh, &dgv_fec); FiniteElementSpace dgi_fespace(&mesh, &dgi_fec); GridFunction h1_x(&h1_fespace); GridFunction dgv_x(&dgv_fespace); GridFunction dgi_x(&dgi_fespace); GridFunctionCoefficient h1_xCoef(&h1_x); GridFunctionCoefficient dgv_xCoef(&dgv_x); GridFunctionCoefficient dgi_xCoef(&dgi_x); h1_x.ProjectCoefficient(linCoef); dgv_x.ProjectCoefficient(linCoef); dgi_x.ProjectCoefficient(linCoef); SECTION("Domain Evaluation 3D") { std::cout << "Domain Evaluation 3D" << std::endl; for (int e = 0; e < mesh.GetNE(); e++) { ElementTransformation *T = mesh.GetElementTransformation(e); const FiniteElement *fe = h1_fespace.GetFE(e); const IntegrationRule &ir = IntRules.Get(fe->GetGeomType(), 2*order + 2); double h1_err = 0.0; double dgv_err = 0.0; double dgi_err = 0.0; double tip_data[dim]; Vector tip(tip_data, dim); for (int j=0; j<ir.GetNPoints(); j++) { npts++; const IntegrationPoint &ip = ir.IntPoint(j); T->SetIntPoint(&ip); T->Transform(ip, tip); double f_val = func_3D_lin(tip); double h1_gf_val = h1_xCoef.Eval(*T, ip); double dgv_gf_val = dgv_xCoef.Eval(*T, ip); double dgi_gf_val = dgi_xCoef.Eval(*T, ip); h1_err += fabs(f_val - h1_gf_val); dgv_err += fabs(f_val - dgv_gf_val); dgi_err += fabs(f_val - dgi_gf_val); if (log > 0 && fabs(f_val - h1_gf_val) > tol) { std::cout << e << ":" << j << " h1 " << f_val << " " << h1_gf_val << " " << fabs(f_val - h1_gf_val) << std::endl; } if (log > 0 && fabs(f_val - dgv_gf_val) > tol) { std::cout << e << ":" << j << " dgv " << f_val << " " << dgv_gf_val << " " << fabs(f_val - dgv_gf_val) << std::endl; } if (log > 0 && fabs(f_val - dgi_gf_val) > tol) { std::cout << e << ":" << j << " dgi " << f_val << " " << dgi_gf_val << " " << fabs(f_val - dgi_gf_val) << std::endl; } } h1_err /= ir.GetNPoints(); dgv_err /= ir.GetNPoints(); dgi_err /= ir.GetNPoints(); REQUIRE(h1_err == Approx(0.0)); REQUIRE(dgv_err == Approx(0.0)); REQUIRE(dgi_err == Approx(0.0)); } } SECTION("Boundary Evaluation 3D (H1 Context)") { std::cout << "Boundary Evaluation 3D (H1 Context)" << std::endl; for (int be = 0; be < mesh.GetNBE(); be++) { ElementTransformation *T = mesh.GetBdrElementTransformation(be); const FiniteElement *fe = h1_fespace.GetBE(be); const IntegrationRule &ir = IntRules.Get(fe->GetGeomType(), 2*order + 2); double h1_err = 0.0; double dgv_err = 0.0; double dgi_err = 0.0; double tip_data[dim]; Vector tip(tip_data, dim); for (int j=0; j<ir.GetNPoints(); j++) { npts++; const IntegrationPoint &ip = ir.IntPoint(j); T->SetIntPoint(&ip); T->Transform(ip, tip); double f_val = func_3D_lin(tip); double h1_gf_val = h1_xCoef.Eval(*T, ip); double dgv_gf_val = dgv_xCoef.Eval(*T, ip); double dgi_gf_val = dgi_xCoef.Eval(*T, ip); h1_err += fabs(f_val - h1_gf_val); dgv_err += fabs(f_val - dgv_gf_val); dgi_err += fabs(f_val - dgi_gf_val); if (log > 0 && fabs(f_val - h1_gf_val) > tol) { std::cout << be << ":" << j << " h1 " << f_val << " " << h1_gf_val << " " << fabs(f_val - h1_gf_val) << std::endl; } if (log > 0 && fabs(f_val - dgv_gf_val) > tol) { std::cout << be << ":" << j << " dgv " << f_val << " " << dgv_gf_val << " " << fabs(f_val - dgv_gf_val) << std::endl; } if (log > 0 && fabs(f_val - dgi_gf_val) > tol) { std::cout << be << ":" << j << " dgi " << f_val << " " << dgi_gf_val << " " << fabs(f_val - dgi_gf_val) << std::endl; } } h1_err /= ir.GetNPoints(); dgv_err /= ir.GetNPoints(); dgi_err /= ir.GetNPoints(); REQUIRE(h1_err == Approx(0.0)); REQUIRE(dgv_err == Approx(0.0)); REQUIRE(dgi_err == Approx(0.0)); } } SECTION("Boundary Evaluation 3D (DG Context)") { std::cout << "Boundary Evaluation 3D (DG Context)" << std::endl; for (int be = 0; be < mesh.GetNBE(); be++) { FaceElementTransformations *T = mesh.GetBdrFaceTransformations(be); const IntegrationRule &ir = IntRules.Get(T->GetGeometryType(), 2*order + 2); double h1_err = 0.0; double dgv_err = 0.0; double dgi_err = 0.0; double tip_data[dim]; Vector tip(tip_data, dim); for (int j=0; j<ir.GetNPoints(); j++) { npts++; const IntegrationPoint &ip = ir.IntPoint(j); T->SetIntPoint(&ip); T->Transform(ip, tip); double f_val = func_3D_lin(tip); double h1_gf_val = h1_xCoef.Eval(*T, ip); double dgv_gf_val = dgv_xCoef.Eval(*T, ip); double dgi_gf_val = dgi_xCoef.Eval(*T, ip); h1_err += fabs(f_val - h1_gf_val); dgv_err += fabs(f_val - dgv_gf_val); dgi_err += fabs(f_val - dgi_gf_val); if (log > 0 && fabs(f_val - h1_gf_val) > tol) { std::cout << be << ":" << j << " h1 " << f_val << " " << h1_gf_val << " " << fabs(f_val - h1_gf_val) << std::endl; } if (log > 0 && fabs(f_val - dgv_gf_val) > tol) { std::cout << be << ":" << j << " dgv " << f_val << " " << dgv_gf_val << " " << fabs(f_val - dgv_gf_val) << std::endl; } if (log > 0 && fabs(f_val - dgi_gf_val) > tol) { std::cout << be << ":" << j << " dgi " << f_val << " " << dgi_gf_val << " " << fabs(f_val - dgi_gf_val) << std::endl; } } h1_err /= ir.GetNPoints(); dgv_err /= ir.GetNPoints(); dgi_err /= ir.GetNPoints(); REQUIRE(h1_err == Approx(0.0)); REQUIRE(dgv_err == Approx(0.0)); REQUIRE(dgi_err == Approx(0.0)); } } SECTION("Edge Evaluation 3D (H1 Context)") { std::cout << "Edge Evaluation 3D (H1 Context)" << std::endl; for (int e = 0; e < mesh.GetNEdges(); e++) { ElementTransformation *T = mesh.GetEdgeTransformation(e); const FiniteElement *fe = h1_fespace.GetEdgeElement(e); const IntegrationRule &ir = IntRules.Get(fe->GetGeomType(), 2*order + 2); double h1_err = 0.0; double tip_data[dim]; Vector tip(tip_data, dim); for (int j=0; j<ir.GetNPoints(); j++) { npts++; const IntegrationPoint &ip = ir.IntPoint(j); T->SetIntPoint(&ip); T->Transform(ip, tip); double f_val = func_3D_lin(tip); double h1_gf_val = h1_xCoef.Eval(*T, ip); h1_err += fabs(f_val - h1_gf_val); if (log > 0 && fabs(f_val - h1_gf_val) > tol) { std::cout << e << ":" << j << " h1 " << f_val << " " << h1_gf_val << " " << fabs(f_val - h1_gf_val) << std::endl; } } h1_err /= ir.GetNPoints(); REQUIRE(h1_err == Approx(0.0)); } } SECTION("Face Evaluation 3D (H1 Context)") { std::cout << "Face Evaluation 3D (H1 Context)" << std::endl; for (int f = 0; f < mesh.GetNFaces(); f++) { ElementTransformation *T = mesh.GetFaceTransformation(f); const FiniteElement *fe = h1_fespace.GetFaceElement(f); const IntegrationRule &ir = IntRules.Get(fe->GetGeomType(), 2*order + 2); double h1_err = 0.0; double tip_data[dim]; Vector tip(tip_data, dim); for (int j=0; j<ir.GetNPoints(); j++) { npts++; const IntegrationPoint &ip = ir.IntPoint(j); T->SetIntPoint(&ip); T->Transform(ip, tip); double f_val = func_3D_lin(tip); double h1_gf_val = h1_xCoef.Eval(*T, ip); h1_err += fabs(f_val - h1_gf_val); if (log > 0 && fabs(f_val - h1_gf_val) > tol) { std::cout << f << ":" << j << " h1 " << f_val << " " << h1_gf_val << " " << fabs(f_val - h1_gf_val) << std::endl; } } h1_err /= ir.GetNPoints(); REQUIRE(h1_err == Approx(0.0)); } } } } std::cout << "Checked GridFunction::GetValue at " << npts << " 3D points" << std::endl; } TEST_CASE("2D GetVectorValue", "[GridFunction]" "[VectorGridFunctionCoefficient]") { int log = 1; int n = 1; int dim = 2; int order = 1; int npts = 0; double tol = 1e-6; for (int type = (int)Element::TRIANGLE; type <= (int)Element::QUADRILATERAL; type++) { Mesh mesh(n, n, (Element::Type)type, 1, 2.0, 3.0); VectorFunctionCoefficient linCoef(dim, Func_2D_lin); SECTION("2D GetVectorValue tests for element type " + std::to_string(type)) { H1_FECollection h1_fec(order, dim); ND_FECollection nd_fec(order+1, dim); RT_FECollection rt_fec(order+1, dim); L2_FECollection l2_fec(order, dim); DG_FECollection dgv_fec(order, dim, BasisType::GaussLegendre, FiniteElement::VALUE); DG_FECollection dgi_fec(order, dim, BasisType::GaussLegendre, FiniteElement::INTEGRAL); FiniteElementSpace h1_fespace(&mesh, &h1_fec, dim); FiniteElementSpace nd_fespace(&mesh, &nd_fec); FiniteElementSpace rt_fespace(&mesh, &rt_fec); FiniteElementSpace l2_fespace(&mesh, &l2_fec, dim); FiniteElementSpace dgv_fespace(&mesh, &dgv_fec, dim); FiniteElementSpace dgi_fespace(&mesh, &dgi_fec, dim); GridFunction h1_x( &h1_fespace); GridFunction nd_x( &nd_fespace); GridFunction rt_x( &rt_fespace); GridFunction l2_x( &l2_fespace); GridFunction dgv_x(&dgv_fespace); GridFunction dgi_x(&dgi_fespace); VectorGridFunctionCoefficient h1_xCoef( &h1_x); VectorGridFunctionCoefficient nd_xCoef( &nd_x); VectorGridFunctionCoefficient rt_xCoef( &rt_x); VectorGridFunctionCoefficient l2_xCoef( &l2_x); VectorGridFunctionCoefficient dgv_xCoef(&dgv_x); VectorGridFunctionCoefficient dgi_xCoef(&dgi_x); h1_x.ProjectCoefficient(linCoef); nd_x.ProjectCoefficient(linCoef); rt_x.ProjectCoefficient(linCoef); l2_x.ProjectCoefficient(linCoef); dgv_x.ProjectCoefficient(linCoef); dgi_x.ProjectCoefficient(linCoef); Vector f_val(dim); f_val = 0.0; Vector h1_gf_val(dim); h1_gf_val = 0.0; Vector nd_gf_val(dim); nd_gf_val = 0.0; Vector rt_gf_val(dim); rt_gf_val = 0.0; Vector l2_gf_val(dim); l2_gf_val = 0.0; Vector dgv_gf_val(dim); dgv_gf_val = 0.0; Vector dgi_gf_val(dim); dgi_gf_val = 0.0; SECTION("Domain Evaluation 2D") { std::cout << "Domain Evaluation 2D" << std::endl; for (int e = 0; e < mesh.GetNE(); e++) { ElementTransformation *T = mesh.GetElementTransformation(e); const FiniteElement *fe = h1_fespace.GetFE(e); const IntegrationRule &ir = IntRules.Get(fe->GetGeomType(), 2*order + 2); double h1_err = 0.0; double nd_err = 0.0; double rt_err = 0.0; double l2_err = 0.0; double dgv_err = 0.0; double dgi_err = 0.0; double tip_data[dim]; Vector tip(tip_data, dim); for (int j=0; j<ir.GetNPoints(); j++) { npts++; const IntegrationPoint &ip = ir.IntPoint(j); T->SetIntPoint(&ip); T->Transform(ip, tip); Func_2D_lin(tip, f_val); h1_xCoef.Eval(h1_gf_val, *T, ip); nd_xCoef.Eval(nd_gf_val, *T, ip); rt_xCoef.Eval(rt_gf_val, *T, ip); l2_xCoef.Eval(l2_gf_val, *T, ip); dgv_xCoef.Eval(dgv_gf_val, *T, ip); dgi_xCoef.Eval(dgi_gf_val, *T, ip); double h1_dist = Distance(f_val, h1_gf_val, 2); double nd_dist = Distance(f_val, nd_gf_val, 2); double rt_dist = Distance(f_val, rt_gf_val, 2); double l2_dist = Distance(f_val, l2_gf_val, 2); double dgv_dist = Distance(f_val, dgv_gf_val, 2); double dgi_dist = Distance(f_val, dgi_gf_val, 2); h1_err += h1_dist; nd_err += nd_dist; rt_err += rt_dist; l2_err += l2_dist; dgv_err += dgv_dist; dgi_err += dgi_dist; if (log > 0 && h1_dist > tol) { std::cout << e << ":" << j << " h1 (" << f_val[0] << "," << f_val[1] << ") vs. (" << h1_gf_val[0] << "," << h1_gf_val[1] << ") " << h1_dist << std::endl; } if (log > 0 && nd_dist > tol) { std::cout << e << ":" << j << " nd (" << f_val[0] << "," << f_val[1] << ") vs. (" << nd_gf_val[0] << "," << nd_gf_val[1] << ") " << nd_dist << std::endl; } if (log > 0 && rt_dist > tol) { std::cout << e << ":" << j << " rt (" << f_val[0] << "," << f_val[1] << ") vs. (" << rt_gf_val[0] << "," << rt_gf_val[1] << ") " << rt_dist << std::endl; } if (log > 0 && l2_dist > tol) { std::cout << e << ":" << j << " l2 (" << f_val[0] << "," << f_val[1] << ") vs. (" << l2_gf_val[0] << "," << l2_gf_val[1] << ") " << l2_dist << std::endl; } if (log > 0 && dgv_dist > tol) { std::cout << e << ":" << j << " dgv (" << f_val[0] << "," << f_val[1] << ") vs. (" << dgv_gf_val[0] << "," << dgv_gf_val[1] << ") " << dgv_dist << std::endl; } if (log > 0 && dgi_dist > tol) { std::cout << e << ":" << j << " dgi (" << f_val[0] << "," << f_val[1] << ") vs. (" << dgi_gf_val[0] << "," << dgi_gf_val[1] << ") " << dgi_dist << std::endl; } } h1_err /= ir.GetNPoints(); nd_err /= ir.GetNPoints(); rt_err /= ir.GetNPoints(); l2_err /= ir.GetNPoints(); dgv_err /= ir.GetNPoints(); dgi_err /= ir.GetNPoints(); REQUIRE( h1_err == Approx(0.0)); REQUIRE( nd_err == Approx(0.0)); REQUIRE( rt_err == Approx(0.0)); REQUIRE( l2_err == Approx(0.0)); REQUIRE(dgv_err == Approx(0.0)); REQUIRE(dgi_err == Approx(0.0)); } } SECTION("Boundary Evaluation 2D (H1 Context)") { std::cout << "Boundary Evaluation 2D (H1 Context)" << std::endl; for (int be = 0; be < mesh.GetNBE(); be++) { ElementTransformation *T = mesh.GetBdrElementTransformation(be); const FiniteElement *fe = h1_fespace.GetBE(be); const IntegrationRule &ir = IntRules.Get(fe->GetGeomType(), 2*order + 2); double h1_err = 0.0; double nd_err = 0.0; double rt_err = 0.0; double l2_err = 0.0; double dgv_err = 0.0; double dgi_err = 0.0; double tip_data[dim]; Vector tip(tip_data, dim); for (int j=0; j<ir.GetNPoints(); j++) { npts++; const IntegrationPoint &ip = ir.IntPoint(j); T->SetIntPoint(&ip); T->Transform(ip, tip); Func_2D_lin(tip, f_val); h1_xCoef.Eval(h1_gf_val, *T, ip); nd_xCoef.Eval(nd_gf_val, *T, ip); rt_xCoef.Eval(rt_gf_val, *T, ip); l2_xCoef.Eval(l2_gf_val, *T, ip); dgv_xCoef.Eval(dgv_gf_val, *T, ip); dgi_xCoef.Eval(dgi_gf_val, *T, ip); double h1_dist = Distance(f_val, h1_gf_val, 2); double nd_dist = Distance(f_val, nd_gf_val, 2); double rt_dist = Distance(f_val, rt_gf_val, 2); double l2_dist = Distance(f_val, l2_gf_val, 2); double dgv_dist = Distance(f_val, dgv_gf_val, 2); double dgi_dist = Distance(f_val, dgi_gf_val, 2); h1_err += h1_dist; nd_err += nd_dist; rt_err += rt_dist; l2_err += l2_dist; dgv_err += dgv_dist; dgi_err += dgi_dist; if (log > 0 && h1_dist > tol) { std::cout << be << ":" << j << " h1 (" << f_val[0] << "," << f_val[1] << ") vs. (" << h1_gf_val[0] << "," << h1_gf_val[1] << ") " << h1_dist << std::endl; } if (log > 0 && nd_dist > tol) { std::cout << be << ":" << j << " nd (" << f_val[0] << "," << f_val[1] << ") vs. (" << nd_gf_val[0] << "," << nd_gf_val[1] << ") " << nd_dist << std::endl; } if (log > 0 && rt_dist > tol) { std::cout << be << ":" << j << " rt (" << f_val[0] << "," << f_val[1] << ") vs. (" << rt_gf_val[0] << "," << rt_gf_val[1] << ") " << rt_dist << std::endl; } if (log > 0 && l2_dist > tol) { std::cout << be << ":" << j << " l2 (" << f_val[0] << "," << f_val[1] << ") vs. (" << l2_gf_val[0] << "," << l2_gf_val[1] << ") " << l2_dist << std::endl; } if (log > 0 && dgv_dist > tol) { std::cout << be << ":" << j << " dgv (" << f_val[0] << "," << f_val[1] << ") vs. (" << dgv_gf_val[0] << "," << dgv_gf_val[1] << ") " << dgv_dist << std::endl; } if (log > 0 && dgi_dist > tol) { std::cout << be << ":" << j << " dgi (" << f_val[0] << "," << f_val[1] << ") vs. (" << dgi_gf_val[0] << "," << dgi_gf_val[1] << ") " << dgi_dist << std::endl; } } h1_err /= ir.GetNPoints(); nd_err /= ir.GetNPoints(); rt_err /= ir.GetNPoints(); l2_err /= ir.GetNPoints(); dgv_err /= ir.GetNPoints(); dgi_err /= ir.GetNPoints(); REQUIRE( h1_err == Approx(0.0)); REQUIRE( nd_err == Approx(0.0)); REQUIRE( rt_err == Approx(0.0)); REQUIRE( l2_err == Approx(0.0)); REQUIRE(dgv_err == Approx(0.0)); REQUIRE(dgi_err == Approx(0.0)); } } SECTION("Boundary Evaluation 2D (DG Context)") { std::cout << "Boundary Evaluation 2D (DG Context)" << std::endl; for (int be = 0; be < mesh.GetNBE(); be++) { FaceElementTransformations *T = mesh.GetBdrFaceTransformations(be); const IntegrationRule &ir = IntRules.Get(T->GetGeometryType(), 2*order + 2); double h1_err = 0.0; double nd_err = 0.0; double rt_err = 0.0; double l2_err = 0.0; double dgv_err = 0.0; double dgi_err = 0.0; double tip_data[dim]; Vector tip(tip_data, dim); for (int j=0; j<ir.GetNPoints(); j++) { npts++; const IntegrationPoint &ip = ir.IntPoint(j); T->SetIntPoint(&ip); T->Transform(ip, tip); Func_2D_lin(tip, f_val); h1_xCoef.Eval(h1_gf_val, *T, ip); nd_xCoef.Eval(nd_gf_val, *T, ip); rt_xCoef.Eval(rt_gf_val, *T, ip); l2_xCoef.Eval(l2_gf_val, *T, ip); dgv_xCoef.Eval(dgv_gf_val, *T, ip); dgi_xCoef.Eval(dgi_gf_val, *T, ip); double h1_dist = Distance(f_val, h1_gf_val, 2); double nd_dist = Distance(f_val, nd_gf_val, 2); double rt_dist = Distance(f_val, rt_gf_val, 2); double l2_dist = Distance(f_val, l2_gf_val, 2); double dgv_dist = Distance(f_val, dgv_gf_val, 2); double dgi_dist = Distance(f_val, dgi_gf_val, 2); h1_err += h1_dist; nd_err += nd_dist; rt_err += rt_dist; l2_err += l2_dist; dgv_err += dgv_dist; dgi_err += dgi_dist; if (log > 0 && h1_dist > tol) { std::cout << be << ":" << j << " h1 (" << f_val[0] << "," << f_val[1] << ") vs. (" << h1_gf_val[0] << "," << h1_gf_val[1] << ") " << h1_dist << std::endl; } if (log > 0 && nd_dist > tol) { std::cout << be << ":" << j << " nd (" << f_val[0] << "," << f_val[1] << ") vs. (" << nd_gf_val[0] << "," << nd_gf_val[1] << ") " << nd_dist << std::endl; } if (log > 0 && rt_dist > tol) { std::cout << be << ":" << j << " rt (" << f_val[0] << "," << f_val[1] << ") vs. (" << rt_gf_val[0] << "," << rt_gf_val[1] << ") " << rt_dist << std::endl; } if (log > 0 && l2_dist > tol) { std::cout << be << ":" << j << " l2 (" << f_val[0] << "," << f_val[1] << ") vs. (" << l2_gf_val[0] << "," << l2_gf_val[1] << ") " << l2_dist << std::endl; } if (log > 0 && dgv_dist > tol) { std::cout << be << ":" << j << " dgv (" << f_val[0] << "," << f_val[1] << ") vs. (" << dgv_gf_val[0] << "," << dgv_gf_val[1] << ") " << dgv_dist << std::endl; } if (log > 0 && dgi_dist > tol) { std::cout << be << ":" << j << " dgi (" << f_val[0] << "," << f_val[1] << ") vs. (" << dgi_gf_val[0] << "," << dgi_gf_val[1] << ") " << dgi_dist << std::endl; } } h1_err /= ir.GetNPoints(); nd_err /= ir.GetNPoints(); rt_err /= ir.GetNPoints(); l2_err /= ir.GetNPoints(); dgv_err /= ir.GetNPoints(); dgi_err /= ir.GetNPoints(); REQUIRE( h1_err == Approx(0.0)); REQUIRE( nd_err == Approx(0.0)); REQUIRE( rt_err == Approx(0.0)); REQUIRE( l2_err == Approx(0.0)); REQUIRE(dgv_err == Approx(0.0)); REQUIRE(dgi_err == Approx(0.0)); } } SECTION("Edge Evaluation 2D") { std::cout << "Edge Evaluation 2D" << std::endl; for (int e = 0; e < mesh.GetNEdges(); e++) { ElementTransformation *T = mesh.GetEdgeTransformation(e); const FiniteElement *fe = h1_fespace.GetEdgeElement(e); const IntegrationRule &ir = IntRules.Get(fe->GetGeomType(), 2*order + 2); double h1_err = 0.0; double tip_data[dim]; Vector tip(tip_data, dim); for (int j=0; j<ir.GetNPoints(); j++) { npts++; const IntegrationPoint &ip = ir.IntPoint(j); T->SetIntPoint(&ip); T->Transform(ip, tip); Func_2D_lin(tip, f_val); h1_xCoef.Eval(h1_gf_val, *T, ip); double h1_dist = Distance(f_val, h1_gf_val, 2); h1_err += h1_dist; if (log > 0 && h1_dist > tol) { std::cout << e << ":" << j << " h1 (" << f_val[0] << "," << f_val[1] << ") vs. (" << h1_gf_val[0] << "," << h1_gf_val[1] << ") " << h1_dist << std::endl; } } h1_err /= ir.GetNPoints(); REQUIRE( h1_err == Approx(0.0)); } } } } std::cout << "Checked GridFunction::GetVectorValue at " << npts << " 2D points" << std::endl; } TEST_CASE("3D GetVectorValue", "[GridFunction]" "[VectorGridFunctionCoefficient]") { int log = 1; int n = 1; int dim = 3; int order = 1; int npts = 0; double tol = 1e-6; for (int type = (int)Element::TETRAHEDRON; type <= (int)Element::HEXAHEDRON; type++) { Mesh mesh(n, n, n, (Element::Type)type, 1, 2.0, 3.0, 5.0); VectorFunctionCoefficient linCoef(dim, Func_3D_lin); SECTION("3D GetVectorValue tests for element type " + std::to_string(type)) { H1_FECollection h1_fec(order, dim); ND_FECollection nd_fec(order+1, dim); RT_FECollection rt_fec(order+1, dim); L2_FECollection l2_fec(order, dim); DG_FECollection dgv_fec(order, dim, BasisType::GaussLegendre, FiniteElement::VALUE); DG_FECollection dgi_fec(order, dim, BasisType::GaussLegendre, FiniteElement::INTEGRAL); FiniteElementSpace h1_fespace(&mesh, &h1_fec, dim); FiniteElementSpace nd_fespace(&mesh, &nd_fec); FiniteElementSpace rt_fespace(&mesh, &rt_fec); FiniteElementSpace l2_fespace(&mesh, &l2_fec, dim); FiniteElementSpace dgv_fespace(&mesh, &dgv_fec, dim); FiniteElementSpace dgi_fespace(&mesh, &dgi_fec, dim); GridFunction h1_x( &h1_fespace); GridFunction nd_x( &nd_fespace); GridFunction rt_x( &rt_fespace); GridFunction l2_x( &l2_fespace); GridFunction dgv_x(&dgv_fespace); GridFunction dgi_x(&dgi_fespace); VectorGridFunctionCoefficient h1_xCoef( &h1_x); VectorGridFunctionCoefficient nd_xCoef( &nd_x); VectorGridFunctionCoefficient rt_xCoef( &rt_x); VectorGridFunctionCoefficient l2_xCoef( &l2_x); VectorGridFunctionCoefficient dgv_xCoef(&dgv_x); VectorGridFunctionCoefficient dgi_xCoef(&dgi_x); h1_x.ProjectCoefficient(linCoef); nd_x.ProjectCoefficient(linCoef); rt_x.ProjectCoefficient(linCoef); l2_x.ProjectCoefficient(linCoef); dgv_x.ProjectCoefficient(linCoef); dgi_x.ProjectCoefficient(linCoef); Vector f_val(dim); f_val = 0.0; Vector h1_gf_val(dim); h1_gf_val = 0.0; Vector nd_gf_val(dim); nd_gf_val = 0.0; Vector rt_gf_val(dim); rt_gf_val = 0.0; Vector l2_gf_val(dim); l2_gf_val = 0.0; Vector dgv_gf_val(dim); dgv_gf_val = 0.0; Vector dgi_gf_val(dim); dgi_gf_val = 0.0; SECTION("Domain Evaluation 3D") { std::cout << "Domain Evaluation 3D" << std::endl; for (int e = 0; e < mesh.GetNE(); e++) { ElementTransformation *T = mesh.GetElementTransformation(e); const FiniteElement *fe = h1_fespace.GetFE(e); const IntegrationRule &ir = IntRules.Get(fe->GetGeomType(), 2*order + 2); double h1_err = 0.0; double nd_err = 0.0; double rt_err = 0.0; double l2_err = 0.0; double dgv_err = 0.0; double dgi_err = 0.0; double tip_data[dim]; Vector tip(tip_data, dim); for (int j=0; j<ir.GetNPoints(); j++) { npts++; const IntegrationPoint &ip = ir.IntPoint(j); T->SetIntPoint(&ip); T->Transform(ip, tip); Func_3D_lin(tip, f_val); h1_xCoef.Eval(h1_gf_val, *T, ip); nd_xCoef.Eval(nd_gf_val, *T, ip); rt_xCoef.Eval(rt_gf_val, *T, ip); l2_xCoef.Eval(l2_gf_val, *T, ip); dgv_xCoef.Eval(dgv_gf_val, *T, ip); dgi_xCoef.Eval(dgi_gf_val, *T, ip); double h1_dist = Distance(f_val, h1_gf_val, dim); double nd_dist = Distance(f_val, nd_gf_val, dim); double rt_dist = Distance(f_val, rt_gf_val, dim); double l2_dist = Distance(f_val, l2_gf_val, dim); double dgv_dist = Distance(f_val, dgv_gf_val, dim); double dgi_dist = Distance(f_val, dgi_gf_val, dim); h1_err += h1_dist; nd_err += nd_dist; rt_err += rt_dist; l2_err += l2_dist; dgv_err += dgv_dist; dgi_err += dgi_dist; if (log > 0 && h1_dist > tol) { std::cout << e << ":" << j << " h1 (" << f_val[0] << "," << f_val[1] << "," << f_val[2] << ") vs. (" << h1_gf_val[0] << "," << h1_gf_val[1] << "," << h1_gf_val[2] << ") " << h1_dist << std::endl; } if (log > 0 && nd_dist > tol) { std::cout << e << ":" << j << " nd (" << f_val[0] << "," << f_val[1] << "," << f_val[2] << ") vs. (" << nd_gf_val[0] << "," << nd_gf_val[1] << "," << nd_gf_val[2] << ") " << nd_dist << std::endl; } if (log > 0 && rt_dist > tol) { std::cout << e << ":" << j << " rt (" << f_val[0] << "," << f_val[1] << "," << f_val[2] << ") vs. (" << rt_gf_val[0] << "," << rt_gf_val[1] << "," << rt_gf_val[2] << ") " << rt_dist << std::endl; } if (log > 0 && l2_dist > tol) { std::cout << e << ":" << j << " l2 (" << f_val[0] << "," << f_val[1] << "," << f_val[2] << ") vs. (" << l2_gf_val[0] << "," << l2_gf_val[1] << "," << l2_gf_val[2] << ") " << l2_dist << std::endl; } if (log > 0 && dgv_dist > tol) { std::cout << e << ":" << j << " dgv (" << f_val[0] << "," << f_val[1] << "," << f_val[2] << ") vs. (" << dgv_gf_val[0] << "," << dgv_gf_val[1] << "," << dgv_gf_val[2] << ") " << dgv_dist << std::endl; } if (log > 0 && dgi_dist > tol) { std::cout << e << ":" << j << " dgi (" << f_val[0] << "," << f_val[1] << "," << f_val[2] << ") vs. (" << dgi_gf_val[0] << "," << dgi_gf_val[1] << "," << dgi_gf_val[2] << ") " << dgi_dist << std::endl; } } h1_err /= ir.GetNPoints(); nd_err /= ir.GetNPoints(); rt_err /= ir.GetNPoints(); l2_err /= ir.GetNPoints(); dgv_err /= ir.GetNPoints(); dgi_err /= ir.GetNPoints(); REQUIRE( h1_err == Approx(0.0)); REQUIRE( nd_err == Approx(0.0)); REQUIRE( rt_err == Approx(0.0)); REQUIRE( l2_err == Approx(0.0)); REQUIRE(dgv_err == Approx(0.0)); REQUIRE(dgi_err == Approx(0.0)); } } SECTION("Boundary Evaluation 3D (H1 Context)") { std::cout << "Boundary Evaluation 3D (H1 Context)" << std::endl; for (int be = 0; be < mesh.GetNBE(); be++) { ElementTransformation *T = mesh.GetBdrElementTransformation(be); const FiniteElement *fe = h1_fespace.GetBE(be); const IntegrationRule &ir = IntRules.Get(fe->GetGeomType(), 2*order + 2); double h1_err = 0.0; double nd_err = 0.0; double rt_err = 0.0; double l2_err = 0.0; double dgv_err = 0.0; double dgi_err = 0.0; double tip_data[dim]; Vector tip(tip_data, dim); for (int j=0; j<ir.GetNPoints(); j++) { npts++; const IntegrationPoint &ip = ir.IntPoint(j); T->SetIntPoint(&ip); T->Transform(ip, tip); Func_3D_lin(tip, f_val); h1_xCoef.Eval(h1_gf_val, *T, ip); nd_xCoef.Eval(nd_gf_val, *T, ip); rt_xCoef.Eval(rt_gf_val, *T, ip); l2_xCoef.Eval(l2_gf_val, *T, ip); dgv_xCoef.Eval(dgv_gf_val, *T, ip); dgi_xCoef.Eval(dgi_gf_val, *T, ip); double h1_dist = Distance(f_val, h1_gf_val, dim); double nd_dist = Distance(f_val, nd_gf_val, dim); double rt_dist = Distance(f_val, rt_gf_val, dim); double l2_dist = Distance(f_val, l2_gf_val, dim); double dgv_dist = Distance(f_val, dgv_gf_val, dim); double dgi_dist = Distance(f_val, dgi_gf_val, dim); h1_err += h1_dist; nd_err += nd_dist; rt_err += rt_dist; l2_err += l2_dist; dgv_err += dgv_dist; dgi_err += dgi_dist; if (log > 0 && h1_dist > tol) { std::cout << be << ":" << j << " h1 (" << f_val[0] << "," << f_val[1] << "," << f_val[2] << ") vs. (" << h1_gf_val[0] << "," << h1_gf_val[1] << "," << h1_gf_val[2] << ") " << h1_dist << std::endl; } if (log > 0 && nd_dist > tol) { std::cout << be << ":" << j << " nd (" << f_val[0] << "," << f_val[1] << "," << f_val[2] << ") vs. (" << nd_gf_val[0] << "," << nd_gf_val[1] << "," << nd_gf_val[2] << ") " << nd_dist << std::endl; } if (log > 0 && rt_dist > tol) { std::cout << be << ":" << j << " rt (" << f_val[0] << "," << f_val[1] << "," << f_val[2] << ") vs. (" << rt_gf_val[0] << "," << rt_gf_val[1] << "," << rt_gf_val[2] << ") " << rt_dist << std::endl; } if (log > 0 && l2_dist > tol) { std::cout << be << ":" << j << " l2 (" << f_val[0] << "," << f_val[1] << "," << f_val[2] << ") vs. (" << l2_gf_val[0] << "," << l2_gf_val[1] << "," << l2_gf_val[2] << ") " << l2_dist << std::endl; } if (log > 0 && dgv_dist > tol) { std::cout << be << ":" << j << " dgv (" << f_val[0] << "," << f_val[1] << "," << f_val[2] << ") vs. (" << dgv_gf_val[0] << "," << dgv_gf_val[1] << "," << dgv_gf_val[2] << ") " << dgv_dist << std::endl; } if (log > 0 && dgi_dist > tol) { std::cout << be << ":" << j << " dgi (" << f_val[0] << "," << f_val[1] << "," << f_val[2] << ") vs. (" << dgi_gf_val[0] << "," << dgi_gf_val[1] << "," << dgi_gf_val[2] << ") " << dgi_dist << std::endl; } } h1_err /= ir.GetNPoints(); nd_err /= ir.GetNPoints(); rt_err /= ir.GetNPoints(); l2_err /= ir.GetNPoints(); dgv_err /= ir.GetNPoints(); dgi_err /= ir.GetNPoints(); REQUIRE( h1_err == Approx(0.0)); REQUIRE( nd_err == Approx(0.0)); REQUIRE( rt_err == Approx(0.0)); REQUIRE( l2_err == Approx(0.0)); REQUIRE(dgv_err == Approx(0.0)); REQUIRE(dgi_err == Approx(0.0)); } } SECTION("Boundary Evaluation 3D (DG Context)") { std::cout << "Boundary Evaluation 3D (DG Context)" << std::endl; for (int be = 0; be < mesh.GetNBE(); be++) { FaceElementTransformations *T = mesh.GetBdrFaceTransformations(be); const IntegrationRule &ir = IntRules.Get(T->GetGeometryType(), 2*order + 2); double h1_err = 0.0; double nd_err = 0.0; double rt_err = 0.0; double l2_err = 0.0; double dgv_err = 0.0; double dgi_err = 0.0; double tip_data[dim]; Vector tip(tip_data, dim); for (int j=0; j<ir.GetNPoints(); j++) { npts++; const IntegrationPoint &ip = ir.IntPoint(j); T->SetIntPoint(&ip); T->Transform(ip, tip); Func_3D_lin(tip, f_val); h1_xCoef.Eval(h1_gf_val, *T, ip); nd_xCoef.Eval(nd_gf_val, *T, ip); rt_xCoef.Eval(rt_gf_val, *T, ip); l2_xCoef.Eval(l2_gf_val, *T, ip); dgv_xCoef.Eval(dgv_gf_val, *T, ip); dgi_xCoef.Eval(dgi_gf_val, *T, ip); double h1_dist = Distance(f_val, h1_gf_val, dim); double nd_dist = Distance(f_val, nd_gf_val, dim); double rt_dist = Distance(f_val, rt_gf_val, dim); double l2_dist = Distance(f_val, l2_gf_val, dim); double dgv_dist = Distance(f_val, dgv_gf_val, dim); double dgi_dist = Distance(f_val, dgi_gf_val, dim); h1_err += h1_dist; nd_err += nd_dist; rt_err += rt_dist; l2_err += l2_dist; dgv_err += dgv_dist; dgi_err += dgi_dist; if (log > 0 && h1_dist > tol) { std::cout << be << ":" << j << " h1 (" << f_val[0] << "," << f_val[1] << "," << f_val[2] << ") vs. (" << h1_gf_val[0] << "," << h1_gf_val[1] << "," << h1_gf_val[2] << ") " << h1_dist << std::endl; } if (log > 0 && nd_dist > tol) { std::cout << be << ":" << j << " nd (" << f_val[0] << "," << f_val[1] << "," << f_val[2] << ") vs. (" << nd_gf_val[0] << "," << nd_gf_val[1] << "," << nd_gf_val[2] << ") " << nd_dist << std::endl; } if (log > 0 && rt_dist > tol) { std::cout << be << ":" << j << " rt (" << f_val[0] << "," << f_val[1] << "," << f_val[2] << ") vs. (" << rt_gf_val[0] << "," << rt_gf_val[1] << "," << rt_gf_val[2] << ") " << rt_dist << std::endl; } if (log > 0 && l2_dist > tol) { std::cout << be << ":" << j << " l2 (" << f_val[0] << "," << f_val[1] << "," << f_val[2] << ") vs. (" << l2_gf_val[0] << "," << l2_gf_val[1] << "," << l2_gf_val[2] << ") " << l2_dist << std::endl; } if (log > 0 && dgv_dist > tol) { std::cout << be << ":" << j << " dgv (" << f_val[0] << "," << f_val[1] << "," << f_val[2] << ") vs. (" << dgv_gf_val[0] << "," << dgv_gf_val[1] << "," << dgv_gf_val[2] << ") " << dgv_dist << std::endl; } if (log > 0 && dgi_dist > tol) { std::cout << be << ":" << j << " dgi (" << f_val[0] << "," << f_val[1] << "," << f_val[2] << ") vs. (" << dgi_gf_val[0] << "," << dgi_gf_val[1] << "," << dgi_gf_val[2] << ") " << dgi_dist << std::endl; } } h1_err /= ir.GetNPoints(); nd_err /= ir.GetNPoints(); rt_err /= ir.GetNPoints(); l2_err /= ir.GetNPoints(); dgv_err /= ir.GetNPoints(); dgi_err /= ir.GetNPoints(); REQUIRE( h1_err == Approx(0.0)); REQUIRE( nd_err == Approx(0.0)); REQUIRE( rt_err == Approx(0.0)); REQUIRE( l2_err == Approx(0.0)); REQUIRE(dgv_err == Approx(0.0)); REQUIRE(dgi_err == Approx(0.0)); } } SECTION("Edge Evaluation 3D") { std::cout << "Edge Evaluation 3D" << std::endl; for (int e = 0; e < mesh.GetNEdges(); e++) { ElementTransformation *T = mesh.GetEdgeTransformation(e); const FiniteElement *fe = h1_fespace.GetEdgeElement(e); const IntegrationRule &ir = IntRules.Get(fe->GetGeomType(), 2*order + 2); double h1_err = 0.0; double tip_data[dim]; Vector tip(tip_data, dim); for (int j=0; j<ir.GetNPoints(); j++) { npts++; const IntegrationPoint &ip = ir.IntPoint(j); T->SetIntPoint(&ip); T->Transform(ip, tip); Func_3D_lin(tip, f_val); h1_xCoef.Eval(h1_gf_val, *T, ip); double h1_dist = Distance(f_val, h1_gf_val, dim); h1_err += h1_dist; if (log > 0 && h1_dist > tol) { std::cout << e << ":" << j << " h1 (" << f_val[0] << "," << f_val[1] << "," << f_val[2] << ") vs. (" << h1_gf_val[0] << "," << h1_gf_val[1] << "," << h1_gf_val[2] << ") " << h1_dist << std::endl; } } h1_err /= ir.GetNPoints(); REQUIRE( h1_err == Approx(0.0)); } } SECTION("Face Evaluation 3D") { std::cout << "Face Evaluation 3D" << std::endl; for (int f = 0; f < mesh.GetNFaces(); f++) { ElementTransformation *T = mesh.GetFaceTransformation(f); const FiniteElement *fe = h1_fespace.GetFaceElement(f); const IntegrationRule &ir = IntRules.Get(fe->GetGeomType(), 2*order + 2); double h1_err = 0.0; double tip_data[dim]; Vector tip(tip_data, dim); for (int j=0; j<ir.GetNPoints(); j++) { npts++; const IntegrationPoint &ip = ir.IntPoint(j); T->SetIntPoint(&ip); T->Transform(ip, tip); Func_3D_lin(tip, f_val); h1_xCoef.Eval(h1_gf_val, *T, ip); double h1_dist = Distance(f_val, h1_gf_val, dim); h1_err += h1_dist; if (log > 0 && h1_dist > tol) { std::cout << f << ":" << j << " h1 (" << f_val[0] << "," << f_val[1] << "," << f_val[2] << ") vs. (" << h1_gf_val[0] << "," << h1_gf_val[1] << "," << h1_gf_val[2] << ") " << h1_dist << std::endl; } } h1_err /= ir.GetNPoints(); REQUIRE( h1_err == Approx(0.0)); } } } } std::cout << "Checked GridFunction::GetVectorValue at " << npts << " 3D points" << std::endl; } } // namespace get_value
40.154937
80
0.391365
[ "mesh", "vector", "transform", "3d" ]
af293d76abe214958a58ac2d82d2817a834bf3c9
555
cpp
C++
helloworld.cpp
LetoThe2nd/node-addon-api-boilerplate
4854c317f679e8d415031b7f7c791a32af0ea75d
[ "MIT" ]
null
null
null
helloworld.cpp
LetoThe2nd/node-addon-api-boilerplate
4854c317f679e8d415031b7f7c791a32af0ea75d
[ "MIT" ]
null
null
null
helloworld.cpp
LetoThe2nd/node-addon-api-boilerplate
4854c317f679e8d415031b7f7c791a32af0ea75d
[ "MIT" ]
null
null
null
#include <napi.h> Napi::String SayHi(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); return Napi::String::New(env, "Hi!"); } Napi::String SayLo(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); return Napi::String::New(env, "Lo!"); } Napi::Object init(Napi::Env env, Napi::Object exports) { exports.Set(Napi::String::New(env, "sayHi"), Napi::Function::New(env, SayHi)); exports.Set(Napi::String::New(env, "sayLo"), Napi::Function::New(env, SayLo)); return exports; }; NODE_API_MODULE(helloworld, init);
25.227273
82
0.657658
[ "object" ]
af2f7ea014c77c012527b5d524596bec6c31a744
7,607
cc
C++
tigon-sql/src/main/c/cluster_manager/cluster_manager.cc
caskdata/tigon
5be6dffd7c79519d1211bb08f75be7dcfbbad392
[ "Apache-2.0" ]
105
2015-01-02T03:41:13.000Z
2018-10-13T01:32:02.000Z
tigon-sql/src/main/c/cluster_manager/cluster_manager.cc
cdapio/tigon
5be6dffd7c79519d1211bb08f75be7dcfbbad392
[ "Apache-2.0" ]
1
2015-03-09T17:00:38.000Z
2015-03-16T20:27:34.000Z
tigon-sql/src/main/c/cluster_manager/cluster_manager.cc
caskdata/tigon
5be6dffd7c79519d1211bb08f75be7dcfbbad392
[ "Apache-2.0" ]
28
2015-02-23T18:59:03.000Z
2017-12-20T01:04:57.000Z
/* ------------------------------------------------ Copyright 2014 AT&T Intellectual Property 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 <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <sys/wait.h> #include <signal.h> #define CLEARINGHOUSE_PORT 6001 #define CLUSTER_INFO_FILE "cluster_info.xml" #define APLLICATION_INFO_FILE "applications.xml" #include <vector> #include <string> using namespace std; extern "C" { #include <lapp.h> } #include "xml_parser.h" #include "iface_q.h" #include "app.h" #include "cluster.h" #include "clearinghouseregistries.h" #include "cluster_manager.h" // cfg directory that stores all the configuration files needed by translate_fta string config_dir; // list of .gsql files vector<string> input_file_names; // root directory of Tigon distribution on all the machines string gscp_dir; // directory into which all the source files and binaries will be placed string build_dir; ifq_t *ifaces_db; map<unsigned, host_info*> host_map; vector<qnode*> top_fta_list; // top level ftas vector<qnode*> lfta_list; // top level ftas map<string, qnode*> qnode_map; map<string, fta_info*> fta_map; map<FTAID, fta_info*, comp_ftaid> reverse_fta_map; map<string, app_node*> app_map; map<FTAID, app_node*, comp_ftaid> reverse_app_map; map<FTAID, fta_node*, comp_ftaid> fta_instance_map; map<string, unsigned> timeout_map; //int flex_fta_lineno, flex_fta_ch; xml_parser* parser = NULL; bool clearinghouse_only = false; unsigned resolve_hostname(const char* hostname) { hostent* ent = NULL; struct in_addr in; unsigned addr; if (isalpha(hostname[0])) { /* host address is a name */ ent = gethostbyname(hostname); } else { addr = inet_addr(hostname); ent = gethostbyaddr((char*)&addr, 4, AF_INET); } if (!ent) { fprintf(stderr, "CLUSTER_MANAGER ERROR: unable to resolve host %s\n", hostname); return 0; } memcpy(&in, ent->h_addr, sizeof(in_addr)); return in.s_addr; } void hand(int iv) { fprintf(stderr, "exiting via signal handler %d...\n", iv); stop_ftas(); //stop_apps(); exit(0); } int main(int argc, char* argv[]) { char buffer[1000]; // ------------------------------- // Handling of Input Arguments // ------------------------------- const char *optstr = "B:C:G:A:"; const char *usage_str = "Usage: %s [-B <build directory>] [-C <config directory>] [-G <tigon directory>] query_file [query_file ...]\n" "\t[-A] : just run remote clearinghouse\n" "\t[-B] : all generated code and executables will be placed in <build directory> on cluster nodes\n" "\t[-C] : use <config directory> for definition files\n" "\t[-G] : <tigon directory> specifies the root of the tigon distribution on all cluster nodes and cluster manager\n\n" "NOTE: all directories must be relative to $HOME"; int i, ret; string ierr; char* home = getenv("HOME"); if (!home) { fprintf(stderr,"CLUSTER_MANAGER ERROR: $HOME is not set - unable to find root directory of tigon distribution\n"); exit(1); } // default values for configuration parameters gscp_dir = string(home) + "/gscpv1"; build_dir = string(home) + "/gscpv1/demos/cluster_demo"; config_dir = string(home) + "/gscpv1/cfg"; // process command-line parameters char chopt; while((chopt = getopt(argc,argv,optstr)) != -1){ switch(chopt){ case 'A': clearinghouse_only = true; break; case 'B': if(optarg != NULL) build_dir = string(home) + "/" + string(optarg) + string("/"); break; case 'C': if(optarg != NULL) config_dir = string(home) + "/" + string(optarg) + string("/"); break; case 'G': if(optarg != NULL) gscp_dir = string(home) + "/" + string(optarg) + string("/"); break; case '?': fprintf(stderr,"Error, argument %c not recognized.\n",optopt); fprintf(stderr,"%s\n", usage_str); exit(1); default: fprintf(stderr,"Invalid arguments\n"); fprintf(stderr,"%s\n", usage_str); exit(1); } } argc -= optind; argv += optind; for (int i = 0; i < argc; ++i) { input_file_names.push_back(argv[i]); } if(input_file_names.size() == 0){ fprintf(stderr,"%s\n", usage_str); exit(1); } // create gscpclearinghouse.cfg file FILE* cfgf = fopen("gscpclearinghouse.cfg", "w"); if (!cfgf) { fprintf(stderr,"CLUSTER_MANAGER ERROR: unable to create gscpclearinghouse.cfg\n"); exit(1); } gethostname(buffer, 1000); unsigned ip = resolve_hostname(buffer); fprintf(cfgf, "%s:%d\n", inet_ntoa(*(in_addr*)(&ip)), CLEARINGHOUSE_PORT); fclose(cfgf); // load the list of cluster nodes cluster_db* cluster = new cluster_db(); if(cluster->load_cluster(CLUSTER_INFO_FILE,ierr)){ fprintf(stderr,"CLUSTER_MANAGER ERROR: can't load cluster definition file %s :\n%s", CLUSTER_INFO_FILE, ierr.c_str()); exit(1); } vector<host_info*> host_list = cluster->get_cluster_nodes(); for (i = 0; i < host_list.size(); ++i) { ip = ntohl(resolve_hostname(host_list[i]->host_name.c_str())) ; fprintf(stderr, "Ip = %d\n", ip); host_map[ip] = host_list[i]; } // load interface definitions ifaces_db = new ifq_t(); string ifx_fname = config_dir + "/ifres.xml"; if(ifaces_db->load_ifaces(ifx_fname,ierr)){ fprintf(stderr,"CLUSTER_MANAGER ERROR: can't load interface resource file %s :\n%s", ifx_fname.c_str(), ierr.c_str()); exit(1); } // now parse application specifications app_db* apps = new app_db(); string apps_fname = APLLICATION_INFO_FILE; if(apps->load_apps(apps_fname,ierr)){ fprintf(stderr,"CLUSTER_MANAGER ERROR: can't load applications definition file %s :\n%s", apps_fname.c_str(), ierr.c_str()); exit(1); } vector<app_node*> app_list = apps->get_apps(); for (i = 0; i < app_list.size(); ++i) { app_map[app_list[i]->app_name] = app_list[i]; } // build and deploy all the quereis if (build_queryset()) { fprintf(stderr, "CLUSTER_MANAGER ERROR: unable to build and deploy query set\n"); return 0; } // start clearinghouse service in a new process if (fork()) { /* initalize host_lib */ printf("Init host lib queue in clearinghouse\n"); if (hostlib_init(CLEARINGHOUSE,0,DEFAULTDEV,0,0)<0) { fprintf(stderr,"%s::error:could not initiate host lib for clearinghouse\n", argv[0]); exit(1); } /* start processing messages should never return*/ if (fta_start_service(-1)<0) { fprintf(stderr,"%s::error:in processing the msg queue\n", argv[0]); exit(1); } fprintf(stderr,"%s::error:start service returned \n",argv[0]); return 0; } // wait a few seconds for clearinghouse to intialize sleep(5); if (!clearinghouse_only) { start_ftas(); // setup the singal handler for proper cleanup signal(SIGTERM, hand); signal(SIGINT, hand); signal(SIGPIPE, hand); // give fta some time to start printf("Waiting for remote ftas to start and register themselves\n"); sleep(30); // start all the applications start_apps(); } // wait for clearinghouse process to terminate wait(NULL); return 0; }
26.05137
136
0.672013
[ "vector" ]
af394e63863cdf3e38db899b087af1830c0f2646
4,817
cpp
C++
src/PathTracer.cpp
jLantxa/PathTracer
37dabfeefebd16799357233242b76eed1f0cd2ab
[ "Apache-2.0" ]
null
null
null
src/PathTracer.cpp
jLantxa/PathTracer
37dabfeefebd16799357233242b76eed1f0cd2ab
[ "Apache-2.0" ]
5
2018-07-11T22:13:05.000Z
2018-07-13T21:22:29.000Z
src/PathTracer.cpp
jLantxa/PathTracer
37dabfeefebd16799357233242b76eed1f0cd2ab
[ "Apache-2.0" ]
null
null
null
/* * This source file is part of PathTracer * * Copyright 2018, 2019 Javier Lancha Vázquez * * 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 "PathTracer.hpp" #include "Common.hpp" #include "Camera.hpp" #include "Light.hpp" #include "Objects.hpp" #include "Surface.hpp" #include "Utils.hpp" #include <algorithm> #include <chrono> #include <limits> #include <vector> #include "debug.hpp" static const char* TAG = "PathTracer"; /// \todo ACCURACY value is completely random Real ACCURACY = 0.0001; void PathTracer::calculateBlocks(std::vector<Block>& blocks, unsigned int width, unsigned int height) { for (unsigned int i = 0; i < width; i += mBlockWidth) { unsigned int right = i + mBlockWidth; if (right > width) right = width; for (unsigned int j = 0; j < height; j += mBlockWidth) { unsigned int down = j + mBlockWidth; if (down > height) down = height; Block block = { .left = i, .up = j, .right = right, .down = down }; blocks.push_back(block); } } } void PathTracer::reorderBlocks(std::vector<Block>& blocks, unsigned width, unsigned height) { int cx = width / 2; int cy = height / 2; std::sort(blocks.begin(), blocks.end(), [&](const Block& lhs, const Block& rhs)-> bool { int lx = (lhs.left + lhs.right) / 2; int ly = (lhs.up + lhs.down) / 2; int rx = (rhs.left + rhs.right) / 2; int ry = (rhs.up + rhs.down) / 2; float dl = pow(lx - cx, 2) + pow(ly - cy, 2); float dr = pow(rx - cx, 2) + pow(ry - cy, 2); return dl < dr; } ); } PathTracer::PathTracer(unsigned spp, unsigned depth) : mMaxDepth(depth), mSPP(spp) { } PathTracer::~PathTracer() { } void PathTracer::addCallback(IResultsListener* listener) { mPartialResultListeners.push_back(listener); } void PathTracer::notifyPartialResult(struct Scene& scene, Camera& camera) { for(IResultsListener* listener : mPartialResultListeners) { listener->onPartialResult(scene, camera); } } void PathTracer::notifyRenderFinished(struct Scene& scene, Camera& camera) { for(IResultsListener* listener : mPartialResultListeners) { listener->onRenderFinished(scene, camera); } } void PathTracer::setBlockSize(unsigned int width, unsigned int height) { mBlockWidth = width; mBlockHeight = height; } void PathTracer::render(struct Scene& scene, Camera& camera) { Surface& surface = camera.getSurface(); const unsigned width = surface.getWidth(); const unsigned height = surface.getHeight(); surface.clear(); Debug::Log::i(TAG, "Render scene: %dx%d", width, height); std::vector<Block> blocks; calculateBlocks(blocks, width, height); reorderBlocks(blocks, width, height); for (unsigned int b = 0; b < blocks.size(); b++) { #pragma omp parallel for for (unsigned int i = blocks[b].left; i < blocks[b].right; i++) { for (unsigned int j = blocks[b].up; j < blocks[b].down; j++) { Ray ray = camera.getRayToPixel(i, j); for (unsigned int n = 0; n < mSPP; n++) { surface[i][j] += traceRay(0, ray, scene); } surface[i][j] *= 1.0f/mSPP; } } notifyPartialResult(scene, camera); } notifyRenderFinished(scene, camera); } Color PathTracer::traceRay(unsigned depth, Ray& ray, struct Scene& scene) { if (depth >= mMaxDepth) { return Color(); } Real t; IObject3D* iObject = intersectObjects(ray, scene.objects, t); if (iObject == nullptr) { return Color(); } Vec3D iPoint_v = ray.point(t); Vec3D iDirection_v = ray.getDirection(); Vec3D iNormal_v = iObject->getHitNormal(iPoint_v, iDirection_v); iPoint_v.set(iPoint_v + ACCURACY*iNormal_v); struct Material iMaterial = iObject->material(); Color emission = iMaterial.emission; Vec3D sample_v = sampleHemisphere(iNormal_v); const Real p = 1.0/(2*M_PI); Ray sampleRay(iPoint_v, sample_v); Color incoming = iMaterial.color * traceRay(depth+1, sampleRay, scene); return emission + p*incoming; }
29.919255
103
0.621549
[ "render", "vector" ]
af3a9fe17818e76e8d6af879c85fd6df190b8afb
967
cc
C++
base/free_list_test.cc
romange/beeri
60718d0f3133fffdf1500f8844852a79c91d8351
[ "BSD-2-Clause" ]
2
2015-01-07T06:34:25.000Z
2019-01-25T10:11:24.000Z
base/free_list_test.cc
romange/beeri
60718d0f3133fffdf1500f8844852a79c91d8351
[ "BSD-2-Clause" ]
null
null
null
base/free_list_test.cc
romange/beeri
60718d0f3133fffdf1500f8844852a79c91d8351
[ "BSD-2-Clause" ]
1
2019-01-25T10:11:28.000Z
2019-01-25T10:11:28.000Z
// Copyright 2015, Beeri 15. All rights reserved. // Author: Roman Gershman (romange@gmail.com) // #include "base/free_list.h" #include <chrono> #include <random> #include <thread> #include "base/gtest.h" namespace base { class FreelistTest : public testing::Test { public: FreelistTest() : list_(100) {} void DeallocSlow(FreeList::T* t) { std::uniform_int_distribution<int> uniform_dist(1, 50); std::chrono::milliseconds dura(uniform_dist(re_)); *t = dura.count(); std::this_thread::sleep_for(dura); list_.Release(t); } protected: FreeList list_; std::default_random_engine re_; }; TEST_F(FreelistTest, Basic) { std::vector<std::thread> workers; for (unsigned i = 0; i < 1000; ++i) { workers.emplace_back(&FreelistTest::DeallocSlow, this, list_.New()); std::this_thread::yield(); } for (unsigned i = 0; i < 1000; ++i) { workers[i].join(); } EXPECT_GE(list_.list_allocated, 100); } } // namespace base
21.488889
72
0.667011
[ "vector" ]
af3d1ebaca2c0005d2a77f07be29b732558d0cbc
3,092
cpp
C++
src/ui/scene_view.cpp
MIXISAMA/Simple-3D-Reconstruction
705977d0206852309f7424dc211dab7682bce0d6
[ "MIT" ]
2
2021-11-22T16:46:21.000Z
2021-11-23T02:19:51.000Z
src/ui/scene_view.cpp
MIXISAMA/Simple-3D-Reconstruction
705977d0206852309f7424dc211dab7682bce0d6
[ "MIT" ]
null
null
null
src/ui/scene_view.cpp
MIXISAMA/Simple-3D-Reconstruction
705977d0206852309f7424dc211dab7682bce0d6
[ "MIT" ]
null
null
null
#include "ui/scene_view.h" #include "file/ply.h" namespace mixi { namespace s3r { SceneView::SceneView( const VertexArray* vertexArray_, const Program* program_ ) : width_(400), height_(400), camera_(glm::vec3(0.0f, 0.0f, 100.0f)), frameBuffer_(new FrameBuffer(width_, height_)), vertexArray_(vertexArray_), program_(program_), projection_( glm::perspective( glm::radians(45.0f), (float)width_ / (float)height_, 1.0f, 10000.0f ) ), view_(camera_.getViewMatrix()), model_(1.0f) { } SceneView::~SceneView() { } void SceneView::resize_(int width, int height) { width_ = width; height_ = height; frameBuffer_ = FrameBuffer::Ptr(new FrameBuffer(width, height)); projection_ = glm::perspective( glm::radians(45.0f), (float)width_ / (float)height_, 1.0f, 10000.0f ); } void SceneView::render() { ImVec2 contentRegionSize = ImGui::GetContentRegionAvail(); if (contentRegionSize.x != width_ || contentRegionSize.y != height_) { resize_(contentRegionSize.x, contentRegionSize.y); } frameBuffer_->bind(); glViewport(0, 0, width_, height_); glClearColor(0.1f, 0.0f, 0.2f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (program_ != nullptr) { program_->use(); onUseProgram_(); if (vertexArray_ != nullptr) { vertexArray_->draw(); } } frameBuffer_->unbind(); ImGui::Image( (void*)(intptr_t)frameBuffer_->texture()->id(), contentRegionSize ); if (!ImGui::IsItemHovered()) { return; } ImGuiIO& io = ImGui::GetIO(); if ( ImGui::IsMouseDown(ImGuiMouseButton_Left) || io.MouseWheel != 0.0f ) { adjustCamera_( io.MouseDelta.x * 0.3f, io.MouseDelta.y * 0.3f, io.MouseWheel ); onAdjustCamera_(); } if (ImGui::IsMouseDown(ImGuiMouseButton_Right)) { adjustModel_( io.MouseDelta.x * 0.01f, io.MouseDelta.y * 0.01f ); onAdjustModel_(); } } void SceneView::setVertexArray(const VertexArray* vertexArray) { vertexArray_ = vertexArray; } void SceneView::setInitTran(const glm::mat4& tran) { model_ = tran; } void SceneView::setProgram(const Program* program) { program_ = program; } void SceneView::adjustCamera_(float left, float down, float forward) { camera_.moveDown(down); camera_.moveLeft(left); camera_.moveForward(forward); view_ = camera_.getViewMatrix(); } void SceneView::adjustModel_(float rx, float ry) { glm::mat4 rotate(1.0f); rotate = glm::rotate(rotate, rx, glm::vec3( 0.0f, 1.0f, 0.0f)); rotate = glm::rotate(rotate, ry, glm::vec3(-1.0f, 0.0f, 0.0f)); model_ = rotate * model_; } void SceneView::onUseProgram_() { program_->setMat4(glm::value_ptr(view_), "view"); program_->setMat4(glm::value_ptr(model_), "model"); program_->setMat4(glm::value_ptr(projection_), "projection"); } } // namespace s3r } // namespace mixi
21.929078
79
0.617076
[ "render", "model" ]
af3ee929c8ef5e978d1fc4e50fc483827bfb6103
1,708
cpp
C++
src/exemplos/kruskal.cpp
marcoputon/CircuitRouting
63bf505fec4169dfc998a85d6472d87040448c9f
[ "MIT" ]
null
null
null
src/exemplos/kruskal.cpp
marcoputon/CircuitRouting
63bf505fec4169dfc998a85d6472d87040448c9f
[ "MIT" ]
null
null
null
src/exemplos/kruskal.cpp
marcoputon/CircuitRouting
63bf505fec4169dfc998a85d6472d87040448c9f
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> using namespace std; struct UF { vector<int> rank; vector<int> root; UF(int n): rank(n, 0), root(n) { for(int i = 0; i < n; ++i) root[i] = i; } int Find(int x) { if (root[x] != x) { root[x] = Find(root[x]); } return root[x]; } void Union(int x, int y) { if (rank[root[x]] > rank[root[y]]) { root[root[y]] = root[x]; } else if (rank[root[x]] < rank[root[y]]) { root[root[x]] = root[y]; } else { root[root[y]] = root[x]; rank[x]++; } } }; struct Edge { int u, v, w; Edge(int u_, int v_, int w_):u(u_), v(v_), w(w_) {} friend bool operator<(const Edge & a, const Edge & b) { return a.w < b.w; } }; struct MST { vector<Edge> edges; vector<Edge> result; int n; int sum; MST(int n_): n(n_), sum(0) {} void compute(bool dir) { UF uf(n); if (dir) sort(edges.rbegin(), edges.rend()); else sort(edges.begin(), edges.end()); result.clear(); sum = 0; for(const Edge & e : edges) { if(uf.Find(e.u) != uf.Find(e.v)) { result.push_back(e); uf.Union(e.u, e.v); sum += e.w; } } } }; int main() { int n; cin >> n; MST mst(n); for(int i = 0; i < n; ++i) { int u, v, w; cin >> u >> v >> w; mst.edges.emplace_back(u-1, v-1, w); } mst.compute(true); cout << mst.sum << '\n'; mst.compute(false); cout << mst.sum << '\n'; }
17.791667
59
0.423888
[ "vector" ]
af4458a4e984aee1b9aff401fc33c32637fb6e2b
511
cpp
C++
src/fs.cpp
AliusDieMorietur/scv
a999e4e8128480eed556f30fe63bcfd7358accc8
[ "MIT" ]
null
null
null
src/fs.cpp
AliusDieMorietur/scv
a999e4e8128480eed556f30fe63bcfd7358accc8
[ "MIT" ]
1
2020-07-22T14:17:55.000Z
2020-07-22T14:17:55.000Z
src/fs.cpp
AliusDieMorietur/scv
a999e4e8128480eed556f30fe63bcfd7358accc8
[ "MIT" ]
null
null
null
#include "headers/fs.h" #include <fstream> #include <filesystem> #include <vector> using namespace std; namespace fs { void write_file(string file_name, string content) { ofstream file (file_name); file << content; file.close(); } string read_file(string file_name) { ifstream file; file.open(file_name); stringstream strStream; strStream << file.rdbuf(); return strStream.str(); } void create_directories(string src) { std::filesystem::create_directories(src); }; }
19.653846
53
0.690802
[ "vector" ]
af544ea103e3b8d8d5b1e4c5e8c03c5d0076bae0
1,914
hpp
C++
AdenitaCoreSE/modules/MSV/includes/MSVDisplayHelper.hpp
edellano/Adenita-SAMSON-Edition-Win-
6df8d21572ef40fe3fc49165dfaa1d4318352a69
[ "BSD-3-Clause" ]
2
2020-09-07T20:48:43.000Z
2021-09-03T05:49:59.000Z
AdenitaCoreSE/modules/MSV/includes/MSVDisplayHelper.hpp
edellano/Adenita-SAMSON-Edition-Linux
a7e267e5dd37e0073f4d1e3e603c5fb1c69a350a
[ "BSD-3-Clause" ]
6
2020-04-05T18:39:28.000Z
2022-01-11T14:28:55.000Z
AdenitaCoreSE/modules/MSV/includes/MSVDisplayHelper.hpp
edellano/Adenita-SAMSON-Edition-Linux
a7e267e5dd37e0073f4d1e3e603c5fb1c69a350a
[ "BSD-3-Clause" ]
2
2021-07-13T12:58:13.000Z
2022-01-11T13:52:00.000Z
#pragma once #include <SAMSON.hpp> #include "ADNAuxiliary.hpp" #include <iostream> #include <iomanip> #include "ADNVectorMath.hpp" #include "DASPolyhedron.hpp" #include "ADNPart.hpp" #include "ADNArray.hpp" #include "ADNConfig.hpp" namespace ADNDisplayHelper { void displayLine(SBPosition3 start, SBPosition3 end, std::string text = ""); void displayCylinder(SBPosition3 start, SBPosition3 end, std::string text = ""); void displayLine(ublas::vector<double> center, ublas::vector<double> dir, int length); void displayVector(SBVector3 vec, SBPosition3 shift); void displayVector(SBVector3 vec, SBPosition3 shift, float * color, int length); void displayArrow(SBVector3 vec, SBPosition3 shift); void displayArrow(SBPosition3 start, SBPosition3 end, unsigned int nodeIndex, float * color, bool selectable = false); void displayLengthText(SBPosition3 start, SBPosition3 end, std::string text = ""); void displayDirectedCylinder(SBPosition3 start, SBPosition3 end); void displayDirectedCylinder(SBPosition3 start, SBPosition3 end, float * color, int radius); void displayDirectedCylinder(float * start, float * end, float * color, int radius); void displayPlane(SBVector3 vec, SBPosition3 shift); void displayOrthoPlane(SBVector3 vec, SBPosition3 shift); void displaySphere(SBPosition3 pos, float radius, ADNArray<float> color); void displayBasePairConnection(ADNPointer<ADNNucleotide> nt); void displayBaseVectors(ADNPointer<ADNNucleotide> nt, SBPosition3 pos); void displayText(SBPosition3 pos, std::string text = ""); void displayTextBottomLeft(std::string text = ""); void displayTriangleMesh(DASPolyhedron * polyhedron); //! Display only the top scales of a part /*! \param ADNPointer to the ADNPart */ void displayPart(ADNPointer<ADNPart> part, float basePairRadius = 1000.0f, float opaqueness = 0.5f); void displayGoldSphere(SBNodeIndexer goldAtoms); };
44.511628
120
0.768548
[ "vector" ]
af6b73546743c16b3d97d2886a749c7d29b1e99c
4,233
cpp
C++
DeepLearning/NeuralNet/PLayer.cpp
dragunovdenis/DeepLearning
1ddd39e7b431b54849e7bd542f9fb0aeb92bb958
[ "MIT" ]
null
null
null
DeepLearning/NeuralNet/PLayer.cpp
dragunovdenis/DeepLearning
1ddd39e7b431b54849e7bd542f9fb0aeb92bb958
[ "MIT" ]
null
null
null
DeepLearning/NeuralNet/PLayer.cpp
dragunovdenis/DeepLearning
1ddd39e7b431b54849e7bd542f9fb0aeb92bb958
[ "MIT" ]
null
null
null
//Copyright (c) 2022 Denys Dragunov, dragunovdenis@gmail.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 "PLayer.h" namespace DeepLearning { PLayer::PLayer(const Index3d& in_size, const Index2d& pool_window_size, const PoolTypeId pool_operator_id) : _in_size(in_size), _pool_window_size(1, pool_window_size.x, pool_window_size.y), _pool_operator_id(pool_operator_id) { _strides = _pool_window_size; } Index3d PLayer::in_size() const { return _in_size; } Index3d PLayer::out_size() const { return Tensor::calc_conv_res_size(_in_size, _pool_window_size, _paddings, _strides); } Index3d PLayer::weight_tensor_size() const { return _pool_window_size; } Tensor PLayer::act(const Tensor& input, AuxLearningData* const aux_learning_data_ptr) const { if (input.size_3d() != in_size()) throw std::exception("Unexpected size of the input tensor"); if (aux_learning_data_ptr) { aux_learning_data_ptr->Input = input; aux_learning_data_ptr->Derivatives = Tensor({0}); } if (_pool_operator_id == PoolTypeId::MIN || _pool_operator_id == PoolTypeId::MAX) { auto [pool_result, index_mapping] = input.min_max_pool_2d({ _pool_window_size.y, _pool_window_size.z }, _pool_operator_id == PoolTypeId::MAX); if (aux_learning_data_ptr) aux_learning_data_ptr->IndexMapping = std::move(index_mapping); return std::move(pool_result); } const auto pool_operator_ptr = PoolOperator::make(weight_tensor_size(), _pool_operator_id); return std::move(input.pool(*pool_operator_ptr, _paddings, _strides)); } std::tuple<Tensor, PLayer::LayerGradient> PLayer::backpropagate(const Tensor& deltas, const AuxLearningData& aux_learning_data, const bool evaluate_input_gradient) const { if (deltas.size_3d() != out_size()) throw std::exception("Unexpected size of the input tensor of derivatives"); if (!evaluate_input_gradient) return std::make_tuple<Tensor, PLayer::LayerGradient>(Tensor(), { Tensor(), std::vector<Tensor>() }); if (_pool_operator_id == PoolTypeId::MIN || _pool_operator_id == PoolTypeId::MAX) { if (aux_learning_data.IndexMapping.size() != out_size().coord_prod()) throw std::exception("Invalid index mapping"); auto input_grad = aux_learning_data.Input.min_max_pool_2d_input_gradient(deltas, aux_learning_data.IndexMapping); return std::make_tuple<Tensor, PLayer::LayerGradient>(std::move(input_grad), { Tensor(), std::vector<Tensor>() }); } const auto pool_operator_ptr = PoolOperator::make(weight_tensor_size(), _pool_operator_id); auto input_grad = aux_learning_data.Input.pool_input_gradient(deltas, *pool_operator_ptr, _paddings, _strides); return std::make_tuple<Tensor, PLayer::LayerGradient>(std::move(input_grad), { Tensor(), std::vector<Tensor>() }); } void PLayer::update(const std::tuple<std::vector<Tensor>, Tensor>& weights_and_biases_increment, const Real& reg_factor) { //Sanity check if (std::get<0>(weights_and_biases_increment).size() != 0 || std::get<1>(weights_and_biases_increment).size() != 0) throw std::exception("There should be no increments for weights and/or biases"); } CummulativeGradient PLayer::init_cumulative_gradient() const { return CummulativeGradient(0, 0); } }
41.097087
145
0.758564
[ "vector" ]
af6fa9b2b5b94c33cfb3c5fe807bf1833d8c43cb
5,175
inl
C++
branch/old_angsys/angsys_beta3/include/angsys/ang/core/inline/listener.inl
ChuyX3/angsys
89b2eaee866bcfd11e66efda49b38acc7468c780
[ "Apache-2.0" ]
null
null
null
branch/old_angsys/angsys_beta3/include/angsys/ang/core/inline/listener.inl
ChuyX3/angsys
89b2eaee866bcfd11e66efda49b38acc7468c780
[ "Apache-2.0" ]
null
null
null
branch/old_angsys/angsys_beta3/include/angsys/ang/core/inline/listener.inl
ChuyX3/angsys
89b2eaee866bcfd11e66efda49b38acc7468c780
[ "Apache-2.0" ]
null
null
null
#ifndef __CORE_LISTENER_H__ #error ... #elif !defined __CORE_LISTENER_INL__ #define __CORE_LISTENER_INL__ template<typename T, typename... Ts> ang::core::delegates::listener<T(Ts...)>::listener() { } template<typename T, typename... Ts> ang::core::delegates::listener<T(Ts...)>::listener(listener&& other) : functions(ang::move(other.functions)) { } template<typename T, typename... Ts> ang::core::delegates::listener<T(Ts...)>::listener(listener const& other) : functions(other.functions) { } template<typename T, typename... Ts> ang::core::delegates::listener<T(Ts...)>::~listener() { clear(); } template<typename T, typename... Ts> void ang::core::delegates::listener<T(Ts...)>::clear() { functions.clear(); } template<typename T, typename... Ts> bool ang::core::delegates::listener<T(Ts...)>::is_empty()const { return functions.is_empty() || functions->is_empty(); } template<typename T, typename... Ts> ang::core::delegates::listen_token<T(Ts...)> ang::core::delegates::listener<T(Ts...)>::push(ang::core::delegates::function<T(Ts...)> func) { functions += ang::move(func); return functions->last(); } template<typename T, typename... Ts> bool ang::core::delegates::listener<T(Ts...)>::pop(ang::core::delegates::listen_token<T(Ts...)> token) { if (functions.is_empty()) return false; return functions->pop_at(token); } template<typename T, typename... Ts> ang::core::delegates::listener<T(Ts...)>& ang::core::delegates::listener<T(Ts...)>::operator = (listener&& other) { functions = ang::move(other.functions); return *this; } template<typename T, typename... Ts> ang::core::delegates::listener<T(Ts...)>& ang::core::delegates::listener<T(Ts...)>::operator = (listener const& other) { functions = other.functions; return *this; } template<typename T, typename... Ts> ang::core::delegates::listen_token<T(Ts...)> ang::core::delegates::listener<T(Ts...)>::operator += (ang::core::delegates::function<T(Ts...)> func) { return push(ang::move(func)); } template<typename T, typename... Ts> bool ang::core::delegates::listener<T(Ts...)>::operator -= (ang::core::delegates::listen_token<T(Ts...)> token) { return pop(ang::move(token)); } template<typename T, typename... Ts> ang::collections::ienum_t<T> ang::core::delegates::listener<T(Ts...)>::operator() (Ts... args)const { collections::vector<T> result; if (!is_empty()) { for (function<T(Ts...)>func : functions) result += func(args...); } return result.get(); } template<typename T, typename... Ts> ang::collections::ienum_t<T> ang::core::delegates::listener<T(Ts...)>::invoke(Ts... args)const { collections::vector<T> result; if (!is_empty()) { for (function<T(Ts...)>func : functions) result += func(args...); } return result.get(); } template<typename... Ts> ang::core::delegates::listener<void(Ts...)>::listener() { } template<typename... Ts> ang::core::delegates::listener<void(Ts...)>::listener(listener&& other) : functions(ang::move(other.functions)) { } template<typename... Ts> ang::core::delegates::listener<void(Ts...)>::listener(listener const& other) : functions(other.functions) { } template<typename... Ts> ang::core::delegates::listener<void(Ts...)>::~listener() { clear(); } template<typename... Ts> void ang::core::delegates::listener<void(Ts...)>::clear() { functions.reset(); } template<typename... Ts> bool ang::core::delegates::listener<void(Ts...)>::is_empty()const { return functions.is_empty() || functions->is_empty(); } template<typename... Ts> ang::core::delegates::listen_token<void(Ts...)> ang::core::delegates::listener<void(Ts...)>::push(ang::core::delegates::function<void(Ts...)> func) { functions += ang::move(func); return functions->last(); } template<typename... Ts> bool ang::core::delegates::listener<void(Ts...)>::pop(ang::core::delegates::listen_token<void(Ts...)> token) { if (functions.is_empty()) return false; return functions->pop_at(token); } template<typename... Ts> ang::core::delegates::listener<void(Ts...)>& ang::core::delegates::listener<void(Ts...)>::operator = (listener&& other) { functions = ang::move(other.functions); return *this; } template<typename... Ts> ang::core::delegates::listener<void(Ts...)>& ang::core::delegates::listener<void(Ts...)>::operator = (listener const& other) { functions = other.functions; return *this; } template<typename... Ts> ang::core::delegates::listen_token<void(Ts...)> ang::core::delegates::listener<void(Ts...)>::operator += (ang::core::delegates::function<void(Ts...)> func) { return push(ang::move(func)); } template<typename... Ts> bool ang::core::delegates::listener<void(Ts...)>::operator -= (ang::core::delegates::listen_token<void(Ts...)> token) { return pop(ang::move(token)); } template<typename... Ts> void ang::core::delegates::listener<void(Ts...)>::invoke(Ts... args)const { if (!is_empty()) { for (function<void(Ts...)> const & func : functions) { func(args...); } } } template<typename... Ts> void ang::core::delegates::listener<void(Ts...)>::operator() (Ts... args)const { if (!is_empty()) { for (function<void(Ts...)> const & func : functions) { func(args...); } } } #endif//__CORE_LISTENER_INL__
24.526066
155
0.667633
[ "vector" ]