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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d1589052523e3f7b0f911b6081b91d04e9f91f8b | 2,039 | cpp | C++ | Project1/Project1/TestCaseRunner.cpp | AdelardBanza/SingleTestHarness | ef9257d56bb161068d9db4b02c8aa06690f87fb6 | [
"MIT"
] | null | null | null | Project1/Project1/TestCaseRunner.cpp | AdelardBanza/SingleTestHarness | ef9257d56bb161068d9db4b02c8aa06690f87fb6 | [
"MIT"
] | null | null | null | Project1/Project1/TestCaseRunner.cpp | AdelardBanza/SingleTestHarness | ef9257d56bb161068d9db4b02c8aa06690f87fb6 | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
// TestCaseRunner.cpp - TestCaseRunner class member-function definitions //
// ver 1.0 //
// Language: C++, Visual Studio 2017 //
// Platform: HP G1 800, Windows 10 //
// Application: Single Test Harness Project, CSE687 - Object Oriented Design //
// Author: Adelard Banza, //
// abanza@syr.edu //
///////////////////////////////////////////////////////////////////////////////
#include "TestHarness.h"
#include <exception>
#include <stdexcept>
using std::exception;
using std::string;
bool TestCaseRunner::run(const std::string& contextStr, TestLogger& testLogger) const
{
// log the begining of the test case
testLogger.logTestCaseBegin(contextStr);
AssertionManager::getInstance().pushCntx(contextStr, &testLogger);
// a variable to hold the test result
bool testResult = true;
// a variable to hold the test message
string msg;
try
{
// run the test executor function
testResult = this->testExecutor();
bool assertResults = AssertionManager::getInstance().popCntx();
testResult &= assertResults;
// deal with no excption case
if (testResult)
{
testLogger.logTestCaseSuccess(contextStr);
}
else
{
testLogger.logTestCaseFail(contextStr);
}
}
catch (std::logic_error e)
{
// deal with a standard library exception
testResult = false;
testLogger.logTestCaseFailWithSpecificException(contextStr, "logic_error", e);
}
catch (exception e)
{
// deal with a standard library exception
testResult = false;
testLogger.logTestCaseFailWithException(contextStr, e);
}
catch (...)
{
// deal with an unknown exception type
testResult = false;
testLogger.logTestCaseFailWithUnknownException(contextStr);
}
return testResult;
} | 29.550725 | 87 | 0.57332 | [
"object"
] |
d15c3ca85b3acab538e2ff7c4be4e90b3d094806 | 14,837 | cpp | C++ | Roller/Content/ParallelTransportFrame.cpp | GarrettVance/Roller | ce996a4e9df785a4d2259360b048dc25b1686696 | [
"MIT"
] | 1 | 2020-06-20T08:27:29.000Z | 2020-06-20T08:27:29.000Z | Roller/Content/ParallelTransportFrame.cpp | GarrettVance/Roller | ce996a4e9df785a4d2259360b048dc25b1686696 | [
"MIT"
] | null | null | null | Roller/Content/ParallelTransportFrame.cpp | GarrettVance/Roller | ce996a4e9df785a4d2259360b048dc25b1686696 | [
"MIT"
] | null | null | null | //
//
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
// ghv : Garrett Vance : 20180607
//
//
// Implementation of Parallel Transport Frames
// following Andrew J. Hanson's 1995 paper
// "Parallel Transport Approach to Curve Framing".
//
//
// DirectX 11 Application for Windows 10 UWP.
//
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
#include "pch.h"
#include "XModLorenzLoft.h"
#include "..\Common\DirectXHelper.h"
#include <fstream>
#include <string>
#include <sstream>
#include <iterator>
using namespace HvyDX;
using namespace DirectX;
using namespace Windows::Foundation;
using Microsoft::WRL::ComPtr;
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void XModLorenzLoft::FiniteDifferences_Derivative()
{
double const e_underflow = 0.0000000001; // TODO: too small;
for (UINT idx_nodes = 0; idx_nodes < loft_axon_arc_density; idx_nodes++)
{
// Obtain an approximate first derivative dr/dt
// (aka tangent vector) via finite difference techniques:
UINT idx_neung = idx_nodes;
UINT idx_song = (idx_nodes == (-1 + loft_axon_arc_density)) ? 0 : 1 + idx_nodes;
double dt =
loft_axons.at(idx_song).axon_elapsed_time -
loft_axons.at(idx_neung).axon_elapsed_time;
if (abs(dt) < e_underflow)
{
if (dt < 0.00) dt = -1.00 * e_underflow;
else if (dt > 0.00) dt = e_underflow;
}
XMVECTOR drdt = (loft_axons.at(idx_song).axon_position_V -
loft_axons.at(idx_neung).axon_position_V) / (float)dt;
XMStoreFloat3(
&loft_axons.at(idx_neung).axon_tangent_drdt,
drdt
);
}
}
template<typename T>
std::vector<T> gv_split_n(const std::string& line) {
std::istringstream is(line);
return std::vector<T>(std::istream_iterator<T>(is), std::istream_iterator<T>());
}
size_t XModLorenzLoft::ReadLorenzDataFile()
{
// My typical Lorenz Attractor data file has 60 thousand records.
loft_axons.resize(1 + loft_axon_arc_density);
#ifdef _DEBUG
std::fstream gFStr("StrangeAttractor\\lorenz_debug.ghvdata", std::ios_base::in);
#else
std::fstream gFStr("StrangeAttractor\\lorenz.ghvdata", std::ios_base::in);
#endif
if (!gFStr.is_open()) { return 0; }
std::string g_line = "";
XMFLOAT3 tmp_position;
float tmp_time;
XMFLOAT3 tmp_drdt;
XMFLOAT3 tmp_d2rdt2;
VHG_Axonodromal_Vertex tmp_axon;
uint32_t idxLoop = 0;
uint32_t trueLoopCount = 0;
while (std::getline(gFStr, g_line))
{
// Fields in data file:
// ==================================
// position_x, position_y, position_z
// elapsed_time
// dr/dt__x, dr/dt__y, dr/dt__z
// d2r/dt2__x, d2r/dt2__y; d2r/dt2__z
// ==================================
// if (trueLoopCount > 1500)
if (trueLoopCount > 1515)
{
std::istringstream gSS(g_line);
gSS >> tmp_position.x >> tmp_position.y >> tmp_position.z >> tmp_time >> tmp_drdt.x >> tmp_drdt.y >> tmp_drdt.z >> tmp_d2rdt2.x >> tmp_d2rdt2.y >> tmp_d2rdt2.z;
XMVECTOR tmp_position_V = XMLoadFloat3(&tmp_position);
tmp_axon = { tmp_position, tmp_position_V, tmp_time, tmp_drdt, tmp_d2rdt2 };
loft_axons.at(idxLoop) = tmp_axon;
idxLoop++;
}
trueLoopCount++;
if (idxLoop >= loft_axon_arc_density) // obfuscate;
{
break;
}
}
gFStr.close(); // CLOSE THE FILE !!!!!
return loft_axons.size();
}
void XModLorenzLoft::HansonParallelTransportFrame()
{
// TODO: merge vectors unit_tangent and transported_normal into one vector
uint32_t card_surfpts = loft_axon_arc_density * (1 + loft_tube_facets);
std::vector<VHG_Vertex_PosTex> *surface_points = new std::vector<VHG_Vertex_PosTex>(card_surfpts);
std::vector<VHG_Vertex_PosTex> *spoke_lines = new std::vector<VHG_Vertex_PosTex>;
std::vector<VHG_Vertex_PosTex> *surface_triangles = new std::vector<VHG_Vertex_PosTex>;
size_t record_count = ReadLorenzDataFile();
//
// Bootstrap: Special case when idx_nodes == 0:
// ========================================
// Construct what Andrew J. Hanson terms the "initial normal vector V0":
//
XMVECTOR axon_delta_r = loft_axons.at(1).axon_position_V - loft_axons.at(0).axon_position_V;
XMVECTOR g_zero = XMVector3Cross(loft_axons.at(0).axon_position_V, axon_delta_r);
XMVECTOR h_normalized_normal = XMVector3Normalize(XMVector3Cross(g_zero, axon_delta_r));
loft_axons.at(0).transported_normal = h_normalized_normal;
XMStoreFloat3(& (loft_axons.at(0).axon_normal), h_normalized_normal); // ghv: added 20190313;
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// End of bootstrap;
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
XMVECTOR nut_curr;
XMVECTOR nut_next = XMVector3Normalize(XMLoadFloat3(&(loft_axons.at(0).axon_tangent_drdt)));
const float epsilon_length = 0.0001f;
for (UINT idx_frame = 0; idx_frame < loft_axon_arc_density; idx_frame++)
{
if (idx_frame < -1 + loft_axon_arc_density)
{
nut_curr = nut_next;
nut_next = XMVector3Normalize(XMLoadFloat3(&(loft_axons.at(1 + idx_frame).axon_tangent_drdt)));
XMVECTOR B_vector = XMVector3Cross(nut_curr, nut_next);
float B_length = XMVectorGetX(XMVector3Length(B_vector));
XMVECTOR next_transported_normal;
if (B_length < epsilon_length)
{
next_transported_normal = loft_axons.at(idx_frame).transported_normal;
}
else
{
XMVECTOR B_unit_vector = XMVector3Normalize(B_vector);
XMVECTOR angle_theta_vector = XMVector3AngleBetweenNormals(nut_curr, nut_next);
float angle_theta = XMVectorGetX(angle_theta_vector);
XMMATRIX gv_rotation_matrix = XMMatrixRotationNormal(B_unit_vector, angle_theta);
next_transported_normal = XMVector3Transform(
loft_axons.at(idx_frame).transported_normal,
gv_rotation_matrix
);
}
loft_axons.at(1 + idx_frame).transported_normal = next_transported_normal;
XMStoreFloat3(&(loft_axons.at(1 + idx_frame).axon_normal), next_transported_normal); // ghv: added 20190313;
}
XMVECTOR unit_normal = XMVector3Normalize(loft_axons.at(idx_frame).transported_normal);
// In order to orient and position the cross-section,
// need another normal vector in addition to the transported_normal.
// I have chosen to use vector B = T cross N.
XMVECTOR binormal = XMVector3Cross(
XMVector3Normalize(XMLoadFloat3(&(loft_axons.at(idx_frame).axon_tangent_drdt))),
unit_normal
);
XMStoreFloat3(& (loft_axons.at(idx_frame).axon_binormal), binormal); // ghv: added 20190315;
// TODO: confirm that the binormal doesn't need explicit normalization;
for (uint32_t k = 0; k <= loft_tube_facets; ++k) // HAZARD : loop upper limit is <= not < !!!!
{
// Poloidal loop:
float t_fraction = k / (float)loft_tube_facets;
float angle_phi = t_fraction * 2 * XM_PI;
float C_x = loft_tube_radius * cosf(angle_phi);
float C_y = loft_tube_radius * sinf(angle_phi);
XMVECTOR vectorP = loft_axons.at(idx_frame).axon_position_V + C_x * unit_normal + C_y * binormal;
XMFLOAT3 tmp_f3;
XMStoreFloat3(&tmp_f3, vectorP);
VHG_Vertex_PosTex tmp_surface_point; // or can use = { tmp_f3, XMFLOAT2(0.f, 0.f) };
tmp_surface_point.e_pos = tmp_f3;
tmp_surface_point.e_texco = XMFLOAT2(0.f, 0.f);
uint32_t ii = idx_frame * (1 + loft_tube_facets) + k;
surface_points->at(ii).e_pos = tmp_f3;
surface_points->at(ii).e_texco = XMFLOAT2(0.f, 0.f);
// std::vector just for LINELIST topology to show radial segments
// from space curve out to points on the tube surface:
VHG_Vertex_PosTex tmp_spoke;
tmp_spoke.e_pos = (loft_axons.at(idx_frame)).axon_position_r;
tmp_spoke.e_texco = XMFLOAT2(0.f, 0.f);
spoke_lines->push_back(tmp_spoke);
spoke_lines->push_back(tmp_surface_point);
}
// for each cross-section facet;
}
loft_vertex_buffer_1_count = (uint32_t)spoke_lines->size();
Create_Vertex_Buffer(
spoke_lines,
loft_vertex_buffer_1_buffer.ReleaseAndGetAddressOf()
); // use topology = LINELIST;
VHG_Vertex_PosTex quad_top_left;
VHG_Vertex_PosTex quad_top_right;
VHG_Vertex_PosTex quad_bottom_right;
VHG_Vertex_PosTex quad_bottom_left;
for (uint32_t i_axial = 0; i_axial < -1 + loft_axon_arc_density; i_axial++)
{
for (uint32_t i_poloidal = 0; i_poloidal < loft_tube_facets; i_poloidal++)
{
// set the texture coordinates:
uint32_t ii = i_poloidal + (loft_tube_facets + 1) * i_axial;
quad_top_left = { surface_points->at(0 + ii).e_pos, XMFLOAT2(0.f, 1.f), i_axial };
quad_top_right = { surface_points->at((loft_tube_facets + 1) + ii).e_pos, XMFLOAT2(0.f, 0.f), i_axial };
quad_bottom_right = { surface_points->at((loft_tube_facets + 2) + ii).e_pos, XMFLOAT2(1.f, 0.f), i_axial };
quad_bottom_left = { surface_points->at(1 + ii).e_pos, XMFLOAT2(1.f, 1.f), i_axial };
// Synthesize the 1st of the 2 triangles:
surface_triangles->push_back(quad_top_left);
surface_triangles->push_back(quad_top_right);
surface_triangles->push_back(quad_bottom_right);
// Synthesize the 2nd triangle:
surface_triangles->push_back(quad_bottom_right);
surface_triangles->push_back(quad_bottom_left);
surface_triangles->push_back(quad_top_left);
}
}
loft_vertex_buffer_2_count = (uint32_t)surface_triangles->size();
Create_Vertex_Buffer(
surface_triangles,
loft_vertex_buffer_2_buffer.ReleaseAndGetAddressOf()
); // use topology = TRIANGLELIST;
#if 3 == 4
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
// Use DirectXMesh ComputeNormals() method
// to generate vertex normals for each triangle:
//
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
XMFLOAT2 nul2 = XMFLOAT2(0.f, 0.f);
XMFLOAT3 nul3 = XMFLOAT3(0.f, 0.f, 0.f);
XMVECTOR nulXMV = XMVectorSet(0.f, 0.f, 0.f, 0.f);
int32_t countOfVertices = (int32_t)surface_triangles->size();
int32_t countOfTriangles = countOfVertices / 3;
DWORD *arrTriangles = new DWORD[countOfVertices]{ 0 };
int32_t idxCWS = 0;
for (idxCWS = 0; idxCWS < countOfVertices; idxCWS++)
{
arrTriangles[idxCWS] = idxCWS;
}
XMFLOAT3 *arrVertices = new XMFLOAT3[countOfVertices]{ nul3 };
XMFLOAT2 *arrTexco = new XMFLOAT2[countOfVertices]{ nul2 };
int32_t idxVertx = 0;
std::vector<VHG_Vertex_PosTex>::iterator itVertx;
for (itVertx = surface_triangles->begin(); itVertx != surface_triangles->end(); ++itVertx)
{
arrVertices[idxVertx] = (*itVertx).e_pos;
arrTexco[idxVertx] = (*itVertx).e_texco;
idxVertx++;
}
XMFLOAT3 *normals = new XMFLOAT3[countOfVertices]{nul3};
DirectX::ComputeNormals(
(uint32_t*)arrTriangles,
countOfTriangles,
arrVertices,
countOfVertices,
CNORM_DEFAULT,
normals
);
// Move the newly generated normals data into the e_master_lofts vector:
idxVertx = 0;
for (itVertx = surface_triangles->begin(); itVertx != surface_triangles->end(); ++itVertx)
{
(*itVertx).e_normal = normals[idxVertx];
idxVertx++;
}
Platform::String^ plat_local_folder =
Windows::Storage::ApplicationData::Current->LocalFolder->Path;
std::wstring local_folder_w(plat_local_folder->Begin());
std::string loclal_folder_a(local_folder_w.begin(), local_folder_w.end());
char fully_qualified_path_a[512];
sprintf_s(
fully_qualified_path_a, 512,
"%s\\ghv_lorenz_data.txt",
(const char*)loclal_folder_a.c_str()
);
#endif
#if 3 == 4
std::ofstream gv_ofstream(fully_qualified_path_a, std::ios::trunc);
if (!gv_ofstream.is_open())
{
DX::ThrowIfFailed(E_FAIL);
}
for (uint32_t idxFile = 0; idxFile < countOfVertices; idxFile++)
{
char file_record[256];
sprintf_s(
file_record, 256,
"%10.6f \t %10.6f \t %10.6f \t %10.6f \t %10.6f \t %10.6f \t %10.6f \t %10.6f \n",
surface_triangles->at(idxFile).e_pos.x,
surface_triangles->at(idxFile).e_pos.y,
surface_triangles->at(idxFile).e_pos.z,
surface_triangles->at(idxFile).e_normal.x,
surface_triangles->at(idxFile).e_normal.y,
surface_triangles->at(idxFile).e_normal.z,
surface_triangles->at(idxFile).e_texco.x,
surface_triangles->at(idxFile).e_texco.y
);
gv_ofstream << file_record;
}
gv_ofstream.close();
#endif
delete surface_triangles; surface_triangles = nullptr;
delete spoke_lines; spoke_lines = nullptr;
delete surface_points; surface_points = nullptr;
}
| 33.797267 | 173 | 0.563861 | [
"vector"
] |
d15f826c8f173d5cea0dca83acff503c778cab7e | 22,210 | cpp | C++ | src/mame/drivers/vulgus.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 26 | 2015-03-31T06:25:51.000Z | 2021-12-14T09:29:04.000Z | src/mame/drivers/vulgus.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | null | null | null | src/mame/drivers/vulgus.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 10 | 2015-03-27T05:45:51.000Z | 2022-02-04T06:57:36.000Z | // license:BSD-3-Clause
// copyright-holders:Mirko Buffoni
/***************************************************************************
Vulgus memory map (preliminary)
driver by Mirko Buffoni
MAIN CPU
0000-9fff ROM
cc00-cc7f Sprites
d000-d3ff Video RAM
d400-d7ff Color RAM
d800-dbff background video RAM
dc00-dfff background color RAM
e000-efff RAM
read:
c000 IN0
c001 IN1
c002 IN2
c003 DSW1
c004 DSW2
write:
c802 background y scroll low 8 bits
c803 background x scroll low 8 bits
c805 background palette bank selector
c902 background y scroll high bit
c903 background x scroll high bit
SOUND CPU
0000-3fff ROM
4000-47ff RAM
write:
8000 AY-3-8910 #1 control
8001 AY-3-8910 #1 write
c000 AY-3-8910 #2 control
c001 AY-3-8910 #2 write
All Clocks and Vsync verified by Corrado Tomaselli (August 2012)
***************************************************************************/
#include "emu.h"
#include "includes/vulgus.h"
#include "cpu/z80/z80.h"
#include "machine/gen_latch.h"
#include "sound/ay8910.h"
#include "screen.h"
#include "speaker.h"
INTERRUPT_GEN_MEMBER(vulgus_state::vblank_irq)
{
device.execute().set_input_line_and_vector(0, HOLD_LINE, 0xd7); /* Z80 - RST 10h - vblank */
}
void vulgus_state::main_map(address_map &map)
{
map(0x0000, 0x9fff).rom();
map(0xc000, 0xc000).portr("SYSTEM");
map(0xc001, 0xc001).portr("P1");
map(0xc002, 0xc002).portr("P2");
map(0xc003, 0xc003).portr("DSW1");
map(0xc004, 0xc004).portr("DSW2");
map(0xc800, 0xc800).w("soundlatch", FUNC(generic_latch_8_device::write));
map(0xc801, 0xc801).nopw(); // ?
map(0xc802, 0xc803).ram().share("scroll_low");
map(0xc804, 0xc804).w(FUNC(vulgus_state::c804_w));
map(0xc805, 0xc805).w(FUNC(vulgus_state::palette_bank_w));
map(0xc902, 0xc903).ram().share("scroll_high");
map(0xcc00, 0xcc7f).ram().share("spriteram");
map(0xd000, 0xd7ff).ram().w(FUNC(vulgus_state::fgvideoram_w)).share("fgvideoram");
map(0xd800, 0xdfff).ram().w(FUNC(vulgus_state::bgvideoram_w)).share("bgvideoram");
map(0xe000, 0xefff).ram();
}
void vulgus_state::sound_map(address_map &map)
{
map(0x0000, 0x1fff).rom();
map(0x4000, 0x47ff).ram();
map(0x6000, 0x6000).r("soundlatch", FUNC(generic_latch_8_device::read));
map(0x8000, 0x8001).w("ay1", FUNC(ay8910_device::address_data_w));
map(0xc000, 0xc001).w("ay2", FUNC(ay8910_device::address_data_w));
}
static INPUT_PORTS_START( vulgus )
PORT_START("SYSTEM")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNKNOWN ) /* probably unused */
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN ) /* probably unused */
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNKNOWN ) /* probably unused */
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNKNOWN ) /* probably unused */
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_START("P1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START("P2")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_COCKTAIL
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_COCKTAIL
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_COCKTAIL
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_COCKTAIL
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_COCKTAIL
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_COCKTAIL
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START("DSW1")
PORT_DIPNAME( 0x03, 0x03, DEF_STR( Lives ) ) PORT_DIPLOCATION("SW1:8,7")
PORT_DIPSETTING( 0x01, "1" )
PORT_DIPSETTING( 0x02, "2" )
PORT_DIPSETTING( 0x03, "3" )
PORT_DIPSETTING( 0x00, "5" )
/* Only the parent set seems to use/see the second coin slot even if set to Cocktail mode */
PORT_DIPNAME( 0x1c, 0x1c, DEF_STR( Coin_B ) ) PORT_DIPLOCATION("SW1:6,5,4")
PORT_DIPSETTING( 0x10, DEF_STR( 5C_1C ) )
PORT_DIPSETTING( 0x08, DEF_STR( 4C_1C ) )
PORT_DIPSETTING( 0x18, DEF_STR( 3C_1C ) )
PORT_DIPSETTING( 0x04, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x1c, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x0c, DEF_STR( 1C_2C ) )
PORT_DIPSETTING( 0x14, DEF_STR( 1C_3C ) )
/* PORT_DIPSETTING( 0x00, "Invalid" ) disables both coins */
PORT_DIPNAME( 0xe0, 0xe0, DEF_STR( Coin_A ) ) PORT_DIPLOCATION("SW1:3,2,1")
PORT_DIPSETTING( 0x80, DEF_STR( 5C_1C ) )
PORT_DIPSETTING( 0x40, DEF_STR( 4C_1C ) )
PORT_DIPSETTING( 0xc0, DEF_STR( 3C_1C ) )
PORT_DIPSETTING( 0x20, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0xe0, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x60, DEF_STR( 1C_2C ) )
PORT_DIPSETTING( 0xa0, DEF_STR( 1C_3C ) )
PORT_DIPSETTING( 0x00, DEF_STR( Free_Play ) )
PORT_START("DSW2")
PORT_DIPUNUSED_DIPLOC( 0x01, 0x01, "SW2:8" ) /* Shown as "Unused" in the manual, are 7 & 8 undocutmented Difficulty?? */
PORT_DIPUNUSED_DIPLOC( 0x02, 0x02, "SW2:7" ) /* Shown as "Unused" in the manual, Code performs a read then (& 0x03) */
PORT_DIPNAME( 0x04, 0x04, "Demo Music" ) PORT_DIPLOCATION("SW2:6")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x04, DEF_STR( On ) )
PORT_DIPNAME( 0x08, 0x08, DEF_STR( Demo_Sounds ) ) PORT_DIPLOCATION("SW2:5")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x08, DEF_STR( On ) )
PORT_DIPNAME( 0x70, 0x70, DEF_STR( Bonus_Life ) ) PORT_DIPLOCATION("SW2:4,3,2")
PORT_DIPSETTING( 0x30, "10000 50000" )
PORT_DIPSETTING( 0x50, "10000 60000" )
PORT_DIPSETTING( 0x10, "10000 70000" )
PORT_DIPSETTING( 0x70, "20000 60000" )
PORT_DIPSETTING( 0x60, "20000 70000" )
PORT_DIPSETTING( 0x20, "20000 80000" )
PORT_DIPSETTING( 0x40, "30000 70000" )
PORT_DIPSETTING( 0x00, DEF_STR( None ) )
PORT_DIPNAME( 0x80, 0x00, DEF_STR( Cabinet ) ) PORT_DIPLOCATION("SW2:1")
PORT_DIPSETTING( 0x00, DEF_STR( Upright ) )
PORT_DIPSETTING( 0x80, DEF_STR( Cocktail ) )
INPUT_PORTS_END
static const gfx_layout charlayout =
{
8,8,
RGN_FRAC(1,1),
2,
{ 4, 0 },
{ 0, 1, 2, 3, 8+0, 8+1, 8+2, 8+3 },
{ 0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16 },
16*8
};
static const gfx_layout tilelayout =
{
16,16,
RGN_FRAC(1,3),
3,
{ RGN_FRAC(0,3), RGN_FRAC(1,3), RGN_FRAC(2,3) },
{ 0, 1, 2, 3, 4, 5, 6, 7,
16*8+0, 16*8+1, 16*8+2, 16*8+3, 16*8+4, 16*8+5, 16*8+6, 16*8+7 },
{ 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8,
8*8, 9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8 },
32*8
};
static const gfx_layout spritelayout =
{
16,16,
RGN_FRAC(1,2),
4,
{ RGN_FRAC(1,2)+4, RGN_FRAC(1,2)+0, 4, 0 },
{ 0, 1, 2, 3, 8+0, 8+1, 8+2, 8+3,
32*8+0, 32*8+1, 32*8+2, 32*8+3, 33*8+0, 33*8+1, 33*8+2, 33*8+3 },
{ 0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16,
8*16, 9*16, 10*16, 11*16, 12*16, 13*16, 14*16, 15*16 },
64*8
};
static GFXDECODE_START( gfx_vulgus )
GFXDECODE_ENTRY( "gfx1", 0, charlayout, 0, 64 )
GFXDECODE_ENTRY( "gfx2", 0, tilelayout, 64*4+16*16, 32*4 )
GFXDECODE_ENTRY( "gfx3", 0, spritelayout, 64*4, 16 )
GFXDECODE_END
void vulgus_state::vulgus(machine_config &config)
{
/* basic machine hardware */
Z80(config, m_maincpu, XTAL(12'000'000)/4); /* 3 MHz */
m_maincpu->set_addrmap(AS_PROGRAM, &vulgus_state::main_map);
m_maincpu->set_vblank_int("screen", FUNC(vulgus_state::vblank_irq));
Z80(config, m_audiocpu, XTAL(12'000'000)/4); /* 3 MHz */
m_audiocpu->set_addrmap(AS_PROGRAM, &vulgus_state::sound_map);
m_audiocpu->set_periodic_int(FUNC(vulgus_state::irq0_line_hold), attotime::from_hz(8*60));
/* video hardware */
screen_device &screen(SCREEN(config, "screen", SCREEN_TYPE_RASTER));
screen.set_raw(XTAL(12'000'000)/2, 384, 128, 0, 262, 22, 246); // hsync is 50..77, vsync is 257..259
screen.set_screen_update(FUNC(vulgus_state::screen_update));
screen.set_palette(m_palette);
GFXDECODE(config, m_gfxdecode, m_palette, gfx_vulgus);
PALETTE(config, m_palette, FUNC(vulgus_state::vulgus_palette), 64*4+16*16+4*32*8, 256);
/* sound hardware */
SPEAKER(config, "mono").front_center();
GENERIC_LATCH_8(config, "soundlatch");
AY8910(config, "ay1", XTAL(12'000'000)/8).add_route(ALL_OUTPUTS, "mono", 0.25); /* 1.5 MHz */
AY8910(config, "ay2", XTAL(12'000'000)/8).add_route(ALL_OUTPUTS, "mono", 0.25); /* 1.5 MHz */
}
/***************************************************************************
Game driver(s)
***************************************************************************/
ROM_START( vulgus ) /* Board ID# 84602-01A-1 */
ROM_REGION( 0x1c000, "maincpu", 0 )
ROM_LOAD( "vulgus.002", 0x0000, 0x2000, CRC(e49d6c5d) SHA1(48072aaa1f2603b6301d7542cc3df10ead2847bb) )
ROM_LOAD( "vulgus.003", 0x2000, 0x2000, CRC(51acef76) SHA1(14dda82b90f9c3a309561a73c300cb54b5fca77d) )
ROM_LOAD( "vulgus.004", 0x4000, 0x2000, CRC(489e7f60) SHA1(f3f685955fc42f238909dcdb5edc4c117e5543db) )
ROM_LOAD( "vulgus.005", 0x6000, 0x2000, CRC(de3a24a8) SHA1(6bc9dda7dbbbef82e9f61c9d5cf1555e5290b249) )
ROM_LOAD( "1-8n.bin", 0x8000, 0x2000, CRC(6ca5ca41) SHA1(6f28d143e984d3d6af3114702ec27d6e878cc35f) )
ROM_REGION( 0x10000, "audiocpu", 0 )
ROM_LOAD( "1-11c.bin", 0x0000, 0x2000, CRC(3bd2acf4) SHA1(b58fb1ea7e30018102ee420d52a1597615412eb1) )
ROM_REGION( 0x02000, "gfx1", 0 )
ROM_LOAD( "1-3d.bin", 0x00000, 0x2000, CRC(8bc5d7a5) SHA1(c572b4a26f12013f5f6463b79ba9cbee4c474bbe) ) /* characters */
ROM_REGION( 0x0c000, "gfx2", 0 )
ROM_LOAD( "2-2a.bin", 0x00000, 0x2000, CRC(e10aaca1) SHA1(f9f0d05475ae4c554552a71bc2f60e02b1442eb1) ) /* tiles */
ROM_LOAD( "2-3a.bin", 0x02000, 0x2000, CRC(8da520da) SHA1(c4c633a909526308de4ad83e8ca449fa71eb3cb5) )
ROM_LOAD( "2-4a.bin", 0x04000, 0x2000, CRC(206a13f1) SHA1(645666895127aededfa7872b20b7725948a9c462) )
ROM_LOAD( "2-5a.bin", 0x06000, 0x2000, CRC(b6d81984) SHA1(c935176f8a9bce0f74ff466e10c23ff6557f85ec) )
ROM_LOAD( "2-6a.bin", 0x08000, 0x2000, CRC(5a26b38f) SHA1(987a4844c4568a088932f43a3aff847e6d6b4860) )
ROM_LOAD( "2-7a.bin", 0x0a000, 0x2000, CRC(1e1ca773) SHA1(dbced07d4a886ed9ad3302aaa37bc02c599ee132) )
ROM_REGION( 0x08000, "gfx3", 0 )
ROM_LOAD( "2-2n.bin", 0x00000, 0x2000, CRC(6db1b10d) SHA1(85bf67ce4d60b260767ba5fe9b9777f857937fe3) ) /* sprites */
ROM_LOAD( "2-3n.bin", 0x02000, 0x2000, CRC(5d8c34ec) SHA1(7b7df89398bf83ace1a8c216ca8526beae90972d) )
ROM_LOAD( "2-4n.bin", 0x04000, 0x2000, CRC(0071a2e3) SHA1(3f7bb4658d2126576a0f8f46f2c947eec1cd231a) )
ROM_LOAD( "2-5n.bin", 0x06000, 0x2000, CRC(4023a1ec) SHA1(8b69b9cd6db37db94a00da8712413055a631186a) )
ROM_REGION( 0x0800, "proms", 0 )
ROM_LOAD( "e8.bin", 0x0000, 0x0100, CRC(06a83606) SHA1(218c1b404b4b5b06f06e04143872f6758f83f266) ) /* red component */
ROM_LOAD( "e9.bin", 0x0100, 0x0100, CRC(beacf13c) SHA1(d597097afc53fef752b2530d2de04e5aabb664b4) ) /* green component */
ROM_LOAD( "e10.bin", 0x0200, 0x0100, CRC(de1fb621) SHA1(c719892f0c6d8c82ee2ff41bfe74b67648f5b4f5) ) /* blue component */
ROM_LOAD( "d1.bin", 0x0300, 0x0100, CRC(7179080d) SHA1(6c1e8572a4c7b4825b89fc9549265be7c8f17788) ) /* char lookup table */
ROM_LOAD( "j2.bin", 0x0400, 0x0100, CRC(d0842029) SHA1(7d76e1ff75466e190bc2e07ff3ffb45034f838cd) ) /* sprite lookup table */
ROM_LOAD( "c9.bin", 0x0500, 0x0100, CRC(7a1f0bd6) SHA1(5a2110e97e82c087999ee4e5adf32d7fa06a3dfb) ) /* tile lookup table */
ROM_LOAD( "82s126.9k", 0x0600, 0x0100, CRC(32b10521) SHA1(10b258e32813cfa3a853cbd146657b11c08cb770) ) /* interrupt timing? (not used) */
ROM_LOAD( "82s129.8n", 0x0700, 0x0100, CRC(4921635c) SHA1(aee37d6cdc36acf0f11ff5f93e7b16e4b12f6c39) ) /* video timing? (not used) */
ROM_END
ROM_START( vulgusa )
ROM_REGION( 0x1c000, "maincpu", 0 )
ROM_LOAD( "v2", 0x0000, 0x2000, CRC(3e18ff62) SHA1(03f61cc25b4c258effac2172f25641b668a1ae97) )
ROM_LOAD( "v3", 0x2000, 0x2000, CRC(b4650d82) SHA1(4567dfe2b12c59f8c75f5198a136a9afe4975e09) )
ROM_LOAD( "v4", 0x4000, 0x2000, CRC(5b26355c) SHA1(4220b70ad2bdfe269d4ac4e957114dbd3cea0975) )
ROM_LOAD( "v5", 0x6000, 0x2000, CRC(4ca7f10e) SHA1(a3c278aecbb63063b660854ccef6fbaff7e58e32) )
ROM_LOAD( "1-8n.bin", 0x8000, 0x2000, CRC(6ca5ca41) SHA1(6f28d143e984d3d6af3114702ec27d6e878cc35f) )
ROM_REGION( 0x10000, "audiocpu", 0 )
ROM_LOAD( "1-11c.bin", 0x0000, 0x2000, CRC(3bd2acf4) SHA1(b58fb1ea7e30018102ee420d52a1597615412eb1) )
ROM_REGION( 0x02000, "gfx1", 0 )
ROM_LOAD( "1-3d.bin", 0x00000, 0x2000, CRC(8bc5d7a5) SHA1(c572b4a26f12013f5f6463b79ba9cbee4c474bbe) ) /* characters */
ROM_REGION( 0x0c000, "gfx2", 0 )
ROM_LOAD( "2-2a.bin", 0x00000, 0x2000, CRC(e10aaca1) SHA1(f9f0d05475ae4c554552a71bc2f60e02b1442eb1) ) /* tiles */
ROM_LOAD( "2-3a.bin", 0x02000, 0x2000, CRC(8da520da) SHA1(c4c633a909526308de4ad83e8ca449fa71eb3cb5) )
ROM_LOAD( "2-4a.bin", 0x04000, 0x2000, CRC(206a13f1) SHA1(645666895127aededfa7872b20b7725948a9c462) )
ROM_LOAD( "2-5a.bin", 0x06000, 0x2000, CRC(b6d81984) SHA1(c935176f8a9bce0f74ff466e10c23ff6557f85ec) )
ROM_LOAD( "2-6a.bin", 0x08000, 0x2000, CRC(5a26b38f) SHA1(987a4844c4568a088932f43a3aff847e6d6b4860) )
ROM_LOAD( "2-7a.bin", 0x0a000, 0x2000, CRC(1e1ca773) SHA1(dbced07d4a886ed9ad3302aaa37bc02c599ee132) )
ROM_REGION( 0x08000, "gfx3", 0 )
ROM_LOAD( "2-2n.bin", 0x00000, 0x2000, CRC(6db1b10d) SHA1(85bf67ce4d60b260767ba5fe9b9777f857937fe3) ) /* sprites */
ROM_LOAD( "2-3n.bin", 0x02000, 0x2000, CRC(5d8c34ec) SHA1(7b7df89398bf83ace1a8c216ca8526beae90972d) )
ROM_LOAD( "2-4n.bin", 0x04000, 0x2000, CRC(0071a2e3) SHA1(3f7bb4658d2126576a0f8f46f2c947eec1cd231a) )
ROM_LOAD( "2-5n.bin", 0x06000, 0x2000, CRC(4023a1ec) SHA1(8b69b9cd6db37db94a00da8712413055a631186a) )
ROM_REGION( 0x0800, "proms", 0 )
ROM_LOAD( "e8.bin", 0x0000, 0x0100, CRC(06a83606) SHA1(218c1b404b4b5b06f06e04143872f6758f83f266) ) /* red component */
ROM_LOAD( "e9.bin", 0x0100, 0x0100, CRC(beacf13c) SHA1(d597097afc53fef752b2530d2de04e5aabb664b4) ) /* green component */
ROM_LOAD( "e10.bin", 0x0200, 0x0100, CRC(de1fb621) SHA1(c719892f0c6d8c82ee2ff41bfe74b67648f5b4f5) ) /* blue component */
ROM_LOAD( "d1.bin", 0x0300, 0x0100, CRC(7179080d) SHA1(6c1e8572a4c7b4825b89fc9549265be7c8f17788) ) /* char lookup table */
ROM_LOAD( "j2.bin", 0x0400, 0x0100, CRC(d0842029) SHA1(7d76e1ff75466e190bc2e07ff3ffb45034f838cd) ) /* sprite lookup table */
ROM_LOAD( "c9.bin", 0x0500, 0x0100, CRC(7a1f0bd6) SHA1(5a2110e97e82c087999ee4e5adf32d7fa06a3dfb) ) /* tile lookup table */
ROM_LOAD( "82s126.9k", 0x0600, 0x0100, CRC(32b10521) SHA1(10b258e32813cfa3a853cbd146657b11c08cb770) ) /* interrupt timing? (not used) */
ROM_LOAD( "82s129.8n", 0x0700, 0x0100, CRC(4921635c) SHA1(aee37d6cdc36acf0f11ff5f93e7b16e4b12f6c39) ) /* video timing? (not used) */
ROM_END
ROM_START( vulgusj )
ROM_REGION( 0x1c000, "maincpu", 0 )
ROM_LOAD( "1-4n.bin", 0x0000, 0x2000, CRC(fe5a5ca5) SHA1(bb1b5ba5ce54f5e329d23fb8ad1357f65f10d6bf) )
ROM_LOAD( "1-5n.bin", 0x2000, 0x2000, CRC(847e437f) SHA1(1d45ca0b92e7aa3099b8a61c27629d9bec3f25b8) )
ROM_LOAD( "1-6n.bin", 0x4000, 0x2000, CRC(4666c436) SHA1(a2c921f30f91fead59c4d85d4a5ea8acbcfbf424) )
ROM_LOAD( "1-7n.bin", 0x6000, 0x2000, CRC(ff2097f9) SHA1(49789c26a2adde043e5dba9d45a89509a211f05c) )
ROM_LOAD( "1-8n.bin", 0x8000, 0x2000, CRC(6ca5ca41) SHA1(6f28d143e984d3d6af3114702ec27d6e878cc35f) )
ROM_REGION( 0x10000, "audiocpu", 0 )
ROM_LOAD( "1-11c.bin", 0x0000, 0x2000, CRC(3bd2acf4) SHA1(b58fb1ea7e30018102ee420d52a1597615412eb1) )
ROM_REGION( 0x02000, "gfx1", 0 )
ROM_LOAD( "1-3d.bin", 0x00000, 0x2000, CRC(8bc5d7a5) SHA1(c572b4a26f12013f5f6463b79ba9cbee4c474bbe) ) /* characters */
ROM_REGION( 0x0c000, "gfx2", 0 )
ROM_LOAD( "2-2a.bin", 0x00000, 0x2000, CRC(e10aaca1) SHA1(f9f0d05475ae4c554552a71bc2f60e02b1442eb1) ) /* tiles */
ROM_LOAD( "2-3a.bin", 0x02000, 0x2000, CRC(8da520da) SHA1(c4c633a909526308de4ad83e8ca449fa71eb3cb5) )
ROM_LOAD( "2-4a.bin", 0x04000, 0x2000, CRC(206a13f1) SHA1(645666895127aededfa7872b20b7725948a9c462) )
ROM_LOAD( "2-5a.bin", 0x06000, 0x2000, CRC(b6d81984) SHA1(c935176f8a9bce0f74ff466e10c23ff6557f85ec) )
ROM_LOAD( "2-6a.bin", 0x08000, 0x2000, CRC(5a26b38f) SHA1(987a4844c4568a088932f43a3aff847e6d6b4860) )
ROM_LOAD( "2-7a.bin", 0x0a000, 0x2000, CRC(1e1ca773) SHA1(dbced07d4a886ed9ad3302aaa37bc02c599ee132) )
ROM_REGION( 0x08000, "gfx3", 0 )
ROM_LOAD( "2-2n.bin", 0x00000, 0x2000, CRC(6db1b10d) SHA1(85bf67ce4d60b260767ba5fe9b9777f857937fe3) ) /* sprites */
ROM_LOAD( "2-3n.bin", 0x02000, 0x2000, CRC(5d8c34ec) SHA1(7b7df89398bf83ace1a8c216ca8526beae90972d) )
ROM_LOAD( "2-4n.bin", 0x04000, 0x2000, CRC(0071a2e3) SHA1(3f7bb4658d2126576a0f8f46f2c947eec1cd231a) )
ROM_LOAD( "2-5n.bin", 0x06000, 0x2000, CRC(4023a1ec) SHA1(8b69b9cd6db37db94a00da8712413055a631186a) )
ROM_REGION( 0x0800, "proms", 0 )
ROM_LOAD( "e8.bin", 0x0000, 0x0100, CRC(06a83606) SHA1(218c1b404b4b5b06f06e04143872f6758f83f266) ) /* red component */
ROM_LOAD( "e9.bin", 0x0100, 0x0100, CRC(beacf13c) SHA1(d597097afc53fef752b2530d2de04e5aabb664b4) ) /* green component */
ROM_LOAD( "e10.bin", 0x0200, 0x0100, CRC(de1fb621) SHA1(c719892f0c6d8c82ee2ff41bfe74b67648f5b4f5) ) /* blue component */
ROM_LOAD( "d1.bin", 0x0300, 0x0100, CRC(7179080d) SHA1(6c1e8572a4c7b4825b89fc9549265be7c8f17788) ) /* char lookup table */
ROM_LOAD( "j2.bin", 0x0400, 0x0100, CRC(d0842029) SHA1(7d76e1ff75466e190bc2e07ff3ffb45034f838cd) ) /* sprite lookup table */
ROM_LOAD( "c9.bin", 0x0500, 0x0100, CRC(7a1f0bd6) SHA1(5a2110e97e82c087999ee4e5adf32d7fa06a3dfb) ) /* tile lookup table */
ROM_LOAD( "82s126.9k", 0x0600, 0x0100, CRC(32b10521) SHA1(10b258e32813cfa3a853cbd146657b11c08cb770) ) /* interrupt timing? (not used) */
ROM_LOAD( "82s129.8n", 0x0700, 0x0100, CRC(4921635c) SHA1(aee37d6cdc36acf0f11ff5f93e7b16e4b12f6c39) ) /* video timing? (not used) */
ROM_END
ROM_START( mach9 )
ROM_REGION( 0x1c000, "maincpu", 0 )
ROM_LOAD( "02_4n.bin", 0x0000, 0x2000, CRC(b3310b0c) SHA1(f083d8633da69acaa03e7566f28e87ef0482927d) )
ROM_LOAD( "03_5n.bin", 0x2000, 0x2000, CRC(51acef76) SHA1(14dda82b90f9c3a309561a73c300cb54b5fca77d) )
ROM_LOAD( "04_6n.bin", 0x4000, 0x2000, CRC(489e7f60) SHA1(f3f685955fc42f238909dcdb5edc4c117e5543db) )
ROM_LOAD( "05_7n.bin", 0x6000, 0x2000, CRC(ef3e4278) SHA1(eb3433827a53b2e9c2b09add7376982e84b29558) )
ROM_LOAD( "06_8n.bin", 0x8000, 0x2000, CRC(6ca5ca41) SHA1(6f28d143e984d3d6af3114702ec27d6e878cc35f) )
ROM_REGION( 0x10000, "audiocpu", 0 )
ROM_LOAD( "07_11c.bin", 0x0000, 0x2000, CRC(3bd2acf4) SHA1(b58fb1ea7e30018102ee420d52a1597615412eb1) )
ROM_REGION( 0x02000, "gfx1", 0 )
ROM_LOAD( "01_3d.bin", 0x00000, 0x2000, CRC(be556775) SHA1(16a4e746ea2462689b7a0e9f01c88d7edf06092d) ) /* characters */
ROM_REGION( 0x0c000, "gfx2", 0 )
ROM_LOAD( "08_2a.bin", 0x00000, 0x2000, CRC(e10aaca1) SHA1(f9f0d05475ae4c554552a71bc2f60e02b1442eb1) ) /* tiles */
ROM_LOAD( "09_3a.bin", 0x02000, 0x2000, CRC(9193f2f1) SHA1(de1ee725627baeabec6823f6ecc4e7f6df152ce3) )
ROM_LOAD( "10_4a.bin", 0x04000, 0x2000, CRC(206a13f1) SHA1(645666895127aededfa7872b20b7725948a9c462) )
ROM_LOAD( "11_5a.bin", 0x06000, 0x2000, CRC(d729b5b7) SHA1(e9af9bc7f627e313ec070dc9e41ce6f2cddc5b38) )
ROM_LOAD( "12_6a.bin", 0x08000, 0x2000, CRC(5a26b38f) SHA1(987a4844c4568a088932f43a3aff847e6d6b4860) )
ROM_LOAD( "13_7a.bin", 0x0a000, 0x2000, CRC(8033cd4f) SHA1(5eb2e5931e44ca6bf64117dd34e9b6072e6b0ffc) )
ROM_REGION( 0x08000, "gfx3", 0 )
ROM_LOAD( "14_2n.bin", 0x00000, 0x2000, CRC(6db1b10d) SHA1(85bf67ce4d60b260767ba5fe9b9777f857937fe3) ) /* sprites */
ROM_LOAD( "15_3n.bin", 0x02000, 0x2000, CRC(5d8c34ec) SHA1(7b7df89398bf83ace1a8c216ca8526beae90972d) )
ROM_LOAD( "16_4n.bin", 0x04000, 0x2000, CRC(0071a2e3) SHA1(3f7bb4658d2126576a0f8f46f2c947eec1cd231a) )
ROM_LOAD( "17_5n.bin", 0x06000, 0x2000, CRC(4023a1ec) SHA1(8b69b9cd6db37db94a00da8712413055a631186a) )
ROM_REGION( 0x0800, "proms", 0 )
ROM_LOAD( "82s129_8e.bin", 0x0000, 0x0100, CRC(06a83606) SHA1(218c1b404b4b5b06f06e04143872f6758f83f266) ) /* red component */
ROM_LOAD( "82s129_9e.bin", 0x0100, 0x0100, CRC(beacf13c) SHA1(d597097afc53fef752b2530d2de04e5aabb664b4) ) /* green component */
ROM_LOAD( "82s129_10e.bin", 0x0200, 0x0100, CRC(8404067c) SHA1(6e8826f56267007e2adf02dc03dd96bd40e64935) ) /* blue component, only PROM slightly different from original? */
ROM_LOAD( "82s129_1d.bin", 0x0300, 0x0100, CRC(7179080d) SHA1(6c1e8572a4c7b4825b89fc9549265be7c8f17788) ) /* char lookup table */
ROM_LOAD( "82s129_2j.bin", 0x0400, 0x0100, CRC(d0842029) SHA1(7d76e1ff75466e190bc2e07ff3ffb45034f838cd) ) /* sprite lookup table */
ROM_LOAD( "82s129_9c.bin", 0x0500, 0x0100, CRC(7a1f0bd6) SHA1(5a2110e97e82c087999ee4e5adf32d7fa06a3dfb) ) /* tile lookup table */
ROM_LOAD( "82s129_9k.bin", 0x0600, 0x0100, CRC(32b10521) SHA1(10b258e32813cfa3a853cbd146657b11c08cb770) ) /* interrupt timing? (not used) */
ROM_LOAD( "82s129_8n.bin", 0x0700, 0x0100, CRC(4921635c) SHA1(aee37d6cdc36acf0f11ff5f93e7b16e4b12f6c39) ) /* video timing? (not used) */
ROM_END
GAME( 1984, vulgus, 0, vulgus, vulgus, vulgus_state, empty_init, ROT270, "Capcom", "Vulgus (set 1)", MACHINE_SUPPORTS_SAVE )
GAME( 1984, vulgusa, vulgus, vulgus, vulgus, vulgus_state, empty_init, ROT90, "Capcom", "Vulgus (set 2)", MACHINE_SUPPORTS_SAVE )
GAME( 1984, vulgusj, vulgus, vulgus, vulgus, vulgus_state, empty_init, ROT270, "Capcom", "Vulgus (Japan?)", MACHINE_SUPPORTS_SAVE )
GAME( 1984, mach9, vulgus, vulgus, vulgus, vulgus_state, empty_init, ROT270, "bootleg (ITISA)", "Mach-9 (bootleg of Vulgus)", MACHINE_SUPPORTS_SAVE )
| 53.133971 | 178 | 0.712697 | [
"3d"
] |
d15fe0b393f254db6da792288ce8be97db7b7f7d | 784 | cpp | C++ | MFC++/SourceCodes/Chapter7/istreamIterator.cpp | CoodingPenguin/StudyMaterial | b6d8084fc38673ad6ffb54bc0bc60b2471168810 | [
"MIT"
] | 9 | 2019-02-21T20:20:25.000Z | 2020-04-14T15:18:59.000Z | MFC++/SourceCodes/Chapter7/istreamIterator.cpp | CoodingPenguin/StudyMaterial | b6d8084fc38673ad6ffb54bc0bc60b2471168810 | [
"MIT"
] | null | null | null | MFC++/SourceCodes/Chapter7/istreamIterator.cpp | CoodingPenguin/StudyMaterial | b6d8084fc38673ad6ffb54bc0bc60b2471168810 | [
"MIT"
] | 2 | 2019-07-09T02:01:37.000Z | 2020-01-07T18:45:25.000Z | /* Written by @nErumin (Github)
* 2017-01-03
*
* Topic - 스트림 반복자에 대해서 알아보자.
*/
#include <algorithm>
#include <numeric>
#include <vector>
#include <list>
#include <functional>
#include <deque>
#include <string>
#include <iostream>
#include <forward_list>
#include <iterator>
using namespace std;
using namespace std::placeholders;
int main()
{
istream_iterator<int> intReadStreamIter{ cin };
istream_iterator<int> intEOFIter;
vector<int> intVec;
while (intReadStreamIter != intEOFIter)
{
intVec.push_back(*(intReadStreamIter++));
cout << "Read : " << intVec.back() << endl;
}
return 0;
}
void Fold()
{
istream_iterator<int> anotherStreamIter{ cin }, anotherEOFIter;
int sum = accumulate(anotherStreamIter, anotherEOFIter, 0);
cout << "Sum : " << sum << endl;
} | 19.121951 | 64 | 0.696429 | [
"vector"
] |
d162d976bb5f70093b25b4bc89db2f2ed53dc904 | 39,101 | cpp | C++ | implementations/ugene/src/plugins/GUITestBase/src/tests/common_scenarios/pcr/GTTestsPrimerLibrary.cpp | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | implementations/ugene/src/plugins/GUITestBase/src/tests/common_scenarios/pcr/GTTestsPrimerLibrary.cpp | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | implementations/ugene/src/plugins/GUITestBase/src/tests/common_scenarios/pcr/GTTestsPrimerLibrary.cpp | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | /**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2020 UniPro <ugene@unipro.ru>
* http://ugene.net
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include <drivers/GTKeyboardDriver.h>
#include <drivers/GTMouseDriver.h>
#include <primitives/GTLineEdit.h>
#include <utils/GTUtilsDialog.h>
#include <QApplication>
#include <QDir>
#include "GTDatabaseConfig.h"
#include "GTTestsPrimerLibrary.h"
#include "GTUtilsAnnotationsTreeView.h"
#include "GTUtilsLog.h"
#include "GTUtilsMdi.h"
#include "GTUtilsOptionPanelSequenceView.h"
#include "GTUtilsPcr.h"
#include "GTUtilsPrimerLibrary.h"
#include "GTUtilsProject.h"
#include "GTUtilsSequenceView.h"
#include "GTUtilsSharedDatabaseDocument.h"
#include "GTUtilsTaskTreeView.h"
#include "runnables/ugene/plugins/pcr/AddPrimerDialogFiller.h"
#include "runnables/ugene/plugins/pcr/ExportPrimersDialogFiller.h"
#include "runnables/ugene/plugins/pcr/ImportPrimersDialogFiller.h"
#include "runnables/ugene/plugins/pcr/PrimerLibrarySelectorFiller.h"
namespace U2 {
namespace GUITest_common_scenarios_primer_library {
using namespace HI;
GUI_TEST_CLASS_DEFINITION(test_0001) {
GTUtilsMdi::click(os, GTGlobals::Close);
//The library is the singleton MDI window
//1. Click the menu Tools -> Primer -> Primer Library.
//Expected: the library MDI window is opened.
QWidget *libraryMdi1 = GTUtilsPrimerLibrary::openLibrary(os);
//2. Click the menu again.
QWidget *libraryMdi2 = GTUtilsPrimerLibrary::openLibrary(os);
//Expected: the same MDI windows is opened (not the second one).
CHECK_SET_ERR(libraryMdi1 == libraryMdi2, "Different MDI windows");
//3. Click the close button.
GTUtilsPrimerLibrary::clickButton(os, GTUtilsPrimerLibrary::Close);
GTGlobals::sleep();
//Expected: The window is closed.
QWidget *libraryMdi3 = GTUtilsMdi::activeWindow(os, GTGlobals::FindOptions(false));
CHECK_SET_ERR(NULL == libraryMdi3, "Library MDI is not closed");
}
GUI_TEST_CLASS_DEFINITION(test_0002) {
//Add new primer:
// Primer line edit ACGT content
// Availability of the OK button
//1. Click the menu Tools -> Primer -> Primer Library.
GTUtilsPrimerLibrary::openLibrary(os);
int librarySize = GTUtilsPrimerLibrary::librarySize(os);
//2. Click the new primer button.
//Expected: the dialog appears. The OK button is disabled.
class Scenario : public CustomScenario {
public:
void run(HI::GUITestOpStatus &os) {
//3. Set the focus at the primer line edit and write "Q%1" (not ACGT).
QLineEdit *primerEdit = dynamic_cast<QLineEdit *>(GTWidget::findWidget(os, "primerEdit"));
GTLineEdit::setText(os, primerEdit, "Q%1", true);
//Expected: the line edit is empty.
CHECK_SET_ERR(primerEdit->text().isEmpty(), "Wrong input");
//4. Write "atcg".
GTLineEdit::setText(os, primerEdit, "atcg", true);
//Expected: the line edit content is "ATCG". The OK button is enabled.
CHECK_SET_ERR(primerEdit->text() == "ATCG", "No upper-case");
//5. Remove the primer name.
QLineEdit *nameEdit = qobject_cast<QLineEdit *>(GTWidget::findWidget(os, "nameEdit"));
GTLineEdit::setText(os, nameEdit, "");
//Expected: The OK button is disabled.
QWidget *dialog = GTWidget::getActiveModalWidget(os);
QPushButton *okButton = GTUtilsDialog::buttonBox(os, dialog)->button(QDialogButtonBox::Ok);
CHECK_SET_ERR(!okButton->isEnabled(), "The OK button is enabled");
//6. Set the name "Primer".
GTLineEdit::setText(os, nameEdit, "Primer");
//7. Click the OK button.
GTUtilsDialog::clickButtonBox(os, dialog, QDialogButtonBox::Ok);
}
};
AddPrimerDialogFiller::Parameters parameters;
parameters.scenario = new Scenario();
GTUtilsDialog::waitForDialog(os, new AddPrimerDialogFiller(os, parameters));
GTUtilsPrimerLibrary::clickButton(os, GTUtilsPrimerLibrary::Add);
//Expected: the new primer appears in the table.
CHECK_SET_ERR(librarySize + 1 == GTUtilsPrimerLibrary::librarySize(os), "Wrong primers count");
CHECK_SET_ERR(GTUtilsPrimerLibrary::getPrimerSequence(os, librarySize) == "ATCG", "Wrong primer");
}
GUI_TEST_CLASS_DEFINITION(test_0003) {
//Remove primers:
// Availability of the button
//1. Click the menu Tools -> Primer -> Primer Library.
GTUtilsPrimerLibrary::openLibrary(os);
int librarySize = GTUtilsPrimerLibrary::librarySize(os);
//2. Add a new primer if the library is empty.
AddPrimerDialogFiller::Parameters parameters;
parameters.primer = "AAAAAAAAAAAAAA";
GTUtilsDialog::waitForDialog(os, new AddPrimerDialogFiller(os, parameters));
GTUtilsPrimerLibrary::clickButton(os, GTUtilsPrimerLibrary::Add);
//3. Click the empty place of the table.
QPoint emptyPoint = GTUtilsPrimerLibrary::getPrimerPoint(os, librarySize);
emptyPoint.setY(emptyPoint.y() + 40);
GTMouseDriver::moveTo(emptyPoint);
GTMouseDriver::click();
//Expected: The remove button is disabled.
QAbstractButton *removeButton = GTUtilsPrimerLibrary::getButton(os, GTUtilsPrimerLibrary::Remove);
CHECK_SET_ERR(!removeButton->isEnabled(), "The remove button is enabled");
//4. Select the primer.
GTMouseDriver::moveTo(GTUtilsPrimerLibrary::getPrimerPoint(os, librarySize));
GTMouseDriver::click();
//Expected: The remove button is enabled.
CHECK_SET_ERR(removeButton->isEnabled(), "The remove button is disabled");
//5. Click the button.
GTUtilsPrimerLibrary::clickButton(os, GTUtilsPrimerLibrary::Remove);
//Expected: the primer is disappeared from the table.
CHECK_SET_ERR(librarySize == GTUtilsPrimerLibrary::librarySize(os), "Wrong primers count");
}
GUI_TEST_CLASS_DEFINITION(test_0004) {
//In silico PCR with the library data:
// Add a primer from the library
// Double click
{ // Pre-test
GTUtilsPrimerLibrary::openLibrary(os);
AddPrimerDialogFiller::Parameters parameters;
parameters.primer = "AAAAAAAAAAAAAA";
GTUtilsDialog::waitForDialog(os, new AddPrimerDialogFiller(os, parameters));
GTUtilsPrimerLibrary::clickButton(os, GTUtilsPrimerLibrary::Add);
GTUtilsPrimerLibrary::clickButton(os, GTUtilsPrimerLibrary::Close);
}
//1. Open "_common_data/fasta/pcr_test.fa".
GTFileDialog::openFile(os, testDir + "_common_data/fasta", "pcr_test.fa");
GTUtilsTaskTreeView::waitTaskFinished(os);
//2. Open the PCR OP.
GTWidget::click(os, GTWidget::findWidget(os, "OP_IN_SILICO_PCR"));
//3. Click the browse library button for the forward primer.
//Expected: the library dialog appears, the OK button is disabled.
//4. Click a primer in the table.
//Expected: the OK button is enabled.
//5. Double click the primer.
GTUtilsDialog::waitForDialog(os, new PrimerLibrarySelectorFiller(os, -1, true));
GTWidget::click(os, GTUtilsPcr::browseButton(os, U2Strand::Direct));
//Expected: the dialog is closed, the chosen primer sequence is in the forward primer line edit.
QLineEdit *primerEdit = GTWidget::findExactWidget<QLineEdit *>(os, "primerEdit", GTUtilsPcr::primerBox(os, U2Strand::Direct));
CHECK_SET_ERR(primerEdit->text() == "AAAAAAAAAAAAAA", "Wrong primer");
}
GUI_TEST_CLASS_DEFINITION(test_0005) {
//Edit primer:
// Availability of the button
//1. Click the menu Tools -> Primer -> Primer Library.
GTUtilsPrimerLibrary::openLibrary(os);
//2. Add a new primer if the library is empty.
for (int i = 0; i < 3; i++) {
AddPrimerDialogFiller::Parameters parameters;
parameters.primer = "AAAAAAAAAAAAAA";
GTUtilsDialog::waitForDialog(os, new AddPrimerDialogFiller(os, parameters));
GTUtilsPrimerLibrary::clickButton(os, GTUtilsPrimerLibrary::Add);
}
int lastPrimer = GTUtilsPrimerLibrary::librarySize(os) - 1;
//3. Click the empty place of the table.
QPoint emptyPoint = GTUtilsPrimerLibrary::getPrimerPoint(os, lastPrimer);
emptyPoint.setY(emptyPoint.y() + 40);
GTMouseDriver::moveTo(emptyPoint);
GTMouseDriver::click();
//Expected: The edit button is disabled.
QAbstractButton *editButton = GTUtilsPrimerLibrary::getButton(os, GTUtilsPrimerLibrary::Edit);
CHECK_SET_ERR(!editButton->isEnabled(), "The remove button is enabled");
//4. Select several primers.
GTMouseDriver::moveTo(GTUtilsPrimerLibrary::getPrimerPoint(os, lastPrimer));
GTMouseDriver::click();
GTMouseDriver::moveTo(GTUtilsPrimerLibrary::getPrimerPoint(os, lastPrimer - 2));
GTKeyboardDriver::keyPress(Qt::Key_Shift);
GTMouseDriver::click();
GTKeyboardDriver::keyRelease(Qt::Key_Shift);
//Expected: The edit button is disabled.
CHECK_SET_ERR(!editButton->isEnabled(), "The remove button is enabled");
//5. Select the primer P.
GTMouseDriver::moveTo(GTUtilsPrimerLibrary::getPrimerPoint(os, lastPrimer));
GTMouseDriver::click();
//Expected: The edit button is enabled.
CHECK_SET_ERR(editButton->isEnabled(), "The remove button is disabled");
//6. Double click the primer P.
//Expected: the dialog appears. The P's data is written.
//7. Edit primer and name and click OK.
AddPrimerDialogFiller::Parameters parameters;
parameters.primer = "CCCCCCCCCCCCCC";
parameters.name = "test_0005";
GTUtilsDialog::waitForDialog(os, new AddPrimerDialogFiller(os, parameters));
GTMouseDriver::doubleClick();
//Expected: the primer is changed in the table.
CHECK_SET_ERR("CCCCCCCCCCCCCC" == GTUtilsPrimerLibrary::getPrimerSequence(os, lastPrimer), "The sequence is not changed");
}
GUI_TEST_CLASS_DEFINITION(test_0006) {
// Export whole library to the fasta file
// 1. Open the library, clear it, add sequences "AAAA", "CCCC", "GGGG", "TTTT".
GTUtilsPrimerLibrary::openLibrary(os);
GTUtilsPrimerLibrary::clearLibrary(os);
GTUtilsPrimerLibrary::addPrimer(os, "primer1", "AAAA");
GTUtilsPrimerLibrary::addPrimer(os, "primer2", "CCCC");
GTUtilsPrimerLibrary::addPrimer(os, "primer3", "GGGG");
GTUtilsPrimerLibrary::addPrimer(os, "primer4", "TTTT");
// 2. Select all sequences.
GTUtilsPrimerLibrary::selectAll(os);
// 3. Click "Export".
// 4. Fill the dialog:
// Export to: "Local file";
// Format: "fasta";
// File path: any valid path;
// and accept the dialog.
class ExportToFastaScenario : public CustomScenario {
void run(HI::GUITestOpStatus &os) {
QWidget *dialog = QApplication::activeModalWidget();
CHECK_SET_ERR(NULL != dialog, "Active modal widget is NULL");
ExportPrimersDialogFiller::setExportTarget(os, ExportPrimersDialogFiller::LocalFile);
ExportPrimersDialogFiller::setFormat(os, "FASTA");
ExportPrimersDialogFiller::setFilePath(os, sandBoxDir + "pcrlib/test_0006/primers.fa");
GTUtilsDialog::clickButtonBox(os, QDialogButtonBox::Ok);
}
};
QDir().mkpath(sandBoxDir + "pcrlib/test_0006");
GTUtilsDialog::waitForDialog(os, new ExportPrimersDialogFiller(os, new ExportToFastaScenario));
GTUtilsPrimerLibrary::clickButton(os, GTUtilsPrimerLibrary::Export);
// 5. Open the exported file.
// Expected state: there are the same sequences in the file as in the library.
GTUtilsTaskTreeView::waitTaskFinished(os);
const QStringList names = QStringList() << "primer1"
<< "primer2"
<< "primer3"
<< "primer4";
GTUtilsProject::openFileExpectSequences(os, sandBoxDir + "pcrlib/test_0006/", "primers.fa", names);
const QString firstSeq = GTUtilsSequenceView::getSequenceAsString(os, 0);
CHECK_SET_ERR("AAAA" == firstSeq, QString("Incorrect sequence data: expect '%1', got '%2'").arg("AAAA").arg(firstSeq));
const QString secondSeq = GTUtilsSequenceView::getSequenceAsString(os, 1);
CHECK_SET_ERR("CCCC" == secondSeq, QString("Incorrect sequence data: expect '%1', got '%2'").arg("CCCC").arg(secondSeq));
const QString thirdSeq = GTUtilsSequenceView::getSequenceAsString(os, 2);
CHECK_SET_ERR("GGGG" == thirdSeq, QString("Incorrect sequence data: expect '%1', got '%2'").arg("GGGG").arg(thirdSeq));
const QString fourthSeq = GTUtilsSequenceView::getSequenceAsString(os, 3);
CHECK_SET_ERR("TTTT" == fourthSeq, QString("Incorrect sequence data: expect '%1', got '%2'").arg("TTTT").arg(fourthSeq));
}
GUI_TEST_CLASS_DEFINITION(test_0007) {
// Export several primers from library to the genbank file
// 1. Open the library, clear it, add sequences "AAAA", "CCCC", "GGGG", "TTTT".
GTUtilsPrimerLibrary::openLibrary(os);
GTUtilsPrimerLibrary::clearLibrary(os);
GTUtilsPrimerLibrary::addPrimer(os, "primer1", "AAAA");
GTUtilsPrimerLibrary::addPrimer(os, "primer2", "CCCC");
GTUtilsPrimerLibrary::addPrimer(os, "primer3", "GGGG");
GTUtilsPrimerLibrary::addPrimer(os, "primer4", "TTTT");
// 2. Select the second and the third sequences.
GTUtilsPrimerLibrary::selectPrimers(os, QList<int>() << 0 << 2);
// 3. Click "Export".
// 4. Fill the dialog:
// Export to: "Local file";
// Format: "GenBank";
// File path: any valid path;
// and accept the dialog.
class ExportToGenbankScenario : public CustomScenario {
void run(HI::GUITestOpStatus &os) {
QWidget *dialog = QApplication::activeModalWidget();
CHECK_SET_ERR(NULL != dialog, "Active modal widget is NULL");
ExportPrimersDialogFiller::setExportTarget(os, ExportPrimersDialogFiller::LocalFile);
ExportPrimersDialogFiller::setFormat(os, "GenBank");
ExportPrimersDialogFiller::setFilePath(os, sandBoxDir + "pcrlib/test_0007/primers.gb");
GTUtilsDialog::clickButtonBox(os, QDialogButtonBox::Ok);
}
};
QDir().mkpath(sandBoxDir + "pcrlib/test_0007");
GTUtilsDialog::waitForDialog(os, new ExportPrimersDialogFiller(os, new ExportToGenbankScenario));
GTUtilsPrimerLibrary::clickButton(os, GTUtilsPrimerLibrary::Export);
// 5. Open the exported file.
// Expected state: there are two sequences (primer1: AAAA, primer3: GGGG) with annotations, that contains qualifiers with primer's parameters.
GTUtilsTaskTreeView::waitTaskFinished(os);
const QStringList names = QStringList() << "primer1"
<< "primer3";
GTUtilsProject::openFileExpectSequences(os, sandBoxDir + "pcrlib/test_0007/", "primers.gb", names);
const QString firstSeq = GTUtilsSequenceView::getSequenceAsString(os, 0);
CHECK_SET_ERR("AAAA" == firstSeq, QString("Incorrect sequence data: expect '%1', got '%2'").arg("AAAA").arg(firstSeq));
const QString secondSeq = GTUtilsSequenceView::getSequenceAsString(os, 1);
CHECK_SET_ERR("GGGG" == secondSeq, QString("Incorrect sequence data: expect '%1', got '%2'").arg("GGGG").arg(secondSeq));
const QList<QTreeWidgetItem *> items = GTUtilsAnnotationsTreeView::findItems(os, "primer_bind");
CHECK_SET_ERR(items.size() == 2, QString("Unexpected annotations count: epxect %1, got %2").arg(2).arg(items.size()));
GTUtilsAnnotationsTreeView::selectItems(os, QStringList() << "primer_bind");
const QString sequenceQualifier = GTUtilsAnnotationsTreeView::getQualifierValue(os, "sequence", "primer_bind");
const QString gcQualifier = GTUtilsAnnotationsTreeView::getQualifierValue(os, "gc%", "primer_bind");
const QString tmQualifier = GTUtilsAnnotationsTreeView::getQualifierValue(os, "tm", "primer_bind");
CHECK_SET_ERR("AAAA" == sequenceQualifier, QString("Incorrect value of sequence qualifier: '%1'").arg(sequenceQualifier));
CHECK_SET_ERR("0" == gcQualifier, QString("Incorrect value of gc content qualifier: '%1'").arg(gcQualifier));
CHECK_SET_ERR("8" == tmQualifier, QString("Incorrect value of tm qualifier: '%1'").arg(tmQualifier));
}
GUI_TEST_CLASS_DEFINITION(test_0008) {
// Export whole library to a shared database
// 1. Open the library, clear it, add sequences "AAAA", "CCCC", "GGGG", "TTTT".
GTDatabaseConfig::initTestConnectionInfo("ugene_gui_test");
GTUtilsPrimerLibrary::openLibrary(os);
GTUtilsPrimerLibrary::clearLibrary(os);
GTUtilsPrimerLibrary::addPrimer(os, "primer1", "AAAA");
GTUtilsPrimerLibrary::addPrimer(os, "primer2", "CCCC");
GTUtilsPrimerLibrary::addPrimer(os, "primer3", "GGGG");
GTUtilsPrimerLibrary::addPrimer(os, "primer4", "TTTT");
// 2. Select all sequences.
GTUtilsPrimerLibrary::selectAll(os);
// 3. Click "Export".
// 4. Fill the dialog:
// Export to: "Shared database";
// Database: connect to the "ugene_gui_test" database;
// Folder: any valid path;
// and accept the dialog.
class ExportToSharedDbScenario : public CustomScenario {
void run(HI::GUITestOpStatus &os) {
QWidget *dialog = QApplication::activeModalWidget();
CHECK_SET_ERR(NULL != dialog, "Active modal widget is NULL");
ExportPrimersDialogFiller::setExportTarget(os, ExportPrimersDialogFiller::SharedDb);
ExportPrimersDialogFiller::setDatabase(os, "ugene_gui_test");
ExportPrimersDialogFiller::setFolder(os, "/pcrlib/test_0008");
GTUtilsDialog::clickButtonBox(os, QDialogButtonBox::Ok);
}
};
GTUtilsDialog::waitForDialog(os, new ExportPrimersDialogFiller(os, new ExportToSharedDbScenario));
GTUtilsPrimerLibrary::clickButton(os, GTUtilsPrimerLibrary::Export);
// 5. Check the database.
// Expected state: there are four sequence objects and four annotation table object with relations between them.
GTUtilsTaskTreeView::waitTaskFinished(os);
GTGlobals::sleep(10000);
Document *databaseConnection = GTUtilsSharedDatabaseDocument::getDatabaseDocumentByName(os, "ugene_gui_test");
GTUtilsSharedDatabaseDocument::openView(os, databaseConnection, "/pcrlib/test_0008/primer1");
const QString firstSeq = GTUtilsSequenceView::getSequenceAsString(os);
CHECK_SET_ERR("AAAA" == firstSeq, QString("Incorrect sequence data: expect '%1', got '%2'").arg("AAAA").arg(firstSeq));
GTUtilsSharedDatabaseDocument::openView(os, databaseConnection, "/pcrlib/test_0008/primer2 features");
const QString secondSeq = GTUtilsSequenceView::getSequenceAsString(os);
CHECK_SET_ERR("CCCC" == secondSeq, QString("Incorrect sequence data: expect '%1', got '%2'").arg("CCCC").arg(secondSeq));
const QStringList itemPaths = QStringList() << "/pcrlib/test_0008/primer1"
<< "/pcrlib/test_0008/primer2"
<< "/pcrlib/test_0008/primer3"
<< "/pcrlib/test_0008/primer4"
<< "/pcrlib/test_0008/primer1 features"
<< "/pcrlib/test_0008/primer2 features"
<< "/pcrlib/test_0008/primer3 features"
<< "/pcrlib/test_0008/primer4 features";
GTUtilsSharedDatabaseDocument::checkThereAreNoItemsExceptListed(os, databaseConnection, "/pcrlib/test_0008/", itemPaths);
}
GUI_TEST_CLASS_DEFINITION(test_0009) {
// Import primers from multifasta
// 1. Open the library, clear it.
GTUtilsPrimerLibrary::openLibrary(os);
GTUtilsPrimerLibrary::clearLibrary(os);
// 2. Click "Import".
// 3. Fill the dialog:
// Import from: "Local file(s)";
// Files: "_common_data/fasta/random_primers.fa"
// and accept the dialog.
class ImportFromMultifasta : public CustomScenario {
void run(HI::GUITestOpStatus &os) {
QWidget *dialog = QApplication::activeModalWidget();
CHECK_SET_ERR(NULL != dialog, "Active modal widget is NULL");
ImportPrimersDialogFiller::setImportTarget(os, ImportPrimersDialogFiller::LocalFiles);
ImportPrimersDialogFiller::addFile(os, testDir + "_common_data/fasta/random_primers.fa");
GTUtilsDialog::clickButtonBox(os, QDialogButtonBox::Ok);
}
};
GTUtilsDialog::waitForDialog(os, new ImportPrimersDialogFiller(os, new ImportFromMultifasta));
GTUtilsPrimerLibrary::clickButton(os, GTUtilsPrimerLibrary::Import);
// 4. Check the library.
// Expected state: the library contains four primers.
GTUtilsTaskTreeView::waitTaskFinished(os);
const int librarySize = GTUtilsPrimerLibrary::librarySize(os);
CHECK_SET_ERR(4 == librarySize, QString("An unexpected library size: expect %1, got %2").arg(4).arg(librarySize));
const QString firstData = GTUtilsPrimerLibrary::getPrimerSequence(os, "primer1");
CHECK_SET_ERR("ACCCGTGCTAGC" == firstData, QString("An unexpected primer '%1' data: expect %2, got %3").arg("primer1").arg("ACCCGTGCTAGC").arg(firstData));
const QString secondData = GTUtilsPrimerLibrary::getPrimerSequence(os, "primer2");
CHECK_SET_ERR("GGCATGATCATTCAACG" == secondData, QString("An unexpected primer '%1' data: expect %2, got %3").arg("primer2").arg("GGCATGATCATTCAACG").arg(secondData));
const QString thirdData = GTUtilsPrimerLibrary::getPrimerSequence(os, "primer3");
CHECK_SET_ERR("GGAACTTCGACTAG" == thirdData, QString("An unexpected primer '%1' data: expect %2, got %3").arg("primer3").arg("GGAACTTCGACTAG").arg(thirdData));
const QString fourthData = GTUtilsPrimerLibrary::getPrimerSequence(os, "primer4");
CHECK_SET_ERR("TTTAGGAGGAATCACACACCCACC" == fourthData, QString("An unexpected primer '%1' data: expect %2, got %3").arg("primer4").arg("TTTAGGAGGAATCACACACCCACC").arg(fourthData));
}
GUI_TEST_CLASS_DEFINITION(test_0010) {
// Import primers from several files
// 1. Open the library, clear it.
GTUtilsPrimerLibrary::openLibrary(os);
GTUtilsPrimerLibrary::clearLibrary(os);
// 2. Click "Import".
// 3. Fill the dialog:
// Import from: "Local file(s)";
// Files: "_common_data/fasta/random_primers.fa",
// "_common_data/fasta/random_primers.fa2"
// and accept the dialog.
class ImportFromSeveralFiles : public CustomScenario {
void run(HI::GUITestOpStatus &os) {
QWidget *dialog = QApplication::activeModalWidget();
CHECK_SET_ERR(NULL != dialog, "Active modal widget is NULL");
ImportPrimersDialogFiller::setImportTarget(os, ImportPrimersDialogFiller::LocalFiles);
ImportPrimersDialogFiller::addFile(os, testDir + "_common_data/fasta/random_primers.fa");
ImportPrimersDialogFiller::addFile(os, testDir + "_common_data/fasta/random_primers2.fa");
GTUtilsDialog::clickButtonBox(os, QDialogButtonBox::Ok);
}
};
GTUtilsDialog::waitForDialog(os, new ImportPrimersDialogFiller(os, new ImportFromSeveralFiles));
GTUtilsPrimerLibrary::clickButton(os, GTUtilsPrimerLibrary::Import);
// 4. Check the library.
// Expected state: the library contains six primers.
GTUtilsTaskTreeView::waitTaskFinished(os);
const int librarySize = GTUtilsPrimerLibrary::librarySize(os);
CHECK_SET_ERR(6 == librarySize, QString("An unexpected library size: expect %1, got %2").arg(6).arg(librarySize));
const QString firstData = GTUtilsPrimerLibrary::getPrimerSequence(os, "primer1");
CHECK_SET_ERR("ACCCGTGCTAGC" == firstData, QString("An unexpected primer '%1' data: expect %2, got %3").arg("primer1").arg("ACCCGTGCTAGC").arg(firstData));
const QString secondData = GTUtilsPrimerLibrary::getPrimerSequence(os, "primer2");
CHECK_SET_ERR("GGCATGATCATTCAACG" == secondData, QString("An unexpected primer '%1' data: expect %2, got %3").arg("primer2").arg("GGCATGATCATTCAACG").arg(secondData));
const QString thirdData = GTUtilsPrimerLibrary::getPrimerSequence(os, "primer3");
CHECK_SET_ERR("GGAACTTCGACTAG" == thirdData, QString("An unexpected primer '%1' data: expect %2, got %3").arg("primer3").arg("GGAACTTCGACTAG").arg(thirdData));
const QString fourthData = GTUtilsPrimerLibrary::getPrimerSequence(os, "primer4");
CHECK_SET_ERR("TTTAGGAGGAATCACACACCCACC" == fourthData, QString("An unexpected primer '%1' data: expect %2, got %3").arg("primer4").arg("TTTAGGAGGAATCACACACCCACC").arg(fourthData));
const QString fifthData = GTUtilsPrimerLibrary::getPrimerSequence(os, "primer5");
CHECK_SET_ERR("GGTTCAGTACAGTCAG" == fifthData, QString("An unexpected primer '%1' data: expect %2, got %3").arg("primer5").arg("GGTTCAGTACAGTCAG").arg(fifthData));
const QString sixthData = GTUtilsPrimerLibrary::getPrimerSequence(os, "primer6");
CHECK_SET_ERR("GGTATATTAATTATTATTA" == sixthData, QString("An unexpected primer '%1' data: expect %2, got %3").arg("primer6").arg("GGTATATTAATTATTATTA").arg(sixthData));
}
GUI_TEST_CLASS_DEFINITION(test_0011) {
// Import primers from shared database objects
// 1. Open the library, clear it.
GTDatabaseConfig::initTestConnectionInfo("ugene_gui_test");
GTUtilsPrimerLibrary::openLibrary(os);
GTUtilsPrimerLibrary::clearLibrary(os);
// 2. Click "Import".
// 3. Fill the dialog:
// Import from: "Shared database";
// Objects: "/pcrlib/test_0011/primer1",
// "/pcrlib/test_0011/primer2",
// "/pcrlib/test_0011/primer3",
// "/pcrlib/test_0011/primer4",
// and accept the dialog.
class ImportFromSharedDatabaseObjects : public CustomScenario {
void run(HI::GUITestOpStatus &os) {
QWidget *dialog = QApplication::activeModalWidget();
CHECK_SET_ERR(NULL != dialog, "Active modal widget is NULL");
ImportPrimersDialogFiller::setImportTarget(os, ImportPrimersDialogFiller::SharedDb);
ImportPrimersDialogFiller::connectDatabase(os, "ugene_gui_test");
ImportPrimersDialogFiller::addObjects(os, "ugene_gui_test", QStringList() << "primerToImport1"
<< "primerToImport2"
<< "primerToImport3"
<< "primerToImport4");
GTUtilsDialog::clickButtonBox(os, QDialogButtonBox::Ok);
}
};
GTUtilsDialog::waitForDialog(os, new ImportPrimersDialogFiller(os, new ImportFromSharedDatabaseObjects));
GTUtilsPrimerLibrary::clickButton(os, GTUtilsPrimerLibrary::Import);
// 4. Check the library.
// Expected state: the library contains four primers.
GTUtilsTaskTreeView::waitTaskFinished(os);
const int librarySize = GTUtilsPrimerLibrary::librarySize(os);
CHECK_SET_ERR(4 == librarySize, QString("An unexpected library size: expect %1, got %2").arg(4).arg(librarySize));
const QString firstData = GTUtilsPrimerLibrary::getPrimerSequence(os, "primerToImport1");
CHECK_SET_ERR("ACCCGTGCTAGC" == firstData, QString("An unexpected primer '%1' data: expect %2, got %3").arg("primerToImport1").arg("ACCCGTGCTAGC").arg(firstData));
const QString secondData = GTUtilsPrimerLibrary::getPrimerSequence(os, "primerToImport2");
CHECK_SET_ERR("GGCATGATCATTCAACG" == secondData, QString("An unexpected primer '%1' data: expect %2, got %3").arg("primerToImport2").arg("GGCATGATCATTCAACG").arg(secondData));
const QString thirdData = GTUtilsPrimerLibrary::getPrimerSequence(os, "primerToImport3");
CHECK_SET_ERR("GGAACTTCGACTAG" == thirdData, QString("An unexpected primer '%1' data: expect %2, got %3").arg("primerToImport3").arg("GGAACTTCGACTAG").arg(thirdData));
const QString fourthData = GTUtilsPrimerLibrary::getPrimerSequence(os, "primerToImport4");
CHECK_SET_ERR("TTTAGGAGGAATCACACACCCACC" == fourthData, QString("An unexpected primer '%1' data: expect %2, got %3").arg("primerToImport4").arg("TTTAGGAGGAATCACACACCCACC").arg(fourthData));
}
GUI_TEST_CLASS_DEFINITION(test_0012) {
// Import primers from shared database folder
// 1. Open the library, clear it.
GTDatabaseConfig::initTestConnectionInfo("ugene_gui_test");
GTUtilsPrimerLibrary::openLibrary(os);
GTUtilsPrimerLibrary::clearLibrary(os);
// 2. Click "Import".
// 3. Fill the dialog:
// Import from: "Shared database";
// Objects: "/pcrlib/test_0012/"
// and accept the dialog.
class ImportFromSharedDatabaseFolder : public CustomScenario {
void run(HI::GUITestOpStatus &os) {
QWidget *dialog = QApplication::activeModalWidget();
CHECK_SET_ERR(NULL != dialog, "Active modal widget is NULL");
ImportPrimersDialogFiller::setImportTarget(os, ImportPrimersDialogFiller::SharedDb);
ImportPrimersDialogFiller::connectDatabase(os, "ugene_gui_test");
ImportPrimersDialogFiller::addObjects(os, "ugene_gui_test", QStringList() << "test_0012");
GTUtilsDialog::clickButtonBox(os, QDialogButtonBox::Ok);
}
};
GTLogTracer l;
GTUtilsDialog::waitForDialog(os, new ImportPrimersDialogFiller(os, new ImportFromSharedDatabaseFolder));
GTUtilsPrimerLibrary::clickButton(os, GTUtilsPrimerLibrary::Import);
// 4. Check the library.
// Expected state: the library contains two primers.
GTUtilsTaskTreeView::waitTaskFinished(os);
const int librarySize = GTUtilsPrimerLibrary::librarySize(os);
CHECK_SET_ERR(2 == librarySize, QString("An unexpected library size: expect %1, got %2").arg(2).arg(librarySize));
const QString firstData = GTUtilsPrimerLibrary::getPrimerSequence(os, "primerToImport5");
CHECK_SET_ERR("GGTTCAGTACAGTCAG" == firstData, QString("An unexpected primer '%1' data: expect %2, got %3").arg("primerToImport1").arg("GGTTCAGTACAGTCAG").arg(firstData));
const QString secondData = GTUtilsPrimerLibrary::getPrimerSequence(os, "primerToImport6");
CHECK_SET_ERR("GGTATATTAATTATTATTA" == secondData, QString("An unexpected primer '%1' data: expect %2, got %3").arg("primerToImport2").arg("GGTATATTAATTATTATTA").arg(secondData));
CHECK_SET_ERR(!l.hasErrors(), "Errors in log: " + l.getJoinedErrorString());
}
GUI_TEST_CLASS_DEFINITION(test_0013) {
// Import primers from different shared databases
// 1. Open the library, clear it.
GTDatabaseConfig::initTestConnectionInfo("ugene_gui_test");
GTDatabaseConfig::initTestConnectionInfo("ugene_gui_test_ro", GTDatabaseConfig::database(), true, true);
GTUtilsPrimerLibrary::openLibrary(os);
GTUtilsPrimerLibrary::clearLibrary(os);
// 2. Click "Import".
// 3. Fill the dialog:
// Import from: "Shared database";
// Objects: "user1@ugene_gui_test/pcrlib/test_0013/folderToImport1/",
// "user1@ugene_gui_test/pcrlib/test_0013/primerToImport7",
// "user2@ugene_gui_test/pcrlib/test_0013/folderToImport2/",
// "user2@ugene_gui_test/pcrlib/test_0013/primerToImport9"
// and accept the dialog.
class ImportFromTwoSharedDatabases : public CustomScenario {
void run(HI::GUITestOpStatus &os) {
QWidget *dialog = QApplication::activeModalWidget();
CHECK_SET_ERR(NULL != dialog, "Active modal widget is NULL");
ImportPrimersDialogFiller::setImportTarget(os, ImportPrimersDialogFiller::SharedDb);
ImportPrimersDialogFiller::connectDatabase(os, "ugene_gui_test");
ImportPrimersDialogFiller::connectDatabase(os, "ugene_gui_test_ro");
QMap<QString, QStringList> itemsToImport;
itemsToImport["ugene_gui_test"] << "folderToImport1"
<< "primerToImport7";
itemsToImport["ugene_gui_test_ro"] << "folderToImport2"
<< "primerToImport9";
ImportPrimersDialogFiller::addObjects(os, itemsToImport);
GTUtilsDialog::clickButtonBox(os, QDialogButtonBox::Ok);
}
};
GTUtilsDialog::waitForDialog(os, new ImportPrimersDialogFiller(os, new ImportFromTwoSharedDatabases));
GTUtilsPrimerLibrary::clickButton(os, GTUtilsPrimerLibrary::Import);
// 4. Check the library.
// Expected state: the library contains two primers.
GTUtilsTaskTreeView::waitTaskFinished(os);
const int librarySize = GTUtilsPrimerLibrary::librarySize(os);
CHECK_SET_ERR(4 == librarySize, QString("An unexpected library size: expect %1, got %2").arg(4).arg(librarySize));
const QString firstData = GTUtilsPrimerLibrary::getPrimerSequence(os, "primerToImport7");
CHECK_SET_ERR("AAAACCCCGG" == firstData, QString("An unexpected primer '%1' data: expect %2, got %3").arg("primerToImport7").arg("AAAACCCCGG").arg(firstData));
const QString secondData = GTUtilsPrimerLibrary::getPrimerSequence(os, "primerToImport8");
CHECK_SET_ERR("TTGGGCATCAGCTACGAT" == secondData, QString("An unexpected primer '%1' data: expect %2, got %3").arg("primerToImport8").arg("TTGGGCATCAGCTACGAT").arg(secondData));
const QString thirdData = GTUtilsPrimerLibrary::getPrimerSequence(os, "primerToImport9");
CHECK_SET_ERR("GCGAGCGACGTCAGCTAGCTA" == thirdData, QString("An unexpected primer '%1' data: expect %2, got %3").arg("primerToImport9").arg("GCGAGCGACGTCAGCTAGCTA").arg(thirdData));
const QString fourthData = GTUtilsPrimerLibrary::getPrimerSequence(os, "primerToImport10");
CHECK_SET_ERR("GACGCTAGCATCGACTAGCA" == fourthData, QString("An unexpected primer '%1' data: expect %2, got %3").arg("primerToImport10").arg("GACGCTAGCATCGACTAGCA").arg(fourthData));
}
GUI_TEST_CLASS_DEFINITION(test_0014) {
// Degenerated primers in the primer library
// 1. Open primer library
GTUtilsPrimerLibrary::openLibrary(os);
GTUtilsPrimerLibrary::clearLibrary(os);
// 2. Create the forward primer "TTNGGTGATGWCGGTGAAARCCTCTGACMCATGCAGCT"
GTUtilsPrimerLibrary::addPrimer(os, "test_0014_forward", "TTNGGTGATGWCGGTGAAARCCTCTGACMCATGCAGCT");
// 3. Create the reverse primer "AAGCGCGCGAACAGAAGCGAGAAGCGAACT"
GTUtilsPrimerLibrary::addPrimer(os, "test_0014_reverse", "AAGCGCGCGAACAGAAGCGAGAAGCGAACT");
// 4. Edit the reverse primer. New value: "AAGCGNNNNNNNNNNNNNNNNNNNNNR"
GTUtilsPrimerLibrary::clickPrimer(os, 1);
AddPrimerDialogFiller::Parameters parameters;
parameters.primer = "AAGCGNNNNNNNNNNNNNNNNNNNNNR";
parameters.name = "test_0014_reverse_edit";
GTUtilsDialog::waitForDialog(os, new AddPrimerDialogFiller(os, parameters));
GTUtilsPrimerLibrary::clickButton(os, GTUtilsPrimerLibrary::Edit);
}
GUI_TEST_CLASS_DEFINITION(test_0015) {
// Find the product with the degenerated primers from the library
// 1. Open primer library
GTUtilsPrimerLibrary::openLibrary(os);
GTUtilsPrimerLibrary::clearLibrary(os);
// 2. Create the forward primer "GGGCCAAACAGGATATCTGTGGTAAGCAGT"
GTUtilsPrimerLibrary::addPrimer(os, "test_0015_forward", "GGGCCAAACAGGATATCTGTGGTAAGCAGT");
// 3. Create the reverse primer "AAGCGNNNNNNNNNNNNNNNNNNNNNR"
GTUtilsPrimerLibrary::addPrimer(os, "test_0015_reverse", "AAGCGNNNNNNNNNNNNNNNNNNNNNR");
GTUtilsPrimerLibrary::clickButton(os, GTUtilsPrimerLibrary::Close);
// 4. Open "_common_data/fasta/begin-end.fa"
GTFileDialog::openFile(os, testDir + "_common_data/cmdline/pcr/begin-end.gb");
GTUtilsTaskTreeView::waitTaskFinished(os);
// 5. Set the primers from the library
GTUtilsOptionPanelSequenceView::openTab(os, GTUtilsOptionPanelSequenceView::InSilicoPcr);
GTUtilsTaskTreeView::waitTaskFinished(os);
GTUtilsDialog::waitForDialog(os, new PrimerLibrarySelectorFiller(os, 0, true));
GTWidget::click(os, GTUtilsPcr::browseButton(os, U2Strand::Direct));
GTUtilsDialog::waitForDialog(os, new PrimerLibrarySelectorFiller(os, 1, true));
GTWidget::click(os, GTUtilsPcr::browseButton(os, U2Strand::Complementary));
// 4. Find the product
GTWidget::click(os, GTWidget::findWidget(os, "findProductButton"));
GTUtilsTaskTreeView::waitTaskFinished(os);
// Expected: 2 results were found
int productsCount = GTUtilsPcr::productsCount(os);
CHECK_SET_ERR(productsCount == 2, "Wrong results count. Expected 2, got " + QString::number(productsCount));
}
GUI_TEST_CLASS_DEFINITION(test_0016) {
// Import primers with degenerated symbols
// 1. Open the library, clear it.
GTUtilsPrimerLibrary::openLibrary(os);
GTUtilsPrimerLibrary::clearLibrary(os);
// 2. Click "Import".
// 3. Fill the dialog:
// Import from: "Local file(s)";
// Files: "_common_data/cmdline/primers/primer_degenerated_1.fasta",
// "_common_data/cmdline/primers/primer_degenerated_2.fasta"
// and accept the dialog.
class ImportFromSeveralFiles : public CustomScenario {
void run(HI::GUITestOpStatus &os) {
QWidget *dialog = QApplication::activeModalWidget();
CHECK_SET_ERR(NULL != dialog, "Active modal widget is NULL");
ImportPrimersDialogFiller::setImportTarget(os, ImportPrimersDialogFiller::LocalFiles);
ImportPrimersDialogFiller::addFile(os, testDir + "_common_data/cmdline/primers/primer_degenerated_1.fasta");
ImportPrimersDialogFiller::addFile(os, testDir + "_common_data/cmdline/primers/primer_degenerated_2.fasta");
GTUtilsDialog::clickButtonBox(os, QDialogButtonBox::Ok);
}
};
GTUtilsDialog::waitForDialog(os, new ImportPrimersDialogFiller(os, new ImportFromSeveralFiles));
GTUtilsPrimerLibrary::clickButton(os, GTUtilsPrimerLibrary::Import);
const int librarySize = GTUtilsPrimerLibrary::librarySize(os);
CHECK_SET_ERR(2 == librarySize, QString("An unexpected library size: expect %1, got %2").arg(2).arg(librarySize));
}
} // namespace GUITest_common_scenarios_primer_library
} // namespace U2
| 50.258355 | 193 | 0.69323 | [
"object"
] |
d1636284f237087b34f522127e34a8c4aa9eaaad | 2,213 | cpp | C++ | src/HexsageApplication.cpp | floriankramer/hexsage | a8fa53e28f9d28d556de78d2aba09636cd4f5ec8 | [
"Apache-2.0"
] | null | null | null | src/HexsageApplication.cpp | floriankramer/hexsage | a8fa53e28f9d28d556de78d2aba09636cd4f5ec8 | [
"Apache-2.0"
] | null | null | null | src/HexsageApplication.cpp | floriankramer/hexsage | a8fa53e28f9d28d556de78d2aba09636cd4f5ec8 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2020 Florian Kramer
*
* 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 "HexsageApplication.h"
#include <gtkmm.h>
#include <iostream>
namespace hexsage {
HexsageApplication::HexsageApplication(int argc, char **argv)
: Gtk::Application(argc, argv, "hex.sage",
Gio::ApplicationFlags::APPLICATION_HANDLES_OPEN) {}
HexsageApplication::~HexsageApplication() {}
void HexsageApplication::on_startup() {
Gtk::Application::on_startup();
buildMenu();
}
void HexsageApplication::on_activate() { createMainWindow()->present(); }
void HexsageApplication::on_open(const Gio::Application::type_vec_files &files,
const Glib::ustring &hint) {
for (const Glib::RefPtr<Gio::File> &file : files) {
MainWindow *window = createMainWindow();
window->model().load(file->get_path());
window->present();
}
};
void HexsageApplication::on_hide_window(Gtk::Window *window) { delete window; }
void HexsageApplication::buildMenu() {
set_accel_for_action("win.open", "<Primary>o");
set_accel_for_action("win.quit", "<Primary>q");
auto test_menu = Gio::Menu::create();
auto file_menu = Gio::Menu::create();
file_menu->append("Open", "win.open");
file_menu->append("Quit", "win.quit");
test_menu->append_submenu("file", file_menu);
set_menubar(test_menu);
return;
}
MainWindow *HexsageApplication::createMainWindow() {
auto window = new MainWindow();
add_window(*window);
// ensure we free the windows memory again
window->signal_hide().connect(sigc::bind<Gtk::Window *>(
sigc::mem_fun(*this, &HexsageApplication::on_hide_window), window));
return window;
}
} // namespace hexsage
| 29.905405 | 79 | 0.701762 | [
"model"
] |
ab764593aa2576260e53364b4bd4137905ef0679 | 553 | hpp | C++ | tests/src/mocks/json_storage_mock.hpp | aahmed-2/telemetry | 7e098e93ef0974739459d296f99ddfab54722c23 | [
"Apache-2.0"
] | 4 | 2019-11-14T10:41:34.000Z | 2021-12-09T23:54:52.000Z | tests/src/mocks/json_storage_mock.hpp | aahmed-2/telemetry | 7e098e93ef0974739459d296f99ddfab54722c23 | [
"Apache-2.0"
] | 2 | 2021-10-04T20:12:53.000Z | 2021-12-14T18:13:03.000Z | tests/src/mocks/json_storage_mock.hpp | aahmed-2/telemetry | 7e098e93ef0974739459d296f99ddfab54722c23 | [
"Apache-2.0"
] | 2 | 2021-08-05T11:17:03.000Z | 2021-12-13T15:22:48.000Z | #pragma once
#include "interfaces/json_storage.hpp"
#include <gmock/gmock.h>
class StorageMock : public interfaces::JsonStorage
{
public:
MOCK_METHOD(void, store, (const FilePath&, const nlohmann::json&),
(override));
MOCK_METHOD(bool, remove, (const FilePath&), (override));
MOCK_METHOD(bool, exist, (const FilePath&), (const, override));
MOCK_METHOD(std::optional<nlohmann::json>, load, (const FilePath&),
(const, override));
MOCK_METHOD(std::vector<FilePath>, list, (), (const, override));
};
| 30.722222 | 71 | 0.658228 | [
"vector"
] |
ab7b2f4c3ad0ccf6d03b43380b017bc4be57e669 | 3,119 | cpp | C++ | src/ui/widgets/refrbrowser.cpp | eckserah/nifskope | 3a85ac55e65cc60abc3434cc4aaca2a5cc712eef | [
"RSA-MD"
] | 434 | 2015-02-06T05:08:20.000Z | 2022-03-28T16:32:15.000Z | src/ui/widgets/refrbrowser.cpp | SpectralPlatypus/nifskope | 7af7af39bfb0b29953024655235fde9fbc97071c | [
"RSA-MD"
] | 155 | 2015-01-10T15:28:01.000Z | 2022-03-05T03:28:09.000Z | src/ui/widgets/refrbrowser.cpp | SpectralPlatypus/nifskope | 7af7af39bfb0b29953024655235fde9fbc97071c | [
"RSA-MD"
] | 205 | 2015-02-07T15:10:16.000Z | 2022-03-12T16:59:05.000Z | /***** BEGIN LICENSE BLOCK *****
BSD License
Copyright (c) 2005-2015, NIF File Format Library and Tools
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the NIF File Format Library and Tools project may not be
used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***** END LICENCE BLOCK *****/
#include "refrbrowser.h"
#include "model/nifmodel.h"
#include <QCoreApplication>
#include <QFileInfo>
ReferenceBrowser::ReferenceBrowser( QWidget * parent )
: QTextBrowser( parent )
{
nif = nullptr;
docFolder.setPath( qApp->applicationDirPath() );
docFolderPresent = docFolder.exists( "doc" );
#ifdef Q_OS_LINUX
if ( !docFolderPresent ) {
docFolder.cd( "/usr/share/nifskope" );
docFolderPresent = docFolder.exists( "doc" );
}
#endif
if ( docFolderPresent ) {
docFolder.cd( "doc" );
}
if ( !docFolderPresent || !QFileInfo( docFolder.filePath( "index.html" ) ).exists() ) {
setText( tr( "Please install the reference documentation into the 'doc' folder." ) );
return;
}
setSearchPaths( { docFolder.absolutePath() } );
setStyleSheet( "docsys.css" );
setSourceFile( "index.html" );
}
void ReferenceBrowser::setNifModel( NifModel * nifModel )
{
nif = nifModel;
}
// TODO: Read documentation from ZIP files
void ReferenceBrowser::setSourceFile( const QString & source )
{
if ( QFileInfo( docFolder.filePath( source ) ).exists() ) {
setSource( QUrl( source ) );
}
}
void ReferenceBrowser::browse( const QModelIndex & index )
{
if ( !nif || !docFolderPresent ) {
return;
}
QString blockType = nif->getBlockType( index );
if ( blockType == "NiBlock" ) {
blockType = nif->getBlockName( index );
}
if ( !QFileInfo( docFolder.filePath( "%1.html" ).arg( blockType ) ).exists() ) {
setText( tr( "The reference file for '%1' could not be found." ).arg( blockType ) );
return;
}
setSourceFile( QString( "%1.html" ).arg( blockType ) );
}
| 29.990385 | 88 | 0.732607 | [
"model"
] |
ab86394c4aae8801345dbe5de565fa5f09ee46a1 | 4,447 | hpp | C++ | include/tags/parser.hpp | jamespeapen/polybar | 1ee11f7c9e72719f62981167a24fe7239774fa69 | [
"MIT"
] | 4,807 | 2016-11-19T05:17:55.000Z | 2019-05-05T16:41:43.000Z | include/tags/parser.hpp | jamespeapen/polybar | 1ee11f7c9e72719f62981167a24fe7239774fa69 | [
"MIT"
] | 1,482 | 2016-11-19T15:48:40.000Z | 2019-05-05T12:47:25.000Z | include/tags/parser.hpp | jamespeapen/polybar | 1ee11f7c9e72719f62981167a24fe7239774fa69 | [
"MIT"
] | 392 | 2016-11-21T01:41:42.000Z | 2019-05-04T14:42:02.000Z | #pragma once
#include "common.hpp"
#include "errors.hpp"
#include "tags/types.hpp"
POLYBAR_NS
namespace tags {
static constexpr char EOL = '\0';
class error : public application_error {
public:
using application_error::application_error;
explicit error(const string& msg) : application_error(msg), msg(msg) {}
/**
* Context string that contains the text region where the parser error
* happened.
*/
void set_context(const string& ctxt) {
msg.append(" (Context: '" + ctxt + "')");
}
virtual const char* what() const noexcept override {
return msg.c_str();
}
private:
string msg;
};
#define DEFINE_INVALID_ERROR(class_name, name) \
class class_name : public error { \
public: \
explicit class_name(const string& val) : error("Invalid " name ": '" + val + "'") {} \
explicit class_name(const string& val, const string& what) \
: error("Invalid " name ": '" + val + "' (reason: '" + what + "')") {} \
}
DEFINE_INVALID_ERROR(color_error, "color");
DEFINE_INVALID_ERROR(font_error, "font index");
DEFINE_INVALID_ERROR(control_error, "control tag");
DEFINE_INVALID_ERROR(offset_error, "offset");
DEFINE_INVALID_ERROR(btn_error, "button id");
#undef DEFINE_INVALID_ERROR
class token_error : public error {
public:
explicit token_error(char token, char expected) : token_error(string{token}, string{expected}) {}
explicit token_error(char token, const string& expected) : token_error(string{token}, expected) {}
explicit token_error(const string& token, const string& expected)
: error("Expected '" + expected + "' but found '" +
(token.size() == 1 && token.at(0) == EOL ? "<End Of Line>" : token) + "'") {}
};
class unrecognized_tag : public error {
public:
explicit unrecognized_tag(char tag) : error("Unrecognized formatting tag '%{" + string{tag} + "}'") {}
};
class unrecognized_attr : public error {
public:
explicit unrecognized_attr(char attr) : error("Unrecognized attribute '" + string{attr} + "'") {}
};
/**
* Thrown when we expect the end of a tag (either } or a space in a compound
* tag.
*/
class tag_end_error : public error {
public:
explicit tag_end_error(char token)
: error("Expected the end of a tag ('}' or ' ') but found '" +
(token == EOL ? "<End Of Line>" : string{token}) + "'") {}
};
/**
* Recursive-descent parser for polybar's formatting tags.
*
* An input string is parsed into a list of elements, each element is either
* a piece of text or a single formatting tag.
*
* The elements can either be retrieved one-by-one with next_element() or all
* at once with parse().
*/
class parser {
public:
/**
* Resets the parser state and sets the new string to parse
*/
void set(const string&& input);
/**
* Whether a call to next_element() suceeds.
*/
bool has_next_element();
/**
* Parses at least one element (if available) and returns the first parsed
* element.
*/
element next_element();
/**
* Parses the remaining string and returns all parsed elements.
*/
format_string parse();
protected:
void parse_step();
bool has_next() const;
char next();
char peek() const;
void revert();
void consume(char c);
void consume_space();
void parse_tag();
void parse_single_tag_content();
color_value parse_color();
int parse_fontindex();
extent_val parse_offset();
controltag parse_control();
std::pair<action_value, string> parse_action();
mousebtn parse_action_btn();
string parse_action_cmd();
attribute parse_attribute();
void push_char(char c);
void push_text(string&& text);
string get_tag_value();
private:
string input;
size_t pos = 0;
/**
* Buffers elements that have been parsed but not yet returned to the user.
*/
format_string buf{};
/**
* Index into buf so that we don't have to call vector.erase everytime.
*
* Only buf[buf_pos, buf.end()) contain valid elements
*/
size_t buf_pos;
};
} // namespace tags
POLYBAR_NS_END
| 27.79375 | 106 | 0.604452 | [
"vector"
] |
ab881edfc0283c9f59bb8449bbc6743443e9c3c7 | 2,299 | cpp | C++ | 140-word-break-2/solution.cpp | darxsys/leetcode | 1174f0dbad56c6bfd8196bc4c14798b5f8cee418 | [
"MIT"
] | null | null | null | 140-word-break-2/solution.cpp | darxsys/leetcode | 1174f0dbad56c6bfd8196bc4c14798b5f8cee418 | [
"MIT"
] | null | null | null | 140-word-break-2/solution.cpp | darxsys/leetcode | 1174f0dbad56c6bfd8196bc4c14798b5f8cee418 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cassert>
#include <vector>
#include <map>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<string> wordBreak(string s, vector<string>& wordDict) {
int n = s.size();
int memo[n];
memset(memo, -1, sizeof(int) * n);
vector<vector<string>> subs(n);
vector<string> res;
inner(s, wordDict, 0, memo, subs, res);
return res;
}
private:
bool inner(const string& s, const vector<string>& wordDict, int start, int* memo, vector<vector<string>>& subs, vector<string>& res)
{
if (start == s.size())
{
res.push_back("");
return true;
}
if (memo[start] != -1)
{
res = subs[start];
return true;
}
memo[start] = false;
for (const string& word : wordDict)
{
int n = s.size();
int c = word.size();
vector<string> substrings;
if (start + c <= n && word == s.substr(start, c) && inner(s, wordDict, start + c, memo, subs, substrings))
{
memo[start] = true;
for (const string& sub : substrings)
{
if (sub != "")
subs[start].push_back(s.substr(start, c) + " " + sub);
else
subs[start].push_back(s.substr(start, c));
}
}
}
res = subs[start];
return memo[start];
}
};
void printVec(const vector<string>& strings)
{
for (int i = 0; i < strings.size(); ++i)
{
printf("%s\n", strings[i].c_str());
}
}
int main()
{
Solution s;
string input = "catsanddog";
vector<string> dict = {"cat", "cats", "and", "sand", "dog"};
printVec(s.wordBreak(input, dict));
input = "pineapplepenapple";
dict = {"apple", "pen", "applepen", "pine", "pineapple"};
printVec(s.wordBreak(input, dict));
input = "catsandog";
dict = {"cats", "dog", "sand", "and", "cat"};
printVec(s.wordBreak(input, dict));
return 0;
} | 25.263736 | 136 | 0.509787 | [
"vector"
] |
ab8c411ad14b6e0070b3e859ffe60d180f10438d | 3,299 | cpp | C++ | net/mmc/remrras/server/ncnetcfg.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | net/mmc/remrras/server/ncnetcfg.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | net/mmc/remrras/server/ncnetcfg.cpp | 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, 1997 - 1999
//
// File: N C N E T C F G . C P P
//
// Contents: Common routines for dealing with INetCfg interfaces.
//
// Notes:
//
// Author: shaunco 24 Mar 1997
//
//----------------------------------------------------------------------------
#include <stdafx.h>
#pragma hdrstop
#include "netcfgx.h"
#include "assert.h"
//nclude "netcfgn.h"
//nclude "ncdebug.h"
//nclude "ncbase.h"
//nclude "ncmisc.h"
#include "ncnetcfg.h"
//nclude "ncreg.h"
//nclude "ncvalid.h"
//+---------------------------------------------------------------------------
//
// Function: HrFindComponents
//
// Purpose: Find multiple INetCfgComponents with one call. This makes
// the error handling associated with multiple calls to
// QueryNetCfgClass and Find much easier.
//
// Arguments:
// pnc [in] pointer to INetCfg object
// cComponents [in] count of class guid pointers, component id
// pointers, and INetCfgComponent output pointers.
// apguidClass [in] array of class guid pointers.
// apszwComponentId [in] array of component id pointers.
// apncc [out] array of returned INetCfgComponet pointers.
//
// Returns: S_OK or an error code.
//
// Author: shaunco 22 Mar 1997
//
// Notes: cComponents is the count of pointers in all three arrays.
// S_OK will still be returned even if no components were
// found! This is by design.
//
HRESULT
HrFindComponents (
INetCfg* pnc,
ULONG cComponents,
const GUID** apguidClass,
const LPCWSTR* apszwComponentId,
INetCfgComponent** apncc)
{
Assert (pnc);
Assert (cComponents);
Assert (apguidClass);
Assert (apszwComponentId);
Assert (apncc);
// Initialize the output parameters.
//
ZeroMemory (apncc, cComponents * sizeof(*apncc));
// Find all of the components requested.
// Variable initialization is important here.
HRESULT hr = S_OK;
ULONG i;
for (i = 0; (i < cComponents) && SUCCEEDED(hr); i++)
{
// Get the class object for this component.
INetCfgClass* pncclass = NULL;
hr = pnc->QueryNetCfgClass (apguidClass[i], IID_INetCfgClass,
reinterpret_cast<void**>(&pncclass));
if (SUCCEEDED(hr) && pncclass)
{
// Find the component.
hr = pncclass->FindComponent (apszwComponentId[i], &apncc[i]);
AssertSz (SUCCEEDED(hr), "pncclass->Find failed.");
ReleaseObj (pncclass);
pncclass = NULL;
}
}
// On any error, release what we found and set the output to NULL.
if (FAILED(hr))
{
for (i = 0; i < cComponents; i++)
{
ReleaseObj (apncc[i]);
apncc[i] = NULL;
}
}
// Otherwise, normalize the HRESULT. (i.e. don't return S_FALSE)
else
{
hr = S_OK;
}
TraceResult ("HrFindComponents", hr);
return hr;
}
| 29.455357 | 79 | 0.524401 | [
"object"
] |
ab9991c6d632f0a31d30b89fe0827a07abef00d5 | 8,282 | cpp | C++ | pwiz_tools/Bumbershoot/freicore/WuManber.cpp | shze/pwizard-deb | 4822829196e915525029a808470f02d24b8b8043 | [
"Apache-2.0"
] | 2 | 2019-12-28T21:24:36.000Z | 2020-04-18T03:52:05.000Z | pwiz_tools/Bumbershoot/freicore/WuManber.cpp | shze/pwizard-deb | 4822829196e915525029a808470f02d24b8b8043 | [
"Apache-2.0"
] | null | null | null | pwiz_tools/Bumbershoot/freicore/WuManber.cpp | shze/pwizard-deb | 4822829196e915525029a808470f02d24b8b8043 | [
"Apache-2.0"
] | null | null | null | //
// $Id: WuManber.cpp 7503 2015-05-21 18:37:51Z chambm $
//
// Implementation of Wu Manber's Multi-Pattern Search Algorithm
// Implemented by Ray Burkholder, ray@oneunified.net
// Copyright (2008) One Unified
// For use without restriction but one: this copyright notice must be preserved.
// Modified by Surendra Dasari (Vanderbilt University)
#include "stdafx.h"
#include "WuManber.h"
#include <math.h>
#include <assert.h>
#include <exception>
#include <iostream>
#include <string>
using namespace std;
namespace freicore {
// use http://www.asciitable.com/ for determining additional character types
char WuManber::rchSpecialCharacters[] = { 0x21, 0x22, 0x23, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29,
0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x5b, 0x5c, 0x5d,
0x5e, 0x5f, 0x60, 0x7b, 0x7c, 0x7d, 0x7e,
0x00 };
unsigned char WuManber::rchExtendedAscii[] = {
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x99, 0x9a, 0x9c, 0x0d, 0x9f,
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5,
0x00 };
WuManber::WuManber( void ):
k( 0 ), m( 0 ), m_bInitialized( false ) {
}
WuManber::~WuManber( void ) {
}
void WuManber::Initialize( const vector<const char *> &patterns,
bool bCaseSensitive, bool bIncludeSpecialCharacters, bool bIncludeExtendedAscii ) {
// bIncludeExtendedAscii, bIncludeSpecialCharacters matched as whitespace when false
k = patterns.size();
m = 0; // start with 0 and grow from there
for ( unsigned int i = 0; i < k; ++i ) {
size_t lenPattern = strlen( patterns[ i ] );
if ( B > lenPattern ) throw runtime_error( "found pattern less than B in length" );
m = ( 0 == m ) ? lenPattern : min( m, lenPattern );
}
m_nSizeOfAlphabet = 1; // at minimum we have a white space character
for ( unsigned short i = 0; i <= 255; ++i ) {
m_lu[i].letter = ' '; // table is defaulted to whitespace
m_lu[i].offset = 0; //
if ( ( i >= 'a' ) && ( i <= 'z' ) ) {
m_lu[i].letter = (char) i; // no problems with lower case letters
m_lu[i].offset = m_nSizeOfAlphabet++;
}
if ( bCaseSensitive ) { // case of !bCaseSensitive fixed up later on
if ( ( i >= 'A' ) && ( i <= 'Z' ) ) {
m_lu[i].letter = (char) i; // map upper case to lower case
m_lu[i].offset = m_nSizeOfAlphabet++;
}
}
if ( ( i >= '0' ) && ( i <= '9' ) ) {
m_lu[i].letter = (char) i; // use digits
m_lu[i].offset = m_nSizeOfAlphabet++;
}
}
if ( !bCaseSensitive ) { // fix up upper case mappings ( uppercase comes before lower case in ascii table )
for ( unsigned short i = 'A'; i <= 'Z'; ++i ) {
char letter = i - 'A' + 'a'; // map upper case to lower case
m_lu[i].letter = letter; // map upper case to lower case
m_lu[i].offset = m_lu[letter].offset;
// no unique characters so don't increment size
}
}
if ( bIncludeSpecialCharacters ) {
for ( char *c = rchSpecialCharacters; 0 != *c; ++c ) {
m_lu[*c].letter = *c;
m_lu[*c].offset = m_nSizeOfAlphabet++;
}
}
if ( bIncludeExtendedAscii ) {
for ( unsigned char *c = rchExtendedAscii; 0 != *c; ++c ) {
m_lu[*c].letter = static_cast<char>( *c );
m_lu[*c].offset = m_nSizeOfAlphabet++;
}
}
m_nBitsInShift = (unsigned short) ceil( log( (double) m_nSizeOfAlphabet ) / log( (double) 2 ) );
// can use fewer bits in shift to turn it into a hash
m_nTableSize = (size_t) pow( pow( (double) 2, m_nBitsInShift ), (int) B );
// 2 ** bits ** B, will be some unused space when not hashed
m_ShiftTable = new size_t[ m_nTableSize ];
for ( size_t i = 0; i < m_nTableSize; ++i ) {
m_ShiftTable[ i ] = m - B + 1; // default to m-B+1 for shift
}
m_vPatternMap = new vector<structPatternMap>[ m_nTableSize ];
for ( size_t j = 0; j < k; ++j ) { // loop through patterns
for ( size_t q = m; q >= B; --q ) {
unsigned int hash;
hash = m_lu[patterns[j][q - 2 - 1]].offset; // bring in offsets of X in pattern j
hash <<= m_nBitsInShift;
hash += m_lu[patterns[j][q - 1 - 1]].offset;
hash <<= m_nBitsInShift;
hash += m_lu[patterns[j][q - 1]].offset;
size_t shiftlen = m - q;
m_ShiftTable[ hash ] = min( m_ShiftTable[ hash ], shiftlen );
if ( 0 == shiftlen ) {
m_PatternMapElement.ix = j;
m_PatternMapElement.PrefixHash = m_lu[patterns[j][0]].offset;
m_PatternMapElement.PrefixHash <<= m_nBitsInShift;
m_PatternMapElement.PrefixHash += m_lu[patterns[j][1]].offset;
m_vPatternMap[ hash ].push_back( m_PatternMapElement );
}
}
}
m_bInitialized = true;
}
map<string,size_t> WuManber::Search( size_t TextLength, const char *Text, const vector<const char *> &patterns ) {
map<string,size_t> matches;
assert( k == patterns.size() );
assert( m < TextLength );
assert( m_bInitialized );
size_t ix = m - 1; // start off by matching end of largest common pattern
while ( ix < TextLength ) {
unsigned int hash1;
hash1 = m_lu[Text[ix-2]].offset;
hash1 <<= m_nBitsInShift;
hash1 += m_lu[Text[ix-1]].offset;
hash1 <<= m_nBitsInShift;
hash1 += m_lu[Text[ix]].offset;
size_t shift = m_ShiftTable[ hash1 ];
if ( shift > 0 ) {
ix += shift;
}
else { // we have a potential match when shift is 0
unsigned int hash2; // check for matching prefixes
hash2 = m_lu[Text[ix-m+1]].offset;
hash2 <<= m_nBitsInShift;
hash2 += m_lu[Text[ix-m+2]].offset;
vector<structPatternMap> &element = m_vPatternMap[ hash1 ];
vector<structPatternMap>::iterator iter = element.begin();
while ( element.end() != iter ) {
if ( hash2 == (*iter).PrefixHash ) {
// since prefix matches, compare target substring with pattern
const char *ixTarget = Text + ix - m + 3; // we know first two characters already match
const char *ixPattern = patterns[ (*iter).ix ] + 2; // ditto
while ( ( 0 != *ixTarget ) && ( 0 != *ixPattern ) ) { // match until we reach end of either string
if ( m_lu[ *ixTarget ].letter == m_lu[ *ixPattern ].letter ) { // match against chosen case sensitivity
++ixTarget;
++ixPattern;
}
else {
break;
}
}
if ( 0 == *ixPattern ) { // we found the end of the pattern, so match found
string match(patterns[ (*iter).ix ]);
matches[match] = ix-m+1;
//cout << "match found: " << patterns[ (*iter).ix ] << endl;
}
}
++iter;
}
++ix;
}
}
return matches;
}
}
| 45.505495 | 132 | 0.487563 | [
"vector"
] |
ab9bbb7993ce884cc70584a48fb6940c98b11961 | 10,015 | cpp | C++ | src/postprocess.cpp | jcuic5/CUDA-PointPillars | 3e1959448366c273914ec5024db39ed4e8c8dcdd | [
"Apache-2.0"
] | null | null | null | src/postprocess.cpp | jcuic5/CUDA-PointPillars | 3e1959448366c273914ec5024db39ed4e8c8dcdd | [
"Apache-2.0"
] | null | null | null | src/postprocess.cpp | jcuic5/CUDA-PointPillars | 3e1959448366c273914ec5024db39ed4e8c8dcdd | [
"Apache-2.0"
] | null | null | null | /*
* SPDX-FileCopyrightText: Copyright (c) 2021 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*
* 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 <iostream>
#include <vector>
#include <algorithm>
#include <math.h>
#include <cuda_runtime_api.h>
#include "postprocess.h"
#include "postprocess_kernels.h"
#define checkCudaErrors(status) \
{ \
if (status != 0) \
{ \
std::cout << "Cuda failure: " << cudaGetErrorString(status) \
<< " at line " << __LINE__ \
<< " in file " << __FILE__ \
<< " error status: " << status \
<< std::endl; \
abort(); \
} \
}
const float ThresHold = 1e-8;
inline float cross(const float2 p1, const float2 p2, const float2 p0) {
return (p1.x - p0.x) * (p2.y - p0.y) - (p2.x - p0.x) * (p1.y - p0.y);
}
inline int check_box2d(const Bndbox box, const float2 p) {
const float MARGIN = 1e-2;
float center_x = box.x;
float center_y = box.y;
float angle_cos = cos(-box.rt);
float angle_sin = sin(-box.rt);
float rot_x = (p.x - center_x) * angle_cos + (p.y - center_y) * (-angle_sin);
float rot_y = (p.x - center_x) * angle_sin + (p.y - center_y) * angle_cos;
return (fabs(rot_x) < box.w / 2 + MARGIN && fabs(rot_y) < box.l / 2 + MARGIN);
}
bool intersection(const float2 p1, const float2 p0, const float2 q1, const float2 q0, float2 &ans) {
if (( std::min(p0.x, p1.x) <= std::max(q0.x, q1.x) &&
std::min(q0.x, q1.x) <= std::max(p0.x, p1.x) &&
std::min(p0.y, p1.y) <= std::max(q0.y, q1.y) &&
std::min(q0.y, q1.y) <= std::max(p0.y, p1.y) ) == 0)
return false;
float s1 = cross(q0, p1, p0);
float s2 = cross(p1, q1, p0);
float s3 = cross(p0, q1, q0);
float s4 = cross(q1, p1, q0);
if (!(s1 * s2 > 0 && s3 * s4 > 0))
return false;
float s5 = cross(q1, p1, p0);
if (fabs(s5 - s1) > ThresHold) {
ans.x = (s5 * q0.x - s1 * q1.x) / (s5 - s1);
ans.y = (s5 * q0.y - s1 * q1.y) / (s5 - s1);
} else {
float a0 = p0.y - p1.y, b0 = p1.x - p0.x, c0 = p0.x * p1.y - p1.x * p0.y;
float a1 = q0.y - q1.y, b1 = q1.x - q0.x, c1 = q0.x * q1.y - q1.x * q0.y;
float D = a0 * b1 - a1 * b0;
ans.x = (b0 * c1 - b1 * c0) / D;
ans.y = (a1 * c0 - a0 * c1) / D;
}
return true;
}
inline void rotate_around_center(const float2 ¢er, const float angle_cos, const float angle_sin, float2 &p) {
float new_x = (p.x - center.x) * angle_cos + (p.y - center.y) * (-angle_sin) + center.x;
float new_y = (p.x - center.x) * angle_sin + (p.y - center.y) * angle_cos + center.y;
p = float2 {new_x, new_y};
}
inline float box_overlap(const Bndbox &box_a, const Bndbox &box_b) {
float a_angle = box_a.rt, b_angle = box_b.rt;
float a_dx_half = box_a.w / 2, b_dx_half = box_b.w / 2, a_dy_half = box_a.l / 2, b_dy_half = box_b.l / 2;
float a_x1 = box_a.x - a_dx_half, a_y1 = box_a.y - a_dy_half;
float a_x2 = box_a.x + a_dx_half, a_y2 = box_a.y + a_dy_half;
float b_x1 = box_b.x - b_dx_half, b_y1 = box_b.y - b_dy_half;
float b_x2 = box_b.x + b_dx_half, b_y2 = box_b.y + b_dy_half;
float2 box_a_corners[5];
float2 box_b_corners[5];
float2 center_a = float2 {box_a.x, box_a.y};
float2 center_b = float2 {box_b.x, box_b.y};
float2 cross_points[16];
float2 poly_center = {0, 0};
int cnt = 0;
bool flag = false;
box_a_corners[0] = float2 {a_x1, a_y1};
box_a_corners[1] = float2 {a_x2, a_y1};
box_a_corners[2] = float2 {a_x2, a_y2};
box_a_corners[3] = float2 {a_x1, a_y2};
box_b_corners[0] = float2 {b_x1, b_y1};
box_b_corners[1] = float2 {b_x2, b_y1};
box_b_corners[2] = float2 {b_x2, b_y2};
box_b_corners[3] = float2 {b_x1, b_y2};
float a_angle_cos = cos(a_angle), a_angle_sin = sin(a_angle);
float b_angle_cos = cos(b_angle), b_angle_sin = sin(b_angle);
for (int k = 0; k < 4; k++) {
rotate_around_center(center_a, a_angle_cos, a_angle_sin, box_a_corners[k]);
rotate_around_center(center_b, b_angle_cos, b_angle_sin, box_b_corners[k]);
}
box_a_corners[4] = box_a_corners[0];
box_b_corners[4] = box_b_corners[0];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
flag = intersection(box_a_corners[i + 1], box_a_corners[i],
box_b_corners[j + 1], box_b_corners[j],
cross_points[cnt]);
if (flag) {
poly_center = {poly_center.x + cross_points[cnt].x, poly_center.y + cross_points[cnt].y};
cnt++;
}
}
}
for (int k = 0; k < 4; k++) {
if (check_box2d(box_a, box_b_corners[k])) {
poly_center = {poly_center.x + box_b_corners[k].x, poly_center.y + box_b_corners[k].y};
cross_points[cnt] = box_b_corners[k];
cnt++;
}
if (check_box2d(box_b, box_a_corners[k])) {
poly_center = {poly_center.x + box_a_corners[k].x, poly_center.y + box_a_corners[k].y};
cross_points[cnt] = box_a_corners[k];
cnt++;
}
}
poly_center.x /= cnt;
poly_center.y /= cnt;
float2 temp;
for (int j = 0; j < cnt - 1; j++) {
for (int i = 0; i < cnt - j - 1; i++) {
if (atan2(cross_points[i].y - poly_center.y, cross_points[i].x - poly_center.x) >
atan2(cross_points[i+1].y - poly_center.y, cross_points[i+1].x - poly_center.x)
) {
temp = cross_points[i];
cross_points[i] = cross_points[i + 1];
cross_points[i + 1] = temp;
}
}
}
float area = 0;
for (int k = 0; k < cnt - 1; k++) {
float2 a = {cross_points[k].x - cross_points[0].x,
cross_points[k].y - cross_points[0].y};
float2 b = {cross_points[k + 1].x - cross_points[0].x,
cross_points[k + 1].y - cross_points[0].y};
area += (a.x * b.y - a.y * b.x);
}
return fabs(area) / 2.0;
}
int nms_cpu(std::vector<Bndbox> bndboxes, const float nms_thresh, std::vector<Bndbox> &nms_pred)
{
std::sort(bndboxes.begin(), bndboxes.end(),
[](Bndbox boxes1, Bndbox boxes2) { return boxes1.score > boxes2.score; });
std::vector<int> suppressed(bndboxes.size(), 0);
for (size_t i = 0; i < bndboxes.size(); i++) {
if (suppressed[i] == 1) {
continue;
}
nms_pred.emplace_back(bndboxes[i]);
for (size_t j = i + 1; j < bndboxes.size(); j++) {
if (suppressed[j] == 1) {
continue;
}
float sa = bndboxes[i].w * bndboxes[i].l;
float sb = bndboxes[j].w * bndboxes[j].l;
float s_overlap = box_overlap(bndboxes[i], bndboxes[j]);
float iou = s_overlap / fmaxf(sa + sb - s_overlap, ThresHold);
if (iou >= nms_thresh) {
suppressed[j] = 1;
}
}
}
return 0;
}
PostProcessCuda::PostProcessCuda(cudaStream_t stream)
{
stream_ = stream;
checkCudaErrors(cudaMalloc((void **)&anchors_, params_.num_anchors * params_.len_per_anchor * sizeof(float)));
checkCudaErrors(cudaMalloc((void **)&anchors_bottom_height_, params_.num_classes * sizeof(float)));
checkCudaErrors(cudaMalloc((void **)&object_counter_, sizeof(int)));
checkCudaErrors(cudaMemcpyAsync(anchors_, params_.anchors,
params_.num_anchors * params_.len_per_anchor * sizeof(float), cudaMemcpyDefault, stream_));
checkCudaErrors(cudaMemcpyAsync(anchors_bottom_height_, params_.anchors_bottom_height,
params_.num_classes * sizeof(float), cudaMemcpyDefault, stream_));
checkCudaErrors(cudaMemsetAsync(object_counter_, 0, sizeof(int), stream_));
}
PostProcessCuda::~PostProcessCuda()
{
checkCudaErrors(cudaFree(anchors_));
checkCudaErrors(cudaFree(anchors_bottom_height_));
checkCudaErrors(cudaFree(object_counter_));
}
void PostProcessCuda::doPostprocessCuda(const float *cls_input, float *box_input, const float *dir_cls_input,
float *bndbox_output)
{
checkCudaErrors(cudaMemsetAsync(object_counter_, 0, sizeof(int)));
postprocess_launch(cls_input,
box_input,
dir_cls_input,
anchors_,
anchors_bottom_height_,
bndbox_output,
object_counter_,
params_.min_x_range,
params_.max_x_range,
params_.min_y_range,
params_.max_y_range,
params_.feature_x_size,
params_.feature_y_size,
params_.num_anchors,
params_.num_classes,
params_.num_box_values,
params_.score_thresh,
params_.dir_offset,
stream_
);
}
| 37.792453 | 113 | 0.547678 | [
"vector"
] |
aba1b5d2154dac7125aeef0612ba0911db077fd6 | 1,160 | cpp | C++ | LeetCode/890.find_and_replace_pattern.cpp | PieroNarciso/cprogramming | d3a53ce2afce6f853e0b7cc394190d5be6427902 | [
"MIT"
] | 2 | 2021-05-22T17:47:01.000Z | 2021-05-27T17:10:58.000Z | LeetCode/890.find_and_replace_pattern.cpp | PieroNarciso/cprogramming | d3a53ce2afce6f853e0b7cc394190d5be6427902 | [
"MIT"
] | null | null | null | LeetCode/890.find_and_replace_pattern.cpp | PieroNarciso/cprogramming | d3a53ce2afce6f853e0b7cc394190d5be6427902 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
vector<string> patterns;
for (string word : words) {
unordered_map<char, char> match;
unordered_map<char, char> matchReverse;
bool goesToPatterns = true;
for (int i = 0; i < word.size(); i++) {
if (match.find(word[i]) != match.end() &&
matchReverse.find(pattern[i]) != matchReverse.end()) {
if (match[word[i]] != pattern[i] || matchReverse[pattern[i]] != word[i]) {
goesToPatterns = false;
break;
}
} else if (match.find(word[i]) == match.end() &&
matchReverse.find(pattern[i]) == matchReverse.end()) {
match[word[i]] = pattern[i];
matchReverse[pattern[i]] = word[i];
} else {
goesToPatterns = false;
break;
}
}
if (goesToPatterns) {
patterns.push_back(word);
}
}
return patterns;
}
int main(int argc, const char** argv) {
vector<string> words = {"a", "b" , "c"};
vector<string> result = findAndReplacePattern(words, "a");
for (string word: result) {
cout << word << ", ";
}
cout << endl;
return 0;
}
| 24.680851 | 78 | 0.62069 | [
"vector"
] |
aba21b9e2efedd6a0bd4780da6f4170b8f30295f | 1,845 | cpp | C++ | Lydsy/P1745 [Usacoxxxx xxx]/P1745.cpp | Wycers/Codelib | 86d83787aa577b8f2d66b5410e73102411c45e46 | [
"MIT"
] | 22 | 2018-08-07T06:55:10.000Z | 2021-06-12T02:12:19.000Z | Lydsy/P1745 [Usacoxxxx xxx]/P1745.cpp | Wycers/Codelib | 86d83787aa577b8f2d66b5410e73102411c45e46 | [
"MIT"
] | 28 | 2020-03-04T23:47:22.000Z | 2022-02-26T18:50:00.000Z | Lydsy/P1745 [Usacoxxxx xxx]/P1745.cpp | Wycers/Codelib | 86d83787aa577b8f2d66b5410e73102411c45e46 | [
"MIT"
] | 4 | 2019-11-09T15:41:26.000Z | 2021-10-10T08:56:57.000Z | #include <cstdio>
#include <algorithm>
#include <queue>
#include <vector>
const int N = 1e4 + 10;
using namespace std;
int Read()
{
int x = 0,f = 1;char ch = getchar();
while (ch < '0' || '9' < ch) ch = getchar();
while ('0' <= ch && ch <= '9') x = x * 10 + ch - 48,ch = getchar();
return x;
}
struct node
{
int v,w;
bool operator < (const node &a) const
{
return v < a.v;
}
};
vector<node> v1[N],v2[N];
int num[2][N],n,c,k;
int Work(vector<node> v[],int* num)
{
priority_queue<node> q;
int res = 0,temp = 0,sz;
node t;
for (int i=1;i<=n;++i)
{
res += num[i];
temp -= num[i];
sz = v[i].size();
for (int j=0;j<sz;++j)
{
temp += v[i][j].w;
q.push(v[i][j]);
}
while (temp > c)
{
t = q.top(); q.pop();
if (temp - t.w > c)
{
temp -= t.w;
num[t.v] -= t.w;
}
else
{
num[t.v] -= (temp - c);
t.w -= (temp - c);
temp = c;
q.push(t);
}
}
}
return res;
}
void Init()
{
k = Read(),n = Read(),c = Read();
int s,e,w;
for (int i=0;i<=n;++i)
{
v1[i].clear();
v2[i].clear();
}
for (int i=1;i<=k;++i)
{
s = Read(); e = Read(); w = Read();
if (s < e)
{
num[0][e] += w;
v1[s].push_back((node){e,w});
}
else
{
s = n - s + 1;e = n - e + 1;
num[1][e] += w;
v2[s].push_back((node){e,w});
}
}
}
void Solve()
{
int ans = 0;
ans += Work(v1,num[0]);
ans += Work(v2,num[1]);
printf("%d\n",ans);
}
int main()
{
Init();
Solve();
return 0;
}
| 19.21875 | 71 | 0.36477 | [
"vector"
] |
aba21e6345aa7ab18be3b14d40cbce70de76a7db | 1,716 | cpp | C++ | src/box/stss.cpp | kounoike/cpp-mp4 | 65703c1402242afcc1e4d822d9828e79f3dcec01 | [
"Apache-2.0"
] | 23 | 2020-12-29T07:17:30.000Z | 2022-03-25T09:18:37.000Z | src/box/stss.cpp | kounoike/cpp-mp4 | 65703c1402242afcc1e4d822d9828e79f3dcec01 | [
"Apache-2.0"
] | 2 | 2021-01-12T06:02:42.000Z | 2021-05-19T01:44:22.000Z | src/box/stss.cpp | kounoike/cpp-mp4 | 65703c1402242afcc1e4d822d9828e79f3dcec01 | [
"Apache-2.0"
] | 2 | 2021-05-04T02:15:17.000Z | 2022-02-19T14:45:00.000Z | #include "shiguredo/mp4/box/stss.hpp"
#include <fmt/core.h>
#include <fmt/ranges.h>
#include <cstdint>
#include <istream>
#include <iterator>
#include <string>
#include <vector>
#include "shiguredo/mp4/bitio/bitio.hpp"
#include "shiguredo/mp4/bitio/reader.hpp"
#include "shiguredo/mp4/bitio/writer.hpp"
#include "shiguredo/mp4/box_type.hpp"
namespace shiguredo::mp4::box {
BoxType box_type_stss() {
return BoxType("stss");
}
Stss::Stss() {
m_type = box_type_stss();
}
Stss::Stss(const StssParmeters& params) : m_sample_numbers(params.sample_numbers) {
setVersion(params.version);
setFlags(params.flags);
m_type = box_type_stss();
}
std::string Stss::toStringOnlyData() const {
return fmt::format("{} EntryCount={} SampleNumbers=[{}]", getVersionAndFlagsString(), std::size(m_sample_numbers),
fmt::join(m_sample_numbers, ", "));
}
std::uint64_t Stss::writeData(std::ostream& os) const {
bitio::Writer writer(os);
std::uint64_t wbits = writeVersionAndFlag(&writer);
std::uint32_t entry_count = static_cast<std::uint32_t>(std::size(m_sample_numbers));
return wbits += bitio::write_uint<std::uint32_t>(&writer, entry_count) +
bitio::write_vector_uint<std::uint32_t>(&writer, m_sample_numbers);
}
std::uint64_t Stss::getDataSize() const {
return 8 + std::size(m_sample_numbers) * 4;
}
std::uint64_t Stss::readData(std::istream& is) {
bitio::Reader reader(is);
std::uint64_t rbits = readVersionAndFlag(&reader);
std::uint32_t entry_count;
rbits += bitio::read_uint<std::uint32_t>(&reader, &entry_count);
return rbits += bitio::read_vector_uint<std::uint32_t>(&reader, entry_count, &m_sample_numbers);
}
} // namespace shiguredo::mp4::box
| 29.084746 | 116 | 0.710373 | [
"vector"
] |
abaa9eb6d6ef7a3d8469206865ec3cbaca622c52 | 1,824 | hpp | C++ | include/measurement_kit/net/connect.hpp | measurement-kit/debian-packaging | ed8b0575d8b487c8981c37cc790449b034028894 | [
"BSD-2-Clause"
] | null | null | null | include/measurement_kit/net/connect.hpp | measurement-kit/debian-packaging | ed8b0575d8b487c8981c37cc790449b034028894 | [
"BSD-2-Clause"
] | null | null | null | include/measurement_kit/net/connect.hpp | measurement-kit/debian-packaging | ed8b0575d8b487c8981c37cc790449b034028894 | [
"BSD-2-Clause"
] | null | null | null | // Part of measurement-kit <https://measurement-kit.github.io/>.
// Measurement-kit is free software. See AUTHORS and LICENSE for more
// information on the copying conditions.
#ifndef MEASUREMENT_KIT_NET_CONNECT_HPP
#define MEASUREMENT_KIT_NET_CONNECT_HPP
#include <measurement_kit/dns.hpp>
#include <measurement_kit/net/transport.hpp>
struct bufferevent;
namespace mk {
namespace net {
struct ResolveHostnameResult {
bool inet_pton_ipv4 = false;
bool inet_pton_ipv6 = false;
Error ipv4_err;
dns::Message ipv4_reply;
Error ipv6_err;
dns::Message ipv6_reply;
std::vector<std::string> addresses;
};
class ConnectResult : public ErrorContext {
public:
ResolveHostnameResult resolve_result;
std::vector<Error> connect_result;
double connect_time = 0.0;
bufferevent *connected_bev = nullptr;
~ConnectResult() override;
};
// Convert error returned by connect() in connect_time
ErrorOr<double> get_connect_time(Error error);
void connect(std::string address, int port,
Callback<Error, Var<Transport>> callback,
Settings settings = {},
Var<Reactor> reactor = Reactor::global(),
Var<Logger> logger = Logger::global());
class ConnectManyResult : public ErrorContext {
public:
std::vector<Var<ConnectResult>> results;
~ConnectManyResult() override;
};
// Convert error returned by connect_many() into connect_times vector
ErrorOr<std::vector<double>> get_connect_times(Error error);
using ConnectManyCb = Callback<Error, std::vector<Var<Transport>>>;
void connect_many(std::string address, int port, int num,
ConnectManyCb callback, Settings settings = {},
Var<Reactor> reactor = Reactor::global(),
Var<Logger> logger = Logger::global());
} // namespace net
} // namespace mk
#endif
| 28.5 | 69 | 0.716557 | [
"vector"
] |
abac9677ecb9dd56a73d1c3da8100f9ceb944a2d | 6,051 | cpp | C++ | Engine/src/ModuleEditorCamera.cpp | JoanMarcBardes/Master-Engine | 2e36395d3a6c147389372a261f60fa76d12ce55c | [
"MIT"
] | null | null | null | Engine/src/ModuleEditorCamera.cpp | JoanMarcBardes/Master-Engine | 2e36395d3a6c147389372a261f60fa76d12ce55c | [
"MIT"
] | null | null | null | Engine/src/ModuleEditorCamera.cpp | JoanMarcBardes/Master-Engine | 2e36395d3a6c147389372a261f60fa76d12ce55c | [
"MIT"
] | null | null | null | #include "ModuleEditorCamera.h"
#include "Globals.h"
#include "Application.h"
#include "ModuleInput.h"
#include "ModuleWindow.h"
#include "Point.h"
#include "SDL.h"
#include "GL/glew.h"
#include "Libraries/MathGeoLib/Geometry/Frustum.h"
#include "Libraries/ImGui/imgui_impl_sdl.h"
#include "Time.h"
#include "DebugLeaks.h"
ModuleEditorCamera::ModuleEditorCamera()
{
}
ModuleEditorCamera::~ModuleEditorCamera()
{
}
bool ModuleEditorCamera::Init()
{
return true;
}
// Called every draw update
update_status ModuleEditorCamera::Update()
{
deltaTime = Time::deltaTime;
MoveForward();
MoveLateral();
MoveUp();
Pitch();
Yaw();
RotateMouse();
MoveMouse();
WheelMouse();
Focus();
Orbit();
UpadateCamera();
return UPDATE_CONTINUE;
}
// Called before quitting
bool ModuleEditorCamera::CleanUp()
{
LOG("Destroying EditorCamera");
return true;
}
void ModuleEditorCamera::WindowResized(unsigned width, unsigned height)
{
currentCamera->WindowResized(width, height);
}
void ModuleEditorCamera::UpadateCamera()
{
currentCamera->UpadateCamera();
}
void ModuleEditorCamera::Yaw()
{
float speedYaw = speed/2;
if (App->input->GetKey(SDL_SCANCODE_LSHIFT))
speedYaw *= 3;
if (App->input->GetKey(SDL_SCANCODE_LEFT))
currentCamera->Yaw(speedYaw);
if (App->input->GetKey(SDL_SCANCODE_RIGHT))
currentCamera->Yaw(-speedYaw);
}
void ModuleEditorCamera::Pitch()
{
float speedPitch = speed/2;
if (App->input->GetKey(SDL_SCANCODE_LSHIFT))
speedPitch *= 3;
if (App->input->GetKey(SDL_SCANCODE_UP))
currentCamera->Pitch(speedPitch);
if (App->input->GetKey(SDL_SCANCODE_DOWN))
currentCamera->Pitch(-speedPitch);
}
void ModuleEditorCamera::MoveForward()
{
float speedForward = speed;
if (App->input->GetKey(SDL_SCANCODE_LSHIFT))
speedForward *= 3;
if (App->input->GetKey(SDL_SCANCODE_W))
currentCamera->MoveForward(speedForward);
if (App->input->GetKey(SDL_SCANCODE_S))
currentCamera->MoveForward(-speedForward);
}
void ModuleEditorCamera::MoveLateral()
{
float speedLateral = speed;
if (App->input->GetKey(SDL_SCANCODE_LSHIFT))
speedLateral *= 3;
if (App->input->GetKey(SDL_SCANCODE_A))
currentCamera->MoveLateral(-speedLateral);
if (App->input->GetKey(SDL_SCANCODE_D))
currentCamera->MoveLateral(speedLateral);
}
void ModuleEditorCamera::MoveUp()
{
float speedUp = speed;
if (App->input->GetKey(SDL_SCANCODE_LSHIFT))
speedUp *= 3;
if (App->input->GetKey(SDL_SCANCODE_Q))
currentCamera->MoveUp(speedUp);
if (App->input->GetKey(SDL_SCANCODE_E))
currentCamera->MoveUp(-speedUp);
}
void ModuleEditorCamera::RotateMouse()
{
float speedRotateMouse = speed / 4;
if (App->input->GetKey(SDL_SCANCODE_LSHIFT))
speedRotateMouse *= 3;
if (App->input->GetMouseButtonDown(SDL_BUTTON_LEFT) && !App->input->GetKey(SDL_SCANCODE_LALT)) {
iPoint mouse = App->input->GetMousePosition();
if (mouse.x > preMousePosX) {
currentCamera->Yaw(-speedRotateMouse);
preMousePosX = mouse.x;
}else if (mouse.x < preMousePosX){
currentCamera->Yaw(speedRotateMouse);
preMousePosX = mouse.x;
}
if (mouse.y > preMousePosY) {
currentCamera->Pitch(-speedRotateMouse);
preMousePosY = mouse.y;
}else if (mouse.y < preMousePosY) {
currentCamera->Pitch(speedRotateMouse);
preMousePosY = mouse.y;
}
//currentCamera->RotateMouse(speedRotateMouse, mouse);
}
}
void ModuleEditorCamera::MoveMouse()
{
float speedMoveMouse = speed;
if (App->input->GetKey(SDL_SCANCODE_LSHIFT))
speedMoveMouse *= 3;
if (App->input->GetMouseButtonDown(SDL_BUTTON_RIGHT) && !App->input->GetKey(SDL_SCANCODE_LALT)) {
iPoint mouse = App->input->GetMousePosition();
if (mouse.x > preMousePosX) {
currentCamera->MoveLateral(-speedMoveMouse);
preMousePosX = mouse.x;
}
else if (mouse.x < preMousePosX) {
currentCamera->MoveLateral(speedMoveMouse);
preMousePosX = mouse.x;
}
if (mouse.y > preMousePosY) {
currentCamera->MoveUp(speedMoveMouse / 2);
preMousePosY = mouse.y;
}
else if (mouse.y < preMousePosY) {
currentCamera->MoveUp(-speedMoveMouse / 2);
preMousePosY = mouse.y;
}
//currentCamera->RotateMouse(speedRotateMouse, mouse);
}
}
void ModuleEditorCamera::WheelMouse()
{
float speedWheelMouse = speed * 100;
if (App->input->GetKey(SDL_SCANCODE_LSHIFT))
speedWheelMouse *= 3;
iPoint mouse_wheel = App->input->GetMouseWhell();
if (mouse_wheel.y != 0)
currentCamera->WheelMouse(speedWheelMouse, mouse_wheel);
}
void ModuleEditorCamera::Focus()
{
if (App->input->GetKey(SDL_SCANCODE_F))
currentCamera->Focus();
}
void ModuleEditorCamera::Orbit()
{
float speedOrbit = 2.0f;
if (App->input->GetKey(SDL_SCANCODE_LSHIFT))
speedOrbit *= 3;
if (App->input->GetMouseButtonDown(SDL_BUTTON_LEFT) && App->input->GetKey(SDL_SCANCODE_LALT)) {
iPoint mouse = App->input->GetMousePosition();
if (mouse.x > preMousePosX) {
currentCamera->Orbit(speedOrbit, mouse);
preMousePosX = mouse.x;
}
else if(mouse.x < preMousePosX) {
currentCamera->Orbit(-speedOrbit, mouse);
preMousePosX = mouse.x;
}
}
}
/*void ModuleEditorCamera::AdaptSizeGeometry(float volume)
{
position = float3(position.x, position.y, volume);
currentCamera->LookAt(target);
UpadateCamera();
}*/
void ModuleEditorCamera::SetCurrentCamera(Camera* camera)
{
currentCamera = camera;
}
void ModuleEditorCamera::RemoveAllCameras()
{
allCameras.clear();
currentCamera = nullptr;
}
void ModuleEditorCamera::AddCamera(Camera* camera, bool setAsCurrentCamera)
{
allCameras.push_back(camera);
if (setAsCurrentCamera)
SetActiveCamera(camera,true);
}
void ModuleEditorCamera::SetActiveCamera(Camera* camera, bool active)
{
if (active)
{
for each (Camera * cam in allCameras)
{
cam->SetActive(false);
}
camera->SetActive(true);
SetCurrentCamera(camera);
}
else
{
bool anyCamera = false;
for each (Camera * cam in allCameras)
{
if (cam != camera)
{
cam->SetActive(true);
SetCurrentCamera(cam);
anyCamera = true;
break;
}
}
camera->SetActive(false);
if(!anyCamera)
SetCurrentCamera(nullptr);
}
}
| 21.381625 | 98 | 0.71955 | [
"geometry"
] |
abb36a88f9124d83c6a85a7a24fa73a7b59e5181 | 2,847 | cc | C++ | packager/media/formats/mp4/composition_offset_iterator_unittest.cc | Acidburn0zzz/shaka-packager | c540e5afa0a649285dc5a2c2a1ce68cc76ab1bd5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2016-07-26T04:05:06.000Z | 2016-07-26T04:05:06.000Z | packager/media/formats/mp4/composition_offset_iterator_unittest.cc | Acidburn0zzz/shaka-packager | c540e5afa0a649285dc5a2c2a1ce68cc76ab1bd5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | packager/media/formats/mp4/composition_offset_iterator_unittest.cc | Acidburn0zzz/shaka-packager | c540e5afa0a649285dc5a2c2a1ce68cc76ab1bd5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 Google Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
#include <gtest/gtest.h>
#include "packager/base/memory/scoped_ptr.h"
#include "packager/media/formats/mp4/composition_offset_iterator.h"
namespace shaka {
namespace media {
namespace mp4 {
const CompositionOffset kCompositionOffsets[] =
{{10, -8}, {9, 5}, {25, 7}, {48, 63}, {8, 2}};
class CompositionOffsetIteratorTest : public testing::Test {
public:
CompositionOffsetIteratorTest() {
// Build composition offset table from kCompositionOffsets.
uint32_t length = sizeof(kCompositionOffsets) / sizeof(CompositionOffset);
for (uint32_t i = 0; i < length; ++i) {
for (uint32_t j = 0; j < kCompositionOffsets[i].sample_count; ++j) {
composition_offset_table_.push_back(
kCompositionOffsets[i].sample_offset);
}
}
composition_time_to_sample_.composition_offset.assign(
kCompositionOffsets, kCompositionOffsets + length);
composition_offset_iterator_.reset(
new CompositionOffsetIterator(composition_time_to_sample_));
}
protected:
std::vector<int64_t> composition_offset_table_;
CompositionTimeToSample composition_time_to_sample_;
scoped_ptr<CompositionOffsetIterator> composition_offset_iterator_;
private:
DISALLOW_COPY_AND_ASSIGN(CompositionOffsetIteratorTest);
};
TEST_F(CompositionOffsetIteratorTest, EmptyCompositionTime) {
CompositionTimeToSample composition_time_to_sample;
CompositionOffsetIterator iterator(composition_time_to_sample);
EXPECT_FALSE(iterator.IsValid());
EXPECT_EQ(0u, iterator.NumSamples());
}
TEST_F(CompositionOffsetIteratorTest, NumSamples) {
ASSERT_EQ(composition_offset_table_.size(),
composition_offset_iterator_->NumSamples());
}
TEST_F(CompositionOffsetIteratorTest, AdvanceSample) {
ASSERT_EQ(composition_offset_table_[0],
composition_offset_iterator_->sample_offset());
for (uint32_t sample = 1; sample < composition_offset_table_.size();
++sample) {
ASSERT_TRUE(composition_offset_iterator_->AdvanceSample());
ASSERT_EQ(composition_offset_table_[sample],
composition_offset_iterator_->sample_offset());
ASSERT_TRUE(composition_offset_iterator_->IsValid());
}
ASSERT_FALSE(composition_offset_iterator_->AdvanceSample());
ASSERT_FALSE(composition_offset_iterator_->IsValid());
}
TEST_F(CompositionOffsetIteratorTest, SampleOffset) {
for (uint32_t sample = 0; sample < composition_offset_table_.size();
++sample) {
ASSERT_EQ(composition_offset_table_[sample],
composition_offset_iterator_->SampleOffset(sample+1));
}
}
} // namespace mp4
} // namespace media
} // namespace shaka
| 34.301205 | 78 | 0.753776 | [
"vector"
] |
abbe48268cb65f0d9dbdcc519064ebc7388e0400 | 1,251 | hpp | C++ | server_engine/src/util.hpp | Jimmyee/Endless-Online-Awaken | 1af1e07fb8ae88d87e76fdf297422cff1c0bacab | [
"MIT"
] | 14 | 2017-06-01T16:00:25.000Z | 2021-12-01T16:02:00.000Z | server_engine/src/util.hpp | Jimmyee/Endless-Online-Awaken | 1af1e07fb8ae88d87e76fdf297422cff1c0bacab | [
"MIT"
] | null | null | null | server_engine/src/util.hpp | Jimmyee/Endless-Online-Awaken | 1af1e07fb8ae88d87e76fdf297422cff1c0bacab | [
"MIT"
] | 4 | 2017-10-04T22:51:44.000Z | 2021-03-18T10:16:02.000Z | // Endless Online Awaken
#ifndef UTIL_HPP_INCLUDED
#define UTIL_HPP_INCLUDED
#include <vector>
#include <array>
#include <chrono>
#include <random>
static const unsigned int MAX1 = 253;
static const unsigned int MAX2 = 64009;
static const unsigned int MAX3 = 16194277;
inline static std::vector<std::string> GetArgs(std::string str)
{
std::vector<std::string> args;
std::string word;
for(std::size_t i = 0; i < str.length(); ++i)
{
if((str[i] == ' ' || i == str.length() - 1))
{
if(str[i] != ' ') word += str[i];
if(!word.empty()) args.push_back(word);
word.clear();
}
else if(str[i] != ' ')
{
word += str[i];
}
}
return args;
}
unsigned int DecodeNumber(unsigned char, unsigned char = 254, unsigned char = 254, unsigned char = 254);
std::array<unsigned char, 4> EncodeNumber(unsigned int);
std::array<unsigned char, 4> EncodeNumber(unsigned int, std::size_t &size);
class RandGen
{
private:
static bool initialized_;
static unsigned int seed;
static std::mt19937 gen;
public:
RandGen();
int RandInt(int imin, int imax);
};
int path_length(int x1, int y1, int x2, int y2);
#endif // UTIL_HPP_INCLUDED
| 22.745455 | 104 | 0.615508 | [
"vector"
] |
abc613afc024472861dd936339629e0a5a285011 | 29,169 | cc | C++ | mysqlshdk/libs/db/uri_parser.cc | mueller/mysql-shell | 29bafc5692bd536a12c4e41c54cb587375fe52cf | [
"Apache-2.0"
] | 119 | 2016-04-14T14:16:22.000Z | 2022-03-08T20:24:38.000Z | mysqlshdk/libs/db/uri_parser.cc | mueller/mysql-shell | 29bafc5692bd536a12c4e41c54cb587375fe52cf | [
"Apache-2.0"
] | 9 | 2017-04-26T20:48:42.000Z | 2021-09-07T01:52:44.000Z | mysqlshdk/libs/db/uri_parser.cc | mueller/mysql-shell | 29bafc5692bd536a12c4e41c54cb587375fe52cf | [
"Apache-2.0"
] | 51 | 2016-07-20T05:06:48.000Z | 2022-03-09T01:20:53.000Z | /*
* Copyright (c) 2016, 2020, Oracle and/or its affiliates.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2.0,
* as published by the Free Software Foundation.
*
* This program is also distributed with certain software (including
* but not limited to OpenSSL) that is licensed under separate terms, as
* designated in a particular file or component or in included license
* documentation. The authors of MySQL hereby grant you an additional
* permission to link the program and your derivative works with the
* separately licensed software that they have included with MySQL.
* 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, version 2.0, 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 "mysqlshdk/libs/db/uri_parser.h"
#include <cctype>
#include "utils/utils_string.h"
// Avoid warnings from protobuf and rapidjson
#if defined __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wshadow"
#pragma GCC diagnostic ignored "-Wconversion"
#pragma GCC diagnostic ignored "-Wpedantic"
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#ifndef __has_warning
#define __has_warning(x) 0
#endif
#if __has_warning("-Wunused-local-typedefs")
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#endif
#elif defined _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4018 4996)
#endif
#ifdef __GNUC__
#pragma GCC diagnostic pop
#elif defined _MSC_VER
#pragma warning(pop)
#endif
namespace mysqlshdk {
namespace db {
namespace uri {
#define URI_SCHEME "scheme"
#define URI_TARGET "targetinfo"
#define URI_USER_INFO "userinfo"
#define URI_PATH "path"
#define URI_QUERY "query"
#define IS_DELIMITER(x) DELIMITERS.find(x) != std::string::npos
#define IS_SUBDELIMITER(x) SUBDELIMITERS.find(x) != std::string::npos
#define IS_ALPHA(x) ALPHA.find(x) != std::string::npos
#define IS_DIGIT(x) DIGIT.find(x) != std::string::npos
#define IS_HEXDIG(x) HEXDIG.find(x) != std::string::npos
#define IS_ALPHANUMERIC(x) ALPHANUMERIC.find(x) != std::string::npos
#define IS_RESERVED(x) RESERVED.find(x) != std::string::npos
#define IS_UNRESERVED(x) UNRESERVED.find(x) != std::string::npos
const std::map<char, char> kUriHexLiterals = {
{'1', 1}, {'2', 2}, {'3', 3}, {'4', 4}, {'5', 5}, {'6', 6},
{'7', 7}, {'8', 8}, {'9', 9}, {'A', 10}, {'B', 11}, {'C', 12},
{'D', 13}, {'E', 14}, {'F', 15}, {'a', 10}, {'b', 11}, {'c', 12},
{'d', 13}, {'e', 14}, {'f', 15}};
Uri_parser::Uri_parser() : _data(nullptr) {}
void Uri_parser::parse_scheme() {
if (_chunks.find(URI_SCHEME) != _chunks.end()) {
// Does schema parsing based on RFC3986
_tokenizer.reset();
_tokenizer.set_allow_spaces(false);
// RFC3986 Defines the next valid chars: +.-
// However, in the Specification we only consider alphanumerics and + for
// extensions
_tokenizer.set_simple_tokens("+");
_tokenizer.set_complex_token("alphanumeric", ALPHANUMERIC);
_tokenizer.process(_chunks[URI_SCHEME]);
std::string scheme = _tokenizer.consume_token("alphanumeric");
if (_tokenizer.tokens_available()) {
std::string scheme_ext;
_tokenizer.consume_token("+");
scheme_ext = _tokenizer.consume_token("alphanumeric");
if (_tokenizer.tokens_available())
throw std::invalid_argument(shcore::str_format(
"Invalid scheme format [%s], only one extension is supported",
get_input_chunk(_chunks[URI_SCHEME]).c_str()));
else
throw std::invalid_argument(shcore::str_format(
"Scheme extension [%s] is not supported", scheme_ext.c_str()));
// TODO(rennox): Internally not supporting URI shcheme extensions
// _data->set_scheme_ext(scheme_ext);
}
// Validate on unique supported schema formats
// In the future we may support additional stuff, like extensions
if (scheme != "mysql" && scheme != "mysqlx")
throw std::invalid_argument(
shcore::str_format("Invalid scheme [%s], supported schemes "
"include: mysql, mysqlx",
scheme.c_str()));
_data->set_scheme(scheme);
}
}
void Uri_parser::parse_userinfo() {
if (_chunks.find(URI_USER_INFO) != _chunks.end()) {
_tokenizer.reset();
_tokenizer.set_allow_spaces(false);
_tokenizer.set_complex_token("pct-encoded", {"%", HEXDIG, HEXDIG});
_tokenizer.set_complex_token("unreserved", UNRESERVED);
_tokenizer.set_complex_token("sub-delims", SUBDELIMITERS);
_tokenizer.set_simple_tokens(":");
_tokenizer.set_final_token_group("password", ":");
_tokenizer.process(_chunks[URI_USER_INFO]);
std::string user, password;
bool has_password = false;
while (_tokenizer.tokens_available()) {
if (_tokenizer.cur_token_type_is(":"))
has_password = true;
else if (_tokenizer.cur_token_type_is("pct-encoded"))
(has_password ? password : user) +=
percent_decode(_tokenizer.peek_token().get_text());
else
(has_password ? password : user) += _tokenizer.peek_token().get_text();
_tokenizer.consume_any_token();
}
// At this point the user name can't be empty
if (user.empty()) throw std::invalid_argument("Missing user name");
_data->set_user(user);
if (has_password) _data->set_password(password);
}
}
void Uri_parser::parse_target() {
if (_chunks.find(URI_TARGET) != _chunks.end()) {
size_t start = _chunks[URI_TARGET].first;
const size_t end = _chunks[URI_TARGET].second;
if (input_contains(".", start) && start == end) {
_data->set_host(".");
} else if (input_contains(".", start) || input_contains("/", start) ||
input_contains("(.", start) || input_contains("(/", start)) {
auto offset = start;
{
// When it starts with / the symbol is skipped and rest is parsed
// as unencoded value
std::string socket;
if (_input[start] == '/') {
socket = "/";
start++;
offset++;
}
socket += parse_value({start, end}, &offset, "");
_data->set_socket(socket);
}
if (offset <= end)
throw std::invalid_argument(
"Unexpected data [" +
get_input_chunk({offset, _chunks[URI_TARGET].second}) +
"] at position " + std::to_string(offset));
} else if (input_contains("\\\\.\\", start) ||
input_contains("(\\\\.\\", start)) {
// Windows pipe
bool unencoded_pipe = false;
if (_input[start] == '\\') {
// move past named pipe prefix
start += 4;
} else {
unencoded_pipe = true;
}
auto offset = start;
auto pipe = parse_value({start, end}, &offset, "", ":");
if (unencoded_pipe) {
// unencoded pipe starts with pipe prefix, needs to be trimmed
pipe = pipe.substr(4);
}
if (pipe.empty()) {
throw std::invalid_argument("Named pipe cannot be empty.");
}
_data->set_pipe(pipe);
if (offset <= end)
throw std::invalid_argument(
"Unexpected data [" +
get_input_chunk({offset, _chunks[URI_TARGET].second}) +
"] at position " + std::to_string(offset));
} else {
parse_host();
}
}
}
std::string Uri_parser::parse_ipv4(size_t *offset) {
std::string ret_val;
std::string host;
if (_tokenizer.cur_token_type_is("digits") &&
_tokenizer.next_token_type(".") &&
_tokenizer.next_token_type("digits", 2) &&
_tokenizer.next_token_type(".", 3) &&
_tokenizer.next_token_type("digits", 4) &&
_tokenizer.next_token_type(".", 5) &&
_tokenizer.next_token_type("digits", 6)) {
for (size_t index = 0; index < 4; index++) {
const std::string octet = _tokenizer.consume_token("digits");
int value = -1;
try {
value = std::stoi(octet);
} catch (const std::out_of_range &) {
} catch (const std::invalid_argument &) {
}
if (value < 0 || value > 255) {
throw std::invalid_argument(
"Error parsing IPV4 address: Octet value out of bounds [" + octet +
"], valid range for IPv4 is 0 to 255 at position " +
std::to_string(*offset));
} else {
host += octet;
(*offset) += octet.length();
if (index < 3) {
host += _tokenizer.consume_token(".");
(*offset)++;
}
}
}
ret_val = host;
}
return host;
}
void Uri_parser::parse_ipv6(const std::pair<size_t, size_t> &range,
size_t *offset) {
_tokenizer.reset();
_tokenizer.set_allow_spaces(false);
_tokenizer.set_simple_tokens(":.[]");
_tokenizer.set_complex_token("digits", DIGIT);
_tokenizer.set_complex_token("hex-digits", HEXDIG);
// RFC6874: IPv6 address with zone ID is defined as:
// IPv6address "%25" ZoneID
// ZoneID = 1*( unreserved / pct-encoded )
_tokenizer.set_complex_token("zone-delimiter", {"%", "2", "5"});
_tokenizer.set_complex_token("unreserved", UNRESERVED);
_tokenizer.set_complex_token("pct-encoded", {"%", HEXDIG, HEXDIG});
_tokenizer.process(range);
_tokenizer.consume_token("[");
(*offset)++;
std::vector<std::string> values;
std::string next_type;
std::string host;
bool ipv4_found = false;
bool ipv4_allowed = false;
bool colon_allowed = false;
bool double_colon_allowed = true;
bool last_was_colon = false;
int segment_count = 0;
auto throw_unexpected_data = [this, &offset]() {
throw std::invalid_argument(
shcore::str_format("Unexpected data [%s] found at position %u",
_tokenizer.peek_token().get_text().c_str(),
static_cast<uint32_t>(*offset)));
};
while (!_tokenizer.cur_token_type_is("]")) {
if (host.empty()) {
// An IP Address may begin with ::
if (_tokenizer.cur_token_type_is(":")) {
host += _tokenizer.consume_token(":");
host += _tokenizer.consume_token(":");
(*offset) += 2;
colon_allowed = false;
double_colon_allowed = false;
ipv4_allowed = true;
last_was_colon = true;
} else if (_tokenizer.cur_token_type_is("unreserved") ||
_tokenizer.cur_token_type_is("pct-encoded") ||
_tokenizer.cur_token_type_is("zone-delimiter") ||
_tokenizer.cur_token_type_is("[") ||
_tokenizer.cur_token_type_is(".")) {
// these tokens are not allowed at the beginning of the address
throw_unexpected_data();
} else {
std::string value;
auto token = _tokenizer.peek_token();
while (token.get_type() == "hex-digits" ||
token.get_type() == "digits") {
value += _tokenizer.consume_any_token().get_text();
token = _tokenizer.peek_token();
}
if (value.length() > 4)
throw std::invalid_argument(
"Invalid IPv6 value [" + value +
"], maximum 4 hexadecimal digits accepted");
host += value;
(*offset) += value.length();
segment_count++;
colon_allowed = true;
double_colon_allowed = true;
}
} else {
// If an IPv4 is read, it must be at the end of the IPv6 definition
// So we are done
std::string ipv4_host;
if (ipv4_allowed) ipv4_host = parse_ipv4(offset);
if (ipv4_allowed && !ipv4_host.empty()) {
host += ipv4_host;
ipv4_found = true;
} else if (_tokenizer.cur_token_type_is("unreserved") ||
_tokenizer.cur_token_type_is("pct-encoded")) {
// these tokens are allowed only after zone delimiter
throw_unexpected_data();
} else if (_tokenizer.cur_token_type_is("zone-delimiter")) {
std::string zone_id;
// zone delimiter detected, all remaining tokens belong to zone ID
while (!_tokenizer.cur_token_type_is("]")) {
const auto &token = _tokenizer.peek_token();
const auto &type = token.get_type();
const auto &text = token.get_text();
if (type == ":" || type == "[" || type == "]") {
// reserved characters, cannot be used in zone ID
throw_unexpected_data();
} else if (type == "zone-delimiter" || type == "pct-encoded") {
zone_id += percent_decode(text);
} else {
zone_id += text;
}
_tokenizer.consume_any_token();
(*offset) += text.length();
}
if (zone_id.length() <= 1) {
throw std::invalid_argument("Zone ID cannot be empty");
}
host += zone_id;
} else if (colon_allowed && _tokenizer.cur_token_type_is(":")) {
// Colon is allowed after each hex-digit or after one colon
host += _tokenizer.consume_token(":");
(*offset)++;
if (last_was_colon) double_colon_allowed = false;
colon_allowed = double_colon_allowed;
// IPv4 is allowed after any colon
ipv4_allowed = true;
last_was_colon = true;
} else {
if (last_was_colon) {
std::string value;
auto token = _tokenizer.peek_token();
while (token.get_type() == "hex-digits" ||
token.get_type() == "digits") {
value += _tokenizer.consume_any_token().get_text();
token = _tokenizer.peek_token();
}
if (value.empty())
throw_unexpected_data();
else if (value.length() > 4)
throw std::invalid_argument(
"Invalid IPv6 value [" + value +
"], maximum 4 hexadecimal digits accepted");
host += value;
(*offset) += value.length();
segment_count++;
} else {
host += _tokenizer.consume_token(":");
(*offset)++;
}
last_was_colon = !last_was_colon;
// Colon is allowed only if the previous token was hex-digits
// Or if the double colon is still an option
colon_allowed = (!last_was_colon || double_colon_allowed);
ipv4_allowed = last_was_colon;
}
}
}
// At this point we should be done with the IPv6 Address
_tokenizer.consume_token("]");
(*offset)++;
// The shortcut :: was not used
if (double_colon_allowed) {
if ((ipv4_found && segment_count != 6) ||
(!ipv4_found && segment_count != 8))
throw std::invalid_argument(
"Invalid IPv6: the number of segments does not match the "
"specification");
} else {
if ((ipv4_found && segment_count >= 6) ||
(!ipv4_found && segment_count >= 8))
throw std::invalid_argument(
"Invalid IPv6: the number of segments does not match the "
"specification");
}
_data->set_host(host);
}
void Uri_parser::parse_port(const std::pair<size_t, size_t> &range,
size_t *offset) {
_tokenizer.reset();
_tokenizer.set_allow_spaces(false);
_tokenizer.set_simple_tokens(":");
_tokenizer.set_complex_token("digits", DIGIT);
_tokenizer.process(range);
_tokenizer.consume_token(":");
(*offset)++;
if (_tokenizer.tokens_available()) {
const std::string str_port = _tokenizer.consume_token("digits");
(*offset) += str_port.length();
int port = -1;
try {
port = std::stoi(str_port);
} catch (const std::out_of_range &) {
} catch (const std::invalid_argument &) {
}
if (port < 0 || port > 65535)
throw std::invalid_argument("Port is out of the valid range: 0 - 65535");
_data->set_port(port);
} else {
throw std::invalid_argument("Missing port number");
}
if (_tokenizer.tokens_available())
throw std::invalid_argument(
shcore::str_format("Unexpected data [%s] found at position %u",
get_input_chunk({*offset, range.second}).c_str(),
static_cast<uint32_t>(*offset)));
}
void Uri_parser::parse_host() {
size_t offset = _chunks[URI_TARGET].first;
if (_input[_chunks[URI_TARGET].first] == '[') {
parse_ipv6(_chunks[URI_TARGET], &offset);
} else {
_tokenizer.reset();
_tokenizer.set_allow_spaces(false);
_tokenizer.set_simple_tokens(".:");
_tokenizer.set_complex_token("pct-encoded", {"%", HEXDIG, HEXDIG});
_tokenizer.set_complex_token("digits", DIGIT);
_tokenizer.set_complex_token("hex-digits", HEXDIG);
_tokenizer.set_complex_token("sub-delims", SUBDELIMITERS);
_tokenizer.set_complex_token("unreserved", UNRESERVED);
_tokenizer.process(_chunks[URI_TARGET]);
std::string host = parse_ipv4(&offset);
if (host.empty()) {
while (_tokenizer.tokens_available() &&
!_tokenizer.cur_token_type_is(":")) {
std::string data = _tokenizer.peek_token().get_text();
if (_tokenizer.cur_token_type_is("pct-encoded"))
host += percent_decode(data);
else
host += data;
offset += data.length();
_tokenizer.consume_any_token();
}
}
_data->set_host(host);
}
if (offset <= _chunks[URI_TARGET].second)
parse_port({offset, _chunks[URI_TARGET].second}, &offset);
}
void Uri_parser::parse_path() {
if (_chunks.find(URI_PATH) != _chunks.end()) {
_tokenizer.reset();
_tokenizer.set_allow_spaces(false);
_tokenizer.set_simple_tokens(":@");
_tokenizer.set_complex_token("pct-encoded", {"%", HEXDIG, HEXDIG});
_tokenizer.set_complex_token("unreserved", UNRESERVED);
_tokenizer.set_complex_token("sub-delims", SUBDELIMITERS);
_tokenizer.process(_chunks[URI_PATH]);
std::string schema;
while (_tokenizer.tokens_available()) {
if (_tokenizer.cur_token_type_is("pct-encoded"))
schema += percent_decode(_tokenizer.peek_token().get_text());
else
schema += _tokenizer.peek_token().get_text();
_tokenizer.consume_any_token();
}
if (!schema.empty()) _data->set_schema(schema);
}
}
void Uri_parser::parse_query() {
size_t offset = _chunks[URI_QUERY].first;
while (offset < _chunks[URI_QUERY].second)
parse_attribute(_chunks[URI_QUERY], &offset);
}
void Uri_parser::parse_attribute(const std::pair<size_t, size_t> &range,
size_t *offset) {
_tokenizer.reset();
_tokenizer.set_allow_spaces(false);
_tokenizer.set_complex_token("pct-encoded", {"%", HEXDIG, HEXDIG});
_tokenizer.set_complex_token("unreserved", UNRESERVED);
// NOTE: The URI grammar specifies that sub-delims should be included on the
// key production rule
// However sub-delims include the = and & chars which are used to join
// several key/value pairs and to associate a key's value, so we have
// excluded them.
// tok.set_complex_token("sub-delims", SUBDELIMITERS);
_tokenizer.set_complex_token("sub-delims", std::string("!$'()*+,;"));
_tokenizer.set_final_token_group("pause", "=&");
// We will skip the first char which is always a delimiter
(*offset)++;
// Pauses the processing on the presense of the next tokens
_tokenizer.process({*offset, range.second});
std::string attribute;
bool has_value = false;
while (_tokenizer.tokens_available()) {
if (_tokenizer.cur_token_type_is("pause")) {
if (_tokenizer.peek_token().get_text()[0] == '=') has_value = true;
break;
} else if (_tokenizer.cur_token_type_is("pct-encoded")) {
attribute += percent_decode(_tokenizer.peek_token().get_text());
} else {
attribute += _tokenizer.peek_token().get_text();
}
_tokenizer.consume_any_token();
}
// Skips to the position right after the attribute or the = symbol
size_t to_skip = attribute.length() + (has_value ? 1 : 0);
(*offset) += to_skip;
if (has_value) {
if (is_value_array({*offset, range.second})) {
_data->set(attribute, parse_values(offset));
} else {
_data->set(attribute, parse_value({*offset, range.second}, offset, "&"));
}
} else {
_data->set(attribute, "");
}
}
bool Uri_parser::is_value_array(const std::pair<size_t, size_t> &range) {
auto closing = _input.find(']');
return _input[range.first] == '[' && closing != std::string::npos &&
closing <= range.second;
}
std::vector<std::string> Uri_parser::parse_values(size_t *offset) {
std::vector<std::string> ret_val;
auto closing = _input.find(']', *offset);
while (_input[*offset] != ']') {
// Next is a delimiter
(*offset)++;
std::string value = parse_value({*offset, closing - 1}, offset, ",]");
ret_val.push_back(value);
}
// Skips the closing ]
(*offset)++;
return ret_val;
}
std::string Uri_parser::parse_value(const std::pair<size_t, size_t> &range,
size_t *offset,
const std::string &finalizers,
const std::string &forbidden_delimiters) {
std::string ret_val;
auto closing = _input.find(')', range.first);
if (_input[range.first] == '(' && closing != std::string::npos &&
closing <= range.second) {
(*offset)++;
ret_val = parse_unencoded_value({range.first + 1, closing - 1}, offset);
(*offset)++;
} else {
ret_val =
parse_encoded_value(range, offset, finalizers, forbidden_delimiters);
}
return ret_val;
}
char Uri_parser::percent_decode(const std::string &value) const {
int ret_val = 0;
try {
ret_val += kUriHexLiterals.at(value[1]) * 16;
} catch (const std::out_of_range &) {
ret_val += 0;
}
try {
ret_val += kUriHexLiterals.at(value[2]);
} catch (const std::out_of_range &) {
ret_val += 0;
}
return ret_val;
}
std::string Uri_parser::get_input_chunk(
const std::pair<size_t, size_t> &range) {
return _input.substr(range.first, range.second - range.first + 1);
}
std::string Uri_parser::parse_unencoded_value(
const std::pair<size_t, size_t> &range, size_t *offset,
const std::string &finalizers) {
_tokenizer.reset();
_tokenizer.set_complex_token("pct-encoded", {"%", HEXDIG, HEXDIG});
// We allow for backslashes in unencoded values in order to make file paths
// easier to type on all the platforms.
// Note that this is not explicitly allowed by MY-300/MY-305.
// Note also that '\' and '/' can be used interchangeably on Windows, while on
// Linux only '/' is treated as a path separator, '\' is a character which can
// be a part of a file/directory name.
_tokenizer.set_complex_token("unreserved",
std::string(UNRESERVED).append("\\"));
_tokenizer.set_complex_token("delims", DELIMITERS);
if (!finalizers.empty()) _tokenizer.set_final_token_group("end", finalizers);
_tokenizer.process(range);
std::string value;
// Reserves enough space for the value
auto last_token = _tokenizer.peek_last_token();
if (last_token)
value.reserve((last_token->get_pos() + last_token->get_text().size()) -
range.first);
// TODO(rennox): Add encoding logic for each appended token
// Yes it is unencoded value, but we support encoded stuff as well
while (_tokenizer.tokens_available()) {
auto token = _tokenizer.consume_any_token();
if (token.get_type() == "pct-encoded")
value += percent_decode(token.get_text());
else
value += token.get_text();
(*offset) += token.get_text().length();
}
return value;
}
std::string Uri_parser::parse_encoded_value(
const std::pair<size_t, size_t> &range, size_t *offset,
const std::string &finalizers, const std::string &forbidden_delimiters) {
// RFC3986: query = ( pchar / "/" / "?" ) pchar = unreserved / pct-encoded /
// sub-delims (!$&'()+,;=) / ":" / "@"
_tokenizer.reset();
_tokenizer.set_complex_token("pct-encoded", {"%", HEXDIG, HEXDIG});
_tokenizer.set_complex_token("unreserved", UNRESERVED);
std::string delims{"!$'()*+;=:,"};
if (!finalizers.empty() || !forbidden_delimiters.empty()) {
const auto forbidden = finalizers + forbidden_delimiters;
delims.erase(std::remove_if(delims.begin(), delims.end(),
[&forbidden](const char c) {
return forbidden.find(c) != std::string::npos;
}),
delims.end());
}
_tokenizer.set_complex_token("delims", delims);
if (!finalizers.empty()) _tokenizer.set_final_token_group("end", finalizers);
_tokenizer.process(range);
std::string value;
// Reserves enough space for the value
auto last_token = _tokenizer.peek_last_token();
if (last_token) value.reserve(last_token->get_pos() - range.first);
// TODO(rennox): Add encoding logic for each appended token
// Yes it is unencoded value, but we support encoded stuff as well
while (_tokenizer.tokens_available() &&
!_tokenizer.cur_token_type_is("end")) {
auto token = _tokenizer.consume_any_token();
if (token.get_type() == "pct-encoded")
value += percent_decode(token.get_text());
else
value += token.get_text();
(*offset) += token.get_text().length();
}
return value;
}
Connection_options Uri_parser::parse(const std::string &input,
Comparison_mode mode) {
Connection_options data(mode);
_data = &data;
_input = input;
_tokenizer.set_input(input);
// Starts by splitting the major components
// 1) Trims from the input the scheme component if found
// first_char points to the first unassigned char
// which at the end will be the same as the start of the target
// (host/socket/pipe)
size_t first_char = 0;
size_t last_char = input.size() - 1;
size_t position = input.find("://");
if (position != std::string::npos) {
if (position) {
_chunks[URI_SCHEME] = {0, position - 1};
first_char = position + 3;
} else {
throw std::invalid_argument("Scheme is missing");
}
}
// 2) Trims from the input the userinfo component if found
// It is safe to look for the first @ symbol since before the
// userinfo@targetinfo the @ should come pct-encoded. i.e. in a password
position = input.find("@", first_char);
if (position != std::string::npos) {
if (position > first_char) {
_chunks[URI_USER_INFO] = {first_char, position - 1};
first_char = position + 1;
} else {
throw std::invalid_argument("Missing user information");
}
}
// 3) Trimming the query component, it starts with a question mark
// last_char will point to the last unassigned char
// If there was a query component, it ahead of this position
position = input.find("?", first_char);
if (position != std::string::npos) {
_chunks[URI_QUERY] = {position, last_char};
last_char = position - 1;
}
// 4) Gotta find the path component if any, path component starts with /
// but if the target is a socket it may also start with / so we need to
// find the right / defining a path component
// Looks for the last / on the unassigned range
// first_char points to the beginning of the target definition
// so if / is on the first position it is not the path but the socket
// definition
position = input.rfind("/", last_char);
if (position != std::string::npos && position > first_char) {
bool has_path = false;
// If the / is found at the second position, it could also be a socket
// definition in the form of: (/path/to/socket)
// So we need to ensure the found / is after the closing ) in this case
if (input_contains("(/", first_char) || input_contains("(.", first_char) ||
input_contains("(\\\\.\\", first_char)) {
size_t closing = input.find(")", first_char);
has_path = closing != std::string::npos && position > closing;
} else {
// The found / was not a socket definition at all
has_path = true;
}
// Path component was found
if (has_path) {
if (position < last_char) {
_chunks[URI_PATH] = {position + 1, last_char};
last_char = position - 1;
} else {
last_char--;
}
}
}
// 5) The rest is target info
if (first_char <= last_char)
_chunks[URI_TARGET] = {first_char, last_char};
else
throw std::invalid_argument("Invalid address");
parse_scheme();
parse_userinfo();
parse_target();
parse_path();
parse_query();
return data;
}
bool Uri_parser::input_contains(const std::string &what, size_t index) {
bool ret_val = false;
if (index == std::string::npos)
ret_val = _input.find(what) != std::string::npos;
else
ret_val = _input.find(what, index) == index;
return ret_val;
}
} // namespace uri
} // namespace db
} // namespace mysqlshdk
| 33.222096 | 80 | 0.626247 | [
"vector"
] |
abc74322ae6cab8fbfcc4eb3413fc2d28db16c41 | 5,746 | hpp | C++ | include/idocp/line_search/unconstr_line_search.hpp | z8674558/idocp | 946524db7ae4591b578be2409ca619961572e7be | [
"BSD-3-Clause"
] | 43 | 2020-10-13T03:43:45.000Z | 2021-09-23T05:29:48.000Z | include/idocp/line_search/unconstr_line_search.hpp | z8674558/idocp | 946524db7ae4591b578be2409ca619961572e7be | [
"BSD-3-Clause"
] | 32 | 2020-10-21T09:40:16.000Z | 2021-10-24T00:00:04.000Z | include/idocp/line_search/unconstr_line_search.hpp | z8674558/idocp | 946524db7ae4591b578be2409ca619961572e7be | [
"BSD-3-Clause"
] | 4 | 2020-10-08T05:47:16.000Z | 2021-10-15T12:15:26.000Z | #ifndef IDOCP_UNCONSTR_LINE_SEARCH_HPP_
#define IDOCP_UNCONSTR_LINE_SEARCH_HPP_
#include <vector>
#include "Eigen/Core"
#include "idocp/robot/robot.hpp"
#include "idocp/utils/aligned_vector.hpp"
#include "idocp/cost/cost_function.hpp"
#include "idocp/constraints/constraints.hpp"
#include "idocp/ocp/ocp.hpp"
#include "idocp/ocp/solution.hpp"
#include "idocp/ocp/direction.hpp"
#include "idocp/ocp/kkt_residual.hpp"
#include "idocp/unconstr/unconstr_ocp.hpp"
#include "idocp/unconstr/unconstr_parnmpc.hpp"
#include "idocp/line_search/line_search_filter.hpp"
namespace idocp {
///
/// @class UnconstrLineSearch
/// @brief Line search for optimal control problems for unconstrained
/// rigid-body systems.
///
class UnconstrLineSearch {
public:
///
/// @brief Construct a line search.
/// @param[in] robot Robot model.
/// @param[in] T Length of the horizon. Must be positive.
/// @param[in] N Number of discretization of the horizon. Must be more than 1.
/// @param[in] nthreads Number of the threads in solving the optimal control
/// problem. Must be positive. Default is 1.
/// @param[in] step_size_reduction_rate Reduction rate of the step size.
/// Defalt is 0.75.
/// @param[in] min_step_size Minimum step size. Default is 0.05.
///
UnconstrLineSearch(const Robot& robot, const double T, const int N,
const int nthreads=1,
const double step_size_reduction_rate=0.75,
const double min_step_size=0.05);
///
/// @brief Default constructor.
///
UnconstrLineSearch();
///
/// @brief Destructor.
///
~UnconstrLineSearch();
///
/// @brief Default copy constructor.
///
UnconstrLineSearch(const UnconstrLineSearch&) = default;
///
/// @brief Default copy assign operator.
///
UnconstrLineSearch& operator=(const UnconstrLineSearch&) = default;
///
/// @brief Default move constructor.
///
UnconstrLineSearch(UnconstrLineSearch&&) noexcept = default;
///
/// @brief Default move assign operator.
///
UnconstrLineSearch& operator=(UnconstrLineSearch&&) noexcept = default;
///
/// @brief Compute primal step size by fliter line search method.
/// @param[in, out] ocp optimal control problem.
/// @param[in] robots aligned_vector of Robot.
/// @param[in] t Initial time of the horizon.
/// @param[in] q Initial configuration.
/// @param[in] v Initial generalized velocity.
/// @param[in] s Solution.
/// @param[in] d Direction.
/// @param[in] max_primal_step_size Maximum primal step size.
///
template <typename UnconstrOCPType>
double computeStepSize(UnconstrOCPType& ocp, aligned_vector<Robot>& robots,
const double t, const Eigen::VectorXd& q,
const Eigen::VectorXd& v, const Solution& s,
const Direction& d,
const double max_primal_step_size) {
assert(max_primal_step_size > 0);
assert(max_primal_step_size <= 1);
// If filter is empty, augment the current solution to the filter.
if (filter_.isEmpty()) {
computeCostAndViolation(ocp, robots, t, q, v, s);
filter_.augment(totalCosts(), totalViolations());
}
double primal_step_size = max_primal_step_size;
while (primal_step_size > min_step_size_) {
computeSolutionTrial(s, d, primal_step_size);
computeCostAndViolation(ocp, robots, t, q, v, s_trial_, primal_step_size);
const double total_costs = totalCosts();
const double total_violations = totalViolations();
if (filter_.isAccepted(total_costs, total_violations)) {
filter_.augment(total_costs, total_violations);
break;
}
primal_step_size *= step_size_reduction_rate_;
}
if (primal_step_size > min_step_size_) {
return primal_step_size;
}
else {
return min_step_size_;
}
}
///
/// @brief Clear the line search filter.
///
void clearFilter();
///
/// @brief Clear the line search filter.
///
bool isFilterEmpty() const;
private:
LineSearchFilter filter_;
int N_, nthreads_;
double T_, dt_, step_size_reduction_rate_, min_step_size_;
Eigen::VectorXd costs_, violations_;
Solution s_trial_;
KKTResidual kkt_residual_;
void computeCostAndViolation(UnconstrOCP& ocp, aligned_vector<Robot>& robots,
const double t, const Eigen::VectorXd& q,
const Eigen::VectorXd& v, const Solution& s,
const double primal_step_size_for_barrier=0);
void computeCostAndViolation(UnconstrParNMPC& parnmpc, aligned_vector<Robot>& robots,
const double t, const Eigen::VectorXd& q,
const Eigen::VectorXd& v, const Solution& s,
const double primal_step_size_for_barrier=0);
void computeSolutionTrial(const Solution& s, const Direction& d,
const double step_size);
static void computeSolutionTrial(const SplitSolution& s,
const SplitDirection& d,
const double step_size,
SplitSolution& s_trial) {
s_trial.q = s.q + step_size * d.dq();
s_trial.v = s.v + step_size * d.dv();
s_trial.a = s.a + step_size * d.da();
s_trial.u = s.u + step_size * d.du;
}
void clearCosts() {
costs_.setZero();
}
void clearViolations() {
violations_.setZero();
}
double totalCosts() const {
return costs_.sum();
}
double totalViolations() const {
return violations_.sum();
}
};
} // namespace idocp
#endif // IDOCP_UNCONSTR_LINE_SEARCH_HPP_ | 31.745856 | 87 | 0.644448 | [
"vector",
"model"
] |
abc7e2bd0cf1903e3923dc8163f5344befa32528 | 10,482 | cc | C++ | harfbuzz/src/hb-ot-shape-fallback.cc | pcwalton/rust-harfbuzz | f07c6ae3111a94945f0f04b5f0d7c4e7c20958e9 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | null | null | null | harfbuzz/src/hb-ot-shape-fallback.cc | pcwalton/rust-harfbuzz | f07c6ae3111a94945f0f04b5f0d7c4e7c20958e9 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | null | null | null | harfbuzz/src/hb-ot-shape-fallback.cc | pcwalton/rust-harfbuzz | f07c6ae3111a94945f0f04b5f0d7c4e7c20958e9 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | null | null | null | /*
* Copyright © 2011,2012 Google, Inc.
*
* This is part of HarfBuzz, a text shaping library.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, provided that the
* above copyright notice and the following two paragraphs appear in
* all copies of this software.
*
* IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*
* Google Author(s): Behdad Esfahbod
*/
#include "hb-ot-shape-fallback-private.hh"
static void
zero_mark_advances (hb_buffer_t *buffer,
unsigned int start,
unsigned int end)
{
for (unsigned int i = start; i < end; i++)
if (_hb_glyph_info_get_general_category (&buffer->info[i]) == HB_UNICODE_GENERAL_CATEGORY_NON_SPACING_MARK)
{
buffer->pos[i].x_advance = 0;
buffer->pos[i].y_advance = 0;
}
}
static unsigned int
recategorize_combining_class (unsigned int modified_combining_class)
{
if (modified_combining_class >= 200)
return modified_combining_class;
/* This should be kept in sync with modified combining class mapping
* from hb-unicode.cc. */
switch (modified_combining_class)
{
/* Hebrew */
case HB_MODIFIED_COMBINING_CLASS_CCC10: /* sheva */
case HB_MODIFIED_COMBINING_CLASS_CCC11: /* hataf segol */
case HB_MODIFIED_COMBINING_CLASS_CCC12: /* hataf patah */
case HB_MODIFIED_COMBINING_CLASS_CCC13: /* hataf qamats */
case HB_MODIFIED_COMBINING_CLASS_CCC14: /* hiriq */
case HB_MODIFIED_COMBINING_CLASS_CCC15: /* tsere */
case HB_MODIFIED_COMBINING_CLASS_CCC16: /* segol */
case HB_MODIFIED_COMBINING_CLASS_CCC17: /* patah */
case HB_MODIFIED_COMBINING_CLASS_CCC18: /* qamats */
case HB_MODIFIED_COMBINING_CLASS_CCC20: /* qubuts */
case HB_MODIFIED_COMBINING_CLASS_CCC22: /* meteg */
return HB_UNICODE_COMBINING_CLASS_BELOW;
case HB_MODIFIED_COMBINING_CLASS_CCC23: /* rafe */
return HB_UNICODE_COMBINING_CLASS_ATTACHED_ABOVE;
case HB_MODIFIED_COMBINING_CLASS_CCC24: /* shin dot */
return HB_UNICODE_COMBINING_CLASS_ABOVE_RIGHT;
case HB_MODIFIED_COMBINING_CLASS_CCC25: /* sin dot */
case HB_MODIFIED_COMBINING_CLASS_CCC19: /* holam */
return HB_UNICODE_COMBINING_CLASS_ABOVE_LEFT;
case HB_MODIFIED_COMBINING_CLASS_CCC26: /* point varika */
return HB_UNICODE_COMBINING_CLASS_ABOVE;
case HB_MODIFIED_COMBINING_CLASS_CCC21: /* dagesh */
break;
/* Arabic and Syriac */
case HB_MODIFIED_COMBINING_CLASS_CCC27: /* fathatan */
case HB_MODIFIED_COMBINING_CLASS_CCC28: /* dammatan */
case HB_MODIFIED_COMBINING_CLASS_CCC30: /* fatha */
case HB_MODIFIED_COMBINING_CLASS_CCC31: /* damma */
case HB_MODIFIED_COMBINING_CLASS_CCC33: /* shadda */
case HB_MODIFIED_COMBINING_CLASS_CCC34: /* sukun */
case HB_MODIFIED_COMBINING_CLASS_CCC35: /* superscript alef */
case HB_MODIFIED_COMBINING_CLASS_CCC36: /* superscript alaph */
return HB_UNICODE_COMBINING_CLASS_ABOVE;
case HB_MODIFIED_COMBINING_CLASS_CCC29: /* kasratan */
case HB_MODIFIED_COMBINING_CLASS_CCC32: /* kasra */
return HB_UNICODE_COMBINING_CLASS_BELOW;
/* Thai */
/* Note: to be useful we also need to position U+0E3A that has ccc=9 (virama).
* But viramas can be both above and below based on the codepoint / script. */
case HB_MODIFIED_COMBINING_CLASS_CCC103: /* sara u / sara uu */
return HB_UNICODE_COMBINING_CLASS_BELOW;
case HB_MODIFIED_COMBINING_CLASS_CCC107: /* mai */
return HB_UNICODE_COMBINING_CLASS_ABOVE;
/* Lao */
case HB_MODIFIED_COMBINING_CLASS_CCC118: /* sign u / sign uu */
return HB_UNICODE_COMBINING_CLASS_BELOW;
case HB_MODIFIED_COMBINING_CLASS_CCC122: /* mai */
return HB_UNICODE_COMBINING_CLASS_ABOVE;
/* Tibetan */
case HB_MODIFIED_COMBINING_CLASS_CCC129: /* sign aa */
return HB_UNICODE_COMBINING_CLASS_BELOW;
case HB_MODIFIED_COMBINING_CLASS_CCC130: /* sign i*/
return HB_UNICODE_COMBINING_CLASS_ABOVE;
case HB_MODIFIED_COMBINING_CLASS_CCC132: /* sign u */
return HB_UNICODE_COMBINING_CLASS_BELOW;
}
return modified_combining_class;
}
static inline void
position_mark (const hb_ot_shape_plan_t *plan,
hb_font_t *font,
hb_buffer_t *buffer,
hb_glyph_extents_t &base_extents,
unsigned int i,
unsigned int combining_class)
{
hb_glyph_extents_t mark_extents;
if (!font->get_glyph_extents (buffer->info[i].codepoint,
&mark_extents))
return;
hb_position_t y_gap = font->y_scale / 16;
hb_glyph_position_t &pos = buffer->pos[i];
pos.x_offset = pos.y_offset = 0;
/* We dont position LEFT and RIGHT marks. */
/* X positioning */
switch (combining_class)
{
case HB_UNICODE_COMBINING_CLASS_DOUBLE_BELOW:
case HB_UNICODE_COMBINING_CLASS_DOUBLE_ABOVE:
/* TODO Do something... For now, fall through. */
case HB_UNICODE_COMBINING_CLASS_ATTACHED_BELOW:
case HB_UNICODE_COMBINING_CLASS_ATTACHED_ABOVE:
case HB_UNICODE_COMBINING_CLASS_BELOW:
case HB_UNICODE_COMBINING_CLASS_ABOVE:
/* Center align. */
pos.x_offset += base_extents.x_bearing + (base_extents.width - mark_extents.width) / 2 - mark_extents.x_bearing;
break;
case HB_UNICODE_COMBINING_CLASS_ATTACHED_BELOW_LEFT:
case HB_UNICODE_COMBINING_CLASS_BELOW_LEFT:
case HB_UNICODE_COMBINING_CLASS_ABOVE_LEFT:
/* Left align. */
pos.x_offset += base_extents.x_bearing - mark_extents.x_bearing;
break;
case HB_UNICODE_COMBINING_CLASS_ATTACHED_ABOVE_RIGHT:
case HB_UNICODE_COMBINING_CLASS_BELOW_RIGHT:
case HB_UNICODE_COMBINING_CLASS_ABOVE_RIGHT:
/* Right align. */
pos.x_offset += base_extents.x_bearing + base_extents.width - mark_extents.width - mark_extents.x_bearing;
break;
}
/* Y positioning */
switch (combining_class)
{
case HB_UNICODE_COMBINING_CLASS_DOUBLE_BELOW:
case HB_UNICODE_COMBINING_CLASS_BELOW_LEFT:
case HB_UNICODE_COMBINING_CLASS_BELOW:
case HB_UNICODE_COMBINING_CLASS_BELOW_RIGHT:
/* Add gap, fall-through. */
base_extents.height -= y_gap;
case HB_UNICODE_COMBINING_CLASS_ATTACHED_BELOW_LEFT:
case HB_UNICODE_COMBINING_CLASS_ATTACHED_BELOW:
pos.y_offset += base_extents.y_bearing + base_extents.height - mark_extents.y_bearing;
base_extents.height += mark_extents.height;
break;
case HB_UNICODE_COMBINING_CLASS_DOUBLE_ABOVE:
case HB_UNICODE_COMBINING_CLASS_ABOVE_LEFT:
case HB_UNICODE_COMBINING_CLASS_ABOVE:
case HB_UNICODE_COMBINING_CLASS_ABOVE_RIGHT:
/* Add gap, fall-through. */
base_extents.y_bearing += y_gap;
base_extents.height -= y_gap;
case HB_UNICODE_COMBINING_CLASS_ATTACHED_ABOVE:
case HB_UNICODE_COMBINING_CLASS_ATTACHED_ABOVE_RIGHT:
pos.y_offset += base_extents.y_bearing - (mark_extents.y_bearing + mark_extents.height);
base_extents.y_bearing -= mark_extents.height;
base_extents.height += mark_extents.height;
break;
}
}
static inline void
position_around_base (const hb_ot_shape_plan_t *plan,
hb_font_t *font,
hb_buffer_t *buffer,
unsigned int base,
unsigned int end)
{
hb_glyph_extents_t base_extents;
if (!font->get_glyph_extents (buffer->info[base].codepoint,
&base_extents))
{
/* If extents don't work, zero marks and go home. */
zero_mark_advances (buffer, base + 1, end);
return;
}
base_extents.x_bearing += buffer->pos[base].x_offset;
base_extents.y_bearing += buffer->pos[base].y_offset;
/* XXX Handle ligature component positioning... */
HB_UNUSED bool is_ligature = is_a_ligature (buffer->info[base]);
hb_position_t x_offset = 0, y_offset = 0;
unsigned int last_combining_class = 255;
hb_glyph_extents_t cluster_extents;
for (unsigned int i = base + 1; i < end; i++)
if (_hb_glyph_info_get_general_category (&buffer->info[i]) == HB_UNICODE_GENERAL_CATEGORY_NON_SPACING_MARK)
{
unsigned int this_combining_class = recategorize_combining_class (_hb_glyph_info_get_modified_combining_class (&buffer->info[i]));
if (this_combining_class != last_combining_class)
cluster_extents = base_extents;
position_mark (plan, font, buffer, base_extents, i, this_combining_class);
buffer->pos[i].x_advance = 0;
buffer->pos[i].y_advance = 0;
buffer->pos[i].x_offset += x_offset;
buffer->pos[i].y_offset += y_offset;
/* combine cluster extents. */
last_combining_class = this_combining_class;
} else {
x_offset -= buffer->pos[i].x_advance;
y_offset -= buffer->pos[i].y_advance;
}
}
static inline void
position_cluster (const hb_ot_shape_plan_t *plan,
hb_font_t *font,
hb_buffer_t *buffer,
unsigned int start,
unsigned int end)
{
if (end - start < 2)
return;
/* Find the base glyph */
for (unsigned int i = start; i < end; i++)
if (is_a_ligature (buffer->info[i]) ||
!(FLAG (_hb_glyph_info_get_general_category (&buffer->info[i])) &
(FLAG (HB_UNICODE_GENERAL_CATEGORY_SPACING_MARK) |
FLAG (HB_UNICODE_GENERAL_CATEGORY_ENCLOSING_MARK) |
FLAG (HB_UNICODE_GENERAL_CATEGORY_NON_SPACING_MARK))))
{
position_around_base (plan, font, buffer, i, end);
break;
}
}
void
_hb_ot_shape_fallback_position (const hb_ot_shape_plan_t *plan,
hb_font_t *font,
hb_buffer_t *buffer)
{
unsigned int start = 0;
unsigned int last_cluster = buffer->info[0].cluster;
unsigned int count = buffer->len;
for (unsigned int i = 1; i < count; i++)
if (buffer->info[i].cluster != last_cluster) {
position_cluster (plan, font, buffer, start, i);
start = i;
last_cluster = buffer->info[i].cluster;
}
position_cluster (plan, font, buffer, start, count);
}
| 33.70418 | 136 | 0.726388 | [
"shape"
] |
abd1e18b48ce57a1373ce8abbfa71bf0656eb7b4 | 105,557 | cpp | C++ | src/librt/primitives/brep/brep_debug.cpp | maths22/brlcad | 44d270fca6e3336013322163ecae2920b30294ae | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | src/librt/primitives/brep/brep_debug.cpp | maths22/brlcad | 44d270fca6e3336013322163ecae2920b30294ae | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | src/librt/primitives/brep/brep_debug.cpp | maths22/brlcad | 44d270fca6e3336013322163ecae2920b30294ae | [
"BSD-4-Clause",
"BSD-3-Clause"
] | null | null | null | /* B R E P _ D E B U G . C P P
* BRL-CAD
*
* Copyright (c) 2007-2016 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this file; see the file named COPYING for more
* information.
*/
/** @addtogroup librt */
/** @{ */
/** @file brep_debug.cpp
*
* brep debugging utilities
*
*/
#include "common.h"
#include <vector>
#include <list>
#include <iostream>
#include <algorithm>
#include <set>
#include <utility>
#include "poly2tri/poly2tri.h"
#include "bu/log.h"
#include "bu/color.h"
#include "bu/str.h"
#include "bu/malloc.h"
#include "bu/list.h"
#include "bu/vls.h"
#include "vmath.h"
#include "bn/plot3.h"
#include "brep.h"
#include "brep_debug.h"
#include "bn/dvec.h"
#include "raytrace.h"
#include "rt/geom.h"
#include "wdb.h"
#include "brep_local.h"
#ifdef __cplusplus
extern "C" {
#endif
RT_EXPORT extern int brep_command(struct bu_vls *vls, const char *solid_name, struct bu_color *color, const struct rt_tess_tol* ttol, const struct bn_tol* tol, struct brep_specific* bs, struct rt_brep_internal* bi, struct bn_vlblock *vbp, int argc, const char *argv[], char *commtag);
extern int single_conversion(struct rt_db_internal* intern, ON_Brep** brep, const struct db_i *dbip);
RT_EXPORT extern int brep_conversion(struct rt_db_internal* in, struct rt_db_internal* out, const struct db_i *dbip);
RT_EXPORT extern int brep_conversion_comb(struct rt_db_internal *old_internal, const char *name, const char *suffix, struct rt_wdb *wdbp, fastf_t local2mm);
RT_EXPORT extern int brep_intersect_point_point(struct rt_db_internal *intern1, struct rt_db_internal *intern2, int i, int j);
RT_EXPORT extern int brep_intersect_point_curve(struct rt_db_internal *intern1, struct rt_db_internal *intern2, int i, int j);
RT_EXPORT extern int brep_intersect_point_surface(struct rt_db_internal *intern1, struct rt_db_internal *intern2, int i, int j);
RT_EXPORT extern int brep_intersect_curve_curve(struct rt_db_internal *intern1, struct rt_db_internal *intern2, int i, int j);
RT_EXPORT extern int brep_intersect_curve_surface(struct rt_db_internal *intern1, struct rt_db_internal *intern2, int i, int j);
RT_EXPORT extern int brep_intersect_surface_surface(struct rt_db_internal *intern1, struct rt_db_internal *intern2, int i, int j, struct bn_vlblock *vbp);
extern void rt_comb_brep(ON_Brep **b, const struct rt_db_internal *ip, const struct bn_tol *UNUSED(tol), const struct db_i *dbip);
#ifdef __cplusplus
}
#endif
extern void poly2tri_CDT(struct bu_list *vhead, ON_BrepFace &face, const struct rt_tess_tol *ttol, const struct bn_tol *tol, const struct rt_view_info *info, bool watertight = false, int plottype = 0, int num_points = -1.0);
/********************************************************************************
* Auxiliary functions
********************************************************************************/
using namespace brlcad;
FILE*
brep_plot_file(const char *pname)
{
static FILE* plot = NULL;
if (plot != NULL) {
(void)fclose(plot);
plot = NULL;
}
if (pname == NULL) {
pname = "out.pl";
}
plot = fopen(pname, "w");
point_t min, max;
VSET(min, -2048, -2048, -2048);
VSET(max, 2048, 2048, 2048);
pdv_3space(plot, min, max);
return plot;
}
#define ARB_FACE(valp, a, b, c, d) \
RT_ADD_VLIST(vhead, valp[a], BN_VLIST_LINE_MOVE); \
RT_ADD_VLIST(vhead, valp[b], BN_VLIST_LINE_DRAW); \
RT_ADD_VLIST(vhead, valp[c], BN_VLIST_LINE_DRAW); \
RT_ADD_VLIST(vhead, valp[d], BN_VLIST_LINE_DRAW);
#define BB_PLOT_VLIST(min, max) { \
fastf_t pt[8][3]; \
VSET(pt[0], max[X], min[Y], min[Z]); \
VSET(pt[1], max[X], max[Y], min[Z]); \
VSET(pt[2], max[X], max[Y], max[Z]); \
VSET(pt[3], max[X], min[Y], max[Z]); \
VSET(pt[4], min[X], min[Y], min[Z]); \
VSET(pt[5], min[X], max[Y], min[Z]); \
VSET(pt[6], min[X], max[Y], max[Z]); \
VSET(pt[7], min[X], min[Y], max[Z]); \
ARB_FACE(pt, 0, 1, 2, 3); \
ARB_FACE(pt, 4, 0, 3, 7); \
ARB_FACE(pt, 5, 4, 7, 6); \
ARB_FACE(pt, 1, 5, 6, 2); \
}
void
plotsurfaceleafs(SurfaceTree* surf) {
vect_t min;
vect_t max;
std::list<BBNode*> leaves;
surf->getLeaves(leaves);
for (std::list<BBNode*>::iterator i = leaves.begin(); i != leaves.end(); i++) {
BBNode* bb = dynamic_cast<BBNode*>(*i);
if (bb->m_trimmed) {
COLOR_PLOT(255, 0, 0);
} else if (bb->m_checkTrim) {
COLOR_PLOT(0, 0, 255);
} else {
COLOR_PLOT(255, 0, 255);
}
/*
if (bb->m_xgrow) {
M_COLOR_PLOT(PURERED);
} else if (bb->m_ygrow) {
M_COLOR_PLOT(GREEN);
} else if (bb->m_zgrow) {
M_COLOR_PLOT(BLUE);
} else {
COLOR_PLOT(100, 100, 100);
}
*/
//if ((!bb->m_trimmed) && (!bb->m_checkTrim)) {
if (false) {
//bb->GetBBox(min, max);
} else {
VSET(min, bb->m_u[0]+0.001, bb->m_v[0]+0.001, 0.0);
VSET(max, bb->m_u[1]-0.001, bb->m_v[1]-0.001, 0.0);
//VSET(min, bb->m_u[0], bb->m_v[0], 0.0);
//VSET(max, bb->m_u[1], bb->m_v[1], 0.0);
}
BB_PLOT(min, max);
//}
}
return;
}
unsigned int
plotsurfaceleafs(SurfaceTree* surf, struct bn_vlblock *vbp, bool dim3d)
{
register struct bu_list *vhead;
fastf_t min[3], max[3];
std::list<BBNode*> leaves;
surf->getLeaves(leaves);
VSETALL(min, 0.0);
ON_TextLog tl(stderr);
vhead = bn_vlblock_find(vbp, PURERED);
RT_ADD_VLIST(vhead, min, BN_VLIST_LINE_MOVE);
vhead = bn_vlblock_find(vbp, BLUE);
RT_ADD_VLIST(vhead, min, BN_VLIST_LINE_MOVE);
vhead = bn_vlblock_find(vbp, MAGENTA);
RT_ADD_VLIST(vhead, min, BN_VLIST_LINE_MOVE);
for (std::list<BBNode*>::iterator i = leaves.begin(); i != leaves.end(); i++) {
BBNode* bb = dynamic_cast<BBNode*>(*i);
if (bb->m_trimmed) {
vhead = bn_vlblock_find(vbp, PURERED);
} else if (bb->m_checkTrim) {
vhead = bn_vlblock_find(vbp, BLUE);
} else {
vhead = bn_vlblock_find(vbp, MAGENTA);
}
if (dim3d) {
bb->GetBBox(min, max);
} else {
VSET(min, bb->m_u[0]+0.001, bb->m_v[0]+0.001, 0.0);
VSET(max, bb->m_u[1]-0.001, bb->m_v[1]-0.001, 0.0);
}
BB_PLOT_VLIST(min, max);
}
return leaves.size();
}
void
plottrimleafs(SurfaceTree* st, struct bn_vlblock *vbp, bool dim3d)
{
register struct bu_list *vhead;
vect_t min;
vect_t max;
std::list<BRNode*> leaves;
st->ctree->getLeaves(leaves);
VSETALL(min, 0.0);
ON_TextLog tl(stderr);
vhead = bn_vlblock_find(vbp, PURERED);
RT_ADD_VLIST(vhead, min, BN_VLIST_LINE_MOVE);
vhead = bn_vlblock_find(vbp, BLUE);
RT_ADD_VLIST(vhead, min, BN_VLIST_LINE_MOVE);
vhead = bn_vlblock_find(vbp, MAGENTA);
RT_ADD_VLIST(vhead, min, BN_VLIST_LINE_MOVE);
for (std::list<BRNode*>::iterator i = leaves.begin(); i != leaves.end(); i++) {
BRNode* bb = dynamic_cast<BRNode*>(*i);
if (bb->m_XIncreasing) {
vhead = bn_vlblock_find(vbp, GREEN);
} else {
vhead = bn_vlblock_find(vbp, BLUE);
}
bb->GetBBox(min, max);
if (dim3d) {
const ON_Surface *surf = st->getSurface();
ON_3dPoint p1 = surf->PointAt(min[0], min[1]);
ON_3dPoint p2 = surf->PointAt(max[0], max[1]);
VMOVE(min, p1);
VMOVE(max, p2);
}
BB_PLOT_VLIST(min, max);
}
return;
}
void
plotleaf3d(BBNode* bb,double within_distance_tol)
{
vect_t min;
vect_t max;
fastf_t u, v;
ON_2dPoint uv[2];
int trim1_status;
int trim2_status;
fastf_t closesttrim1;
fastf_t closesttrim2;
if (bb->m_trimmed) {
COLOR_PLOT(255, 0, 0);
} else if (bb->m_checkTrim) {
COLOR_PLOT(0, 0, 255);
} else {
COLOR_PLOT(255, 0, 255);
}
if (true) {
bb->GetBBox(min, max);
} else {
// VSET(min, bb->m_u[0]+0.001, bb->m_v[0]+0.001, 0.0);
// VSET(max, bb->m_u[1]-0.001, bb->m_v[1]-0.001, 0.0);
}
BB_PLOT(min, max);
M_COLOR_PLOT(YELLOW);
point_t a, b;
ON_3dPoint p;
BRNode* trimBR = NULL;
const ON_BrepFace* f = bb->m_face;
const ON_Surface* surf = f->SurfaceOf();
fastf_t uinc = (bb->m_u[1] - bb->m_u[0])/100.0;
fastf_t vinc = (bb->m_v[1] - bb->m_v[0])/100.0;
for (u=bb->m_u[0];u<bb->m_u[1];u=u+uinc) {
for (v=bb->m_v[0];v<bb->m_v[1];v=v+vinc) {
uv[0].x = u;
uv[0].y = v;
uv[1].x = u+uinc;
uv[1].y = v+vinc;
trim1_status = bb->isTrimmed(uv[0], &trimBR, closesttrim1,within_distance_tol);
trim2_status = bb->isTrimmed(uv[1], &trimBR, closesttrim2,within_distance_tol);
if (((trim1_status != 1) || (fabs(closesttrim1) < within_distance_tol)) &&
((trim2_status != 1) || (fabs(closesttrim2) < within_distance_tol))) {
p = surf->PointAt(uv[0].x, uv[0].y);
VMOVE(a, p);
p = surf->PointAt(uv[1].x, uv[1].y);
VMOVE(b, p);
LINE_PLOT(a, b);
}
}
}
return;
}
void
plotleafuv(BBNode* bb)
{
vect_t min;
vect_t max;
if (bb->m_trimmed) {
COLOR_PLOT(255, 0, 0);
} else if (bb->m_checkTrim) {
COLOR_PLOT(0, 0, 255);
} else {
COLOR_PLOT(255, 0, 255);
}
if (false) {
// bb->GetBBox(min, max);
} else {
VSET(min, bb->m_u[0]+0.001, bb->m_v[0]+0.001, 0.0);
VSET(max, bb->m_u[1]-0.001, bb->m_v[1]-0.001, 0.0);
}
BB_PLOT(min, max);
return;
}
void
plottrim(ON_BrepFace &face, struct bn_vlblock *vbp, int plotres, bool dim3d, const int red = 255, const int green = 255, const int blue = 0)
{
register struct bu_list *vhead;
const ON_Surface* surf = face.SurfaceOf();
fastf_t umin, umax;
fastf_t pt1[3], pt2[3];
ON_2dPoint from, to;
ON_TextLog tl(stderr);
vhead = bn_vlblock_find(vbp, red, green, blue);
surf->GetDomain(0, &umin, &umax);
for (int i = 0; i < face.LoopCount(); i++) {
ON_BrepLoop* loop = face.Loop(i);
// for each trim
for (int j = 0; j < loop->m_ti.Count(); j++) {
ON_BrepTrim& trim = face.Brep()->m_T[loop->m_ti[j]];
const ON_Curve* trimCurve = trim.TrimCurveOf();
//trimCurve->Dump(tl);
ON_Interval dom = trimCurve->Domain();
// XXX todo: dynamically sample the curve
for (int k = 1; k <= plotres; k++) {
ON_3dPoint p = trimCurve->PointAt(dom.ParameterAt((double) (k - 1) / (double) plotres));
if (dim3d)
p = surf->PointAt(p.x, p.y);
VMOVE(pt1, p);
p = trimCurve->PointAt(dom.ParameterAt((double) k / (double) plotres));
if (dim3d)
p = surf->PointAt(p.x, p.y);
VMOVE(pt2, p);
RT_ADD_VLIST(vhead, pt1, BN_VLIST_LINE_MOVE);
RT_ADD_VLIST(vhead, pt2, BN_VLIST_LINE_DRAW);
}
}
}
return;
}
void
plottrim2d(ON_BrepFace &face, struct bn_vlblock *vbp, int plotres)
{
register struct bu_list *vhead;
const ON_Surface* surf = face.SurfaceOf();
fastf_t umin, umax;
fastf_t pt1[3], pt2[3];
ON_2dPoint from, to;
ON_TextLog tl(stderr);
vhead = bn_vlblock_find(vbp, YELLOW);
surf->GetDomain(0, &umin, &umax);
for (int i = 0; i < face.LoopCount(); i++) {
ON_BrepLoop* loop = face.Loop(i);
// for each trim
for (int j = 0; j < loop->m_ti.Count(); j++) {
ON_BrepTrim& trim = face.Brep()->m_T[loop->m_ti[j]];
const ON_Curve* trimCurve = trim.TrimCurveOf();
//trimCurve->Dump(tl);
ON_Interval dom = trimCurve->Domain();
// XXX todo: dynamically sample the curve
for (int k = 1; k <= plotres; k++) {
ON_3dPoint p = trimCurve->PointAt(dom.ParameterAt((double) (k - 1) / (double) plotres));
//p = surf->PointAt(p.x, p.y);
VMOVE(pt1, p);
p = trimCurve->PointAt(dom.ParameterAt((double) k / (double) plotres));
//p = surf->PointAt(p.x, p.y);
VMOVE(pt2, p);
RT_ADD_VLIST(vhead, pt1, BN_VLIST_LINE_MOVE);
RT_ADD_VLIST(vhead, pt2, BN_VLIST_LINE_DRAW);
}
}
}
return;
}
void
plotUVDomain2d(ON_BrepFace &face, struct bn_vlblock *vbp)
{
register struct bu_list *vhead;
const ON_Surface* surf = face.SurfaceOf();
fastf_t umin, umax, urange;
fastf_t vmin, vmax, vrange;
fastf_t pt1[3], pt2[3];
ON_2dPoint from, to;
ON_TextLog tl(stderr);
vhead = bn_vlblock_find(vbp, PURERED);
double width, height;
ON_BoundingBox loop_bb;
ON_BoundingBox trim_bb;
#ifndef RESETDOMAIN
if (face.GetSurfaceSize(&width, &height)) {
face.SetDomain(0, 0.0, width);
face.SetDomain(1, 0.0, height);
}
#endif
surf->GetDomain(0, &umin, &umax);
surf->GetDomain(1, &vmin, &vmax);
// add a little offset so we can see the boundary curves
urange = umax - umin;
vrange = vmax - vmin;
umin = umin - 0.01*urange;
vmin = vmin - 0.01*vrange;
umax = umax + 0.01*urange;
vmax = vmax + 0.01*vrange;
//umin
VSET(pt1, umin, vmin, 0.0);
VSET(pt2, umin, vmax, 0.0);
RT_ADD_VLIST(vhead, pt1, BN_VLIST_LINE_MOVE);
RT_ADD_VLIST(vhead, pt2, BN_VLIST_LINE_DRAW);
// umax
VSET(pt1, umax, vmin, 0.0);
VSET(pt2, umax, vmax, 0.0);
RT_ADD_VLIST(vhead, pt1, BN_VLIST_LINE_MOVE);
RT_ADD_VLIST(vhead, pt2, BN_VLIST_LINE_DRAW);
//vmin
VSET(pt1, umin, vmin, 0.0);
VSET(pt2, umax, vmin, 0.0);
RT_ADD_VLIST(vhead, pt1, BN_VLIST_LINE_MOVE);
RT_ADD_VLIST(vhead, pt2, BN_VLIST_LINE_DRAW);
//vmax
VSET(pt1, umin, vmax, 0.0);
VSET(pt2, umax, vmax, 0.0);
RT_ADD_VLIST(vhead, pt1, BN_VLIST_LINE_MOVE);
RT_ADD_VLIST(vhead, pt2, BN_VLIST_LINE_DRAW);
return;
}
void
plottrim(ON_BrepTrim& trim, struct bn_vlblock *vbp, int plotres, bool dim3d, const int red = 255, const int green = 255, const int blue = 0)
{
register struct bu_list *vhead;
ON_BrepFace *face = trim.Face();
point_t pt;
ON_TextLog tl(stderr);
vhead = bn_vlblock_find(vbp, red, green, blue);
const ON_Curve* trimCurve = trim.TrimCurveOf();
ON_Interval dom = trimCurve->Domain();
//trimCurve->Dump(tl);
for (int k = 0; k <= plotres; ++k) {
ON_3dPoint p = trimCurve->PointAt(dom.ParameterAt((double)k / plotres));
if (dim3d) {
p = face->PointAt(p.x, p.y);
}
VMOVE(pt, p);
if (k != 0) {
RT_ADD_VLIST(vhead, pt, BN_VLIST_LINE_DRAW);
} else {
RT_ADD_VLIST(vhead, pt, BN_VLIST_LINE_MOVE);
}
}
return;
}
void
plottrimdirection(ON_BrepFace &face, struct bn_vlblock *vbp, int plotres)
{
register struct bu_list *vhead;
const ON_Surface* surf = face.SurfaceOf();
fastf_t umin, umax;
fastf_t pt1[3], pt2[3];
ON_2dPoint from, to;
ON_TextLog tl(stderr);
vhead = bn_vlblock_find(vbp, GREEN);
surf->GetDomain(0, &umin, &umax);
for (int i = 0; i < face.LoopCount(); i++) {
ON_BrepLoop* loop = face.Loop(i);
// for each trim
for (int j = 0; j < loop->m_ti.Count(); j++) {
ON_BrepTrim& trim = face.Brep()->m_T[loop->m_ti[j]];
const ON_Curve* trimCurve = trim.TrimCurveOf();
//trimCurve->Dump(tl);
int knotcnt = trimCurve->SpanCount();
fastf_t *knots = new fastf_t[knotcnt + 1];
trimCurve->GetSpanVector(knots);
for (int k = 1; k <= knotcnt; k++) {
fastf_t dist = knots[k] - knots[k-1];
fastf_t step = dist/plotres;
for (fastf_t t=knots[k-1]+step; t<=knots[k]; t=t+step) {
ON_3dPoint p = trimCurve->PointAt(t);
p = surf->PointAt(p.x, p.y);
ON_3dPoint prev = trimCurve->PointAt(t-step*0.1);
prev = surf->PointAt(prev.x, prev.y);
ON_3dVector N = surf->NormalAt(p.x, p.y);
N.Unitize();
ON_3dVector tan = p - prev;
tan.Unitize();
prev = p - tan;
ON_3dVector A = ON_CrossProduct(tan, N);
A.Unitize();
ON_3dVector B = ON_CrossProduct(N, tan);
B.Unitize();
ON_3dPoint a = prev + A;
ON_3dPoint b = prev + B;
VMOVE(pt1, p);
VMOVE(pt2, a);
RT_ADD_VLIST(vhead, pt1, BN_VLIST_LINE_MOVE);
RT_ADD_VLIST(vhead, pt2, BN_VLIST_LINE_DRAW);
VMOVE(pt2, b);
RT_ADD_VLIST(vhead, pt1, BN_VLIST_LINE_MOVE);
RT_ADD_VLIST(vhead, pt2, BN_VLIST_LINE_DRAW);
}
}
}
}
return;
}
void
plotsurface(ON_Surface &surf, struct bn_vlblock *vbp, int isocurveres, int gridres, const int red = 200, const int green = 200, const int blue = 200)
{
register struct bu_list *vhead;
fastf_t pt1[3], pt2[3];
ON_2dPoint from, to;
fastf_t hsv[3];
unsigned char fill_rgb[3];
VSET(fill_rgb,(unsigned char)red,(unsigned char)green,(unsigned char)blue);
bu_rgb_to_hsv(fill_rgb,hsv);
// simply fill with 50% lightness/value of outline
hsv[2] = hsv[2] * 0.5;
bu_hsv_to_rgb(hsv,fill_rgb);
vhead = bn_vlblock_find(vbp, red, green, blue);
ON_Interval udom = surf.Domain(0);
ON_Interval vdom = surf.Domain(1);
for (int u = 0; u <= gridres; u++) {
if (u == 0 || u == gridres) {
vhead = bn_vlblock_find(vbp, red, green, blue);
} else {
vhead = bn_vlblock_find(vbp, (int)(fill_rgb[0]), (int)(fill_rgb[1]), (int)(fill_rgb[2]));
}
for (int v = 1; v <= isocurveres; v++) {
ON_3dPoint p = surf.PointAt(udom.ParameterAt((double)u/(double)gridres), vdom.ParameterAt((double)(v-1)/(double)isocurveres));
VMOVE(pt1, p);
p = surf.PointAt(udom.ParameterAt((double)u/(double)gridres), vdom.ParameterAt((double)v/(double)isocurveres));
VMOVE(pt2, p);
RT_ADD_VLIST(vhead, pt1, BN_VLIST_LINE_MOVE);
RT_ADD_VLIST(vhead, pt2, BN_VLIST_LINE_DRAW);
}
}
for (int v = 0; v <= gridres; v++) {
if (v == 0 || v == gridres) {
vhead = bn_vlblock_find(vbp, red, green, blue);
} else {
vhead = bn_vlblock_find(vbp, (int)(fill_rgb[0]), (int)(fill_rgb[1]), (int)(fill_rgb[2]));
}
for (int u = 1; u <= isocurveres; u++) {
ON_3dPoint p = surf.PointAt(udom.ParameterAt((double)(u-1)/(double)isocurveres), vdom.ParameterAt((double)v/(double)gridres));
VMOVE(pt1, p);
p = surf.PointAt(udom.ParameterAt((double)u/(double)isocurveres), vdom.ParameterAt((double)v/(double)gridres));
VMOVE(pt2, p);
RT_ADD_VLIST(vhead, pt1, BN_VLIST_LINE_MOVE);
RT_ADD_VLIST(vhead, pt2, BN_VLIST_LINE_DRAW);
}
}
return;
}
void
plotsurfacenormals(ON_Surface &surf, struct bn_vlblock *vbp, int gridres)
{
register struct bu_list *vhead;
fastf_t pt1[3], pt2[3];
ON_2dPoint from, to;
vhead = bn_vlblock_find(vbp, GREEN);
ON_Interval udom = surf.Domain(0);
ON_Interval vdom = surf.Domain(1);
for (int u = 0; u <= gridres; u++) {
for (int v = 1; v <= gridres; v++) {
ON_3dPoint p = surf.PointAt(udom.ParameterAt((double)u/(double)gridres), vdom.ParameterAt((double)(v-1)/(double)gridres));
ON_3dVector n = surf.NormalAt(udom.ParameterAt((double)u/(double)gridres), vdom.ParameterAt((double)(v-1)/(double)gridres));
n.Unitize();
VMOVE(pt1, p);
VSCALE(pt2, n, surf.BoundingBox().Diagonal().Length()*0.1);
VADD2(pt2, pt1, pt2);
RT_ADD_VLIST(vhead, pt1, BN_VLIST_LINE_MOVE);
RT_ADD_VLIST(vhead, pt2, BN_VLIST_LINE_DRAW);
}
}
return;
}
void
plotsurfaceknots(ON_Surface &surf, struct bn_vlblock *vbp, bool dim3d)
{
register struct bu_list *vhead;
fastf_t pt1[3], pt2[3];
ON_2dPoint from, to;
int spanu_cnt = surf.SpanCount(0);
int spanv_cnt = surf.SpanCount(1);
fastf_t *spanu = NULL;
fastf_t *spanv = NULL;
spanu = new fastf_t[spanu_cnt+1];
spanv = new fastf_t[spanv_cnt+1];
#ifndef RESETDOMAIN
double width, height;
if (surf.GetSurfaceSize(&width, &height)) {
surf.SetDomain(0, 0.0, width);
surf.SetDomain(1, 0.0, height);
}
#endif
surf.GetSpanVector(0, spanu);
surf.GetSpanVector(1, spanv);
vhead = bn_vlblock_find(vbp, GREEN);
ON_Interval udom = surf.Domain(0);
ON_Interval vdom = surf.Domain(1);
if (dim3d) {
for (int u = 0; u <= spanu_cnt; u++) {
for (int v = 0; v <= spanv_cnt; v++) {
ON_3dPoint p = surf.PointAt(spanu[u], spanv[v]);
ON_3dVector n = surf.NormalAt(spanu[u], spanv[v]);
n.Unitize();
VMOVE(pt1, p);
VSCALE(pt2, n, 3.0);
VADD2(pt2, pt1, pt2);
RT_ADD_VLIST(vhead, pt1, BN_VLIST_LINE_MOVE);
RT_ADD_VLIST(vhead, pt2, BN_VLIST_LINE_DRAW);
}
}
} else {
for (int u = 0; u <= spanu_cnt; u++) {
for (int v = 0; v <= spanv_cnt; v++) {
VSET(pt1, spanu[u], spanv[v], 0.0);
RT_ADD_VLIST(vhead, pt1, BN_VLIST_POINT_DRAW);
}
}
}
return;
}
void
plotcurve(ON_Curve &curve, struct bn_vlblock *vbp, int plotres, const int red = 255, const int green = 255, const int blue = 0)
{
register struct bu_list *vhead;
fastf_t pt1[3], pt2[3];
ON_2dPoint from, to;
vhead = bn_vlblock_find(vbp, red, green, blue);
if (curve.IsLinear()) {
/*
ON_BrepVertex& v1 = face.Brep()->m_V[trim.m_vi[0]];
ON_BrepVertex& v2 = face.Brep()->m_V[trim.m_vi[1]];
VMOVE(pt1, v1.Point());
VMOVE(pt2, v2.Point());
LINE_PLOT(pt1, pt2);
*/
int knotcnt = curve.SpanCount();
fastf_t *knots = new fastf_t[knotcnt + 1];
curve.GetSpanVector(knots);
for (int i = 1; i <= knotcnt; i++) {
ON_3dPoint p = curve.PointAt(knots[i - 1]);
VMOVE(pt1, p);
p = curve.PointAt(knots[i]);
VMOVE(pt2, p);
RT_ADD_VLIST(vhead, pt1, BN_VLIST_LINE_MOVE);
RT_ADD_VLIST(vhead, pt2, BN_VLIST_LINE_DRAW);
}
} else {
ON_Interval dom = curve.Domain();
// XXX todo: dynamically sample the curve
for (int i = 1; i <= plotres; i++) {
ON_3dPoint p = curve.PointAt(dom.ParameterAt((double) (i - 1)
/ (double)plotres));
VMOVE(pt1, p);
p = curve.PointAt(dom.ParameterAt((double) i / (double)plotres));
VMOVE(pt2, p);
RT_ADD_VLIST(vhead, pt1, BN_VLIST_LINE_MOVE);
RT_ADD_VLIST(vhead, pt2, BN_VLIST_LINE_DRAW);
}
}
return;
}
void
plotpoint(const ON_3dPoint &point, struct bn_vlblock *vbp, const int red = 255, const int green = 255, const int blue = 0)
{
register struct bu_list *vhead;
ON_3dPoint pointsize(4.0,0,0);
vhead = bn_vlblock_find(vbp, red, green, blue);
RT_ADD_VLIST(vhead, pointsize, BN_VLIST_POINT_SIZE);
RT_ADD_VLIST(vhead, point, BN_VLIST_POINT_DRAW);
return;
}
void plotcurveonsurface(ON_Curve *curve,
ON_Surface *surface,
struct bn_vlblock *vbp,
int plotres,
const int red = 255,
const int green = 255,
const int blue = 0)
{
if (curve->Dimension() != 2)
return;
register struct bu_list *vhead;
vhead = bn_vlblock_find(vbp, red, green, blue);
for (int i = 0; i <= plotres; i++) {
ON_2dPoint pt2d;
ON_3dPoint pt3d;
ON_3dPoint pt1, pt2;
pt2d = curve->PointAt(curve->Domain().ParameterAt((double)i/plotres));
pt3d = surface->PointAt(pt2d.x, pt2d.y);
pt1 = pt2;
pt2 = pt3d;
if (i != 0) {
RT_ADD_VLIST(vhead, pt1, BN_VLIST_LINE_MOVE);
RT_ADD_VLIST(vhead, pt2, BN_VLIST_LINE_DRAW);
}
}
return;
}
void
plottrim(const ON_Curve &curve, double from, double to)
{
point_t pt1, pt2;
// XXX todo: dynamically sample the curve
for (int i = 0; i <= 10000; i++) {
ON_3dPoint p = curve.PointAt(from + (to-from)*(double)i/10000.0);//dom.ParameterAt((double)i/10000.0));
VMOVE(pt2, p);
if (i != 0) {
LINE_PLOT(pt1, pt2);
}
VMOVE(pt1, p);
}
}
void
plottrim(ON_Curve &curve)
{
point_t pt1, pt2;
// XXX todo: dynamically sample the curve
ON_Interval dom = curve.Domain();
for (int i = 0; i <= 10000; i++) {
ON_3dPoint p = curve.PointAt(dom.ParameterAt((double)i/10000.0));
VMOVE(pt2, p);
if (i != 0) {
LINE_PLOT(pt1, pt2);
}
VMOVE(pt1, p);
}
}
int
brep_info(struct brep_specific* bs, struct bu_vls *vls)
{
ON_Brep *brep = bs->brep;
bu_vls_printf(vls, "surfaces: %d\n", brep->m_S.Count());
bu_vls_printf(vls, "3d curve: %d\n", brep->m_C3.Count());
bu_vls_printf(vls, "2d curves: %d\n", brep->m_C2.Count());
bu_vls_printf(vls, "vertices: %d\n", brep->m_V.Count());
bu_vls_printf(vls, "edges: %d\n", brep->m_E.Count());
bu_vls_printf(vls, "trims: %d\n", brep->m_T.Count());
bu_vls_printf(vls, "loops: %d\n", brep->m_L.Count());
bu_vls_printf(vls, "faces: %d\n", brep->m_F.Count());
return 0;
}
int
brep_surface_info(struct brep_specific* bs, struct bu_vls *vls, int si)
{
ON_wString wonstr;
ON_TextLog info_output(wonstr);
ON_Brep *brep = bs->brep;
if (brep == NULL) {
return -1;
}
if (!brep->IsValid(&info_output)) {
bu_log("brep is NOT valid");
}
if ((si >= 0) && (si < brep->m_S.Count())) {
const ON_Surface* srf = brep->m_S[si];
if (srf) {
//ON_wString wonstr;
//ON_TextLog info_output(wonstr);
ON_Interval udom = srf->Domain(0);
ON_Interval vdom = srf->Domain(1);
const char* s = srf->ClassId()->ClassName();
if (!s)
s = "";
bu_vls_printf(vls, "surface[%2d]: %s u(%g, %g) v(%g, %g)\n",
si, s,
udom[0], udom[1],
vdom[0], vdom[1]
);
bu_vls_printf(vls, "NURBS form of Surface:\n");
ON_NurbsSurface *nsrf = ON_NurbsSurface::New();
srf->GetNurbForm(*nsrf, 0.0);
nsrf->Dump(info_output);
ON_String onstr = ON_String(wonstr);
const char *infodesc = onstr.Array();
bu_vls_strcat(vls, infodesc);
delete nsrf;
} else {
bu_vls_printf(vls, "surface[%2d]: NULL\n", si);
}
}
return 0;
}
int
brep_surface_bezier_info(struct brep_specific* bs, struct bu_vls *vls, int si)
{
ON_wString wonstr;
ON_TextLog info_output(wonstr);
ON_Brep *brep = bs->brep;
if (brep == NULL) {
return -1;
}
if (!brep->IsValid(&info_output)) {
bu_log("brep is NOT valid");
}
if ((si >= 0) && (si < brep->m_S.Count())) {
const ON_Surface* srf = brep->m_S[si];
if (srf) {
//ON_wString wonstr;
//ON_TextLog info_output(wonstr);
ON_Interval udom = srf->Domain(0);
ON_Interval vdom = srf->Domain(1);
const char* s = srf->ClassId()->ClassName();
if (!s)
s = "";
bu_vls_printf(vls, "surface[%2d]: %s u(%g, %g) v(%g, %g)\n",
si, s,
udom[0], udom[1],
vdom[0], vdom[1]
);
ON_NurbsSurface *nsrf = ON_NurbsSurface::New();
srf->GetNurbForm(*nsrf, 0.0);
int knotlength0 = nsrf->m_order[0] + nsrf->m_cv_count[0] - 2;
int knotlength1 = nsrf->m_order[1] + nsrf->m_cv_count[1] - 2;
int order0 = nsrf->m_order[0];
int order1 = nsrf->m_order[1];
fastf_t *knot0 = nsrf->m_knot[0];
fastf_t *knot1 = nsrf->m_knot[1];
int cnt = 0;
bu_vls_printf(vls, "bezier patches:\n");
for (int i = 0; i < knotlength0; ++i) {
for (int j = 0; j < knotlength1; ++j) {
ON_BezierSurface *bezier = new ON_BezierSurface;
if (nsrf->ConvertSpanToBezier(i, j, *bezier)) {
info_output.Print("NO.%d segment\n", ++cnt);
info_output.Print("spanindex u from %d to %d\n", i + order0 - 2, i + order0 - 1);
info_output.Print("spanindex v from %d to %d\n", j + order1 - 2, j + order1 - 1);
info_output.Print("knot u from %.2f to %.2f\n ", knot0[i + order0 - 2], knot0[i + order0 - 1]);
info_output.Print("knot v from %.2f to %.2f\n ", knot1[j + order1 - 2], knot1[j + order1 - 1]);
info_output.Print("domain u(%g, %g)\n", bezier->Domain(0)[0], bezier->Domain(0)[1]);
info_output.Print("domain v(%g, %g)\n", bezier->Domain(1)[0], bezier->Domain(1)[1]);
bezier->Dump(info_output);
info_output.Print("\n");
}
delete bezier;
}
}
ON_String onstr = ON_String(wonstr);
const char *infodesc = onstr.Array();
bu_vls_strcat(vls, infodesc);
delete nsrf;
} else {
bu_vls_printf(vls, "surface[%2d]: NULL\n", si);
}
}
return 0;
}
int
brep_face_info(struct brep_specific* bs, struct bu_vls *vls, int fi)
{
ON_wString s;
ON_TextLog dump(s);
ON_Brep *brep = bs->brep;
if (brep == NULL) {
return -1;
}
if (!brep->IsValid(&dump)) {
bu_log("brep is NOT valid");
}
if (!((fi >= 0) && (fi < brep->m_F.Count())))
return 0;
//ON_wString s;
//ON_TextLog dump(s);
const ON_BrepFace& face = brep->m_F[fi];
const ON_Surface* face_srf = face.SurfaceOf();
dump.Print("face[%2d]: surface(%d) reverse(%d) loops(", fi, face.m_si, face.m_bRev);
int fli;
for (fli = 0; fli < face.m_li.Count(); fli++) {
dump.Print((fli) ? ", %d" : "%d", face.m_li[fli]);
}
dump.Print(")\n");
dump.PushIndent();
for (fli = 0; fli < face.m_li.Count(); fli++) {
const int li = face.m_li[fli];
const ON_BrepLoop& loop = brep->m_L[li];
const char* sLoopType = 0;
switch (loop.m_type) {
case ON_BrepLoop::unknown:
sLoopType = "unknown";
break;
case ON_BrepLoop::outer:
sLoopType = "outer";
break;
case ON_BrepLoop::inner:
sLoopType = "inner";
break;
case ON_BrepLoop::slit:
sLoopType = "slit";
break;
case ON_BrepLoop::crvonsrf:
sLoopType = "crvonsrf";
break;
default:
sLoopType = "unknown";
break;
}
dump.Print("loop[%2d]: type(%s) %d trims(", li, sLoopType, loop.m_ti.Count());
int lti;
for (lti = 0; lti < loop.m_ti.Count(); lti++) {
dump.Print((lti) ? ", %d" : "%d", loop.m_ti[lti]);
}
dump.Print(")\n");
dump.PushIndent();
for (lti = 0; lti < loop.m_ti.Count(); lti++) {
const int ti = loop.m_ti[lti];
const ON_BrepTrim& trim = brep->m_T[ti];
const char* sTrimType = "?";
const char* sTrimIso = "-?";
const ON_Curve* c2 = trim.TrimCurveOf();
ON_NurbsCurve* nc2 = ON_NurbsCurve::New();
c2->GetNurbForm(*nc2, 0.0);
ON_3dPoint trim_start, trim_end;
switch (trim.m_type) {
case ON_BrepTrim::unknown:
sTrimType = "unknown ";
break;
case ON_BrepTrim::boundary:
sTrimType = "boundary";
break;
case ON_BrepTrim::mated:
sTrimType = "mated ";
break;
case ON_BrepTrim::seam:
sTrimType = "seam ";
break;
case ON_BrepTrim::singular:
sTrimType = "singular";
break;
case ON_BrepTrim::crvonsrf:
sTrimType = "crvonsrf";
break;
default:
sTrimType = "unknown";
break;
}
switch (trim.m_iso) {
case ON_Surface::not_iso:
sTrimIso = "";
break;
case ON_Surface::x_iso:
sTrimIso = "-u iso";
break;
case ON_Surface::W_iso:
sTrimIso = "-west side iso";
break;
case ON_Surface::E_iso:
sTrimIso = "-east side iso";
break;
case ON_Surface::y_iso:
sTrimIso = "-v iso";
break;
case ON_Surface::S_iso:
sTrimIso = "-south side iso";
break;
case ON_Surface::N_iso:
sTrimIso = "-north side iso";
break;
default:
sTrimIso = "-unknown_iso_flag";
break;
}
dump.Print("trim[%2d]: edge(%2d) v0(%2d) v1(%2d) tolerance(%g, %g)\n", ti, trim.m_ei, trim.m_vi[0], trim.m_vi[1], trim.m_tolerance[0], trim.m_tolerance[1]);
dump.PushIndent();
dump.Print("type(%s%s) rev3d(%d) 2d_curve(%d)\n", sTrimType, sTrimIso, trim.m_bRev3d, trim.m_c2i);
if (c2) {
trim_start = trim.PointAtStart();
trim_end = trim.PointAtEnd();
dump.Print("domain(%g, %g) start(%g, %g) end(%g, %g)\n", trim.Domain()[0], trim.Domain()[1], trim_start.x, trim_start.y, trim_end.x, trim_end.y);
if (0 != face_srf) {
ON_3dPoint trim_srfstart = face_srf->PointAt(trim_start.x, trim_start.y);
ON_3dPoint trim_srfend = face_srf->PointAt(trim_end.x, trim_end.y);
dump.Print("surface points start(%g, %g, %g) end(%g, %g, %g)\n", trim_srfstart.x, trim_srfstart.y, trim_srfstart.z, trim_srfend.x, trim_srfend.y, trim_srfend.z);
}
} else {
dump.Print("domain(%g, %g) start(?, ?) end(?, ?)\n", trim.Domain()[0], trim.Domain()[1]);
}
dump.PopIndent();
}
dump.PopIndent();
}
dump.PopIndent();
ON_String ss = s;
bu_vls_printf(vls, "%s\n", ss.Array());
return 0;
}
int
brep_trim_info(struct brep_specific* bs, struct bu_vls *vls, int ti)
{
ON_Brep* brep = bs->brep;
ON_wString wstr;
ON_TextLog dump(wstr);
if (brep == NULL) {
return -1;
}
if (!brep->IsValid(&dump)) {
bu_log("brep is NOT valid");
}
if (!((ti >= 0) && (ti < brep->m_T.Count())))
return 0;
const ON_BrepTrim &trim = brep->m_T[ti];
const ON_Surface* trim_srf = trim.SurfaceOf();
const ON_BrepLoop &loop = brep->m_L[trim.m_li];
const ON_BrepFace &face = brep->m_F[loop.m_fi];
const char* sTrimType = "?";
const char* sTrimIso = "-?";
const ON_Curve* c2 = trim.TrimCurveOf();
ON_NurbsCurve* nc2 = ON_NurbsCurve::New();
c2->GetNurbForm(*nc2, 0.0);
ON_3dPoint trim_start, trim_end;
dump.Print("trim[%2d]: surface(%2d) faces(%2d) loops(%2d)\n", ti, face.m_si, face.m_face_index, loop.m_loop_index);
switch (trim.m_type) {
case ON_BrepTrim::unknown:
sTrimType = "unknown ";
break;
case ON_BrepTrim::boundary:
sTrimType = "boundary";
break;
case ON_BrepTrim::mated:
sTrimType = "mated ";
break;
case ON_BrepTrim::seam:
sTrimType = "seam ";
break;
case ON_BrepTrim::singular:
sTrimType = "singular";
break;
case ON_BrepTrim::crvonsrf:
sTrimType = "crvonsrf";
break;
default:
sTrimType = "unknown";
break;
}
switch (trim.m_iso) {
case ON_Surface::not_iso:
sTrimIso = "";
break;
case ON_Surface::x_iso:
sTrimIso = "-u iso";
break;
case ON_Surface::W_iso:
sTrimIso = "-west side iso";
break;
case ON_Surface::E_iso:
sTrimIso = "-east side iso";
break;
case ON_Surface::y_iso:
sTrimIso = "-v iso";
break;
case ON_Surface::S_iso:
sTrimIso = "-south side iso";
break;
case ON_Surface::N_iso:
sTrimIso = "-north side iso";
break;
default:
sTrimIso = "-unknown_iso_flag";
break;
}
dump.Print("\tedge(%2d) v0(%2d) v1(%2d) tolerance(%g, %g)\n", trim.m_ei, trim.m_vi[0], trim.m_vi[1], trim.m_tolerance[0], trim.m_tolerance[1]);
dump.PushIndent();
dump.Print("\ttype(%s%s) rev3d(%d) 2d_curve(%d)\n", sTrimType, sTrimIso, trim.m_bRev3d, trim.m_c2i);
if (c2) {
trim_start = trim.PointAtStart();
trim_end = trim.PointAtEnd();
dump.Print("\tdomain(%g, %g) start(%g, %g) end(%g, %g)\n", trim.Domain()[0], trim.Domain()[1], trim_start.x, trim_start.y, trim_end.x, trim_end.y);
if (0 != trim_srf) {
ON_3dPoint trim_srfstart = trim_srf->PointAt(trim_start.x, trim_start.y);
ON_3dPoint trim_srfend = trim_srf->PointAt(trim_end.x, trim_end.y);
dump.Print("\tsurface points start(%g, %g, %g) end(%g, %g, %g)\n", trim_srfstart.x, trim_srfstart.y, trim_srfstart.z, trim_srfend.x, trim_srfend.y, trim_srfend.z);
}
} else {
dump.Print("\tdomain(%g, %g) start(?, ?) end(?, ?)\n", trim.Domain()[0], trim.Domain()[1]);
}
dump.PopIndent();
dump.Print("NURBS form of 2d_curve(trim)\n");
nc2->Dump(dump);
delete nc2;
ON_String ss = wstr;
bu_vls_printf(vls, "%s\n", ss.Array());
return 0;
}
int
brep_trim_bezier_info(struct brep_specific* bs, struct bu_vls *vls, int ti)
{
ON_Brep* brep = bs->brep;
ON_wString wstr;
ON_TextLog dump(wstr);
if (brep == NULL) {
return -1;
}
if (!brep->IsValid(&dump)) {
bu_log("brep is NOT valid");
}
if (!((ti >= 0) && (ti < brep->m_T.Count())))
return 0;
const ON_BrepTrim &trim = brep->m_T[ti];
const ON_Curve* c2 = trim.TrimCurveOf();
ON_NurbsCurve* nc2 = ON_NurbsCurve::New();
c2->GetNurbForm(*nc2, 0.0);
int knotlength = nc2->m_order + nc2->m_cv_count - 2;
int order = nc2->m_order;
fastf_t *knot = nc2->m_knot;
dump.Print("trim[%2d]: domain(%g, %g)\n", ti, nc2->Domain()[0], nc2->Domain()[1]);
int cnt = 0;
dump.Print("NURBS converts to Bezier\n");
for (int i = 0; i < knotlength - 1; ++i) {
ON_BezierCurve* bezier = new ON_BezierCurve;
if (nc2->ConvertSpanToBezier(i, *bezier)) {
dump.Print("NO.%d segment\n", ++cnt);
dump.Print("spanindex from %d to %d\n", i + order - 2, i + order - 1);
dump.Print("knot from %.2f to %.2f\n ", knot[i + order - 2], knot[i + order - 1]);
dump.Print("domain(%g, %g)\n", bezier->Domain()[0], bezier->Domain()[1]);
bezier->Dump(dump);
dump.Print("\n");
}
delete bezier;
}
delete nc2;
ON_String ss = wstr;
bu_vls_printf(vls, "%s\n", ss.Array());
return 0;
}
int
brep_curve_info(struct brep_specific* bs, struct bu_vls *vls, int ci)
{
ON_Brep* brep = bs->brep;
ON_wString wstr;
ON_TextLog dump(wstr);
if (brep == NULL) {
return -1;
}
if (!((ci >= 0) && (ci < brep->m_C3.Count())))
return 0;
const ON_Curve *curve = brep->m_C3[ci];
ON_NurbsCurve* nc3 = ON_NurbsCurve::New();
curve->GetNurbForm(*nc3, 0.0);
dump.Print("NURBS form of 3d_curve(edge) \n");
nc3->Dump(dump);
delete nc3;
ON_String ss = wstr;
bu_vls_printf(vls, "%s\n", ss.Array());
return 0;
}
int
brep_loop_info(struct brep_specific* bs, struct bu_vls *vls, int li)
{
ON_Brep* brep = bs->brep;
ON_wString wstr;
ON_TextLog dump(wstr);
if (brep == NULL) {
return -1;
}
if (!brep->IsValid(&dump)) {
bu_log("brep is NOT valid");
}
if (!((li >= 0) && (li < brep->m_L.Count())))
return 0;
const ON_BrepLoop &loop = brep->m_L[li];
dump.Print("loop[%d] on face %d with %d trims\n", li, loop.m_fi, loop.TrimCount());
if (loop.TrimCount() > 0) {
dump.Print("trims: ");
for (int i = 0; i < loop.TrimCount() - 1; ++i) {
dump.Print("%d,", loop.m_ti[i]);
}
dump.Print("%d\n", loop.m_ti[loop.TrimCount() - 1]);
}
ON_String ss = wstr;
bu_vls_printf(vls, "%s\n", ss.Array());
return 0;
}
int
brep_edge_info(struct brep_specific* bs, struct bu_vls *vls, int ei)
{
ON_Brep* brep = bs->brep;
ON_wString wstr;
ON_TextLog dump(wstr);
if (brep == NULL) {
return -1;
}
if (!brep->IsValid(&dump)) {
bu_log("brep is NOT valid");
}
if (!((ei >= 0) && (ei < brep->m_E.Count())))
return 0;
const ON_BrepEdge &edge = brep->m_E[ei];
int trim_cnt = edge.m_ti.Count();
const ON_Curve* c3 = edge.EdgeCurveOf();
ON_NurbsCurve* nc3 = ON_NurbsCurve::New();
c3->GetNurbForm(*nc3, 0.0);
ON_3dPoint edge_start, edge_end;
dump.Print("edge[%2d]: for ", ei);
for (int i = 0; i < trim_cnt; ++i) {
dump.Print("trim[%2d] ", edge.m_ti[i]);
}
dump.Print("\n");
dump.Print("v0(%2d) v1(%2d) 3d_curve(%2d) tolerance(%g, %g)\n", ei, edge.m_vi[0], edge.m_vi[1], edge.m_c3i, edge.m_tolerance);
dump.PushIndent();
if (c3) {
edge_start = edge.PointAtStart();
edge_end = edge.PointAtEnd();
dump.Print("\tdomain(%g, %g) surface points start(%g, %g, %g) end(%g, %g, %g)\n", edge.Domain()[0], edge.Domain()[1], edge_start.x, edge_start.y, edge_start.z, edge_end.x, edge_end.y, edge_end.z);
} else {
dump.Print("\tdomain(%g, %g) start(?, ?) end(?, ?)\n", edge.Domain()[0], edge.Domain()[1]);
}
dump.PopIndent();
dump.Print("NURBS form of 3d_curve(edge) \n");
nc3->Dump(dump);
delete nc3;
ON_String ss = wstr;
bu_vls_printf(vls, "%s\n", ss.Array());
return 0;
}
int brep_facecdt_plot(struct bu_vls *vls, const char *solid_name,
const struct rt_tess_tol *ttol, const struct bn_tol *tol,
struct brep_specific* bs, struct rt_brep_internal*UNUSED(bi),
struct bn_vlblock *vbp, int index, int plottype, int num_points = -1)
{
register struct bu_list *vhead = bn_vlblock_find(vbp, YELLOW);
bool watertight = true;
ON_wString wstr;
ON_TextLog tl(wstr);
ON_Brep* brep = bs->brep;
if (brep == NULL || !brep->IsValid(&tl)) {
if (wstr.Length() > 0) {
ON_String onstr = ON_String(wstr);
const char *isvalidinfo = onstr.Array();
bu_vls_strcat(vls, "brep (");
bu_vls_strcat(vls, solid_name);
bu_vls_strcat(vls, ") is NOT valid:");
bu_vls_strcat(vls, isvalidinfo);
} else {
bu_vls_strcat(vls, "brep (");
bu_vls_strcat(vls, solid_name);
bu_vls_strcat(vls, ") is NOT valid.");
}
//for now try to draw - return -1;
}
for (int face_index = 0; face_index < brep->m_F.Count(); face_index++) {
ON_BrepFace *face = brep->Face(face_index);
const ON_Surface *s = face->SurfaceOf();
double surface_width, surface_height;
if (s->GetSurfaceSize(&surface_width, &surface_height)) {
// reparameterization of the face's surface and transforms the "u"
// and "v" coordinates of all the face's parameter space trimming
// curves to minimize distortion in the map from parameter space to 3d..
face->SetDomain(0, 0.0, surface_width);
face->SetDomain(1, 0.0, surface_height);
}
}
if (index == -1) {
for (index = 0; index < brep->m_F.Count(); index++) {
ON_BrepFace& face = brep->m_F[index];
poly2tri_CDT(vhead, face, ttol, tol, NULL, watertight, plottype, num_points);
}
} else if (index < brep->m_F.Count()) {
ON_BrepFaceArray& faces = brep->m_F;
if (index < faces.Count()) {
ON_BrepFace& face = faces[index];
face.Dump(tl);
poly2tri_CDT(vhead, face, ttol, tol, NULL, watertight, plottype, num_points);
}
}
bu_vls_printf(vls, ON_String(wstr).Array());
return 0;
}
int
brep_facetrim_plot(struct bu_vls *vls, struct brep_specific* bs, struct rt_brep_internal*, struct bn_vlblock *vbp, int index, struct bu_color *color, int plotres, bool dim3d)
{
ON_wString wstr;
ON_TextLog tl(wstr);
ON_Brep* brep = bs->brep;
if (brep == NULL) {
return -1;
}
if (!brep->IsValid(&tl)) {
bu_log("brep is NOT valid");
}
if (index == -1) {
for (index = 0; index < brep->m_F.Count(); index++) {
ON_BrepFace& face = brep->m_F[index];
if (!dim3d)
plotUVDomain2d(face, vbp);
if (color) {
plottrim(face, vbp, plotres, dim3d, (int)color->buc_rgb[0], (int)color->buc_rgb[1], (int)color->buc_rgb[2]);
} else {
plottrim(face, vbp, plotres, dim3d);
}
}
} else if (index < brep->m_F.Count()) {
ON_BrepFaceArray& faces = brep->m_F;
if (index < faces.Count()) {
ON_BrepFace& face = faces[index];
face.Dump(tl);
if (!dim3d)
plotUVDomain2d(face, vbp);
if (color) {
plottrim(face, vbp, plotres, dim3d, (int)color->buc_rgb[0], (int)color->buc_rgb[1], (int)color->buc_rgb[2]);
} else {
plottrim(face, vbp, plotres, dim3d);
}
}
}
bu_vls_printf(vls, ON_String(wstr).Array());
return 0;
}
int
brep_trim_direction_plot(struct bu_vls *vls, struct brep_specific* bs, struct rt_brep_internal*, struct bn_vlblock *vbp, int index, int plotres)
{
ON_wString wstr;
ON_TextLog tl(wstr);
ON_Brep* brep = bs->brep;
if (brep == NULL) {
return -1;
}
if (!brep->IsValid(&tl)) {
bu_log("brep is NOT valid");
}
if (index == -1) {
for (index = 0; index < brep->m_F.Count(); index++) {
ON_BrepFace& face = brep->m_F[index];
plottrimdirection(face, vbp, plotres);
}
} else if (index < brep->m_F.Count()) {
ON_BrepFaceArray& faces = brep->m_F;
if (index < faces.Count()) {
ON_BrepFace& face = faces[index];
face.Dump(tl);
plottrimdirection(face, vbp, plotres);
}
}
bu_vls_printf(vls, ON_String(wstr).Array());
return 0;
}
int
brep_surface_uv_plot(struct bu_vls *vls, struct brep_specific* bs, struct rt_brep_internal*, struct bn_vlblock *vbp, int index, double u, double v)
{
ON_wString wstr;
ON_TextLog tl(wstr);
ON_Brep* brep = bs->brep;
if (brep == NULL) {
return -1;
}
if (!brep->IsValid(&tl)) {
bu_log("brep is NOT valid");
}
if (index == -1) {
for (index = 0; index < brep->m_S.Count(); index++) {
ON_Surface *surf = brep->m_S[index];
plotpoint(surf->PointAt(u, v), vbp, GREEN);
}
} else if (index < brep->m_S.Count()) {
ON_Surface *surf = brep->m_S[index];
surf->Dump(tl);
plotpoint(surf->PointAt(u, v), vbp, GREEN);
}
bu_vls_printf(vls, ON_String(wstr).Array());
return 0;
}
int
brep_surface_uv_plot(struct bu_vls *vls, struct brep_specific* bs, struct rt_brep_internal*, struct bn_vlblock *vbp, int index, ON_Interval &U, ON_Interval &V)
{
ON_wString wstr;
ON_TextLog tl(wstr);
ON_Brep* brep = bs->brep;
if (brep == NULL) {
return -1;
}
if (!brep->IsValid(&tl)) {
bu_log("brep is NOT valid");
}
if ((index >= 0)&&(index < brep->m_S.Count())) {
ON_Surface *surf = brep->m_S[index];
register struct bu_list *vhead;
fastf_t pt1[3], pt2[3];
fastf_t delta = U.Length()/1000.0;
vhead = bn_vlblock_find(vbp, YELLOW);
for (int i = 0; i < 2; i++) {
fastf_t v = V.m_t[i];
for (fastf_t u = U.m_t[0]; u < U.m_t[1]; u = u + delta) {
ON_3dPoint p = surf->PointAt(u, v);
//bu_log("p1 2d - %f, %f 3d - %f, %f, %f\n", pt.x, y, p.x, p.y, p.z);
VMOVE(pt1, p);
if (u + delta > U.m_t[1]) {
p = surf->PointAt(U.m_t[1], v);
} else {
p = surf->PointAt(u + delta, v);
}
//bu_log("p1 2d - %f, %f 3d - %f, %f, %f\n", pt.x, y+deltay, p.x, p.y, p.z);
VMOVE(pt2, p);
RT_ADD_VLIST(vhead, pt1, BN_VLIST_LINE_MOVE);
RT_ADD_VLIST(vhead, pt2, BN_VLIST_LINE_DRAW);
}
}
delta = V.Length()/1000.0;
for (int i = 0; i < 2; i++) {
fastf_t u = U.m_t[i];
for (fastf_t v = V.m_t[0]; v < V.m_t[1]; v = v + delta) {
ON_3dPoint p = surf->PointAt(u, v);
//bu_log("p1 2d - %f, %f 3d - %f, %f, %f\n", pt.x, y, p.x, p.y, p.z);
VMOVE(pt1, p);
if (v + delta > V.m_t[1]) {
p = surf->PointAt(u,V.m_t[1]);
} else {
p = surf->PointAt(u, v + delta);
}
//bu_log("p1 2d - %f, %f 3d - %f, %f, %f\n", pt.x, y+deltay, p.x, p.y, p.z);
VMOVE(pt2, p);
RT_ADD_VLIST(vhead, pt1, BN_VLIST_LINE_MOVE);
RT_ADD_VLIST(vhead, pt2, BN_VLIST_LINE_DRAW);
}
}
}
bu_vls_printf(vls, ON_String(wstr).Array());
return 0;
}
int
brep_surface_plot(struct bu_vls *vls, struct brep_specific* bs, struct rt_brep_internal*, struct bn_vlblock *vbp, int index, struct bu_color *color, int plotres)
{
ON_wString wstr;
ON_TextLog tl(wstr);
ON_Brep* brep = bs->brep;
if (brep == NULL) {
return -1;
}
if (!brep->IsValid(&tl)) {
bu_log("brep is NOT valid");
}
if (index == -1) {
for (index = 0; index < brep->m_S.Count(); index++) {
ON_Surface *surf = brep->m_S[index];
if (color) {
plotsurface(*surf, vbp, plotres, 10, (int)color->buc_rgb[0], (int)color->buc_rgb[1], (int)color->buc_rgb[2]);
} else {
plotsurface(*surf, vbp, plotres, 10);
}
}
} else if (index < brep->m_S.Count()) {
ON_Surface *surf = brep->m_S[index];
surf->Dump(tl);
if (color) {
plotsurface(*surf, vbp, plotres, 10, (int)color->buc_rgb[0], (int)color->buc_rgb[1], (int)color->buc_rgb[2]);
} else {
plotsurface(*surf, vbp, plotres, 10);
}
}
bu_vls_printf(vls, ON_String(wstr).Array());
return 0;
}
int
brep_surface_normal_plot(struct bu_vls *vls, struct brep_specific* bs, struct rt_brep_internal*, struct bn_vlblock *vbp, int index, int plotres)
{
ON_wString wstr;
ON_TextLog tl(wstr);
ON_Brep* brep = bs->brep;
if (brep == NULL) {
return -1;
}
if (!brep->IsValid(&tl)) {
bu_log("brep is NOT valid");
}
if (index == -1) {
for (index = 0; index < brep->m_S.Count(); index++) {
ON_Surface *surf = brep->m_S[index];
plotsurfaceknots(*surf, vbp, true);
plotsurfacenormals(*surf, vbp, plotres);
}
} else if (index < brep->m_S.Count()) {
ON_Surface *surf = brep->m_S[index];
surf->Dump(tl);
plotsurfaceknots(*surf, vbp, true);
plotsurfacenormals(*surf, vbp, plotres);
}
bu_vls_printf(vls, ON_String(wstr).Array());
return 0;
}
int
brep_surface_knot_plot(struct bu_vls *vls, struct brep_specific* bs, struct rt_brep_internal*, struct bn_vlblock *vbp, int index, bool dim3d)
{
ON_wString wstr;
ON_TextLog tl(wstr);
ON_Brep* brep = bs->brep;
if (brep == NULL) {
return -1;
}
if (!brep->IsValid(&tl)) {
bu_log("brep is NOT valid");
}
if (index == -1) {
for (index = 0; index < brep->m_S.Count(); index++) {
ON_Surface *surf = brep->m_S[index];
plotsurfaceknots(*surf, vbp, dim3d);
}
} else if (index < brep->m_S.Count()) {
ON_Surface *surf = brep->m_S[index];
surf->Dump(tl);
plotsurfaceknots(*surf, vbp, dim3d);
}
bu_vls_printf(vls, ON_String(wstr).Array());
return 0;
}
int
brep_edge3d_plot(struct bu_vls *vls, struct brep_specific* bs, struct rt_brep_internal*, struct bn_vlblock *vbp, struct bu_color *color, int index, int plotres)
{
ON_wString wstr;
ON_TextLog tl(wstr);
ON_Brep* brep = bs->brep;
if (brep == NULL) {
return -1;
}
if (!brep->IsValid(&tl)) {
bu_log("brep is NOT valid");
}
if (index == -1) {
int num_curves = brep->m_C3.Count();
for (index = 0; index < num_curves; index++) {
ON_Curve *curve = brep->m_C3[index];
if (color) {
plotcurve(*curve, vbp, plotres, (int)color->buc_rgb[0], (int)color->buc_rgb[1], (int)color->buc_rgb[2]);
} else {
plotcurve(*curve, vbp, plotres);
}
}
} else if (index < brep->m_C3.Count()) {
ON_Curve *curve = brep->m_C3[index];
curve->Dump(tl);
if (color) {
plotcurve(*curve, vbp, plotres, (int)color->buc_rgb[0], (int)color->buc_rgb[1], (int)color->buc_rgb[2]);
} else {
plotcurve(*curve, vbp, plotres);
}
}
bu_vls_printf(vls, ON_String(wstr).Array());
return 0;
}
static void
plot_nurbs_cv(struct bn_vlblock *vbp, int ucount, int vcount, ON_NurbsSurface *ns)
{
register struct bu_list *vhead;
vhead = bn_vlblock_find(vbp, PEACH);
ON_3dPoint cp;
fastf_t pt1[3], pt2[3];
int i, j, k, temp;
for (k = 0; k < 2; k++) {
/* two times i loop */
for (i = 0; i < ucount; ++i) {
if (k == 1)
ns->GetCV(0, i, cp); /* i < ucount */
else
ns->GetCV(i, 0, cp); /* i < vcount */
VMOVE(pt1, cp);
for (j = 0; j < vcount; ++j) {
if (k == 1)
ns->GetCV(j, i, cp);
else
ns->GetCV(i, j, cp);
VMOVE(pt2, cp);
RT_ADD_VLIST(vhead, pt1, BN_VLIST_LINE_MOVE);
RT_ADD_VLIST(vhead, pt2, BN_VLIST_LINE_DRAW);
VMOVE(pt1, cp);
RT_ADD_VLIST(vhead, cp, BN_VLIST_POINT_DRAW);
}
}
temp = ucount;
ucount = vcount;
vcount = temp;
}
}
int
brep_trim_plot(struct bu_vls *vls, struct brep_specific* bs, struct rt_brep_internal*, struct bn_vlblock *vbp, int index, struct bu_color *color, int plotres, bool dim3d)
{
ON_wString wstr;
ON_TextLog tl(wstr);
ON_Brep* brep = bs->brep;
if (brep == NULL) {
return -1;
}
if (!brep->IsValid(&tl)) {
bu_log("brep is NOT valid");
}
if (index == -1) {
int num_trims = brep->m_T.Count();
for (index = 0; index < num_trims; index++) {
ON_BrepTrim &trim = brep->m_T[index];
if (color) {
plottrim(trim, vbp, plotres, dim3d, (int)color->buc_rgb[0], (int)color->buc_rgb[1], (int)color->buc_rgb[2]);
} else {
plottrim(trim, vbp, plotres, dim3d);
}
}
} else if (index < brep->m_T.Count()) {
ON_BrepTrim &trim = brep->m_T[index];
if (color) {
plottrim(trim, vbp, plotres, dim3d, (int)color->buc_rgb[0], (int)color->buc_rgb[1], (int)color->buc_rgb[2]);
} else {
plottrim(trim, vbp, plotres, dim3d);
}
}
bu_vls_printf(vls, ON_String(wstr).Array());
return 0;
}
int
brep_loop_plot(struct bu_vls *vls, struct brep_specific* bs, struct rt_brep_internal*, struct bn_vlblock *vbp, int index, int plotres, bool dim3d)
{
ON_wString wstr;
ON_TextLog ll(wstr);
ON_Brep* brep = bs->brep;
if (brep == NULL) {
return -1;
}
if (!brep->IsValid(&ll)) {
bu_log("brep is NOT valid");
}
if (index == -1) {
for (int i = 0; i < brep->m_L.Count(); i++) {
ON_BrepLoop* loop = &(brep->m_L[i]);
for (int ti = 0; ti < loop->m_ti.Count(); ti++) {
ON_BrepTrim& trim = brep->m_T[loop->m_ti[ti]];
plottrim(trim, vbp, plotres, dim3d);
}
}
} else if (index < brep->m_L.Count()) {
ON_BrepLoop* loop = &(brep->m_L[index]);
for (int ti = 0; ti < loop->m_ti.Count(); ti++) {
ON_BrepTrim& trim = brep->m_T[loop->m_ti[ti]];
plottrim(trim, vbp, plotres, dim3d);
}
}
bu_vls_printf(vls, ON_String(wstr).Array());
return 0;
}
int
brep_surface_cv_plot(struct bu_vls *vls, struct brep_specific* bs, struct rt_brep_internal*, struct bn_vlblock *vbp, int index)
{
ON_wString wstr;
ON_TextLog tl(wstr);
ON_Brep* brep = bs->brep;
if (brep == NULL) {
return -1;
}
if (!brep->IsValid(&tl)) {
bu_log("brep is NOT valid");
}
if (index == -1) {
for (index = 0; index < brep->m_S.Count(); index++) {
ON_Surface *surf = brep->m_S[index];
ON_NurbsSurface *ns = ON_NurbsSurface::New();
surf->GetNurbForm(*ns, 0.0);
int ucount, vcount;
ucount = ns->m_cv_count[0];
vcount = ns->m_cv_count[1];
surf->Dump(tl);
plot_nurbs_cv(vbp, ucount, vcount, ns);
}
} else if (index < brep->m_S.Count()) {
ON_Surface *surf = brep->m_S[index];
ON_NurbsSurface *ns = ON_NurbsSurface::New();
surf->GetNurbForm(*ns, 0.0);
int ucount, vcount;
ucount = ns->m_cv_count[0];
vcount = ns->m_cv_count[1];
plot_nurbs_cv(vbp, ucount, vcount, ns);
}
bu_vls_printf(vls, ON_String(wstr).Array());
return 0;
}
/* a binary predicate for std:list implemented as a function */
extern bool near_equal (double first, double second);
void
plotFace(SurfaceTree* st, struct bn_vlblock *vbp, int UNUSED(isocurveres), int gridres)
{
register struct bu_list *vhead;
fastf_t pt1[3], pt2[3];
ON_2dPoint from, to;
std::list<BRNode*> m_trims_above_or_right;
std::list<fastf_t> trim_hits;
vhead = bn_vlblock_find(vbp, PEACH);
const ON_Surface *surf = st->getSurface();
CurveTree *ctree = st->ctree;
ON_Interval udom = surf->Domain(0);
ON_Interval vdom = surf->Domain(1);
//bu_log("udom %f, %f vdom %f, %f\n", udom.m_t[0], udom.m_t[1], vdom.m_t[0], vdom.m_t[1]);
m_trims_above_or_right.clear();
ON_2dPoint pt;
for (int gd = 1; gd < gridres; gd++) {
pt.x = udom.ParameterAt((double)gd /(double)gridres);
pt.y = vdom.ParameterAt(0.0);
if (ctree != NULL) {
m_trims_above_or_right.clear();
ctree->getLeavesAbove(m_trims_above_or_right, pt, 0.0000001);
}
int cnt=1;
//bu_log("U - %f\n", pt.x);
trim_hits.clear();
for (std::list<BRNode*>::iterator i = m_trims_above_or_right.begin(); i != m_trims_above_or_right.end(); i++, cnt++) {
BRNode* br = dynamic_cast<BRNode*>(*i);
point_t bmin, bmax;
br->GetBBox(bmin, bmax);
if ((bmin[X] <= pt[X]) && (pt[X] <= bmax[X])) { //if check trim and in BBox
fastf_t v = br->getCurveEstimateOfV(pt[X], 0.0000001);
trim_hits.push_back(v);
//bu_log("%d V %d - %f pt %f, %f bmin %f, %f bmax %f, %f\n", br->m_face->m_face_index, cnt, v, pt.x, pt.y, bmin[X], bmin[Y], bmax[X], bmax[Y]);
}
}
trim_hits.sort();
trim_hits.unique(near_equal);
size_t hit_cnt = trim_hits.size();
if ((hit_cnt > 1) && ((hit_cnt % 2) == 0)) {
//bu_log("U - %f\n", pt.x);
while (!trim_hits.empty()) {
fastf_t tfrom = trim_hits.front();
trim_hits.pop_front();
fastf_t tto = trim_hits.front();
trim_hits.pop_front();
//bu_log("\tfrom - %f, to - %f\n", tfrom, tto);
fastf_t deltay = (tto-tfrom)/50.0;
for (fastf_t y = tfrom; y < tto - deltay; y = y + deltay) {
ON_3dPoint p = surf->PointAt(pt.x, y);
//bu_log("p1 2d - %f, %f 3d - %f, %f, %f\n", pt.x, y, p.x, p.y, p.z);
VMOVE(pt1, p);
p = surf->PointAt(pt.x, y+deltay);
if (y+deltay > tto) {
p = surf->PointAt(pt.x, tto);
} else {
p = surf->PointAt(pt.x, y+deltay);
}
//bu_log("p1 2d - %f, %f 3d - %f, %f, %f\n", pt.x, y+deltay, p.x, p.y, p.z);
VMOVE(pt2, p);
RT_ADD_VLIST(vhead, pt1, BN_VLIST_LINE_MOVE);
RT_ADD_VLIST(vhead, pt2, BN_VLIST_LINE_DRAW);
}
}
}
// v direction
pt.x = udom.ParameterAt(0.0);
pt.y = vdom.ParameterAt((double)gd /(double)gridres);
if (ctree != NULL) {
m_trims_above_or_right.clear();
ctree->getLeavesRight(m_trims_above_or_right, pt, 0.0000001);
}
cnt=1;
//bu_log("V - %f\n", pt.x);
trim_hits.clear();
for (std::list<BRNode*>::iterator i = m_trims_above_or_right.begin(); i != m_trims_above_or_right.end(); i++, cnt++) {
BRNode* br = dynamic_cast<BRNode*>(*i);
point_t bmin, bmax;
br->GetBBox(bmin, bmax);
if ((bmin[Y] <= pt[Y]) && (pt[Y] <= bmax[Y])) { //if check trim and in BBox
fastf_t u = br->getCurveEstimateOfU(pt[Y], 0.0000001);
trim_hits.push_back(u);
//bu_log("%d U %d - %f pt %f, %f bmin %f, %f bmax %f, %f\n", br->m_face->m_face_index, cnt, u, pt.x, pt.y, bmin[X], bmin[Y], bmax[X], bmax[Y]);
}
}
trim_hits.sort();
trim_hits.unique(near_equal);
hit_cnt = trim_hits.size();
if ((hit_cnt > 1) && ((hit_cnt % 2) == 0)) {
//bu_log("V - %f\n", pt.y);
while (!trim_hits.empty()) {
fastf_t tfrom = trim_hits.front();
trim_hits.pop_front();
fastf_t tto = trim_hits.front();
trim_hits.pop_front();
//bu_log("\tfrom - %f, to - %f\n", tfrom, tto);
fastf_t deltax = (tto-tfrom)/50.0;
for (fastf_t x = tfrom; x < tto; x = x + deltax) {
ON_3dPoint p = surf->PointAt(x, pt.y);
VMOVE(pt1, p);
if (x+deltax > tto) {
p = surf->PointAt(tto, pt.y);
} else {
p = surf->PointAt(x+deltax, pt.y);
}
VMOVE(pt2, p);
RT_ADD_VLIST(vhead, pt1, BN_VLIST_LINE_MOVE);
RT_ADD_VLIST(vhead, pt2, BN_VLIST_LINE_DRAW);
}
}
}
}
return;
}
void
drawisoUCheckForTrim(SurfaceTree* st, struct bn_vlblock *vbp, fastf_t from, fastf_t to, fastf_t v, int UNUSED(curveres))
{
register struct bu_list *vhead;
fastf_t pt1[3], pt2[3];
std::list<BRNode*> m_trims_right;
std::list<fastf_t> trim_hits;
vhead = bn_vlblock_find(vbp, YELLOW);
const ON_Surface *surf = st->getSurface();
CurveTree *ctree = st->ctree;
fastf_t umin, umax;
surf->GetDomain(0, &umin, &umax);
m_trims_right.clear();
fastf_t tol = 0.001;
ON_2dPoint pt;
pt.x = umin;
pt.y = v;
if (ctree != NULL) {
m_trims_right.clear();
ctree->getLeavesRight(m_trims_right, pt, tol);
}
int cnt = 1;
//bu_log("V - %f\n", pt.x);
trim_hits.clear();
for (std::list<BRNode*>::iterator i = m_trims_right.begin(); i != m_trims_right.end(); i++, cnt++) {
BRNode* br = dynamic_cast<BRNode*> (*i);
point_t bmin, bmax;
if (!br->m_Horizontal) {
br->GetBBox(bmin, bmax);
if (((bmin[Y] - tol) <= pt[Y]) && (pt[Y] <= (bmax[Y]+tol))) { //if check trim and in BBox
fastf_t u = br->getCurveEstimateOfU(pt[Y], tol);
trim_hits.push_back(u);
//bu_log("%d U %d - %f pt %f, %f bmin %f, %f bmax %f, %f\n", br->m_face->m_face_index, cnt, u, pt.x, pt.y, bmin[X], bmin[Y], bmax[X], bmax[Y]);
}
}
}
trim_hits.sort();
trim_hits.unique(near_equal);
int hit_cnt = trim_hits.size();
cnt = 1;
//bu_log("\tdrawisoUCheckForTrim: hit_cnt %d from center %f %f 0.0 to center %f %f 0.0\n", hit_cnt, from, v , to, v);
if ((hit_cnt > 0) && ((hit_cnt % 2) == 0)) {
/*
if ((hit_cnt % 2) != 0) {
//bu_log("V - %f\n", pt.y);
if (!trim_hits.empty()) {
fastf_t end = trim_hits.front();
trim_hits.pop_front();
//bu_log("\tfrom - %f, to - %f\n", from, to);
fastf_t deltax = (end - from) / 50.0;
if (deltax > 0.001) {
for (fastf_t x = from; x < end && x < to; x = x + deltax) {
ON_3dPoint p = surf->PointAt(x, pt.y);
VMOVE(pt1, p);
if (x + deltax > end) {
if (x + deltax > to) {
p = surf->PointAt(to, pt.y);
} else {
p = surf->PointAt(end, pt.y);
}
} else {
if (x + deltax > to) {
p = surf->PointAt(to, pt.y);
} else {
p = surf->PointAt(x + deltax, pt.y);
}
}
VMOVE(pt2, p);
//bu_log(
// "\t\t%d from center %f %f 0.0 to center %f %f 0.0\n",
// cnt++, x, v, x + deltax, v);
RT_ADD_VLIST(vhead, pt1, BN_VLIST_LINE_MOVE);
RT_ADD_VLIST(vhead, pt2, BN_VLIST_LINE_DRAW);
}
}
}
}
*/
while (!trim_hits.empty()) {
fastf_t start = trim_hits.front();
if (start < from) {
start = from;
}
trim_hits.pop_front();
fastf_t end = trim_hits.front();
if (end > to) {
end = to;
}
trim_hits.pop_front();
//bu_log("\tfrom - %f, to - %f\n", from, to);
fastf_t deltax = (end - start) / 50.0;
if (deltax > 0.001) {
for (fastf_t x = start; x < end; x = x + deltax) {
ON_3dPoint p = surf->PointAt(x, pt.y);
VMOVE(pt1, p);
if (x + deltax > end) {
p = surf->PointAt(end, pt.y);
} else {
p = surf->PointAt(x + deltax, pt.y);
}
VMOVE(pt2, p);
// bu_log(
// "\t\t%d from center %f %f 0.0 to center %f %f 0.0\n",
// cnt++, x, v, x + deltax, v);
RT_ADD_VLIST(vhead, pt1, BN_VLIST_LINE_MOVE);
RT_ADD_VLIST(vhead, pt2, BN_VLIST_LINE_DRAW);
}
}
}
}
return;
}
void
drawisoVCheckForTrim(SurfaceTree* st, struct bn_vlblock *vbp, fastf_t from, fastf_t to, fastf_t u, int UNUSED(curveres))
{
register struct bu_list *vhead;
fastf_t pt1[3], pt2[3];
std::list<BRNode*> m_trims_above;
std::list<fastf_t> trim_hits;
vhead = bn_vlblock_find(vbp, YELLOW);
const ON_Surface *surf = st->getSurface();
CurveTree *ctree = st->ctree;
fastf_t vmin, vmax;
surf->GetDomain(1, &vmin, &vmax);
m_trims_above.clear();
fastf_t tol = 0.001;
ON_2dPoint pt;
pt.x = u;
pt.y = vmin;
if (ctree != NULL) {
m_trims_above.clear();
ctree->getLeavesAbove(m_trims_above, pt, tol);
}
int cnt = 1;
trim_hits.clear();
for (std::list<BRNode*>::iterator i = m_trims_above.begin(); i != m_trims_above.end(); i++, cnt++) {
BRNode* br = dynamic_cast<BRNode*>(*i);
point_t bmin, bmax;
if (!br->m_Vertical) {
br->GetBBox(bmin, bmax);
if (((bmin[X] - tol) <= pt[X]) && (pt[X] <= (bmax[X]+tol))) { //if check trim and in BBox
fastf_t v = br->getCurveEstimateOfV(pt[X], tol);
trim_hits.push_back(v);
//bu_log("%d V %d - %f pt %f, %f bmin %f, %f bmax %f, %f\n", br->m_face->m_face_index, cnt, v, pt.x, pt.y, bmin[X], bmin[Y], bmax[X], bmax[Y]);
}
}
}
trim_hits.sort();
trim_hits.unique(near_equal);
size_t hit_cnt = trim_hits.size();
cnt = 1;
//bu_log("\tdrawisoVCheckForTrim: hit_cnt %d from center %f %f 0.0 to center %f %f 0.0\n", hit_cnt, u, from, u, to);
if ((hit_cnt > 0) && ((hit_cnt % 2) == 0)) {
/*
if ((hit_cnt % 2) != 0) { //odd starting inside
//bu_log("V - %f\n", pt.y);
if (!trim_hits.empty()) {
fastf_t end = trim_hits.front();
trim_hits.pop_front();
//bu_log("\tfrom - %f, to - %f\n", from, to);
fastf_t deltay = (end - from) / 50.0;
if (deltay > 0.001) {
for (fastf_t y = from; y < end && y < to; y = y + deltay) {
ON_3dPoint p = surf->PointAt(pt.x, y);
VMOVE(pt1, p);
if (y + deltay > end) {
if (y + deltay > to) {
p = surf->PointAt(pt.x, to);
} else {
p = surf->PointAt(pt.x, end);
}
} else {
if (y + deltay > to) {
p = surf->PointAt(pt.x, to);
} else {
p = surf->PointAt(pt.x, y + deltay);
}
}
VMOVE(pt2, p);
//bu_log(
// "\t\t%d from center %f %f 0.0 to center %f %f 0.0\n",
// cnt++, u, y, u, y + deltay);
RT_ADD_VLIST(vhead, pt1, BN_VLIST_LINE_MOVE);
RT_ADD_VLIST(vhead, pt2, BN_VLIST_LINE_DRAW);
}
}
}
}
*/
while (!trim_hits.empty()) {
fastf_t start = trim_hits.front();
trim_hits.pop_front();
if (start < from) {
start = from;
}
fastf_t end = trim_hits.front();
trim_hits.pop_front();
if (end > to) {
end = to;
}
//bu_log("\tfrom - %f, to - %f\n", from, to);
fastf_t deltay = (end - start) / 50.0;
if (deltay > 0.001) {
for (fastf_t y = start; y < end; y = y + deltay) {
ON_3dPoint p = surf->PointAt(pt.x, y);
VMOVE(pt1, p);
if (y + deltay > end) {
p = surf->PointAt(pt.x, end);
} else {
p = surf->PointAt(pt.x, y + deltay);
}
VMOVE(pt2, p);
//bu_log("\t\t%d from center %f %f 0.0 to center %f %f 0.0\n",
// cnt++, u, y, u, y + deltay);
RT_ADD_VLIST(vhead, pt1, BN_VLIST_LINE_MOVE);
RT_ADD_VLIST(vhead, pt2, BN_VLIST_LINE_DRAW);
}
}
}
}
return;
}
void
drawisoU(SurfaceTree* st, struct bn_vlblock *vbp, fastf_t from, fastf_t to, fastf_t v, int curveres)
{
register struct bu_list *vhead;
fastf_t pt1[3], pt2[3];
fastf_t deltau = (to - from) / curveres;
const ON_Surface *surf = st->getSurface();
vhead = bn_vlblock_find(vbp, YELLOW);
for (fastf_t u = from; u < to; u = u + deltau) {
ON_3dPoint p = surf->PointAt(u, v);
//bu_log("p1 2d - %f, %f 3d - %f, %f, %f\n", pt.x, y, p.x, p.y, p.z);
VMOVE(pt1, p);
if (u + deltau > to) {
p = surf->PointAt(to, v);
} else {
p = surf->PointAt(u + deltau, v);
}
//bu_log("p1 2d - %f, %f 3d - %f, %f, %f\n", pt.x, y+deltay, p.x, p.y, p.z);
VMOVE(pt2, p);
RT_ADD_VLIST(vhead, pt1, BN_VLIST_LINE_MOVE);
RT_ADD_VLIST(vhead, pt2, BN_VLIST_LINE_DRAW);
}
}
void
drawisoV(SurfaceTree* st, struct bn_vlblock *vbp, fastf_t from, fastf_t to, fastf_t u, int curveres)
{
register struct bu_list *vhead;
fastf_t pt1[3], pt2[3];
fastf_t deltav = (to - from) / curveres;
const ON_Surface *surf = st->getSurface();
vhead = bn_vlblock_find(vbp, YELLOW);
for (fastf_t v = from; v < to; v = v + deltav) {
ON_3dPoint p = surf->PointAt(u, v);
//bu_log("p1 2d - %f, %f 3d - %f, %f, %f\n", pt.x, y, p.x, p.y, p.z);
VMOVE(pt1, p);
if (v + deltav > to) {
p = surf->PointAt(u, to);
} else {
p = surf->PointAt(u, v + deltav);
}
//bu_log("p1 2d - %f, %f 3d - %f, %f, %f\n", pt.x, y+deltay, p.x, p.y, p.z);
VMOVE(pt2, p);
RT_ADD_VLIST(vhead, pt1, BN_VLIST_LINE_MOVE);
RT_ADD_VLIST(vhead, pt2, BN_VLIST_LINE_DRAW);
}
}
void
drawBBNode(SurfaceTree* st, struct bn_vlblock *vbp, BBNode * node) {
if (node->isLeaf()) {
//draw leaf
if (node->m_trimmed) {
return; // nothing to do node is trimmed
} else if (node->m_checkTrim) { // node may contain trim check all corners
fastf_t u = node->m_u[0];
fastf_t v = node->m_v[0];
fastf_t from = u;
fastf_t to = node->m_u[1];
//bu_log("drawBBNode: node %x uvmin center %f %f 0.0, uvmax center %f %f 0.0\n", node, node->m_u[0], node->m_v[0], node->m_u[1], node->m_v[1]);
drawisoUCheckForTrim(st, vbp, from, to, v, 3); //bottom
v = node->m_v[1];
drawisoUCheckForTrim(st, vbp, from, to, v, 3); //top
from = node->m_v[0];
to = node->m_v[1];
drawisoVCheckForTrim(st, vbp, from, to, u, 3); //left
u = node->m_u[1];
drawisoVCheckForTrim(st, vbp, from, to, u, 3); //right
return;
} else { // fully untrimmed just draw bottom and right edges
fastf_t u = node->m_u[0];
fastf_t v = node->m_v[0];
fastf_t from = u;
fastf_t to = node->m_u[1];
drawisoU(st, vbp, from, to, v, 10); //bottom
from = v;
to = node->m_v[1];
drawisoV(st, vbp, from, to, u, 10); //right
return;
}
} else {
if (node->m_children->size() > 0) {
for (std::vector<BBNode*>::iterator childnode = node->m_children->begin(); childnode
!= node->m_children->end(); childnode++) {
drawBBNode(st, vbp, *childnode);
}
}
}
}
void
plotFaceFromSurfaceTree(SurfaceTree* st, struct bn_vlblock *vbp, int UNUSED(isocurveres), int UNUSED(gridres)) {
BBNode *root = st->getRootNode();
drawBBNode(st, vbp, root);
}
int
brep_isosurface_plot(struct bu_vls *vls, struct brep_specific* bs, struct rt_brep_internal*, struct bn_vlblock *vbp, int index, int plotres)
{
ON_wString wstr;
ON_TextLog tl(wstr);
ON_Brep* brep = bs->brep;
if (brep == NULL) {
return -1;
}
if (!brep->IsValid(&tl)) {
bu_log("brep is NOT valid");
}
if (index == -1) {
for (index = 0; index < brep->m_F.Count(); index++) {
ON_BrepFace& face = brep->m_F[index];
SurfaceTree* st = new SurfaceTree(&face, true, 0);
plottrim(face, vbp, plotres, true);
plotFaceFromSurfaceTree(st, vbp, plotres, plotres);
delete st;
}
} else if (index < brep->m_F.Count()) {
ON_BrepFaceArray& faces = brep->m_F;
if (index < faces.Count()) {
ON_BrepFace& face = faces[index];
SurfaceTree* st = new SurfaceTree(&face, true, 0);
plottrim(face, vbp, plotres, true);
plotFaceFromSurfaceTree(st, vbp, plotres, plotres);
delete st;
}
}
bu_vls_printf(vls, ON_String(wstr).Array());
return 0;
}
int
brep_surfaceleafs_plot(struct bu_vls *vls, struct brep_specific* bs, struct rt_brep_internal*, struct bn_vlblock *vbp, bool dim3d, int index, int)
{
ON_wString wstr;
ON_TextLog tl(wstr);
ON_Brep* brep = bs->brep;
if (brep == NULL) {
return -1;
}
if (!brep->IsValid(&tl)) {
bu_log("brep is NOT valid");
}
if (index == -1) {
for (index = 0; index < brep->m_F.Count(); index++) {
ON_BrepFace& face = brep->m_F[index];
const ON_Surface *s = face.SurfaceOf();
double surface_width,surface_height;
if (s->GetSurfaceSize(&surface_width,&surface_height)) {
// reparameterization of the face's surface and transforms the "u"
// and "v" coordinates of all the face's parameter space trimming
// curves to minimize distortion in the map from parameter space to 3d..
face.SetDomain(0, 0.0, surface_width);
face.SetDomain(1, 0.0, surface_height);
}
SurfaceTree* st = new SurfaceTree(&face);
bu_log("Face: %d contains %d SBBs",index,plotsurfaceleafs(st, vbp, dim3d));
}
} else if (index < brep->m_F.Count()) {
ON_BrepFaceArray& faces = brep->m_F;
if (index < faces.Count()) {
ON_BrepFace& face = faces[index];
const ON_Surface *s = face.SurfaceOf();
double surface_width,surface_height;
if (s->GetSurfaceSize(&surface_width,&surface_height)) {
// reparameterization of the face's surface and transforms the "u"
// and "v" coordinates of all the face's parameter space trimming
// curves to minimize distortion in the map from parameter space to 3d..
face.SetDomain(0, 0.0, surface_width);
face.SetDomain(1, 0.0, surface_height);
}
SurfaceTree* st = new SurfaceTree(&face);
bu_log("Face: %d contains %d SBBs",index,plotsurfaceleafs(st, vbp, dim3d));
}
}
bu_vls_printf(vls, ON_String(wstr).Array());
return 0;
}
int
brep_trimleafs_plot(struct bu_vls *vls, struct brep_specific* bs, struct rt_brep_internal*, struct bn_vlblock *vbp, bool dim3d, int index, int)
{
ON_wString wstr;
ON_TextLog tl(wstr);
ON_Brep* brep = bs->brep;
if (brep == NULL) {
return -1;
}
if (!brep->IsValid(&tl)) {
bu_log("brep is NOT valid");
}
if (index == -1) {
for (index = 0; index < brep->m_F.Count(); index++) {
ON_BrepFace& face = brep->m_F[index];
SurfaceTree* st = new SurfaceTree(&face);
plottrimleafs(st, vbp, dim3d);
}
} else if (index < brep->m_F.Count()) {
ON_BrepFaceArray& faces = brep->m_F;
if (index < faces.Count()) {
ON_BrepFace& face = faces[index];
SurfaceTree* st = new SurfaceTree(&face);
plottrimleafs(st, vbp, dim3d);
}
}
bu_vls_printf(vls, ON_String(wstr).Array());
return 0;
}
void
info_usage(struct bu_vls *vls)
{
bu_vls_printf(vls, "mged>brep brepname.s info\n");
bu_vls_printf(vls, "\tinfo - return count information for specific BREP\n");
bu_vls_printf(vls, "\tinfo C [index] or C [index-index] - return information for specific BREP '3D curve'\n");
bu_vls_printf(vls, "\tinfo S [index] or S [index-index] - return information for specific BREP 'surface'\n");
bu_vls_printf(vls, "\tinfo F [index] or F [index-index]- return information for specific BREP 'face'\n");
bu_vls_printf(vls, "\tinfo T [index] or T [index-index]- return information for specific BREP 'trim'\n");
bu_vls_printf(vls, "\tinfo L [index] or L [index-index]- return information for specific BREP 'loop'\n");
bu_vls_printf(vls, "\tinfo E [index] or E [index-index]- return information for specific BREP 'edge'\n");
bu_vls_printf(vls, "\tinfo TB [index] or TB [index-index]- return information for specific BREP 'piecewise bezier trim'\n");
bu_vls_printf(vls, "\tinfo SB [index] or SB [index-index]- return information for specific BREP 'piecewise bezier surface'\n");
}
void
plot_usage(struct bu_vls *vls)
{
bu_vls_printf(vls, "mged>brep brepname.s plot\n");
bu_vls_printf(vls, "\tplot - plot entire BREP\n");
bu_vls_printf(vls, "\tplot S [index] or S [index-index]- plot specific BREP 'surface'\n");
bu_vls_printf(vls, "\tplot Suv index[-index] u v- plot specific BREP 'surface' 3d point at specified uv\n");
bu_vls_printf(vls, "\tplot UV index[-index] u1 u2 v1 v2 - plot specific BREP 'surface' 3d bounds at specified uv bounds\n");
bu_vls_printf(vls, "\tplot F [index] or F [index-index]- plot specific BREP 'face'\n");
bu_vls_printf(vls, "\tplot I [index] or I [index-index]- plot specific BREP 'isosurface'\n");
bu_vls_printf(vls, "\tplot SN [index] or SN [index-index]- plot specific BREP 'surface normal'\n");
bu_vls_printf(vls, "\tplot KN [index] or KN [index-index]- plot specific BREP 'surface knot'\n");
bu_vls_printf(vls, "\tplot F2d [index] or F2d [index-index]- plot specific BREP 'face in 2d'\n");
bu_vls_printf(vls, "\tplot SBB [index] or SBB [index-index]- plot specific BREP 'surfaceleafs'\n");
bu_vls_printf(vls, "\tplot SBB2d [index] or SBB2d [index-index]- plot specific BREP 'surfaceleafs in 2d'\n");
bu_vls_printf(vls, "\tplot TD [index] or TD [index-index]- plot specific BREP 'trim direction'\n");
bu_vls_printf(vls, "\tplot T [index] or T [index-index]- plot specific BREP 'trim'\n");
bu_vls_printf(vls, "\tplot T2d [index] or T2d [index-index]- plot specific BREP 'trim in 2d'\n");
bu_vls_printf(vls, "\tplot TBB [index] or TBB [index-index]- plot specific BREP 'trimleafs'\n");
bu_vls_printf(vls, "\tplot TBB2d [index] or TBB2d [index-index]- plot specific BREP 'trimleafs in 2d'\n");
bu_vls_printf(vls, "\tplot E [index] or E [index-index]- plot specific BREP 'edge3d'\n");
bu_vls_printf(vls, "\tplot L [index] or L [index-index]- plot specific BREP 'loop'\n");
bu_vls_printf(vls, "\tplot L2d [index] or L2d [index-index]- plot specific BREP 'loops in 2d'\n");
bu_vls_printf(vls, "\tplot SCV [index] or SCV [index-index]- plot specific BREP 'nurbs control net'\n");
}
int
single_conversion(struct rt_db_internal* intern, ON_Brep** brep, const struct db_i* dbip)
{
struct bn_tol tol;
tol.magic = BN_TOL_MAGIC;
tol.dist = BN_TOL_DIST;
tol.dist_sq = tol.dist * tol.dist;
tol.perp = SMALL_FASTF;
tol.para = 1.0 - tol.perp;
if (intern->idb_type == ID_BREP) {
// already a brep
RT_BREP_CK_MAGIC(intern->idb_ptr);
**brep = *((struct rt_brep_internal *)intern->idb_ptr)->brep;
} else if (intern->idb_type == ID_COMBINATION) {
rt_comb_brep(brep, intern, &tol, dbip);
} else if (intern->idb_meth->ft_brep != NULL) {
intern->idb_meth->ft_brep(brep, intern, &tol);
} else {
*brep = NULL;
return -1;
}
if (*brep == NULL) {
return -2;
}
return 0;
}
int
brep_conversion(struct rt_db_internal* in, struct rt_db_internal* out, const struct db_i *dbip)
{
if (out == NULL)
return -1;
ON_Brep *brep, *old;
old = brep = ON_Brep::New();
int ret;
if ((ret = single_conversion(in, &brep, dbip)) < 0) {
delete old;
return ret;
}
struct rt_brep_internal *bip_out;
BU_ALLOC(bip_out, struct rt_brep_internal);
bip_out->magic = RT_BREP_INTERNAL_MAGIC;
bip_out->brep = brep;
RT_DB_INTERNAL_INIT(out);
out->idb_ptr = (void *)bip_out;
out->idb_major_type = DB5_MAJORTYPE_BRLCAD;
out->idb_meth = &OBJ[ID_BREP];
out->idb_minor_type = ID_BREP;
return 0;
}
int
brep_conversion_tree(const struct db_i *dbip, const union tree *oldtree, union tree *newtree, const char *suffix, struct rt_wdb *wdbp, fastf_t local2mm)
{
int ret = 0;
*newtree = *oldtree;
rt_comb_internal *comb = NULL;
switch (oldtree->tr_op) {
case OP_UNION:
case OP_INTERSECT:
case OP_SUBTRACT:
case OP_XOR:
/* convert right */
comb = new rt_comb_internal;
newtree->tr_b.tb_right = new tree;
RT_TREE_INIT(newtree->tr_b.tb_right);
ret = brep_conversion_tree(dbip, oldtree->tr_b.tb_right, newtree->tr_b.tb_right, suffix, wdbp, local2mm);
if (ret) {
delete newtree->tr_b.tb_right;
break;
}
/* fall through */
case OP_NOT:
case OP_GUARD:
case OP_XNOP:
/* convert left */
BU_ALLOC(newtree->tr_b.tb_left, union tree);
RT_TREE_INIT(newtree->tr_b.tb_left);
ret = brep_conversion_tree(dbip, oldtree->tr_b.tb_left, newtree->tr_b.tb_left, suffix, wdbp, local2mm);
if (!ret) {
comb->tree = newtree;
} else {
delete newtree->tr_b.tb_left;
delete newtree->tr_b.tb_right;
}
break;
case OP_DB_LEAF:
char *tmpname;
char *oldname;
oldname = oldtree->tr_l.tl_name;
tmpname = (char*)bu_malloc(strlen(oldname)+strlen(suffix)+1, "char");
newtree->tr_l.tl_name = (char*)bu_malloc(strlen(oldname)+strlen(suffix)+1, "char");
bu_strlcpy(tmpname, oldname, strlen(oldname)+1);
bu_strlcat(tmpname, suffix, strlen(oldname)+strlen(suffix)+1);
if (db_lookup(dbip, tmpname, LOOKUP_QUIET) == RT_DIR_NULL) {
directory *dir;
dir = db_lookup(dbip, oldname, LOOKUP_QUIET);
if (dir != RT_DIR_NULL) {
rt_db_internal *intern;
BU_ALLOC(intern, struct rt_db_internal);
rt_db_get_internal(intern, dir, dbip, bn_mat_identity, &rt_uniresource);
if (BU_STR_EQUAL(intern->idb_meth->ft_name, "ID_COMBINATION")) {
ret = brep_conversion_comb(intern, tmpname, suffix, wdbp, local2mm);
if (ret) {
bu_free(tmpname, "char");
rt_db_free_internal(intern);
break;
}
bu_strlcpy(newtree->tr_l.tl_name, tmpname, strlen(tmpname)+1);
bu_free(tmpname, "char");
break;
}
// It's a primitive. If it's a b-rep object, just duplicate it. Otherwise call the
// function to convert it to b-rep.
ON_Brep** brep;
BU_ALLOC(brep, ON_Brep*);
if (BU_STR_EQUAL(intern->idb_meth->ft_name, "ID_BREP")) {
*brep = ((struct rt_brep_internal *)intern->idb_ptr)->brep->Duplicate();
} else {
*brep = ON_Brep::New();
ret = single_conversion(intern, brep, dbip);
if (ret == -1) {
bu_log("The brep conversion of %s is unsuccessful.\n", oldname);
newtree = NULL;
bu_free(tmpname, "char");
bu_free(brep, "ON_Brep*");
break;
} else if (ret == -2) {
ret = wdb_export(wdbp, tmpname, intern->idb_ptr, intern->idb_type, local2mm);
if (ret) {
bu_log("ERROR: failure writing [%s] to disk\n", tmpname);
} else {
bu_log("The conversion of [%s] (type: %s) is skipped. Implicit form remains as %s.\n",
oldname, intern->idb_meth->ft_label, tmpname);
bu_strlcpy(newtree->tr_l.tl_name, tmpname, strlen(tmpname)+1);
}
bu_free(tmpname, "char");
bu_free(brep, "ON_Brep*");
break;
}
}
if (brep != NULL) {
rt_brep_internal *bi;
BU_ALLOC(bi, struct rt_brep_internal);
bi->magic = RT_BREP_INTERNAL_MAGIC;
bi->brep = *brep;
ret = wdb_export(wdbp, tmpname, (void *)bi, ID_BREP, local2mm);
if (ret) {
bu_log("ERROR: failure writing [%s] to disk\n", tmpname);
} else {
bu_log("%s is made.\n", tmpname);
bu_strlcpy(newtree->tr_l.tl_name, tmpname, strlen(tmpname)+1);
}
} else {
bu_log("The brep conversion of %s is unsuccessful.\n", oldname);
newtree = NULL;
ret = -1;
}
bu_free(brep, "ON_Brep*");
} else {
bu_log("Cannot find %s.\n", oldname);
newtree = NULL;
ret = -1;
}
} else {
bu_log("%s already exists.\n", tmpname);
bu_strlcpy(newtree->tr_l.tl_name, tmpname, strlen(tmpname)+1);
}
bu_free(tmpname, "char");
break;
default:
bu_log("OPCODE NOT IMPLEMENTED: %d\n", oldtree->tr_op);
ret = -1;
}
if (comb)
delete comb;
return ret;
}
int
brep_conversion_comb(struct rt_db_internal *old_internal, const char *name, const char *suffix, struct rt_wdb *wdbp, fastf_t local2mm)
{
RT_CK_COMB(old_internal->idb_ptr);
rt_comb_internal *comb_internal;
comb_internal = (rt_comb_internal *)old_internal->idb_ptr;
int ret;
if (comb_internal->tree == NULL) {
// Empty tree. Also output an empty comb.
ret = wdb_export(wdbp, name, comb_internal, ID_COMBINATION, local2mm);
if (ret)
return ret;
bu_log("%s is made.\n", name);
return 0;
}
RT_CK_TREE(comb_internal->tree);
union tree *oldtree = comb_internal->tree;
rt_comb_internal *new_internal;
BU_ALLOC(new_internal, struct rt_comb_internal);
*new_internal = *comb_internal;
BU_ALLOC(new_internal->tree, union tree);
RT_TREE_INIT(new_internal->tree);
union tree *newtree = new_internal->tree;
ret = brep_conversion_tree(wdbp->dbip, oldtree, newtree, suffix, wdbp, local2mm);
if (!ret) {
ret = wdb_export(wdbp, name, (void *)new_internal, ID_COMBINATION, local2mm);
} else {
bu_free(new_internal->tree, "tree");
bu_free(new_internal, "rt_comb_internal");
}
if (!ret)
bu_log("%s is made.\n", name);
return ret;
}
int
brep_translate_scv(
ON_Brep *brep,
int surface_index,
int i,
int j,
fastf_t dx,
fastf_t dy,
fastf_t dz)
{
ON_NurbsSurface *nurbsSurface = NULL;
if (surface_index < 0 || surface_index >= brep->m_S.Count()) {
bu_log("brep_translate_scv: invalid surface index %d\n", surface_index);
return -1;
}
ON_Surface *surface = brep->m_S[surface_index];
if (surface) {
nurbsSurface = dynamic_cast<ON_NurbsSurface *>(surface);
} else {
return -1;
}
double *cv = NULL;
if (nurbsSurface) {
cv = nurbsSurface->CV(i, j);
} else {
return -2;
}
if (cv) {
ON_3dPoint newPt;
newPt.x = cv[X] + dx;
newPt.y = cv[Y] + dy;
newPt.z = cv[Z] + dz;
nurbsSurface->SetCV(i, j, newPt);
} else {
return -3;
}
return 0;
}
int
translate_command(
struct bu_vls *result,
struct brep_specific *bs,
int argc,
const char *argv[])
{
// 0 1 2 3 4 5 6 7 8 9
// brep <solid_name> translate SCV index i j dx dy dz
if (argc != 10) {
return -1;
}
ON_Brep *brep = bs->brep;
if (BU_STR_EQUAL(argv[3], "SCV")) {
int surface_index = atoi(argv[4]);
int i = atoi(argv[5]);
int j = atoi(argv[6]);
fastf_t dx = atof(argv[7]);
fastf_t dy = atof(argv[8]);
fastf_t dz = atof(argv[9]);
int ret = brep_translate_scv(brep, surface_index, i, j, dx, dy, dz);
switch (ret) {
case -1:
bu_vls_printf(result, "No surface %d.\n", surface_index);
break;
case -2:
bu_vls_printf(result, "Surface %d is not a NURBS surface.\n", surface_index);
break;
case -3:
bu_vls_printf(result, "No control vertex (%d, %d).\n", i, j);
}
return ret;
} else {
return -1;
}
return 0;
}
int
brep_command(struct bu_vls *vls, const char *solid_name, struct bu_color *color, const struct rt_tess_tol *ttol, const struct bn_tol *tol, struct brep_specific* bs, struct rt_brep_internal* bi, struct bn_vlblock *vbp, int argc, const char *argv[], char *commtag)
{
const char *command;
int ret = 0;
if (argc == 2)
command = "info";
else
command = (const char *) argv[2];
snprintf(commtag, 64, "_BC_"); //default name pre/postfix tag for fake bn_vlblock solid
if (BU_STR_EQUAL(command, "info")) {
if (argc == 3) {
ret = brep_info(bs, vls);
info_usage(vls);
} else if (argc == 4) {
const char *part = argv[3];
ON_Brep *brep = bs->brep;
if (BU_STR_EQUAL(part, "S")) {
for (int i = 0; i < brep->m_S.Count(); ++i) {
ret = brep_surface_info(bs, vls, i);
}
} else if (BU_STR_EQUAL(part, "F")) {
for (int i = 0; i < brep->m_F.Count(); ++i) {
ret = brep_face_info(bs, vls, i);
}
} else if (BU_STR_EQUAL(part, "T")) {
for (int i = 0; i < brep->m_T.Count(); ++i) {
ret = brep_trim_info(bs, vls, i);
}
} else if (BU_STR_EQUAL(part, "E")) {
for (int i = 0; i < brep->m_E.Count(); ++i) {
ret = brep_edge_info(bs, vls, i);
}
} else if (BU_STR_EQUAL(part, "SB")) {
for (int i = 0; i < brep->m_S.Count(); ++i) {
ret = brep_surface_bezier_info(bs, vls, i);
}
} else if (BU_STR_EQUAL(part, "TB")) {
for (int i = 0; i < brep->m_T.Count(); ++i) {
ret = brep_trim_bezier_info(bs, vls, i);
}
} else if (BU_STR_EQUAL(part, "C")) {
for (int i = 0; i < brep->m_C3.Count(); ++i) {
ret = brep_curve_info(bs, vls, i);
}
}
} else if (argc == 5) {
const char *part = argv[3];
const char *strindex = argv[4];
std::set<int> elements;
std::set<int>::iterator e_it;
if (BU_STR_EQUAL(strindex, "all")) {
ON_Brep *brep = bs->brep;
if (BU_STR_EQUAL(part, "S")) {
for (int i = 0; i < brep->m_S.Count(); ++i) {
ret = brep_surface_info(bs, vls, i);
}
} else if (BU_STR_EQUAL(part, "F")) {
for (int i = 0; i < brep->m_F.Count(); ++i) {
ret = brep_face_info(bs, vls, i);
}
} else if (BU_STR_EQUAL(part, "T")) {
for (int i = 0; i < brep->m_T.Count(); ++i) {
ret = brep_trim_info(bs, vls, i);
}
} else if (BU_STR_EQUAL(part, "E")) {
for (int i = 0; i < brep->m_E.Count(); ++i) {
ret = brep_edge_info(bs, vls, i);
}
} else if (BU_STR_EQUAL(part, "L")) {
for (int i = 0; i < brep->m_L.Count(); ++i) {
ret = brep_loop_info(bs, vls, i);
}
} else if (BU_STR_EQUAL(part, "SB")) {
for (int i = 0; i < brep->m_S.Count(); ++i) {
ret = brep_surface_bezier_info(bs, vls, i);
}
} else if (BU_STR_EQUAL(part, "TB")) {
for (int i = 0; i < brep->m_T.Count(); ++i) {
ret = brep_trim_bezier_info(bs, vls, i);
}
} else if (BU_STR_EQUAL(part, "C")) {
for (int i = 0; i < brep->m_C3.Count(); ++i) {
ret = brep_curve_info(bs, vls, i);
}
}
} else if (BU_STR_EQUAL(strindex, "?")) {
info_usage(vls);
} else {
ON_Brep *brep = bs->brep;
const char *dash = strchr(strindex, '-');
const char *comma = strchr(strindex, ',');
if (dash) {
int startindex = -1;
int endindex = -1;
struct bu_vls tmpstr = BU_VLS_INIT_ZERO;
bu_vls_strcpy(&tmpstr, strindex);
bu_vls_trunc(&tmpstr, dash - strindex);
startindex = atoi(bu_vls_addr(&tmpstr));
bu_vls_strcpy(&tmpstr, ++dash);
endindex = atoi(bu_vls_addr(&tmpstr));
bu_vls_free(&tmpstr);
for (int elem = startindex; elem <= endindex; elem++) {
elements.insert(elem);
}
} else if (comma) {
struct bu_vls tmpstr = BU_VLS_INIT_ZERO;
bu_vls_strcpy(&tmpstr, strindex);
while (strlen(bu_vls_addr(&tmpstr)) > 0) {
struct bu_vls tmpstr2 = BU_VLS_INIT_ZERO;
int idx = 0;
bu_vls_strcpy(&tmpstr2, bu_vls_addr(&tmpstr));
bu_vls_trunc(&tmpstr2, comma - bu_vls_addr(&tmpstr));
idx = atoi(bu_vls_addr(&tmpstr2));
bu_vls_free(&tmpstr2);
elements.insert(idx);
int stp = 0;
while (idx >= 10) {
int idx2 = idx / 10;
idx = idx2;
stp++;
}
bu_vls_nibble(&tmpstr, stp+2);
comma = strchr(bu_vls_addr(&tmpstr), ',');
}
bu_vls_free(&tmpstr);
} else {
int idx = atoi(strindex);
elements.insert(idx);
}
if (BU_STR_EQUAL(part, "S")) {
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
if (*e_it < brep->m_S.Count()) ret = brep_surface_info(bs, vls, (*e_it));
}
} else if (BU_STR_EQUAL(part, "F")) {
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
if (*e_it < brep->m_F.Count()) ret = brep_face_info(bs, vls, (*e_it));
}
} else if (BU_STR_EQUAL(part, "T")) {
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
if (*e_it < brep->m_T.Count()) ret = brep_trim_info(bs, vls, (*e_it));
}
} else if (BU_STR_EQUAL(part, "E")) {
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
if (*e_it < brep->m_E.Count()) ret = brep_edge_info(bs, vls, (*e_it));
}
} else if (BU_STR_EQUAL(part, "L")) {
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
if (*e_it < brep->m_L.Count()) ret = brep_loop_info(bs, vls, (*e_it));
}
} else if (BU_STR_EQUAL(part, "SB")) {
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
if (*e_it < brep->m_S.Count()) ret = brep_surface_bezier_info(bs, vls, (*e_it));
}
} else if (BU_STR_EQUAL(part, "TB")) {
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
if (*e_it < brep->m_T.Count()) ret = brep_trim_bezier_info(bs, vls, (*e_it));
}
} else if (BU_STR_EQUAL(part, "C")) {
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
if (*e_it < brep->m_C3.Count()) ret = brep_curve_info(bs, vls, (*e_it));
}
}
}
}
} else if (BU_STR_EQUAL(command, "plot")) {
if (argc == 3) {
plot_usage(vls);
} else if (argc >= 4) {
const char *part = argv[3];
int numpoints = -1;
int plotres = 100;
std::set<int> elements;
std::set<int>::iterator e_it;
if (argc == 6) {
const char *strres = argv[5];
plotres = numpoints = atoi(strres);
}
if (argc >= 5) {
const char *str = argv[4];
if (BU_STR_EQUAL(str, "all")) {
ON_Brep *brep = bs->brep;
if (BU_STR_EQUAL(part, "S")) {
for (int i = 0; i < brep->m_S.Count(); ++i) {
elements.insert(i);
}
} else if (BU_STR_EQUAL(part, "F")) {
for (int i = 0; i < brep->m_F.Count(); ++i) {
elements.insert(i);
}
} else if (BU_STR_EQUAL(part, "T")) {
for (int i = 0; i < brep->m_T.Count(); ++i) {
elements.insert(i);
}
} else if (BU_STR_EQUAL(part, "E")) {
for (int i = 0; i < brep->m_E.Count(); ++i) {
elements.insert(i);
}
} else if (BU_STR_EQUAL(part, "L")) {
for (int i = 0; i < brep->m_L.Count(); ++i) {
elements.insert(i);
}
} else if (BU_STR_EQUAL(part, "SB")) {
for (int i = 0; i < brep->m_S.Count(); ++i) {
elements.insert(i);
}
} else if (BU_STR_EQUAL(part, "TB")) {
for (int i = 0; i < brep->m_T.Count(); ++i) {
elements.insert(i);
}
} else if (BU_STR_EQUAL(part, "C")) {
for (int i = 0; i < brep->m_C3.Count(); ++i) {
elements.insert(i);
}
}
} else if (BU_STR_EQUAL(str, "?")) {
plot_usage(vls);
} else {
if (!str || strlen(str) == 0) {
plot_usage(vls);
} else {
const char *dash = strchr(str, '-');
const char *comma = strchr(str, ',');
if (dash) {
int startindex = -1;
int endindex = -1;
struct bu_vls tmpstr = BU_VLS_INIT_ZERO;
bu_vls_strcpy(&tmpstr, str);
bu_vls_trunc(&tmpstr, dash - str);
startindex = atoi(bu_vls_addr(&tmpstr));
bu_vls_strcpy(&tmpstr, ++dash);
endindex = atoi(bu_vls_addr(&tmpstr));
bu_vls_free(&tmpstr);
for (int elem = startindex; elem <= endindex; elem++) {
elements.insert(elem);
}
} else if (comma) {
struct bu_vls tmpstr = BU_VLS_INIT_ZERO;
bu_vls_strcpy(&tmpstr, str);
while (strlen(bu_vls_addr(&tmpstr)) > 0) {
struct bu_vls tmpstr2 = BU_VLS_INIT_ZERO;
int idx = 0;
bu_vls_strcpy(&tmpstr2, bu_vls_addr(&tmpstr));
bu_vls_trunc(&tmpstr2, comma - bu_vls_addr(&tmpstr));
idx = atoi(bu_vls_addr(&tmpstr2));
bu_vls_free(&tmpstr2);
elements.insert(idx);
int stp = 0;
while (idx >= 10) {
int idx2 = idx / 10;
idx = idx2;
stp++;
}
bu_vls_nibble(&tmpstr, stp+2);
comma = strchr(bu_vls_addr(&tmpstr), ',');
}
bu_vls_free(&tmpstr);
} else {
int idx = atoi(str);
elements.insert(idx);
}
}
}
}
if (BU_STR_EQUAL(part, "S")) {
snprintf(commtag, 64, "_BC_S_");
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
ret = brep_surface_plot(vls, bs, bi, vbp, (*e_it), color, plotres);
}
} else if (BU_STR_EQUAL(part, "Suv")) {
double u = 0.0;
double v = 0.0;
if (argc == 7) {
const char *ustr = argv[5];
const char *vstr = argv[6];
u = atof(ustr);
v = atof(vstr);
}
snprintf(commtag, 64, "_BC_Suv_");
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
ret = brep_surface_uv_plot(vls, bs, bi, vbp, (*e_it), u, v);
}
} else if (BU_STR_EQUAL(part, "UV")) {
ON_Interval u;
ON_Interval v;
if (argc == 9) {
const char *u1str = argv[5];
const char *u2str = argv[6];
const char *v1str = argv[7];
const char *v2str = argv[8];
u.m_t[0] = atof(u1str);
u.m_t[1] = atof(u2str);
v.m_t[0] = atof(v1str);
v.m_t[1] = atof(v2str);
}
snprintf(commtag, 64, "_BC_UV_");
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
ret = brep_surface_uv_plot(vls, bs, bi, vbp, (*e_it), u, v);
}
} else if (BU_STR_EQUAL(part, "I")) {
snprintf(commtag, 64, "_BC_I_");
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
ret = brep_isosurface_plot(vls, bs, bi, vbp, (*e_it), plotres);
}
} else if (BU_STR_EQUAL(part, "SN")) {
snprintf(commtag, 64, "_BC_SN_");
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
ret = brep_surface_normal_plot(vls, bs, bi, vbp, (*e_it),
plotres);
}
} else if (BU_STR_EQUAL(part, "KN2d")) {
snprintf(commtag, 64, "_BC_KN2d_");
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
ret = brep_surface_knot_plot(vls, bs, bi, vbp, (*e_it), false);
}
} else if (BU_STR_EQUAL(part, "KN")) {
snprintf(commtag, 64, "_BC_KN_");
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
ret = brep_surface_knot_plot(vls, bs, bi, vbp, (*e_it), true);
}
} else if (BU_STR_EQUAL(part, "F")) {
snprintf(commtag, 64, "_BC_F_");
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
ret = brep_facetrim_plot(vls, bs, bi, vbp, (*e_it), color, plotres,
true);
}
} else if (BU_STR_EQUAL(part, "F2d")) {
snprintf(commtag, 64, "_BC_F2d_");
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
ret = brep_facetrim_plot(vls, bs, bi, vbp, (*e_it), color, plotres,
false);
}
} else if (BU_STR_EQUAL(part, "FCDT")) {
snprintf(commtag, 64, "_BC_FCDT_");
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
ret = brep_facecdt_plot(vls, solid_name, ttol, tol, bs, bi, vbp, (*e_it), 0);
}
} else if (BU_STR_EQUAL(part, "FCDTw")) {
snprintf(commtag, 64, "_BC_FCDT_");
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
ret = brep_facecdt_plot(vls, solid_name, ttol, tol, bs, bi, vbp, (*e_it), 1, numpoints);
}
} else if (BU_STR_EQUAL(part, "FCDT2d")) {
snprintf(commtag, 64, "_BC_FCDT2d_");
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
ret = brep_facecdt_plot(vls, solid_name, ttol, tol, bs, bi, vbp, (*e_it), 2);
}
} else if (BU_STR_EQUAL(part, "FCDTm2d")) {
snprintf(commtag, 64, "_BC_FCDTm2d_");
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
ret = brep_facecdt_plot(vls, solid_name, ttol, tol, bs, bi, vbp, (*e_it), 3, numpoints);
}
} else if (BU_STR_EQUAL(part, "FCDTp2d")) {
snprintf(commtag, 64, "_BC_FCDTp2d_");
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
ret = brep_facecdt_plot(vls, solid_name, ttol, tol, bs, bi, vbp, (*e_it), 4, numpoints);
}
} else if (BU_STR_EQUAL(part, "SBB")) {
snprintf(commtag, 64, "_BC_SBB_");
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
ret = brep_surfaceleafs_plot(vls, bs, bi, vbp, true, (*e_it),
plotres);
}
} else if (BU_STR_EQUAL(part, "SBB2d")) {
snprintf(commtag, 64, "_BC_SBB2d_");
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
ret = brep_surfaceleafs_plot(vls, bs, bi, vbp, false, (*e_it),
plotres);
}
} else if (BU_STR_EQUAL(part, "TD")) {
snprintf(commtag, 64, "_BC_TD_");
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
ret = brep_trim_direction_plot(vls, bs, bi, vbp, (*e_it),
plotres);
}
} else if (BU_STR_EQUAL(part, "T")) {
snprintf(commtag, 64, "_BC_T_");
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
ret = brep_trim_plot(vls, bs, bi, vbp, (*e_it), color, plotres, true);
}
} else if (BU_STR_EQUAL(part, "T2d")) {
snprintf(commtag, 64, "_BC_T2d_");
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
ret = brep_trim_plot(vls, bs, bi, vbp, (*e_it), color, plotres, false);
}
} else if (BU_STR_EQUAL(part, "L")) {
snprintf(commtag, 64, "_BC_L_");
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
ret = brep_loop_plot(vls, bs, bi, vbp, (*e_it), plotres, true);
}
} else if (BU_STR_EQUAL(part, "L2d")) {
snprintf(commtag, 64, "_BC_L2d_");
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
ret = brep_loop_plot(vls, bs, bi, vbp, (*e_it), plotres, false);
}
} else if (BU_STR_EQUAL(part, "TBB")) {
snprintf(commtag, 64, "_BC_TBB_");
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
ret = brep_trimleafs_plot(vls, bs, bi, vbp, true, (*e_it),
plotres);
}
} else if (BU_STR_EQUAL(part, "TBB2d")) {
snprintf(commtag, 64, "_BC_TBB2d_");
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
ret = brep_trimleafs_plot(vls, bs, bi, vbp, false, (*e_it),
plotres);
}
} else if (BU_STR_EQUAL(part, "E")) {
snprintf(commtag, 64, "_BC_E_");
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
ret = brep_edge3d_plot(vls, bs, bi, vbp, color, (*e_it), plotres);
}
} else if (BU_STR_EQUAL(part, "SCV")) {
snprintf(commtag, 64, "_BC_SCV_");
for (e_it = elements.begin(); e_it != elements.end(); e_it++) {
ret = brep_surface_cv_plot(vls, bs, bi, vbp, (*e_it));
}
}
}
} else if (BU_STR_EQUAL(command, "translate")) {
ret = translate_command(vls, bs, argc, argv);
}
return ret;
}
int
brep_intersect_point_point(struct rt_db_internal *intern1, struct rt_db_internal *intern2, int i, int j)
{
RT_CK_DB_INTERNAL(intern1);
RT_CK_DB_INTERNAL(intern2);
struct rt_brep_internal *bi1, *bi2;
bi1 = (struct rt_brep_internal *)intern1->idb_ptr;
bi2 = (struct rt_brep_internal *)intern2->idb_ptr;
RT_BREP_CK_MAGIC(bi1);
RT_BREP_CK_MAGIC(bi2);
ON_Brep *brep1 = bi1->brep;
ON_Brep *brep2 = bi2->brep;
if (i < 0 || i >= brep1->m_V.Count() || j < 0 || j >= brep2->m_V.Count()) {
bu_log("Out of range: \n");
bu_log("\t0 <= i <= %d\n", brep1->m_V.Count() - 1);
bu_log("\t0 <= j <= %d\n", brep2->m_V.Count() - 1);
return -1;
}
ON_ClassArray<ON_PX_EVENT> events;
if (ON_Intersect(brep1->m_V[i].Point(), brep2->m_V[j].Point(), events)) {
for (int k = 0; k < events.Count(); k++) {
ON_wString wstr;
ON_TextLog textlog(wstr);
events[k].Dump(textlog);
ON_String str = ON_String(wstr);
bu_log("Intersection event %d:\n %s", k + 1, str.Array());
}
} else {
bu_log("No intersection.\n");
}
return 0;
}
int
brep_intersect_point_curve(struct rt_db_internal *intern1, struct rt_db_internal *intern2, int i, int j)
{
RT_CK_DB_INTERNAL(intern1);
RT_CK_DB_INTERNAL(intern2);
struct rt_brep_internal *bi1, *bi2;
bi1 = (struct rt_brep_internal *)intern1->idb_ptr;
bi2 = (struct rt_brep_internal *)intern2->idb_ptr;
RT_BREP_CK_MAGIC(bi1);
RT_BREP_CK_MAGIC(bi2);
ON_Brep *brep1 = bi1->brep;
ON_Brep *brep2 = bi2->brep;
if (i < 0 || i >= brep1->m_V.Count() || j < 0 || j >= brep2->m_C3.Count()) {
bu_log("Out of range: \n");
bu_log("\t0 <= i <= %d\n", brep1->m_V.Count() - 1);
bu_log("\t0 <= j <= %d\n", brep2->m_C3.Count() - 1);
return -1;
}
ON_ClassArray<ON_PX_EVENT> events;
if (ON_Intersect(brep1->m_V[i].Point(), *(brep2->m_C3[j]), events)) {
for (int k = 0; k < events.Count(); k++) {
ON_wString wstr;
ON_TextLog textlog(wstr);
events[k].Dump(textlog);
ON_String str = ON_String(wstr);
bu_log("Intersection event %d:\n %s", k + 1, str.Array());
}
} else {
bu_log("No intersection.\n");
}
return 0;
}
int
brep_intersect_point_surface(struct rt_db_internal *intern1, struct rt_db_internal *intern2, int i, int j)
{
RT_CK_DB_INTERNAL(intern1);
RT_CK_DB_INTERNAL(intern2);
struct rt_brep_internal *bi1, *bi2;
bi1 = (struct rt_brep_internal *)intern1->idb_ptr;
bi2 = (struct rt_brep_internal *)intern2->idb_ptr;
RT_BREP_CK_MAGIC(bi1);
RT_BREP_CK_MAGIC(bi2);
ON_Brep *brep1 = bi1->brep;
ON_Brep *brep2 = bi2->brep;
if (i < 0 || i >= brep1->m_V.Count() || j < 0 || j >= brep2->m_S.Count()) {
bu_log("Out of range: \n");
bu_log("\t0 <= i <= %d\n", brep1->m_V.Count() - 1);
bu_log("\t0 <= j <= %d\n", brep2->m_S.Count() - 1);
return -1;
}
ON_ClassArray<ON_PX_EVENT> events;
if (ON_Intersect(brep1->m_V[i].Point(), *(brep2->m_S[j]), events)) {
for (int k = 0; k < events.Count(); k++) {
ON_wString wstr;
ON_TextLog textlog(wstr);
events[k].Dump(textlog);
ON_String str = ON_String(wstr);
bu_log("Intersection event %d:\n %s", k + 1, str.Array());
}
} else {
bu_log("No intersection.\n");
}
return 0;
}
int
brep_intersect_curve_curve(struct rt_db_internal *intern1, struct rt_db_internal *intern2, int i, int j)
{
RT_CK_DB_INTERNAL(intern1);
RT_CK_DB_INTERNAL(intern2);
struct rt_brep_internal *bi1, *bi2;
bi1 = (struct rt_brep_internal *)intern1->idb_ptr;
bi2 = (struct rt_brep_internal *)intern2->idb_ptr;
RT_BREP_CK_MAGIC(bi1);
RT_BREP_CK_MAGIC(bi2);
ON_Brep *brep1 = bi1->brep;
ON_Brep *brep2 = bi2->brep;
if (i < 0 || i >= brep1->m_C3.Count() || j < 0 || j >= brep2->m_C3.Count()) {
bu_log("Out of range: \n");
bu_log("\t0 <= i <= %d\n", brep1->m_C3.Count() - 1);
bu_log("\t0 <= j <= %d\n", brep2->m_C3.Count() - 1);
return -1;
}
ON_SimpleArray<ON_X_EVENT> events;
if (ON_Intersect(brep1->m_C3[i], brep2->m_C3[j], events)) {
for (int k = 0; k < events.Count(); k++) {
ON_wString wstr;
ON_TextLog textlog(wstr);
events[k].Dump(textlog);
ON_String str = ON_String(wstr);
bu_log("Intersection event %d:\n %s", k + 1, str.Array());
}
} else {
bu_log("No intersection.\n");
}
return 0;
}
int
brep_intersect_curve_surface(struct rt_db_internal *intern1, struct rt_db_internal *intern2, int i, int j)
{
RT_CK_DB_INTERNAL(intern1);
RT_CK_DB_INTERNAL(intern2);
struct rt_brep_internal *bi1, *bi2;
bi1 = (struct rt_brep_internal *)intern1->idb_ptr;
bi2 = (struct rt_brep_internal *)intern2->idb_ptr;
RT_BREP_CK_MAGIC(bi1);
RT_BREP_CK_MAGIC(bi2);
ON_Brep *brep1 = bi1->brep;
ON_Brep *brep2 = bi2->brep;
if (i < 0 || i >= brep1->m_C3.Count() || j < 0 || j >= brep2->m_S.Count()) {
bu_log("Out of range: \n");
bu_log("\t0 <= i <= %d\n", brep1->m_C3.Count() - 1);
bu_log("\t0 <= j <= %d\n", brep2->m_S.Count() - 1);
return -1;
}
ON_SimpleArray<ON_X_EVENT> events;
if (ON_Intersect(brep1->m_C3[i], brep2->m_S[j], events)) {
for (int k = 0; k < events.Count(); k++) {
ON_wString wstr;
ON_TextLog textlog(wstr);
events[k].Dump(textlog);
ON_String str = ON_String(wstr);
bu_log("Intersection event %d:\n %s", k + 1, str.Array());
}
} else {
bu_log("No intersection.\n");
}
return 0;
}
int
brep_intersect_surface_surface(struct rt_db_internal *intern1, struct rt_db_internal *intern2, int i, int j, struct bn_vlblock *vbp)
{
RT_CK_DB_INTERNAL(intern1);
RT_CK_DB_INTERNAL(intern2);
struct rt_brep_internal *bi1, *bi2;
bi1 = (struct rt_brep_internal *)intern1->idb_ptr;
bi2 = (struct rt_brep_internal *)intern2->idb_ptr;
RT_BREP_CK_MAGIC(bi1);
RT_BREP_CK_MAGIC(bi2);
ON_Brep *brep1 = bi1->brep;
ON_Brep *brep2 = bi2->brep;
ON_NurbsSurface surf1;
ON_NurbsSurface surf2;
if (i < 0 || i >= brep1->m_S.Count() || j < 0 || j >= brep2->m_S.Count()) {
bu_log("Out of range: \n");
bu_log("\t0 <= i <= %d\n", brep1->m_S.Count() - 1);
bu_log("\t0 <= j <= %d\n", brep2->m_S.Count() - 1);
return -1;
}
brep1->m_S[i]->GetNurbForm(surf1);
brep2->m_S[j]->GetNurbForm(surf2);
ON_ClassArray<ON_SSX_EVENT> events;
if (ON_Intersect(&surf1, &surf2, events) < 0) {
bu_log("Intersection failed\n");
return -1;
}
plotsurface(surf1, vbp, 100, 10, PURERED);
plotsurface(surf2, vbp, 100, 10, BLUE);
// Plot the intersection curves (or points) (3D and 2D)
for (int k = 0; k < events.Count(); k++) {
switch (events[k].m_type) {
case ON_SSX_EVENT::ssx_overlap:
case ON_SSX_EVENT::ssx_tangent:
case ON_SSX_EVENT::ssx_transverse:
plotcurveonsurface(events[k].m_curveA, &surf1, vbp, 1000, PEACH);
plotcurveonsurface(events[k].m_curveB, &surf2, vbp, 1000, DARKVIOLET);
plotcurve(*(events[k].m_curve3d), vbp, 1000, GREEN);
break;
case ON_SSX_EVENT::ssx_tangent_point:
case ON_SSX_EVENT::ssx_transverse_point:
plotpoint(surf1.PointAt(events[k].m_pointA.x, events[k].m_pointB.y), vbp, PEACH);
plotpoint(surf2.PointAt(events[k].m_pointB.x, events[k].m_pointB.y), vbp, DARKVIOLET);
plotpoint(events[k].m_point3d, vbp, GREEN);
break;
default:
break;
}
}
return 0;
}
/** @} */
/*
* Local Variables:
* mode: C++
* tab-width: 8
* c-basic-offset: 4
* indent-tabs-mode: t
* c-file-style: "stroustrup"
* End:
* ex: shiftwidth=4 tabstop=8
*/
| 29.751127 | 288 | 0.607255 | [
"cad",
"object",
"vector",
"3d",
"solid"
] |
abd35a554b3d2521fb0891e2f7b06cf08876ad86 | 70,601 | cpp | C++ | src/CPMDecorator/CPMDecorator/ModelComplexPart.cpp | lefevre-fraser/openmeta-mms | 08f3115e76498df1f8d70641d71f5c52cab4ce5f | [
"MIT"
] | null | null | null | src/CPMDecorator/CPMDecorator/ModelComplexPart.cpp | lefevre-fraser/openmeta-mms | 08f3115e76498df1f8d70641d71f5c52cab4ce5f | [
"MIT"
] | null | null | null | src/CPMDecorator/CPMDecorator/ModelComplexPart.cpp | lefevre-fraser/openmeta-mms | 08f3115e76498df1f8d70641d71f5c52cab4ce5f | [
"MIT"
] | null | null | null | //################################################################################################
//
// Model complex part class (decorator part)
// ModelComplexPart.cpp
//
//################################################################################################
#include "StdAfx.h"
#include "ModelComplexPart.h"
#include "DecoratorExceptions.h"
#include "Resource.h"
#include "TextPart.h"
#include "PortLabelPart.h"
#include <algorithm>
#include <new>
#include <io.h>
#define MAXIMUM_ICON_SIZE_NONOVERLAPPING_WITH_PORT_LABELS 250
static const int cornerRadius = 15;
namespace Decor{
bool operator==(const _bstr_t& a, const wchar_t* b) {
if (a.length() == 0) {
return wcslen(b) == 0;
}
return wcscmp(a, b) == 0;
}
struct {
const wchar_t* kind;
const wchar_t* fileAttribute;
} PETKinds[] = {
{ L"AnalysisBlock", L"PyFilename" },
{ L"ExcelWrapper", L"ExcelFilename" },
{ L"MATLABWrapper", L"MFilename" },
{ L"PythonWrapper", L"PyFilename" },
};
const wchar_t* PETWrapperLookup(_bstr_t& kind) {
for (size_t i = 0; i < _countof(PETKinds); i++) {
if (kind == PETKinds[i].kind) {
return PETKinds[i].fileAttribute;
}
}
return NULL;
}
void invokeCyPhyPETMethod(IMgaFCO* fco, const wchar_t* methodName) {
CComDispatchDriver dd;
if (SUCCEEDED(dd.CoCreateInstance(L"MGA.Interpreter.CyPhyPET", nullptr, CLSCTX_INPROC))) {
IMgaProjectPtr proj = fco->Project;
CComPtr<IMgaTerritory> terr;
proj->BeginTransactionInNewTerr(TRANSACTION_NON_NESTED, &terr);
CComVariant variantFCO = (IDispatch*)fco;
dd.Invoke1(methodName, &variantFCO);
proj->CommitTransaction();
}
};
void PETRefreshButtonClicked(IMgaFCO* fco) {
invokeCyPhyPETMethod(fco, L"RefreshButtonClicked");
}
void PETEditButtonClicked(IMgaFCO* fco) {
invokeCyPhyPETMethod(fco, L"EditButtonClicked");
}
class CPMPortLabelPart : public PortLabelPart
{
public:
CString GetText() const {
return m_vecText[0];
}
};
//################################################################################################
//
// CLASS : PortPartData
//
//################################################################################################
class PortPartData {
public:
PortPartData(PortPart* pD, CComPtr<IMgaMetaPart>& pPart, CComPtr<IMgaFCO>& pFCO):
portPart(pD), spPart(pPart), spFCO(pFCO) {};
~PortPartData() { if(portPart) delete portPart; };
void Destroy() { if(portPart) portPart->Destroy(); }
PortPart* portPart;
CComPtr<IMgaMetaPart> spPart;
CComPtr<IMgaFCO> spFCO;
};
//################################################################################################
//
// CLASS : ModelComplexPart
//
//################################################################################################
ModelComplexPart::ModelComplexPart(PartBase* pPart, CComPtr<IMgaCommonDecoratorEvents>& eventSink):
TypeableBitmapPart (pPart, eventSink),
m_iMaxPortTextLength (MAX_PORT_LENGTH),
m_crPortText (COLOR_BLACK),
m_bPortLabelInside (true),
m_iLongestPortTextLength (0),
m_bStretch(false)
{
m_prominentAttrsCY = 0;
m_prominentAttrsNamesCX = 0;
m_prominentAttrsValuesCX = 0;
m_LeftPortsMaxLabelLength = 0;
m_RightPortsMaxLabelLength = 0;
}
ModelComplexPart::~ModelComplexPart()
{
m_LeftPorts.clear();
m_RightPorts.clear();
for (std::vector<PortPartData*>::iterator ii = m_AllPorts.begin(); ii != m_AllPorts.end(); ++ii)
delete (*ii);
m_AllPorts.clear();
}
void ModelComplexPart::Initialize(CComPtr<IMgaProject>& pProject, CComPtr<IMgaMetaPart>& pPart, CComPtr<IMgaFCO>& pFCO)
{
// Akos: when this gets called, the left and right ports list should not exist
/*
for (std::vector<Decor::PortPart*>::iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
(*ii)->Initialize(pProject, pPart, pFCO);
}
for (std::vector<Decor::PortPart*>::iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
(*ii)->Initialize(pProject, pPart, pFCO);
}*/
TypeableBitmapPart::Initialize(pProject, pPart, pFCO);
embelishment = Embelishment::NONE;
if (pFCO)
{
IMgaReferencePtr ref = pFCO.p;
std::wstring kinds[] = { // keep these alphabetical
L"BuiltDesignEntityRef",
L"ComponentAssemblyRef",
L"ComponentRef",
L"DesignEntityRef",
L"TestBenchRef",
L"TestInjectionPoint",
L"TopLevelSystemUnderTest",
};
if (ref && std::binary_search(kinds, kinds + (sizeof(kinds)/sizeof(kinds[0])), std::wstring(ref->Meta->Name),
[](const std::wstring& s1, const std::wstring& s2) { return wcscmp(s1.c_str(), s2.c_str()) < 0; }))
{
if (ref->Referred)
embelishment = Embelishment::REFERENCE;
else
embelishment = Embelishment::NULL_REFERENCE;
}
}
}
void ModelComplexPart::Destroy()
{
for (std::vector<PortPartData*>::iterator ii = m_AllPorts.begin(); ii != m_AllPorts.end(); ++ii)
(*ii)->Destroy();
TypeableBitmapPart::Destroy();
}
CString ModelComplexPart::GetMnemonic(void) const
{
return TypeableBitmapPart::GetMnemonic();
}
feature_code ModelComplexPart::GetFeatures(void) const
{
feature_code featureCodes = 0;
for (std::vector<Decor::PortPart*>::const_iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
feature_code portFeatureCodes = (*ii)->GetFeatures();
featureCodes |= portFeatureCodes;
}
for (std::vector<Decor::PortPart*>::const_iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
feature_code portFeatureCodes = (*ii)->GetFeatures();
featureCodes |= portFeatureCodes;
}
feature_code partFeatureCodes = TypeableBitmapPart::GetFeatures();
featureCodes |= partFeatureCodes;
return featureCodes;
}
void ModelComplexPart::SetParam(const CString& strName, VARIANT vValue)
{
CString pName(DEC_CONNECTED_PORTS_ONLY_PARAM);
if(pName == strName && vValue.boolVal == VARIANT_TRUE)
ReOrderConnectedOnlyPorts();
else
{
for (std::vector<Decor::PortPart*>::iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
(*ii)->SetParam(strName, vValue);
}
for (std::vector<Decor::PortPart*>::iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
(*ii)->SetParam(strName, vValue);
}
TypeableBitmapPart::SetParam(strName, vValue);
}
}
bool ModelComplexPart::GetParam(const CString& strName, VARIANT* pvValue)
{
try {
if (TypeableBitmapPart::GetParam(strName, pvValue))
return true;
}
catch(UnknownParameterException&) {
}
return false;
}
void ModelComplexPart::SetActive(bool bIsActive)
{
for (std::vector<Decor::PortPart*>::iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
(*ii)->SetActive(bIsActive);
}
for (std::vector<Decor::PortPart*>::iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
(*ii)->SetActive(bIsActive);
}
TypeableBitmapPart::SetActive(bIsActive);
}
template<typename IT, typename F>
int transform_max(IT begin, IT end, F func)
{
int max_ret = INT_MIN;
while (begin != end)
{
max_ret = max(max_ret, func(*begin));
++begin;
}
return max_ret;
}
CSize ModelComplexPart::GetPreferredSize(void) const
{
const auto& button = this->button;
const auto& button2 = this->button2;
int RightPortsMaxLabelLength = 0;
auto setButtonPosition = [&RightPortsMaxLabelLength, &button, &button2](const CSize& size) {
if (button && button->m_bmp) {
// bottom right, left of port names
int y = size.cy - button->m_bmp->GetHeight();
int x = size.cx - RightPortsMaxLabelLength - button->m_bmp->GetWidth();
button->position = CRect(x, y, x + button->m_bmp->GetWidth(), y + button->m_bmp->GetHeight());
if (button2 && button2->m_bmp) {
// left of button
y -= button->m_bmp->GetHeight() - button2->m_bmp->GetHeight();
x -= button2->m_bmp->GetWidth();
button2->position = CRect(x, y, x + button2->m_bmp->GetWidth(), y + button2->m_bmp->GetHeight());
}
}
};
CSize size = ResizablePart::GetPreferredSize();
bool hasStoredCustomSize = (size.cx * size.cy != 0);
if (!hasStoredCustomSize && m_LeftPorts.empty() && m_RightPorts.empty()) {
if (!m_pBitmap) {
CSize ret(WIDTH_MODEL, HEIGHT_MODEL);
setButtonPosition(ret);
return ret;
} else {
CSize bitmapSize = TypeableBitmapPart::GetPreferredSize();
setButtonPosition(bitmapSize);
return bitmapSize;
}
}
const_cast<ModelComplexPart*>(this)->m_prominentAttrsCY = 0;
const_cast<ModelComplexPart*>(this)->m_prominentAttrsNamesCX = 0;
const_cast<ModelComplexPart*>(this)->m_prominentAttrsValuesCX = 0;
int LeftPortsMaxLabelLength = 0;
LOGFONT logFont;
getFacilities().GetFont(FONT_PORT)->gdipFont->GetLogFontW(getFacilities().getGraphics(), &logFont);
{
HDC dc = GetDC(NULL);
Gdiplus::Graphics g(dc);
Gdiplus::Font f(dc, &logFont);
Gdiplus::PointF zero(0.0, 0.0);
Gdiplus::RectF box;
auto measure_f = [&](const Decor::PortPart* portPart) -> int {
CStringW porttext = static_cast<CPMPortLabelPart* /* n.b. this lie doesn't matter */>(portPart->GetTextPart())->GetText();
g.MeasureString(static_cast<const wchar_t*>(porttext), min(porttext.GetLength(), m_iMaxPortTextLength == 0 ? INT_MAX : m_iMaxPortTextLength), &f, zero, &box);
return (int)(box.Width + 0.5f);
};
int base_port_gap = max(cornerRadius, GAP_LABEL + WIDTH_PORT + GAP_XMODELPORT);
LeftPortsMaxLabelLength = max(-base_port_gap, transform_max(this->m_LeftPorts.begin(), m_LeftPorts.end(), measure_f)) + base_port_gap;
RightPortsMaxLabelLength = max(-base_port_gap, transform_max(this->m_RightPorts.begin(), m_RightPorts.end(), measure_f)) + base_port_gap;
LeftPortsMaxLabelLength = max(cornerRadius, LeftPortsMaxLabelLength);
RightPortsMaxLabelLength = max(cornerRadius, RightPortsMaxLabelLength);
const_cast<ModelComplexPart*>(this)->m_LeftPortsMaxLabelLength = LeftPortsMaxLabelLength;
const_cast<ModelComplexPart*>(this)->m_RightPortsMaxLabelLength = RightPortsMaxLabelLength;
for (auto prominentIt = prominentAttrs.begin(); prominentIt != prominentAttrs.end(); ++prominentIt)
{
Gdiplus::RectF prominentNameSize;
g.MeasureString(static_cast<const wchar_t*>(prominentIt->name + L": "), -1, &f, zero, &prominentNameSize);
Gdiplus::RectF prominentValueSize;
g.MeasureString(static_cast<const wchar_t*>(prominentIt->value), -1, &f, zero, &prominentValueSize);
const_cast<ModelComplexPart*>(this)->m_prominentAttrsCY += max(prominentNameSize.Height, prominentValueSize.Height);
const_cast<ModelComplexPart*>(this)->m_prominentAttrsNamesCX = max(m_prominentAttrsNamesCX, prominentNameSize.Width);
const_cast<ModelComplexPart*>(this)->m_prominentAttrsValuesCX = max(m_prominentAttrsValuesCX, prominentValueSize.Width);
}
::ReleaseDC(NULL, dc);
}
long lWidth = 0;
if (m_bPortLabelInside) {
ASSERT(m_iLongestPortTextLength >= 0 && m_iLongestPortTextLength <= 1000);
ASSERT(m_iMaxPortTextLength >= 0 && m_iMaxPortTextLength <= 1000);
lWidth = LeftPortsMaxLabelLength + RightPortsMaxLabelLength + max(m_prominentAttrsSize.cx, min(TypeableBitmapPart::GetPreferredSize().cx, MAXIMUM_ICON_SIZE_NONOVERLAPPING_WITH_PORT_LABELS));
} else {
lWidth = (8 * 3 + GAP_LABEL + WIDTH_PORT + GAP_XMODELPORT) * 2 + GAP_PORTLABEL;
}
long lHeight = GAP_YMODELPORT * 2 +
max(m_LeftPorts.size(), m_RightPorts.size()) * (HEIGHT_PORT + GAP_PORT) - GAP_PORT;
if (hasStoredCustomSize) {
CSize calcSize = CSize(min(size.cx, lWidth), min(size.cy, lHeight));
const_cast<Decor::ModelComplexPart*>(this)->resizeLogic.SetMinimumSize(calcSize);
setButtonPosition(size);
return size;
}
else {
CSize bitmapSize = TypeableBitmapPart::GetPreferredSize();
lWidth = max(lWidth, max(bitmapSize.cx, m_prominentAttrsSize.cx));
lHeight = max(lHeight, bitmapSize.cy + m_prominentAttrsSize.cy);
const_cast<Decor::ModelComplexPart*>(this)->resizeLogic.SetMinimumSize(CSize(lWidth, lHeight));
CSize size(max((long)WIDTH_MODEL, lWidth), max((long)HEIGHT_MODEL, lHeight));
setButtonPosition(size);
return size;
}
}
void ModelComplexPart::SetLocation(const CRect& location)
{
for (std::vector<Decor::PortPart*>::iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
(*ii)->SetLocation(location);
}
for (std::vector<Decor::PortPart*>::iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
(*ii)->SetLocation(location);
}
TypeableBitmapPart::SetLocation(location);
}
CRect ModelComplexPart::GetLocation(void) const
{
return TypeableBitmapPart::GetLocation();
}
CRect ModelComplexPart::GetLabelLocation(void) const
{
CRect labelLocation(0,0,0,0);
try {
labelLocation = TypeableBitmapPart::GetLabelLocation();
}
catch(NotImplementedException&) {
for (std::vector<Decor::PortPart*>::const_iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
labelLocation = (*ii)->GetLabelLocation();
if (!labelLocation.IsRectEmpty())
break;
}
if (labelLocation.IsRectEmpty()) {
for (std::vector<Decor::PortPart*>::const_iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
labelLocation = (*ii)->GetLabelLocation();
if (!labelLocation.IsRectEmpty())
break;
}
}
}
return labelLocation;
}
CRect ModelComplexPart::GetPortLocation(CComPtr<IMgaFCO>& pFCO) const
{
CRect portLocation(0,0,0,0);
Decor::PortPart* pPortPart = GetPort(pFCO);
if (pPortPart != NULL) {
portLocation = pPortPart->GetLocation();
CPoint offset = GetLocation().TopLeft();
portLocation.OffsetRect(-offset.x, -offset.y);
}
portLocation.InflateRect(1, 1, 1, 1);
return portLocation;
}
bool ModelComplexPart::GetPorts(CComPtr<IMgaFCOs>& portFCOs) const
{
CComPtr<IMgaFCOs> spFCOs;
COMTHROW(spFCOs.CoCreateInstance(OLESTR("Mga.MgaFCOs")));
for (std::vector<Decor::PortPart*>::const_iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
COMTHROW(spFCOs->Append((*ii)->GetFCO()));
}
for (std::vector<Decor::PortPart*>::const_iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
COMTHROW(spFCOs->Append((*ii)->GetFCO()));
}
portFCOs = spFCOs.Detach();
return true;
}
void ModelComplexPart::DrawMarker(Gdiplus::Graphics& g, const wchar_t* s, CPoint p, Gdiplus::Color& bgColor)
{
using namespace Gdiplus;
//g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
FontFamily family(L"Palatino Linotype");
Gdiplus::Font f(&family, 11, FontStyleBold, Gdiplus::UnitPixel);
StringFormat format;
format.SetAlignment(StringAlignmentCenter);
format.SetLineAlignment(StringAlignmentCenter);
RectF area((REAL)p.x - 13 / 2, (REAL)p.y - 13 / 2, (REAL)13, (REAL)13);
RectF shadow = area;
shadow.X -= 1;
shadow.Y += 1;
shadow.Width += 1;
shadow.Height += 1;
SolidBrush b(Color(128, 0, 0, 0));
g.FillEllipse(&b, shadow);
SolidBrush b2(bgColor);
g.FillEllipse(&b2, area);
Pen darkBlue(Color::DarkBlue);
g.DrawEllipse(&darkBlue, area);
SolidBrush blackBrush(Color::Black);
area.X += 0.5;
area.Y += 0.5;
g.DrawString(s, 1, &f, area, &format, &blackBrush);
}
void ModelComplexPart::DrawEmbellishments(Gdiplus::Graphics& g)
{
if (embelishment != Embelishment::NONE)
{
CPoint loc(this->m_Rect.right - 1, this->m_Rect.top - 1);
if (embelishment == Embelishment::REFERENCE)
{
Gdiplus::Color bgColor(m_bActive ? Gdiplus::Color::LightBlue : Gdiplus::Color::Gray);
DrawMarker(g, L"R", loc, bgColor);
}
else if (embelishment == Embelishment::NULL_REFERENCE)
{
Gdiplus::Color bgColor(m_bActive ? Gdiplus::Color::Red : Gdiplus::Color::Gray);
DrawMarker(g, L"R", loc, bgColor);
}
}
}
void ModelComplexPart::Draw(CDC* pDC, Gdiplus::Graphics* gdip)
{
TypeableBitmapPart::Draw(pDC, gdip);
DrawEmbellishments(*gdip);
}
void ModelComplexPart::SaveState()
{
for (std::vector<Decor::PortPart*>::iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
(*ii)->SaveState();
}
for (std::vector<Decor::PortPart*>::iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
(*ii)->SaveState();
}
TypeableBitmapPart::SaveState();
}
// New functions
void ModelComplexPart::InitializeEx(CComPtr<IMgaProject>& pProject, CComPtr<IMgaMetaPart>& pPart, CComPtr<IMgaFCO>& pFCO,
HWND parentWnd, PreferenceMap& preferences)
{
preferences[PREF_ICONDEFAULT] = PreferenceVariant(createResString(IDB_MODEL));
preferences[PREF_TILESDEFAULT] = PreferenceVariant(getFacilities().getTileVector(TILE_MODELDEFAULT));
preferences[PREF_TILESUNDEF] = PreferenceVariant(getFacilities().getTileVector(TILE_PORTDEFAULT));
if (pPart) {
kind = pPart->Role->Kind->Name;
}
if (pFCO) {
PreferenceMap::iterator it = preferences.find(PREF_PORTLABELCOLOR);
if (it != preferences.end())
m_crPortText = it->second.uValue.crValue;
else
getFacilities().getPreference(pFCO, PREF_PORTLABELCOLOR, m_crPortText);
it = preferences.find(PREF_PORTLABELINSIDE);
if (it != preferences.end())
m_bPortLabelInside = it->second.uValue.bValue;
else
getFacilities().getPreference(pFCO, PREF_PORTLABELINSIDE, m_bPortLabelInside);
long o = m_iMaxPortTextLength;
it = preferences.find(PREF_PORTLABELLENGTH);
if (it != preferences.end()) {
m_iMaxPortTextLength = it->second.uValue.lValue;
} else {
if (getFacilities().getPreference(pFCO, PREF_PORTLABELLENGTH, m_iMaxPortTextLength))
m_iMaxPortTextLength = abs(m_iMaxPortTextLength); //convert any negative value to positive
else //if not found in registry
m_iMaxPortTextLength = MAX_PORT_LENGTH; // the default value in Preferences
}
if (m_iMaxPortTextLength == 0) // if 0 it means it has to show all way long
m_iMaxPortTextLength = 999; // so we set a huge value
TypeableBitmapPart::InitializeEx(pProject, pPart, pFCO, parentWnd, preferences);
LoadPorts();
IMgaReferencePtr ref = pFCO.p;
if (ref && ref->Referred && wcscmp(static_cast<const wchar_t*>(ref->Referred->Meta->Name), L"Component") == 0)
{
IMgaModelPtr component = ref->Referred;
auto children = component->ChildFCOs;
for (int i = 1; i <= children->Count; i++)
{
IMgaFCOPtr child = children->Item[i];
if ((wcscmp(static_cast<const wchar_t*>(child->Meta->Name), L"Property") == 0 && child->GetBoolAttrByName(L"IsProminent") != VARIANT_FALSE)
|| wcscmp(static_cast<const wchar_t*>(child->Meta->Name), L"Parameter") == 0)
{
_bstr_t dispValue = child->GetStrAttrByName(L"Value");
dispValue += L" ";
IMgaReferencePtr childRef = child;
if (childRef && childRef->Referred)
{
if (wcscmp(childRef->Referred->Meta->Name, L"si_unit") == 0 || wcscmp(childRef->Referred->Meta->Name, L"conversion_based_unit") == 0
|| wcscmp(childRef->Referred->Meta->Name, L"derived_unit") == 0) {
//dispValue += childRef->Referred->Name;
dispValue += childRef->Referred->GetStrAttrByName(L"Symbol");
}
}
ProminentAttr prominentAttr;
prominentAttr.name = child->GetName();
prominentAttr.value = dispValue;
prominentAttrs.emplace_back(std::move(prominentAttr));
}
}
std::sort(prominentAttrs.begin(), prominentAttrs.end(), [](const ProminentAttr& l, const ProminentAttr& r) { return l.name < r.name; });
}
const auto petFileAttribute = PETWrapperLookup(kind);
if (petFileAttribute) {
button = std::unique_ptr<ModelButton>(new ModelButton());
button->callback = PETRefreshButtonClicked;
if (wcscmp(kind, L"ExcelWrapper") != 0 &&
wcslen(m_spFCO->GetStrAttrByName(_bstr_t(PETWrapperLookup(kind)))) > 0)
{
button2 = std::unique_ptr<ModelButton>(new ModelButton());
button2->callback = PETEditButtonClicked;
}
if (getFacilities().arePathesValid())
{
std::vector<CString> vecPathes = getFacilities().getPathes();
CString filenames[] = { L"refresh.png", L"open_button.png" };
std::unique_ptr<ModelButton>* buttons[] = { &button, &button2 };
for (int i = 0; i < _countof(buttons) && *buttons[i]; i++)
{
CString& strFName = filenames[i];
auto& m_bmp = (**buttons[i]).m_bmp;
for (unsigned int i = 0; i < vecPathes.size(); i++)
{
CString imageFileName = vecPathes[i] + strFName;
m_bmp = std::unique_ptr<Gdiplus::Bitmap>(Gdiplus::Bitmap::FromFile(CStringW(imageFileName)));
if (m_bmp && m_bmp->GetLastStatus() == Gdiplus::Ok)
{
UINT widthToSet = m_bmp->GetWidth();
UINT heightToSet = m_bmp->GetHeight();
ASSERT(widthToSet > 0); // valid sizes, otherwise AutoRouter fails
ASSERT(heightToSet > 0);
break;
}
else
{
m_bmp = nullptr;
}
}
}
}
}
} else {
TypeableBitmapPart::InitializeEx(pProject, pPart, pFCO, parentWnd, preferences);
}
if (m_LeftPorts.empty() && m_RightPorts.empty())
m_pTileVector = getFacilities().getTileVector(TILE_ATOMDEFAULT);
PreferenceMap::iterator iconint = preferences.find("iconint");
if (iconint != preferences.end())
{
m_bmp = std::unique_ptr<Gdiplus::Bitmap>(new Gdiplus::Bitmap(((HINSTANCE)&__ImageBase), (WCHAR*) MAKEINTRESOURCE(iconint->second.uValue.lValue)));
}
else if (preferences.find(PREF_ICON) != preferences.end())
{
if ( ! getFacilities().arePathesValid() )
return;
std::vector<CString> vecPathes = getFacilities().getPathes();
bool success = false;
CString& strFName = *preferences.find(PREF_ICON)->second.uValue.pstrValue;
for (unsigned int i = 0; i < vecPathes.size() ; i++ )
{
CString imageFileName = vecPathes[ i ] + strFName;
m_bmp = std::unique_ptr<Gdiplus::Bitmap>(Gdiplus::Bitmap::FromFile(CStringW(imageFileName)));
if( m_bmp && m_bmp->GetLastStatus() == Gdiplus::Ok)
{
UINT widthToSet = m_bmp->GetWidth();
UINT heightToSet = m_bmp->GetHeight();
ASSERT( widthToSet > 0); // valid sizes, otherwise AutoRouter fails
ASSERT( heightToSet > 0);
break;
}
else
{
m_bmp = nullptr;
}
}
}
if (preferences.find(brushColorVariableName) == preferences.end() &&
getFacilities().getPreference(m_spFCO, m_spMetaFCO, brushColorVariableName, m_crBrush) == false)
{
m_crBrush = RGB(0xdd, 0xdd, 0xdd);
}
}
void ModelComplexPart::SetSelected(bool bIsSelected)
{
if (this->m_spFCO)
{
auto addOns = this->m_spFCO->Project->AddOnComponents;
for (int i = 1; i <= addOns->Count; i++)
{
if (wcscmp(addOns->GetItem(i)->ComponentName, L"CyPhyMetaLinkAddon") == 0)
{
IDispatchPtr disp = addOns->GetItem(i);
if (disp)
{
CComDispatchDriver d(disp);
CComVariant varFCO(this->m_spFCO);
CComVariant varSelected(bIsSelected);
d.Invoke2(L"SetSelected", &varFCO, &varSelected);
}
}
}
}
for (std::vector<Decor::PortPart*>::iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
(*ii)->SetSelected(bIsSelected);
}
for (std::vector<Decor::PortPart*>::iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
(*ii)->SetSelected(bIsSelected);
}
TypeableBitmapPart::SetSelected(bIsSelected);
}
bool ModelComplexPart::MouseMoved(UINT nFlags, const CPoint& point, HDC transformHDC)
{
HRESULT retVal = S_OK;
try {
if (TypeableBitmapPart::MouseMoved(nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
try {
if ((*ii)->MouseMoved(nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
try {
if ((*ii)->MouseMoved(nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
return false;
}
bool ModelComplexPart::MouseLeftButtonDown(UINT nFlags, const CPoint& point, HDC transformHDC)
{
HRESULT retVal = S_OK;
std::unique_ptr<ModelButton>* buttons[] = { &button, &button2, nullptr };
for (std::unique_ptr<ModelButton>** it = &buttons[0]; *it; it++) {
std::unique_ptr<ModelButton>& button = **it;
if (!button || !button->m_bmp) {
continue;
}
//HWND wnd = WindowFromDC(transformHDC);
CPoint converted = point;
//ClientToScreen(wnd, &converted);
CRect loc = TypeableBitmapPart::GetBoxLocation(false);
CRect buttonPosition = button->position;
buttonPosition.OffsetRect(loc.TopLeft());
if (buttonPosition.PtInRect(converted)) {
button->callback(m_spFCO);
return true;
}
}
try {
if (TypeableBitmapPart::MouseLeftButtonDown(nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
try {
if ((*ii)->MouseLeftButtonDown(nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
try {
if ((*ii)->MouseLeftButtonDown(nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
return false;
}
bool ModelComplexPart::MouseLeftButtonUp(UINT nFlags, const CPoint& point, HDC transformHDC)
{
HRESULT retVal = S_OK;
try {
if (TypeableBitmapPart::MouseLeftButtonUp(nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
try {
if ((*ii)->MouseLeftButtonUp(nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
try {
if ((*ii)->MouseLeftButtonUp(nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
return false;
}
bool ModelComplexPart::MouseLeftButtonDoubleClick(UINT nFlags, const CPoint& point, HDC transformHDC)
{
CComPtr<IMgaProject> proj;
if (m_spFCO && m_spMetaFCO && SUCCEEDED(m_spFCO->get_Project(&proj)))
{
CComPtr<IMgaTerritory> terr;
if (kind.length() && kind == L"Data Sheet")
{
proj->BeginTransactionInNewTerr(TRANSACTION_NON_NESTED, &terr);
CComBSTR path;
if (SUCCEEDED(m_spFCO->get_StrAttrByName(CComBSTR(L"Path"), &path)) && path)
{
std::wstring docpath;
CComBSTR connStr;
HRESULT hr = S_OK;
if (SUCCEEDED(hr))
hr = proj->get_ProjectConnStr(&connStr);
wchar_t fullpath[MAX_PATH];
wchar_t* filepart;
if (SUCCEEDED(hr))
if (wcsncmp(connStr, L"MGA=", 4) == 0)
if (GetFullPathNameW(static_cast<const wchar_t*>(connStr) + 4, sizeof(fullpath)/sizeof(fullpath[0]), fullpath, &filepart) != 0 && filepart)
{
*filepart = L'\0';
docpath = fullpath;
docpath += path;
ShellExecuteW(0, L"open", docpath.c_str(), NULL, NULL, SW_SHOW);
proj->CommitTransaction();
return true;
}
}
// n.b. don't abort, it will Reset the view and destruct this
proj->CommitTransaction();
}
if (kind.length() && PETWrapperLookup(kind))
{
proj->BeginTransactionInNewTerr(TRANSACTION_NON_NESTED, &terr);
if (m_spFCO->GetStrAttrByName(_bstr_t(PETWrapperLookup(kind))).length() > 0) {
; // use default action (open model)
}
else {
CComDispatchDriver dd;
CComVariant variantFCO = (IDispatch*)m_spFCO.p;
if (SUCCEEDED(dd.CoCreateInstance(L"MGA.Interpreter.CyPhyPET", nullptr, CLSCTX_INPROC))) {
dd.Invoke1(L"RefreshButtonClicked", &variantFCO);
proj->CommitTransaction();
return true;
}
}
// n.b. don't abort, it will Reset the view and destruct this
proj->CommitTransaction();
}
}
HRESULT retVal = S_OK;
try {
if (TypeableBitmapPart::MouseLeftButtonDoubleClick(nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
try {
if ((*ii)->MouseLeftButtonDoubleClick(nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
try {
if ((*ii)->MouseLeftButtonDoubleClick(nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
return false;
}
bool ModelComplexPart::MouseRightButtonDown(HMENU hCtxMenu, UINT nFlags, const CPoint& point, HDC transformHDC)
{
HRESULT retVal = S_OK;
try {
if (TypeableBitmapPart::MouseRightButtonDown(hCtxMenu, nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
try {
if ((*ii)->MouseRightButtonDown(hCtxMenu, nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
try {
if ((*ii)->MouseRightButtonDown(hCtxMenu, nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
return false;
}
bool ModelComplexPart::MouseRightButtonUp(UINT nFlags, const CPoint& point, HDC transformHDC)
{
HRESULT retVal = S_OK;
try {
if (TypeableBitmapPart::MouseRightButtonUp(nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
try {
if ((*ii)->MouseRightButtonUp(nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
try {
if ((*ii)->MouseRightButtonUp(nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
return false;
}
bool ModelComplexPart::MouseRightButtonDoubleClick(UINT nFlags, const CPoint& point, HDC transformHDC)
{
HRESULT retVal = S_OK;
try {
if (TypeableBitmapPart::MouseRightButtonDoubleClick(nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
try {
if ((*ii)->MouseRightButtonDoubleClick(nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
try {
if ((*ii)->MouseRightButtonDoubleClick(nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
return false;
}
bool ModelComplexPart::MouseMiddleButtonDown(UINT nFlags, const CPoint& point, HDC transformHDC)
{
HRESULT retVal = S_OK;
try {
if (TypeableBitmapPart::MouseMiddleButtonDown(nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
try {
if ((*ii)->MouseMiddleButtonDown(nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
try {
if ((*ii)->MouseMiddleButtonDown(nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
return false;
}
bool ModelComplexPart::MouseMiddleButtonUp(UINT nFlags, const CPoint& point, HDC transformHDC)
{
HRESULT retVal = S_OK;
try {
if (TypeableBitmapPart::MouseMiddleButtonUp(nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
try {
if ((*ii)->MouseMiddleButtonUp(nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
try {
if ((*ii)->MouseMiddleButtonUp(nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
return false;
}
bool ModelComplexPart::MouseMiddleButtonDoubleClick(UINT nFlags, const CPoint& point, HDC transformHDC)
{
HRESULT retVal = S_OK;
try {
if (TypeableBitmapPart::MouseMiddleButtonDoubleClick(nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
try {
if ((*ii)->MouseMiddleButtonDoubleClick(nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
try {
if ((*ii)->MouseMiddleButtonDoubleClick(nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
return false;
}
bool ModelComplexPart::MouseWheelTurned(UINT nFlags, short distance, const CPoint& point, HDC transformHDC)
{
HRESULT retVal = S_OK;
try {
if (TypeableBitmapPart::MouseWheelTurned(nFlags, distance, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
try {
if ((*ii)->MouseWheelTurned(nFlags, distance, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
try {
if ((*ii)->MouseWheelTurned(nFlags, distance, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
return false;
}
bool ModelComplexPart::DragEnter(DROPEFFECT* dropEffect, COleDataObject* pDataObject, DWORD dwKeyState, const CPoint& point, HDC transformHDC)
{
HRESULT retVal = S_OK;
try {
if (TypeableBitmapPart::DragEnter(dropEffect, pDataObject, dwKeyState, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
try {
if ((*ii)->DragEnter(dropEffect, pDataObject, dwKeyState, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
try {
if ((*ii)->DragEnter(dropEffect, pDataObject, dwKeyState, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
return false;
}
bool ModelComplexPart::DragOver(DROPEFFECT* dropEffect, COleDataObject* pDataObject, DWORD dwKeyState, const CPoint& point, HDC transformHDC)
{
HRESULT retVal = S_OK;
try {
if (TypeableBitmapPart::DragOver(dropEffect, pDataObject, dwKeyState, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
try {
if ((*ii)->DragOver(dropEffect, pDataObject, dwKeyState, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
try {
if ((*ii)->DragOver(dropEffect, pDataObject, dwKeyState, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
return false;
}
bool ModelComplexPart::Drop(COleDataObject* pDataObject, DROPEFFECT dropEffect, const CPoint& point, HDC transformHDC)
{
HRESULT retVal = S_OK;
try {
if (TypeableBitmapPart::Drop(pDataObject, dropEffect, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
try {
if ((*ii)->Drop(pDataObject, dropEffect, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
try {
if ((*ii)->Drop(pDataObject, dropEffect, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
return false;
}
bool ModelComplexPart::DropFile(HDROP p_hDropInfo, const CPoint& point, HDC transformHDC)
{
HRESULT retVal = S_OK;
try {
if (TypeableBitmapPart::DropFile(p_hDropInfo, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
try {
if ((*ii)->DropFile(p_hDropInfo, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
try {
if ((*ii)->DropFile(p_hDropInfo, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
return false;
}
bool ModelComplexPart::MenuItemSelected(UINT menuItemId, UINT nFlags, const CPoint& point, HDC transformHDC)
{
HRESULT retVal = S_OK;
try {
if (TypeableBitmapPart::MenuItemSelected(menuItemId, nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
try {
if ((*ii)->MenuItemSelected(menuItemId, nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
try {
if ((*ii)->MenuItemSelected(menuItemId, nFlags, point, transformHDC))
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
return false;
}
bool ModelComplexPart::OperationCanceledByGME(void)
{
HRESULT retVal = S_OK;
try {
if (TypeableBitmapPart::OperationCanceledByGME())
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
try {
if ((*ii)->OperationCanceledByGME())
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
if (retVal == S_OK || retVal == S_DECORATOR_EVENT_NOT_HANDLED || retVal == E_DECORATOR_NOT_IMPLEMENTED) {
for (std::vector<Decor::PortPart*>::iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
try {
if ((*ii)->OperationCanceledByGME())
return true;
}
catch(hresult_exception& e) {
retVal = e.hr;
}
catch(DecoratorException& e) {
retVal = e.GetHResult();
}
if (retVal != S_OK && retVal != S_DECORATOR_EVENT_NOT_HANDLED && retVal != E_DECORATOR_NOT_IMPLEMENTED)
break;
}
}
return false;
}
void ModelComplexPart::DrawBackground(CDC* pDC, Gdiplus::Graphics* gdip)
{
CSize cExtentD = pDC->GetViewportExt();
CSize cExtentL = pDC->GetWindowExt();
int prominent_x = m_bmp.get() ? 0 : m_LeftPortsMaxLabelLength;
if (m_bStretch && m_bmp.get())
{
CRect cRect = TypeableBitmapPart::GetBoxLocation(false);
Gdiplus::Rect grect(cRect.left, cRect.top, cRect.Width(), cRect.Height());
gdip->DrawImage(m_bmp.get(), grect, 0, 0, m_bmp->GetWidth(), m_bmp->GetHeight(), Gdiplus::UnitPixel);
}
else
{
CRect cRect = TypeableBitmapPart::GetBoxLocation(false);
cRect.BottomRight() -= CPoint(1, 1);
CRect location = cRect;
if (m_LeftPorts.size() != 0 || m_RightPorts.size() != 0 || m_bmp.get() == nullptr)
{
Gdiplus::Rect rect(cRect.left, cRect.top, cRect.Width(), cRect.Height());
Gdiplus::LinearGradientBrush linearGradientBrush(rect,
Gdiplus::Color(GetRValue(m_crBrush), GetGValue(m_crBrush), GetBValue(m_crBrush)),
Gdiplus::Color(GetRValue(m_crGradient), GetGValue(m_crGradient), GetBValue(m_crGradient)),
Gdiplus::LinearGradientModeVertical);
Gdiplus::SolidBrush solidBrush(Gdiplus::Color(GetRValue(m_crBrush), GetGValue(m_crBrush), GetBValue(m_crBrush)));
Gdiplus::Brush& brush = m_bGradientFill ? (Gdiplus::Brush&)linearGradientBrush : (Gdiplus::Brush&)solidBrush;
Gdiplus::GraphicsPath path;
path.AddArc(location.left, location.top, cornerRadius, cornerRadius, 180, 90);
path.AddArc(location.right - cornerRadius, location.top, cornerRadius, cornerRadius, 270, 90);
path.AddArc(location.right - cornerRadius, location.bottom - cornerRadius, cornerRadius, cornerRadius, 0, 90);
path.AddArc(location.left, location.bottom - cornerRadius, cornerRadius, cornerRadius, 90, 90);
gdip->FillPath(&brush, &path);
}
if (m_bmp.get())
{
int height = m_bmp->GetHeight();
int width = m_bmp->GetWidth();
int x; // Render according to m_LeftPortsMaxLabelLength if the image fits inside the rounded rectangle
// if not, just center it
int gutter = min(m_LeftPortsMaxLabelLength + m_RightPortsMaxLabelLength, cRect.Width() - width);
int x_margin = (int)(gutter * (double)m_LeftPortsMaxLabelLength / (m_LeftPortsMaxLabelLength + m_RightPortsMaxLabelLength));
int left_corner = cornerRadius;
int right_corner = cRect.Width() - cornerRadius;
if (x_margin < left_corner - 1 /*slop*/ || x_margin > right_corner - width + 1 /*slop*/)
{
// center
x = cRect.Width() / 2 - (int)m_bmp->GetWidth() / 2;
}
else
{
x = x_margin;
}
x += max(0, m_prominentAttrsSize.cx - (int)m_bmp->GetWidth()) / 2;
prominent_x = x;
Gdiplus::Rect grect((int)cRect.left + x, (int)cRect.top + (cRect.Height() - m_prominentAttrsSize.cy) / 2 - (int)m_bmp->GetHeight() / 2,
width, height);
gdip->DrawImage(m_bmp.get(), grect, 0, 0, (int)m_bmp->GetWidth(), (int)m_bmp->GetHeight(), Gdiplus::UnitPixel);
}
}
for (std::vector<Decor::PortPart*>::iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
(*ii)->Draw(pDC, gdip);
}
for (std::vector<Decor::PortPart*>::iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
(*ii)->Draw(pDC, gdip);
}
LOGFONTA logFont;
getFacilities().GetFont(FONT_PORT)->gdipFont->GetLogFontA(getFacilities().getGraphics(), &logFont);
HDC hdc = gdip->GetHDC();
Gdiplus::Font f(hdc, &logFont);
gdip->ReleaseHDC(hdc);
{
CRect cRect = TypeableBitmapPart::GetBoxLocation(false);
cRect.BottomRight() -= CPoint(1, 1);
Gdiplus::PointF p;
p.X = (int)cRect.left + cRect.Width() / 2 - prominent_x / 2;
p.X = (int)cRect.left + prominent_x + m_prominentAttrsNamesCX;
p.X = (int)cRect.left + (cRect.Width() - m_LeftPortsMaxLabelLength - m_RightPortsMaxLabelLength) / 2 + m_LeftPortsMaxLabelLength + (m_prominentAttrsNamesCX - m_prominentAttrsValuesCX) / 2;
p.Y = (int)cRect.top + (cRect.Height() - m_prominentAttrsSize.cy) / 2 + (m_bmp.get() ? (int)m_bmp->GetHeight() : 0) / 2;
for (auto prominentIt = prominentAttrs.begin(); prominentIt != prominentAttrs.end(); ++prominentIt)
{
Gdiplus::SolidBrush blackBrush(Gdiplus::Color::Black);
Gdiplus::RectF prominentBox;
Gdiplus::StringFormat format;
format.SetAlignment(Gdiplus::StringAlignmentFar);
format.SetLineAlignment(Gdiplus::StringAlignmentNear);
gdip->DrawString(static_cast<const wchar_t*>(prominentIt->name), -1, &f, p, &format, &blackBrush);
format.SetAlignment(Gdiplus::StringAlignmentNear);
format.SetLineAlignment(Gdiplus::StringAlignmentNear);
gdip->DrawString(static_cast<const wchar_t*>(prominentIt->value), -1, &f, p, &format, &blackBrush);
p.Y += 11; // FIXME depends on font
}
std::unique_ptr<ModelButton>* buttons[] = { &button, &button2, nullptr };
for (std::unique_ptr<ModelButton>** it = &buttons[0]; *it; it++) {
std::unique_ptr<ModelButton>& button = **it;
if (button && button->m_bmp) {
Gdiplus::Rect grect(cRect.left + button->position.left, cRect.top + button->position.top, button->position.Width(), button->position.Height());
gdip->DrawImage(button->m_bmp.get(), grect, 0, 0, (int)button->m_bmp->GetWidth(), (int)button->m_bmp->GetHeight(), Gdiplus::UnitPixel);
}
}
}
}
void ModelComplexPart::LoadPorts()
{
if (m_spPart == NULL)
return;
CComBSTR regName("showPorts");
CComBSTR dispPortTxt;
CComPtr<IMgaFCO> obj = m_parentPart->GetFCO();
obj->get_RegistryValue(regName, &dispPortTxt);
if(dispPortTxt.Length())
{
if(dispPortTxt == "false")
return; // do not need ports for this reference: see Meta paradigm ReferTo connection showPorts attribute
}
CComPtr<IMgaMetaAspect> spParentAspect;
COMTHROW(m_spPart->get_ParentAspect(&spParentAspect));
CComBSTR bstrParentAspect;
COMTHROW(spParentAspect->get_Name(&bstrParentAspect));
CComQIPtr<IMgaModel> spModel = m_spFCO;
CComQIPtr<IMgaReference> spRef = m_spFCO;
while (spModel == NULL && spRef != NULL)
{
CComPtr<IMgaFCO> referred;
spRef->get_Referred(&referred);
spRef = referred;
spModel = referred;
}
if (spModel == NULL)
return;
CComPtr<IMgaMetaFCO> spMetaFCO;
COMTHROW(spModel->get_Meta(&spMetaFCO));
CComQIPtr<IMgaMetaModel> spMetaModel = spMetaFCO;
CComBSTR bstrAspect;
COMTHROW(m_spPart->get_KindAspect(&bstrAspect));
if (bstrAspect.Length() == 0) {
bstrAspect.Empty();
COMTHROW( spParentAspect->get_Name(&bstrAspect));
}
CComPtr<IMgaMetaAspect> spAspect;
HRESULT hr = spMetaModel->get_AspectByName(bstrAspect, &spAspect);
if (hr == E_NOTFOUND) {
// hr = spMetaModel->get_AspectByName(CComBSTR(L"All"), &spAspect);
}
if (hr == E_NOTFOUND) {
try {
// PETER: If the proper aspect cannot be found, use the first one
spAspect = NULL;
CComPtr<IMgaMetaAspects> spAspects;
COMTHROW(spMetaModel->get_Aspects(&spAspects));
ASSERT(spAspects);
long nAspects = 0;
COMTHROW(spAspects->get_Count(&nAspects));
if (nAspects > 0) {
COMTHROW(spAspects->get_Item(1, &spAspect));
}
}
catch(hresult_exception&) {
}
}
if (spAspect) {
CComPtr<IMgaFCOs> spFCOs;
COMTHROW(spModel->get_ChildFCOs(&spFCOs));
MGACOLL_ITERATE(IMgaFCO, spFCOs) {
CComPtr<IMgaPart> spPart;
if (MGACOLL_ITER->get_Part(spAspect, &spPart) == S_OK) {
if (spPart) {
CComPtr<IMgaFCO> mgaFco = MGACOLL_ITER;
CComPtr<IMgaMetaPart> spMetaPart;
COMTHROW(spPart->get_Meta(&spMetaPart));
VARIANT_BOOL vbLinked;
COMTHROW(spMetaPart->get_IsLinked(&vbLinked));
CComPtr<IMgaMetaFCO> child_meta;
COMTHROW(MGACOLL_ITER->get_Meta(&child_meta));
CComBSTR child_kind_name;
COMTHROW(child_meta->get_Name(&child_kind_name));
// Only display Propertys and Parameters in ValueFlow, TBValueFlowAspect, All, TestBenchCompositionAspect, and DesignSpace aspects
bool display_port =
(child_kind_name != L"Property"
&& child_kind_name != L"Parameter"
&& child_kind_name != L"CADProperty"
&& child_kind_name != L"CADParameter"
&& child_kind_name != L"CyberParameter")
|| bstrParentAspect == L"ValueFlowAspect"
|| bstrParentAspect == L"TBValueFlowAspect"
|| bstrParentAspect == L"DesignSpaceAspect"
|| bstrParentAspect == L"All"
|| bstrParentAspect == L"TestBenchCompositionAspect";
// TBDriverMonitor: no StructuralInterfaceRoleForwarder ports
display_port &=
child_kind_name != L"StructuralInterfaceRoleForwarder"
|| bstrParentAspect != L"TBDriverMonitorAspect";
// Except in ValueFlow, show AggregatePort
display_port |=
bstrParentAspect != L"ValueFlow"
&& bstrParentAspect != L"TBValueFlowAspect"
&& child_kind_name == L"AggregatePort";
// In dynamics aspect, Components have only power ports
display_port &=
( bstrParentAspect != L"Dynamics" || bstrParentAspect != L"All")
|| ( child_kind_name == L"HydraulicPowerPort"
|| child_kind_name == L"ThermalPowerPort"
|| child_kind_name == L"ElectricalPowerPort"
|| child_kind_name == L"MagneticPowerPort"
|| child_kind_name == L"PneumaticPowerPort"
|| child_kind_name == L"AcousticPowerPort"
|| child_kind_name == L"RotationalPowerPort"
|| child_kind_name == L"TranslationalPowerPort"
|| child_kind_name == L"InSignal"
|| child_kind_name == L"OutSignal");
if ( (bstrParentAspect == L"Dynamics" || bstrParentAspect == L"DynamicsAspect")
&& (child_kind_name == L"StructuralInterface" || child_kind_name == L"StructuralInterfaceForwarder"))
{
display_port = false;
}
if ( bstrParentAspect == L"SolidModeling"
&& child_kind_name == L"AggregatePort")
{
display_port = false;
}
if (display_port && m_spFCO->ParentModel && m_spFCO->ParentModel->Meta->Name == _bstr_t(L"Configurations"))
{
display_port = false;
}
if (child_kind_name == L"Property" && mgaFco->GetBoolAttrByName(L"IsProminent") == VARIANT_FALSE)
{
display_port = false;
}
if (display_port && vbLinked) {
long lX = 0;
long lY = 0;
//COMTHROW( spPart->GetGmeAttrs( 0, &lX, &lY ) );
// zolmol, in case regnodes are not present or invalid will throw otherwise
if(spPart->GetGmeAttrs(0, &lX, &lY) != S_OK)
ASSERT(0);
//new code
CComBSTR bstr;
COMTHROW(spMetaPart->get_Name(&bstr));
CString pname(bstr);
_bstr_t icon;
mgaFco->GetRegistryValueDisp(_bstr_t(PREF_PORTICON), icon.GetAddress());
if (icon.length() == 0)
mgaFco->GetRegistryValueDisp(_bstr_t(PREF_ICON), icon.GetAddress());
if (icon.length() == 0)
icon = L"Component_piece.png";
PortPart* portPart = new PortPart(static_cast<TypeableBitmapPart*> (this), m_eventSink, CPoint(lX, lY), icon);
PortPartData* partData = new PortPartData(portPart, spMetaPart, MGACOLL_ITER);
m_AllPorts.push_back(partData);
} else {
COMTHROW(MGACOLL_ITER->Close());
}
} else {
COMTHROW(MGACOLL_ITER->Close());
}
}
} MGACOLL_ITERATE_END;
OrderPorts();
}
}
struct PortLess
{
bool operator()(Decor::PortPart* pPortA, Decor::PortPart* pPortB)
{
CPoint posA = pPortA->GetInnerPosition();
CPoint posB = pPortB->GetInnerPosition();
if (posA.y != posB.y)
return posA.y < posB.y;
if (posA.x != posB.x)
return posA.x < posB.x;
_bstr_t pPortAName = pPortA->GetFCO()->Name;
_bstr_t pPortBName = pPortB->GetFCO()->Name;
const wchar_t* zPortAName = pPortAName.length() == 0 ? L"" : pPortAName;
const wchar_t* zPortBName = pPortBName.length() == 0 ? L"" : pPortBName;
return (wcscmp(zPortAName, zPortBName) < 0);
}
};
void ModelComplexPart::OrderPorts()
{
long lMin = 100000000;
long lMax = 0;
for (std::vector<Decor::PortPartData*>::iterator ii = m_AllPorts.begin(); ii != m_AllPorts.end(); ++ii) {
lMin = min(lMin, (*ii)->portPart->GetInnerPosition().x);
lMax = max(lMax, (*ii)->portPart->GetInnerPosition().x);
}
for (std::vector<Decor::PortPartData*>::iterator ii = m_AllPorts.begin(); ii != m_AllPorts.end(); ++ii) {
PreferenceMap mapPrefs;
mapPrefs[PREF_LABELCOLOR] = PreferenceVariant(m_crPortText);
mapPrefs[PREF_LABELLENGTH] = PreferenceVariant((long) m_iMaxPortTextLength);
mapPrefs[PREF_PORTLABELINSIDE] = PreferenceVariant(m_bPortLabelInside);
if ((*ii)->portPart->GetInnerPosition().x <= WIDTH_MODELSIDE ||
(*ii)->portPart->GetInnerPosition().x < lMax / 2)
{
mapPrefs[PREF_LABELLOCATION] = PreferenceVariant(m_bPortLabelInside ? L_EAST : L_WEST);
m_LeftPorts.push_back((*ii)->portPart);
} else {
mapPrefs[PREF_LABELLOCATION] = PreferenceVariant(m_bPortLabelInside? L_WEST: L_EAST);
m_RightPorts.push_back((*ii)->portPart);
}
(*ii)->portPart->InitializeEx(m_spProject, (*ii)->spPart, (*ii)->spFCO, m_parentWnd, mapPrefs);
long k = (*ii)->portPart->GetLongest();
if (m_iLongestPortTextLength < k)
{
m_iLongestPortTextLength = k;
}
}
std::sort(m_LeftPorts.begin(), m_LeftPorts.end(), PortLess());
std::sort(m_RightPorts.begin(), m_RightPorts.end(), PortLess());
}
void ModelComplexPart::ReOrderConnectedOnlyPorts()
{
long lMin = 100000000;
long lMax = 0;
m_LeftPorts.clear();
m_RightPorts.clear();
m_iLongestPortTextLength = 0;
for (std::vector<PortPartData*>::iterator ii = m_AllPorts.begin(); ii != m_AllPorts.end(); ++ii) {
lMin = min(lMin, (*ii)->portPart->GetInnerPosition().x);
lMax = max(lMax, (*ii)->portPart->GetInnerPosition().x);
}
for (std::vector<PortPartData*>::iterator ii = m_AllPorts.begin(); ii != m_AllPorts.end(); ++ii) {
PreferenceMap mapPrefs;
mapPrefs[PREF_LABELCOLOR] = PreferenceVariant(m_crPortText);
mapPrefs[PREF_LABELLENGTH] = PreferenceVariant((long) m_iMaxPortTextLength);
mapPrefs[PREF_PORTLABELINSIDE] = PreferenceVariant(m_bPortLabelInside);
bool needThisPort = false;
CComPtr<IMgaConnPoints> cps;
(*ii)->spFCO->get_PartOfConns(&cps);
long num;
cps->get_Count(&num);
if(num > 0)
{
MGACOLL_ITERATE( IMgaConnPoint , cps ) {
CComPtr<IMgaConnPoint> cp = MGACOLL_ITER;
CComPtr<IMgaFCOs> refs;
COMTHROW( cp->get_References( &refs));
long l;
COMTHROW( refs->get_Count( &l));
CComPtr<IMgaConnection> conn;
COMTHROW( cp->get_Owner( &conn));
CComPtr<IMgaParts> connParts;
COMTHROW(conn->get_Parts(&connParts));
CComPtr<IMgaMetaAspect> spParentAspect;
COMTHROW(m_spPart->get_ParentAspect(&spParentAspect));
bool aspectMatch = false;
MGACOLL_ITERATE( IMgaPart , connParts ) {
CComPtr<IMgaPart> connPart = MGACOLL_ITER;
CComPtr<IMgaMetaAspect> connAsp;
COMTHROW(connPart->get_MetaAspect(&connAsp));
if(connAsp == spParentAspect)
{
aspectMatch = true;
break;
}
} MGACOLL_ITERATE_END;
if(aspectMatch)
{
CComPtr<IMgaModel> container;
COMTHROW( conn->get_ParentModel( &container));
CComPtr<IMgaFCO> parent = m_parentPart->GetFCO();
CComPtr<IMgaModel> grandparent;
COMTHROW(parent->get_ParentModel(&grandparent));
if(l == 0)
{
needThisPort = (parent == m_spFCO && container == grandparent);
}
else
{
CComPtr<IMgaFCO> ref;
COMTHROW( refs->get_Item( 1, &ref));
needThisPort = (ref == parent && container == grandparent);
}
if(needThisPort)
break;
}
} MGACOLL_ITERATE_END;
}
if(needThisPort)
{
if ((*ii)->portPart->GetInnerPosition().x <= WIDTH_MODELSIDE ||
(*ii)->portPart->GetInnerPosition().x < lMax / 2)
{
mapPrefs[PREF_LABELLOCATION] = PreferenceVariant(m_bPortLabelInside ? L_EAST : L_WEST);
m_LeftPorts.push_back((*ii)->portPart);
} else {
mapPrefs[PREF_LABELLOCATION] = PreferenceVariant(m_bPortLabelInside? L_WEST: L_EAST);
m_RightPorts.push_back((*ii)->portPart);
}
long k = (*ii)->portPart->GetLongest();
if (m_iLongestPortTextLength < k)
m_iLongestPortTextLength = k;
}
}
std::sort(m_LeftPorts.begin(), m_LeftPorts.end(), PortLess());
std::sort(m_RightPorts.begin(), m_RightPorts.end(), PortLess());
}
void ModelComplexPart::SetBoxLocation(const CRect& cRect)
{
TypeableBitmapPart::SetBoxLocation(cRect);
long lY = (m_Rect.Height() - m_LeftPorts.size() * (HEIGHT_PORT + GAP_PORT) + GAP_PORT) / 2;
for (std::vector<Decor::PortPart*>::iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
CRect boxRect = CRect(GAP_XMODELPORT, lY, GAP_XMODELPORT + WIDTH_PORT, lY + HEIGHT_PORT);
boxRect.OffsetRect(cRect.TopLeft());
(*ii)->SetBoxLocation(boxRect);
lY += HEIGHT_PORT + GAP_PORT;
}
lY = (m_Rect.Height() - m_RightPorts.size() * (HEIGHT_PORT + GAP_PORT) + GAP_PORT) / 2;
for (std::vector<Decor::PortPart*>::iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
CRect boxRect = CRect(cRect.Width() - GAP_XMODELPORT - WIDTH_PORT, lY, cRect.Width() - GAP_XMODELPORT, lY + HEIGHT_PORT);
boxRect.OffsetRect(cRect.TopLeft());
(*ii)->SetBoxLocation(boxRect);
lY += HEIGHT_PORT + GAP_PORT;
}
}
void ModelComplexPart::SetReferenced(bool referenced)
{
for (std::vector<Decor::PortPart*>::iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
(*ii)->SetReferenced(referenced);
}
for (std::vector<Decor::PortPart*>::iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
(*ii)->SetReferenced(referenced);
}
TypeableBitmapPart::SetReferenced(referenced);
}
void ModelComplexPart::SetParentPart(PartBase* pPart)
{
for (std::vector<Decor::PortPart*>::iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
(*ii)->SetParentPart(pPart);
}
for (std::vector<Decor::PortPart*>::iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
(*ii)->SetParentPart(pPart);
}
TypeableBitmapPart::SetParentPart(pPart);
}
Decor::PortPart* ModelComplexPart::GetPort(CComPtr<IMgaFCO> spFCO) const
{
for (std::vector<Decor::PortPart*>::const_iterator ii = m_LeftPorts.begin(); ii != m_LeftPorts.end(); ++ii) {
if (spFCO == (*ii)->GetFCO()) {
return (*ii);
}
}
for (std::vector<Decor::PortPart*>::const_iterator ii = m_RightPorts.begin(); ii != m_RightPorts.end(); ++ii) {
if (spFCO == (*ii)->GetFCO()) {
return (*ii);
}
}
return NULL;
}
}; // namespace Decor
| 33.926478 | 193 | 0.659141 | [
"render",
"vector",
"model"
] |
abd7e38e5517ea600f9fc9b8a96c7d0d26df0620 | 31,760 | cpp | C++ | src/resource_provider/manager.cpp | mengzhugithub/mesos | 7e3f5b067d757aab038d82c870194fb0bc652d19 | [
"Apache-2.0"
] | 2 | 2017-01-13T19:40:15.000Z | 2018-05-16T21:37:13.000Z | src/resource_provider/manager.cpp | mengzhugithub/mesos | 7e3f5b067d757aab038d82c870194fb0bc652d19 | [
"Apache-2.0"
] | 1 | 2018-07-22T19:45:42.000Z | 2018-07-22T19:45:42.000Z | src/resource_provider/manager.cpp | mengzhugithub/mesos | 7e3f5b067d757aab038d82c870194fb0bc652d19 | [
"Apache-2.0"
] | null | null | null | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "resource_provider/manager.hpp"
#include <string>
#include <utility>
#include <vector>
#include <glog/logging.h>
#include <mesos/http.hpp>
#include <mesos/resource_provider/resource_provider.hpp>
#include <mesos/v1/resource_provider/resource_provider.hpp>
#include <process/collect.hpp>
#include <process/dispatch.hpp>
#include <process/id.hpp>
#include <process/process.hpp>
#include <process/metrics/pull_gauge.hpp>
#include <process/metrics/metrics.hpp>
#include <stout/hashmap.hpp>
#include <stout/nothing.hpp>
#include <stout/protobuf.hpp>
#include <stout/uuid.hpp>
#include "common/http.hpp"
#include "common/protobuf_utils.hpp"
#include "common/recordio.hpp"
#include "common/resources_utils.hpp"
#include "internal/devolve.hpp"
#include "internal/evolve.hpp"
#include "resource_provider/registry.hpp"
#include "resource_provider/validation.hpp"
namespace http = process::http;
using std::string;
using std::vector;
using mesos::internal::resource_provider::validation::call::validate;
using mesos::resource_provider::AdmitResourceProvider;
using mesos::resource_provider::Call;
using mesos::resource_provider::Event;
using mesos::resource_provider::Registrar;
using mesos::resource_provider::registry::Registry;
using process::Failure;
using process::Future;
using process::Owned;
using process::Process;
using process::ProcessBase;
using process::Promise;
using process::Queue;
using process::collect;
using process::dispatch;
using process::spawn;
using process::terminate;
using process::wait;
using process::http::Accepted;
using process::http::BadRequest;
using process::http::MethodNotAllowed;
using process::http::NotAcceptable;
using process::http::NotImplemented;
using process::http::OK;
using process::http::Pipe;
using process::http::UnsupportedMediaType;
using process::http::authentication::Principal;
using process::metrics::PullGauge;
namespace mesos {
namespace internal {
mesos::resource_provider::registry::ResourceProvider
createRegistryResourceProvider(const ResourceProviderInfo& resourceProviderInfo)
{
mesos::resource_provider::registry::ResourceProvider resourceProvider;
CHECK(resourceProviderInfo.has_id());
resourceProvider.mutable_id()->CopyFrom(resourceProviderInfo.id());
resourceProvider.set_name(resourceProviderInfo.name());
resourceProvider.set_type(resourceProviderInfo.type());
return resourceProvider;
}
// Represents the streaming HTTP connection to a resource provider.
struct HttpConnection
{
HttpConnection(const http::Pipe::Writer& _writer,
ContentType _contentType,
id::UUID _streamId)
: writer(_writer),
contentType(_contentType),
streamId(_streamId),
encoder(lambda::bind(serialize, contentType, lambda::_1)) {}
// Converts the message to an Event before sending.
template <typename Message>
bool send(const Message& message)
{
// We need to evolve the internal 'message' into a
// 'v1::resource_provider::Event'.
return writer.write(encoder.encode(evolve(message)));
}
bool close()
{
return writer.close();
}
Future<Nothing> closed() const
{
return writer.readerClosed();
}
http::Pipe::Writer writer;
ContentType contentType;
id::UUID streamId;
::recordio::Encoder<v1::resource_provider::Event> encoder;
};
struct ResourceProvider
{
ResourceProvider(
const ResourceProviderInfo& _info,
const HttpConnection& _http)
: info(_info),
http(_http) {}
~ResourceProvider()
{
LOG(INFO) << "Terminating resource provider " << info.id();
http.close();
foreachvalue (const Owned<Promise<Nothing>>& publish, publishes) {
publish->fail(
"Failed to publish resources from resource provider " +
stringify(info.id()) + ": Connection closed");
}
}
ResourceProviderInfo info;
HttpConnection http;
hashmap<UUID, Owned<Promise<Nothing>>> publishes;
};
class ResourceProviderManagerProcess
: public Process<ResourceProviderManagerProcess>
{
public:
ResourceProviderManagerProcess(Owned<Registrar> _registrar);
Future<http::Response> api(
const http::Request& request,
const Option<Principal>& principal);
void applyOperation(const ApplyOperationMessage& message);
void acknowledgeOperationStatus(
const AcknowledgeOperationStatusMessage& message);
void reconcileOperations(const ReconcileOperationsMessage& message);
Future<Nothing> publishResources(const Resources& resources);
Queue<ResourceProviderMessage> messages;
private:
void subscribe(
const HttpConnection& http,
const Call::Subscribe& subscribe);
void _subscribe(
const Future<bool>& admitResourceProvider,
Owned<ResourceProvider> resourceProvider);
void updateOperationStatus(
ResourceProvider* resourceProvider,
const Call::UpdateOperationStatus& update);
void updateState(
ResourceProvider* resourceProvider,
const Call::UpdateState& update);
void updatePublishResourcesStatus(
ResourceProvider* resourceProvider,
const Call::UpdatePublishResourcesStatus& update);
Future<Nothing> recover(
const mesos::resource_provider::registry::Registry& registry);
void initialize() override;
ResourceProviderID newResourceProviderId();
double gaugeSubscribed();
struct ResourceProviders
{
hashmap<ResourceProviderID, Owned<ResourceProvider>> subscribed;
hashmap<
ResourceProviderID,
mesos::resource_provider::registry::ResourceProvider>
known;
} resourceProviders;
struct Metrics
{
explicit Metrics(const ResourceProviderManagerProcess& manager);
~Metrics();
PullGauge subscribed;
};
Owned<Registrar> registrar;
Promise<Nothing> recovered;
Metrics metrics;
};
ResourceProviderManagerProcess::ResourceProviderManagerProcess(
Owned<Registrar> _registrar)
: ProcessBase(process::ID::generate("resource-provider-manager")),
registrar(std::move(_registrar)),
metrics(*this)
{
CHECK_NOTNULL(registrar.get());
}
void ResourceProviderManagerProcess::initialize()
{
// Recover the registrar.
registrar->recover()
.then(defer(self(), &ResourceProviderManagerProcess::recover, lambda::_1))
.onAny([](const Future<Nothing>& recovered) {
if (!recovered.isReady()) {
LOG(FATAL)
<< "Failed to recover resource provider manager registry: "
<< recovered;
}
});
}
Future<Nothing> ResourceProviderManagerProcess::recover(
const mesos::resource_provider::registry::Registry& registry)
{
foreach (
const mesos::resource_provider::registry::ResourceProvider&
resourceProvider,
registry.resource_providers()) {
resourceProviders.known.put(resourceProvider.id(), resourceProvider);
}
recovered.set(Nothing());
return Nothing();
}
Future<http::Response> ResourceProviderManagerProcess::api(
const http::Request& request,
const Option<Principal>& principal)
{
// TODO(bbannier): This implementation does not limit the number of messages
// in the actor's inbox which could become large should a big number of
// resource providers attempt to subscribe before recovery completed. Consider
// rejecting requests until the resource provider manager has recovered. This
// would likely require implementing retry logic in resource providers.
return recovered.future().then(defer(
self(), [this, request, principal](const Nothing&) -> http::Response {
if (request.method != "POST") {
return MethodNotAllowed({"POST"}, request.method);
}
v1::resource_provider::Call v1Call;
// TODO(anand): Content type values are case-insensitive.
Option<string> contentType = request.headers.get("Content-Type");
if (contentType.isNone()) {
return BadRequest("Expecting 'Content-Type' to be present");
}
if (contentType.get() == APPLICATION_PROTOBUF) {
if (!v1Call.ParseFromString(request.body)) {
return BadRequest("Failed to parse body into Call protobuf");
}
} else if (contentType.get() == APPLICATION_JSON) {
Try<JSON::Value> value = JSON::parse(request.body);
if (value.isError()) {
return BadRequest(
"Failed to parse body into JSON: " + value.error());
}
Try<v1::resource_provider::Call> parse =
::protobuf::parse<v1::resource_provider::Call>(value.get());
if (parse.isError()) {
return BadRequest(
"Failed to convert JSON into Call protobuf: " + parse.error());
}
v1Call = parse.get();
} else {
return UnsupportedMediaType(
string("Expecting 'Content-Type' of ") + APPLICATION_JSON +
" or " + APPLICATION_PROTOBUF);
}
Call call = devolve(v1Call);
Option<Error> error = validate(call);
if (error.isSome()) {
return BadRequest(
"Failed to validate resource_provider::Call: " + error->message);
}
if (call.type() == Call::SUBSCRIBE) {
// We default to JSON 'Content-Type' in the response since an empty
// 'Accept' header results in all media types considered acceptable.
ContentType acceptType = ContentType::JSON;
if (request.acceptsMediaType(APPLICATION_JSON)) {
acceptType = ContentType::JSON;
} else if (request.acceptsMediaType(APPLICATION_PROTOBUF)) {
acceptType = ContentType::PROTOBUF;
} else {
return NotAcceptable(
string("Expecting 'Accept' to allow ") + "'" +
APPLICATION_PROTOBUF + "' or '" + APPLICATION_JSON + "'");
}
if (request.headers.contains("Mesos-Stream-Id")) {
return BadRequest(
"Subscribe calls should not include the 'Mesos-Stream-Id' "
"header");
}
Pipe pipe;
OK ok;
ok.headers["Content-Type"] = stringify(acceptType);
ok.type = http::Response::PIPE;
ok.reader = pipe.reader();
// Generate a stream ID and return it in the response.
id::UUID streamId = id::UUID::random();
ok.headers["Mesos-Stream-Id"] = streamId.toString();
HttpConnection http(pipe.writer(), acceptType, streamId);
this->subscribe(http, call.subscribe());
return std::move(ok);
}
if (!this->resourceProviders.subscribed.contains(
call.resource_provider_id())) {
return BadRequest("Resource provider is not subscribed");
}
ResourceProvider* resourceProvider =
this->resourceProviders.subscribed.at(call.resource_provider_id())
.get();
// This isn't a `SUBSCRIBE` call, so the request should include a stream
// ID.
if (!request.headers.contains("Mesos-Stream-Id")) {
return BadRequest(
"All non-subscribe calls should include to 'Mesos-Stream-Id' "
"header");
}
const string& streamId = request.headers.at("Mesos-Stream-Id");
if (streamId != resourceProvider->http.streamId.toString()) {
return BadRequest(
"The stream ID '" + streamId +
"' included in this request "
"didn't match the stream ID currently associated with "
" resource provider ID " +
resourceProvider->info.id().value());
}
switch (call.type()) {
case Call::UNKNOWN: {
return NotImplemented();
}
case Call::SUBSCRIBE: {
// `SUBSCRIBE` call should have been handled above.
LOG(FATAL) << "Unexpected 'SUBSCRIBE' call";
}
case Call::UPDATE_OPERATION_STATUS: {
this->updateOperationStatus(
resourceProvider, call.update_operation_status());
return Accepted();
}
case Call::UPDATE_STATE: {
this->updateState(resourceProvider, call.update_state());
return Accepted();
}
case Call::UPDATE_PUBLISH_RESOURCES_STATUS: {
this->updatePublishResourcesStatus(
resourceProvider, call.update_publish_resources_status());
return Accepted();
}
}
UNREACHABLE();
}));
}
void ResourceProviderManagerProcess::applyOperation(
const ApplyOperationMessage& message)
{
const Offer::Operation& operation = message.operation_info();
const FrameworkID& frameworkId = message.framework_id();
const UUID& operationUUID = message.operation_uuid();
Result<ResourceProviderID> resourceProviderId =
getResourceProviderId(operation);
if (!resourceProviderId.isSome()) {
LOG(ERROR) << "Failed to get the resource provider ID of operation "
<< "'" << operation.id() << "' (uuid: " << operationUUID
<< ") from framework " << frameworkId << ": "
<< (resourceProviderId.isError() ? resourceProviderId.error()
: "Not found");
return;
}
if (!resourceProviders.subscribed.contains(resourceProviderId.get())) {
LOG(WARNING) << "Dropping operation '" << operation.id() << "' (uuid: "
<< operationUUID << ") from framework " << frameworkId
<< " because resource provider " << resourceProviderId.get()
<< " is not subscribed";
return;
}
ResourceProvider* resourceProvider =
resourceProviders.subscribed.at(resourceProviderId.get()).get();
CHECK(message.resource_version_uuid().has_resource_provider_id());
CHECK_EQ(message.resource_version_uuid().resource_provider_id(),
resourceProviderId.get())
<< "Resource provider ID "
<< message.resource_version_uuid().resource_provider_id()
<< " in resource version UUID does not match that in the operation "
<< resourceProviderId.get();
Event event;
event.set_type(Event::APPLY_OPERATION);
event.mutable_apply_operation()
->mutable_framework_id()->CopyFrom(frameworkId);
event.mutable_apply_operation()->mutable_info()->CopyFrom(operation);
event.mutable_apply_operation()
->mutable_operation_uuid()->CopyFrom(message.operation_uuid());
event.mutable_apply_operation()
->mutable_resource_version_uuid()
->CopyFrom(message.resource_version_uuid().uuid());
if (!resourceProvider->http.send(event)) {
LOG(WARNING) << "Failed to send operation '" << operation.id() << "' "
<< "(uuid: " << operationUUID << ") from framework "
<< frameworkId << " to resource provider "
<< resourceProviderId.get() << ": connection closed";
}
}
void ResourceProviderManagerProcess::acknowledgeOperationStatus(
const AcknowledgeOperationStatusMessage& message)
{
CHECK(message.has_resource_provider_id());
if (!resourceProviders.subscribed.contains(message.resource_provider_id())) {
LOG(WARNING) << "Dropping operation status acknowledgement with"
<< " status_uuid " << message.status_uuid() << " and"
<< " operation_uuid " << message.operation_uuid() << " because"
<< " resource provider " << message.resource_provider_id()
<< " is not subscribed";
return;
}
ResourceProvider& resourceProvider =
*resourceProviders.subscribed.at(message.resource_provider_id());
Event event;
event.set_type(Event::ACKNOWLEDGE_OPERATION_STATUS);
event.mutable_acknowledge_operation_status()
->mutable_status_uuid()
->CopyFrom(message.status_uuid());
event.mutable_acknowledge_operation_status()
->mutable_operation_uuid()
->CopyFrom(message.operation_uuid());
if (!resourceProvider.http.send(event)) {
LOG(WARNING) << "Failed to send operation status acknowledgement with"
<< " status_uuid " << message.status_uuid() << " and"
<< " operation_uuid " << message.operation_uuid() << " to"
<< " resource provider " << message.resource_provider_id()
<< ": connection closed";
}
}
void ResourceProviderManagerProcess::reconcileOperations(
const ReconcileOperationsMessage& message)
{
hashmap<ResourceProviderID, Event> events;
auto addOperation =
[&events](const ReconcileOperationsMessage::Operation& operation) {
const ResourceProviderID resourceProviderId =
operation.resource_provider_id();
if (events.contains(resourceProviderId)) {
events.at(resourceProviderId).mutable_reconcile_operations()
->add_operation_uuids()->CopyFrom(operation.operation_uuid());
} else {
Event event;
event.set_type(Event::RECONCILE_OPERATIONS);
event.mutable_reconcile_operations()
->add_operation_uuids()->CopyFrom(operation.operation_uuid());
events[resourceProviderId] = event;
}
};
// Construct events for individual resource providers.
foreach (
const ReconcileOperationsMessage::Operation& operation,
message.operations()) {
if (operation.has_resource_provider_id()) {
if (!resourceProviders.subscribed.contains(
operation.resource_provider_id())) {
LOG(WARNING) << "Dropping operation reconciliation message with"
<< " operation_uuid " << operation.operation_uuid()
<< " because resource provider "
<< operation.resource_provider_id()
<< " is not subscribed";
continue;
}
addOperation(operation);
}
}
foreachpair (
const ResourceProviderID& resourceProviderId,
const Event& event,
events) {
CHECK(resourceProviders.subscribed.contains(resourceProviderId));
ResourceProvider& resourceProvider =
*resourceProviders.subscribed.at(resourceProviderId);
if (!resourceProvider.http.send(event)) {
LOG(WARNING) << "Failed to send operation reconciliation event"
<< " to resource provider " << resourceProviderId
<< ": connection closed";
}
}
}
Future<Nothing> ResourceProviderManagerProcess::publishResources(
const Resources& resources)
{
hashmap<ResourceProviderID, Resources> providedResources;
foreach (const Resource& resource, resources) {
// NOTE: We ignore agent default resources here because those
// resources do not need publish, and shouldn't be handled by the
// resource provider manager.
if (!resource.has_provider_id()) {
continue;
}
const ResourceProviderID& resourceProviderId = resource.provider_id();
if (!resourceProviders.subscribed.contains(resourceProviderId)) {
// TODO(chhsiao): If the manager is running on an agent and the
// resource comes from an external resource provider, we may want
// to load the provider's agent component.
return Failure(
"Resource provider " + stringify(resourceProviderId) +
" is not subscribed");
}
providedResources[resourceProviderId] += resource;
}
vector<Future<Nothing>> futures;
foreachpair (const ResourceProviderID& resourceProviderId,
const Resources& resources,
providedResources) {
UUID uuid = protobuf::createUUID();
Event event;
event.set_type(Event::PUBLISH_RESOURCES);
event.mutable_publish_resources()->mutable_uuid()->CopyFrom(uuid);
event.mutable_publish_resources()->mutable_resources()->CopyFrom(resources);
ResourceProvider* resourceProvider =
resourceProviders.subscribed.at(resourceProviderId).get();
LOG(INFO)
<< "Sending PUBLISH event " << uuid << " with resources '" << resources
<< "' to resource provider " << resourceProviderId;
if (!resourceProvider->http.send(event)) {
return Failure(
"Failed to send PUBLISH_RESOURCES event to resource provider " +
stringify(resourceProviderId) + ": connection closed");
}
Owned<Promise<Nothing>> promise(new Promise<Nothing>());
futures.push_back(promise->future());
resourceProvider->publishes.put(uuid, std::move(promise));
}
return collect(futures).then([] { return Nothing(); });
}
void ResourceProviderManagerProcess::subscribe(
const HttpConnection& http,
const Call::Subscribe& subscribe)
{
const ResourceProviderInfo& resourceProviderInfo =
subscribe.resource_provider_info();
LOG(INFO) << "Subscribing resource provider " << resourceProviderInfo;
// We always create a new `ResourceProvider` struct when a
// resource provider subscribes or resubscribes, and replace the
// existing `ResourceProvider` if needed.
Owned<ResourceProvider> resourceProvider(
new ResourceProvider(resourceProviderInfo, http));
Future<bool> admitResourceProvider;
if (!resourceProviderInfo.has_id()) {
// The resource provider is subscribing for the first time.
resourceProvider->info.mutable_id()->CopyFrom(newResourceProviderId());
// If we are handing out a new `ResourceProviderID` persist the ID by
// triggering a `AdmitResourceProvider` operation on the registrar.
admitResourceProvider =
registrar->apply(Owned<mesos::resource_provider::Registrar::Operation>(
new AdmitResourceProvider(
createRegistryResourceProvider(resourceProvider->info))));
} else {
// TODO(chhsiao): The resource provider is resubscribing after being
// restarted or an agent failover. The 'ResourceProviderInfo' might
// have been updated, but its type and name should remain the same.
// We should checkpoint its 'type', 'name' and ID, then check if the
// resubscription is consistent with the checkpointed record.
const ResourceProviderID& resourceProviderId = resourceProviderInfo.id();
if (!resourceProviders.known.contains(resourceProviderId)) {
LOG(INFO)
<< "Dropping resubscription attempt of resource provider with ID "
<< resourceProviderId
<< " since it is unknown";
return;
}
// Check whether the resource provider has change
// information which should be static.
mesos::resource_provider::registry::ResourceProvider resourceProvider_ =
createRegistryResourceProvider(resourceProvider->info);
const mesos::resource_provider::registry::ResourceProvider&
storedResourceProvider = resourceProviders.known.at(resourceProviderId);
if (resourceProvider_ != storedResourceProvider) {
LOG(INFO)
<< "Dropping resubscription attempt of resource provider "
<< resourceProvider_
<< " since it does not match the previous information "
<< storedResourceProvider;
return;
}
// If the resource provider is known we do not need to admit it
// again, and the registrar operation implicitly succeeded.
admitResourceProvider = true;
}
admitResourceProvider.onAny(defer(
self(),
&ResourceProviderManagerProcess::_subscribe,
lambda::_1,
std::move(resourceProvider)));
}
void ResourceProviderManagerProcess::_subscribe(
const Future<bool>& admitResourceProvider,
Owned<ResourceProvider> resourceProvider)
{
if (!admitResourceProvider.isReady()) {
LOG(INFO)
<< "Not subscribing resource provider " << resourceProvider->info.id()
<< " as registry update did not succeed: " << admitResourceProvider;
return;
}
CHECK(admitResourceProvider.get())
<< "Could not admit resource provider " << resourceProvider->info.id()
<< " as registry update was rejected";
const ResourceProviderID& resourceProviderId = resourceProvider->info.id();
Event event;
event.set_type(Event::SUBSCRIBED);
event.mutable_subscribed()->mutable_provider_id()
->CopyFrom(resourceProviderId);
if (!resourceProvider->http.send(event)) {
LOG(WARNING) << "Failed to send SUBSCRIBED event to resource provider "
<< resourceProviderId << ": connection closed";
return;
}
resourceProvider->http.closed()
.onAny(defer(self(), [=](const Future<Nothing>& future) {
// Iff the remote side closes the HTTP connection, the future will be
// ready. We will remove the resource provider in that case.
// This side closes the HTTP connection only when removing a resource
// provider, therefore we shouldn't try to remove it again here.
if (future.isReady()) {
CHECK(resourceProviders.subscribed.contains(resourceProviderId));
// NOTE: All pending futures of publish requests for the resource
// provider will become failed.
resourceProviders.subscribed.erase(resourceProviderId);
}
ResourceProviderMessage::Disconnect disconnect{resourceProviderId};
ResourceProviderMessage message;
message.type = ResourceProviderMessage::Type::DISCONNECT;
message.disconnect = std::move(disconnect);
messages.put(std::move(message));
}));
if (!resourceProviders.known.contains(resourceProviderId)) {
mesos::resource_provider::registry::ResourceProvider resourceProvider_ =
createRegistryResourceProvider(resourceProvider->info);
resourceProviders.known.put(
resourceProviderId,
std::move(resourceProvider_));
}
// TODO(jieyu): Start heartbeat for the resource provider.
resourceProviders.subscribed.put(
resourceProviderId,
std::move(resourceProvider));
}
void ResourceProviderManagerProcess::updateOperationStatus(
ResourceProvider* resourceProvider,
const Call::UpdateOperationStatus& update)
{
ResourceProviderMessage::UpdateOperationStatus body;
body.update.mutable_status()->CopyFrom(update.status());
body.update.mutable_operation_uuid()->CopyFrom(update.operation_uuid());
if (update.has_framework_id()) {
body.update.mutable_framework_id()->CopyFrom(update.framework_id());
}
if (update.has_latest_status()) {
body.update.mutable_latest_status()->CopyFrom(update.latest_status());
}
ResourceProviderMessage message;
message.type = ResourceProviderMessage::Type::UPDATE_OPERATION_STATUS;
message.updateOperationStatus = std::move(body);
messages.put(std::move(message));
}
void ResourceProviderManagerProcess::updateState(
ResourceProvider* resourceProvider,
const Call::UpdateState& update)
{
foreach (const Resource& resource, update.resources()) {
CHECK_EQ(resource.provider_id(), resourceProvider->info.id());
}
// TODO(chhsiao): Report pending operations.
hashmap<UUID, Operation> operations;
foreach (const Operation &operation, update.operations()) {
operations.put(operation.uuid(), operation);
}
LOG(INFO)
<< "Received UPDATE_STATE call with resources '" << update.resources()
<< "' and " << operations.size() << " operations from resource provider "
<< resourceProvider->info.id();
ResourceProviderMessage::UpdateState updateState{
resourceProvider->info,
update.resource_version_uuid(),
update.resources(),
std::move(operations)};
ResourceProviderMessage message;
message.type = ResourceProviderMessage::Type::UPDATE_STATE;
message.updateState = std::move(updateState);
messages.put(std::move(message));
}
void ResourceProviderManagerProcess::updatePublishResourcesStatus(
ResourceProvider* resourceProvider,
const Call::UpdatePublishResourcesStatus& update)
{
const UUID& uuid = update.uuid();
if (!resourceProvider->publishes.contains(uuid)) {
LOG(ERROR) << "Ignoring UpdatePublishResourcesStatus from resource"
<< " provider " << resourceProvider->info.id()
<< " because UUID " << uuid << " is unknown";
return;
}
LOG(INFO)
<< "Received UPDATE_PUBLISH_RESOURCES_STATUS call for PUBLISH_RESOURCES"
<< " event " << uuid << " with " << update.status()
<< " status from resource provider " << resourceProvider->info.id();
if (update.status() == Call::UpdatePublishResourcesStatus::OK) {
resourceProvider->publishes.at(uuid)->set(Nothing());
} else {
// TODO(jieyu): Consider to include an error message in
// 'UpdatePublishResourcesStatus' and surface that to the caller.
resourceProvider->publishes.at(uuid)->fail(
"Failed to publish resources for resource provider " +
stringify(resourceProvider->info.id()) + ": Received " +
stringify(update.status()) + " status");
}
resourceProvider->publishes.erase(uuid);
}
ResourceProviderID ResourceProviderManagerProcess::newResourceProviderId()
{
ResourceProviderID resourceProviderId;
resourceProviderId.set_value(id::UUID::random().toString());
return resourceProviderId;
}
double ResourceProviderManagerProcess::gaugeSubscribed()
{
return static_cast<double>(resourceProviders.subscribed.size());
}
ResourceProviderManagerProcess::Metrics::Metrics(
const ResourceProviderManagerProcess& manager)
: subscribed(
"resource_provider_manager/subscribed",
defer(manager, &ResourceProviderManagerProcess::gaugeSubscribed))
{
process::metrics::add(subscribed);
}
ResourceProviderManagerProcess::Metrics::~Metrics()
{
process::metrics::remove(subscribed);
}
ResourceProviderManager::ResourceProviderManager(Owned<Registrar> registrar)
: process(new ResourceProviderManagerProcess(std::move(registrar)))
{
spawn(CHECK_NOTNULL(process.get()));
}
ResourceProviderManager::~ResourceProviderManager()
{
terminate(process.get());
wait(process.get());
}
Future<http::Response> ResourceProviderManager::api(
const http::Request& request,
const Option<Principal>& principal) const
{
return dispatch(
process.get(),
&ResourceProviderManagerProcess::api,
request,
principal);
}
void ResourceProviderManager::applyOperation(
const ApplyOperationMessage& message) const
{
return dispatch(
process.get(),
&ResourceProviderManagerProcess::applyOperation,
message);
}
void ResourceProviderManager::acknowledgeOperationStatus(
const AcknowledgeOperationStatusMessage& message) const
{
return dispatch(
process.get(),
&ResourceProviderManagerProcess::acknowledgeOperationStatus,
message);
}
void ResourceProviderManager::reconcileOperations(
const ReconcileOperationsMessage& message) const
{
return dispatch(
process.get(),
&ResourceProviderManagerProcess::reconcileOperations,
message);
}
Future<Nothing> ResourceProviderManager::publishResources(
const Resources& resources)
{
return dispatch(
process.get(),
&ResourceProviderManagerProcess::publishResources,
resources);
}
Queue<ResourceProviderMessage> ResourceProviderManager::messages() const
{
return process->messages;
}
} // namespace internal {
} // namespace mesos {
| 31.76 | 80 | 0.686366 | [
"vector"
] |
abd93f5778624f50b913ea5e0fed9b803b42c5e4 | 2,214 | hpp | C++ | src/Statement.hpp | Spidey01/ngen | 60621ebba41265f802c3a94367b84e3aba889c9a | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/Statement.hpp | Spidey01/ngen | 60621ebba41265f802c3a94367b84e3aba889c9a | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/Statement.hpp | Spidey01/ngen | 60621ebba41265f802c3a94367b84e3aba889c9a | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | #ifndef NGEN_STATEMENT__HPP
#define NGEN_STATEMENT__HPP
/*
* Copyright 2019-current Terry Mathew Poulin <BigBoss1964@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <fstream>
#include <iomanip>
#include <iostream>
#include <memory>
#include <nlohmann/json.hpp>
#include <string>
#include <vector>
struct Bundle;
/** Ninja generator - base class.
*/
class Statement
{
public:
using string = std::string;
using list = std::vector<std::string>;
/** Creates an empty build statement.
*
* @param rule what rule to use.
*/
Statement(const string& rule);
Statement& appendInput(const string& input);
Statement& appendInputs(const list& inputs);
Statement& appendOutput(const string& output);
Statement& appendOutputs(const list& outputs);
Statement& appendImplicitOutput(const string& output);
Statement& appendImplicitOutputs(const list& outputs);
/** Adds implicit (|) dependencies.
*/
Statement& appendDependency(const string& dep);
Statement& appendDependencies(const list& deps);
/** Adds order-only (||) dependencies.
*/
Statement& appendOrderOnlyDependency(const string& dep);
Statement& appendOrderOnlyDependencies(const list& deps);
Statement& appendVariable(const string& name, const string& value);
friend std::ostream& operator<<(std::ostream& os, const Statement& stmt);
protected:
private:
string mRule;
list mInputs;
list mOutputs;
list mImplicitOutputs;
list mDependencies;
list mOrderOnlyDependencies;
list mVariables;
};
std::ostream& operator<<(std::ostream& os, const Statement& stmt);
#endif // NGEN_STATEMENT__HPP
| 26.357143 | 77 | 0.71093 | [
"vector"
] |
abdd8e56eba30a659dc11680ec3a7be745c6edf0 | 40,204 | cpp | C++ | Source/platform/graphics/ListContainerTest.cpp | crosswalk-project/blink-crosswalk | 16d1b69626699e9ca703e0c24c829e96d07fcd3e | [
"BSD-3-Clause"
] | 18 | 2015-04-16T09:57:11.000Z | 2020-12-09T15:58:55.000Z | Source/platform/graphics/ListContainerTest.cpp | crosswalk-project/blink-crosswalk | 16d1b69626699e9ca703e0c24c829e96d07fcd3e | [
"BSD-3-Clause"
] | 58 | 2015-01-02T14:37:31.000Z | 2015-11-30T04:58:51.000Z | Source/platform/graphics/ListContainerTest.cpp | crosswalk-project/blink-crosswalk | 16d1b69626699e9ca703e0c24c829e96d07fcd3e | [
"BSD-3-Clause"
] | 35 | 2015-01-14T00:10:29.000Z | 2022-01-20T10:28:15.000Z | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "config.h"
#include "platform/graphics/ListContainer.h"
#include "wtf/OwnPtr.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/RefPtr.h"
#include <algorithm>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
using testing::Test;
namespace blink {
namespace {
// Element class having derived classes.
class DerivedElement {
public:
virtual ~DerivedElement() {}
protected:
bool boolValues[1];
char charValues[1];
int intValues[1];
long longValues[1];
};
class DerivedElement1 : public DerivedElement {
protected:
bool boolValues1[1];
char charValues1[1];
int intValues1[1];
long longValues1[1];
};
class DerivedElement2 : public DerivedElement {
protected:
bool boolValues2[2];
char charValues2[2];
int intValues2[2];
long longValues2[2];
};
class DerivedElement3 : public DerivedElement {
protected:
bool boolValues3[3];
char charValues3[3];
int intValues3[3];
long longValues3[3];
};
const size_t kLargestDerivedElementSize = sizeof(DerivedElement3);
size_t largestDerivedElementSize()
{
static_assert(sizeof(DerivedElement1) <= kLargestDerivedElementSize,
"Largest Derived Element size needs update. DerivedElement1 is currently largest.");
static_assert(sizeof(DerivedElement2) <= kLargestDerivedElementSize,
"Largest Derived Element size needs update. DerivedElement2 is currently largest.");
return kLargestDerivedElementSize;
}
// Element class having no derived classes.
class NonDerivedElement {
public:
NonDerivedElement() {}
~NonDerivedElement() {}
int intValues[1];
};
bool isConstNonDerivedElementPointer(const NonDerivedElement* ptr)
{
return true;
}
bool isConstNonDerivedElementPointer(NonDerivedElement* ptr)
{
return false;
}
const int kMagicNumberToUseForSimpleDerivedElementOne = 42;
const int kMagicNumberToUseForSimpleDerivedElementTwo = 314;
const int kMagicNumberToUseForSimpleDerivedElementThree = 1618;
class SimpleDerivedElement : public DerivedElement {
public:
~SimpleDerivedElement() override {}
void setValue(int val) { value = val; }
int getValue() { return value; }
private:
int value;
};
class SimpleDerivedElementConstructMagicNumberOne : public SimpleDerivedElement {
public:
SimpleDerivedElementConstructMagicNumberOne()
{
setValue(kMagicNumberToUseForSimpleDerivedElementOne);
}
};
class SimpleDerivedElementConstructMagicNumberTwo : public SimpleDerivedElement {
public:
SimpleDerivedElementConstructMagicNumberTwo()
{
setValue(kMagicNumberToUseForSimpleDerivedElementTwo);
}
};
class SimpleDerivedElementConstructMagicNumberThree : public SimpleDerivedElement {
public:
SimpleDerivedElementConstructMagicNumberThree()
{
setValue(kMagicNumberToUseForSimpleDerivedElementThree);
}
};
class MockDerivedElement : public SimpleDerivedElementConstructMagicNumberOne {
public:
~MockDerivedElement() override { Destruct(); }
MOCK_METHOD0(Destruct, void());
};
class MockDerivedElementSubclass : public MockDerivedElement {
public:
MockDerivedElementSubclass()
{
setValue(kMagicNumberToUseForSimpleDerivedElementTwo);
}
};
const size_t kCurrentLargestDerivedElementSize = std::max(largestDerivedElementSize(), sizeof(MockDerivedElementSubclass));
TEST(ListContainerTest, ConstructorCalledInAllocateAndConstruct)
{
ListContainer<DerivedElement> list(kCurrentLargestDerivedElementSize);
size_t size = 2;
SimpleDerivedElementConstructMagicNumberOne* derivedElement1 = list.allocateAndConstruct<SimpleDerivedElementConstructMagicNumberOne>();
SimpleDerivedElementConstructMagicNumberTwo* derivedElement2 = list.allocateAndConstruct<SimpleDerivedElementConstructMagicNumberTwo>();
EXPECT_EQ(size, list.size());
EXPECT_EQ(derivedElement1, list.front());
EXPECT_EQ(derivedElement2, list.back());
EXPECT_EQ(kMagicNumberToUseForSimpleDerivedElementOne, derivedElement1->getValue());
EXPECT_EQ(kMagicNumberToUseForSimpleDerivedElementTwo, derivedElement2->getValue());
}
TEST(ListContainerTest, AllocateAndConstructWithArguments)
{
// Create a new OwnPtr<SimpleDerivedElement> by passing in a new SimpleDerivedElement.
ListContainer<OwnPtr<SimpleDerivedElement>> list1(kCurrentLargestDerivedElementSize);
auto* sdeOwnPtr1 = list1.allocateAndConstruct<OwnPtr<SimpleDerivedElement>>(adoptPtr(new SimpleDerivedElementConstructMagicNumberOne()));
EXPECT_EQ(1u, list1.size());
EXPECT_EQ(sdeOwnPtr1, list1.back());
EXPECT_EQ(kMagicNumberToUseForSimpleDerivedElementOne, (*sdeOwnPtr1)->getValue());
(*sdeOwnPtr1)->setValue(kMagicNumberToUseForSimpleDerivedElementTwo);
// Transfer an OwnPtr<SimpleDerivedElement> to another list.
ListContainer<OwnPtr<SimpleDerivedElement>> list2(kCurrentLargestDerivedElementSize);
auto* sdeOwnPtr2 = list2.allocateAndConstruct<OwnPtr<SimpleDerivedElement>>(sdeOwnPtr1->release());
EXPECT_EQ(1u, list2.size());
EXPECT_EQ(sdeOwnPtr2, list2.back());
EXPECT_EQ(kMagicNumberToUseForSimpleDerivedElementTwo, (*sdeOwnPtr2)->getValue());
// Verify the first OwnPtr is null after moving.
EXPECT_EQ(nullptr, list1.back()->get());
}
TEST(ListContainerTest, DestructorCalled)
{
ListContainer<DerivedElement> list(kCurrentLargestDerivedElementSize);
size_t size = 1;
MockDerivedElement* derivedElement1 = list.allocateAndConstruct<MockDerivedElement>();
EXPECT_CALL(*derivedElement1, Destruct());
EXPECT_EQ(size, list.size());
EXPECT_EQ(derivedElement1, list.front());
}
TEST(ListContainerTest, DestructorCalledOnceWhenClear)
{
ListContainer<DerivedElement> list(kCurrentLargestDerivedElementSize);
size_t size = 1;
MockDerivedElement* derivedElement1 = list.allocateAndConstruct<MockDerivedElement>();
EXPECT_EQ(size, list.size());
EXPECT_EQ(derivedElement1, list.front());
// Make sure destructor is called once during clear, and won't be called
// again.
testing::MockFunction<void()> separator;
{
testing::InSequence s;
EXPECT_CALL(*derivedElement1, Destruct());
EXPECT_CALL(separator, Call());
EXPECT_CALL(*derivedElement1, Destruct()).Times(0);
}
list.clear();
separator.Call();
}
TEST(ListContainerTest, ClearDoesNotMalloc)
{
const size_t reserve = 10;
ListContainer<DerivedElement> list(kCurrentLargestDerivedElementSize, reserve);
// Memory from the initial inner list that should be re-used after clear().
Vector<DerivedElement*> reservedElementPointers;
for (size_t i = 0; i < reserve; i++) {
DerivedElement* element = list.allocateAndConstruct<DerivedElement>();
reservedElementPointers.append(element);
}
EXPECT_EQ(0u, list.availableSizeWithoutAnotherAllocationForTesting());
// Allocate more than the reserve count, forcing new capacity to be added.
list.allocateAndConstruct<DerivedElement>();
EXPECT_NE(0u, list.availableSizeWithoutAnotherAllocationForTesting());
// Clear should free all memory except the first |reserve| elements.
list.clear();
EXPECT_EQ(reserve, list.availableSizeWithoutAnotherAllocationForTesting());
// Verify the first |reserve| elements are re-used after clear().
for (size_t i = 0; i < reserve; i++) {
DerivedElement* element = list.allocateAndConstruct<DerivedElement>();
EXPECT_EQ(element, reservedElementPointers[i]);
}
EXPECT_EQ(0u, list.availableSizeWithoutAnotherAllocationForTesting());
// Verify that capacity can still grow properly.
list.allocateAndConstruct<DerivedElement>();
EXPECT_NE(0u, list.availableSizeWithoutAnotherAllocationForTesting());
}
TEST(ListContainerTest, ReplaceExistingElement)
{
ListContainer<DerivedElement> list(kCurrentLargestDerivedElementSize);
size_t size = 1;
MockDerivedElement* derivedElement1 = list.allocateAndConstruct<MockDerivedElement>();
EXPECT_EQ(size, list.size());
EXPECT_EQ(derivedElement1, list.front());
// Make sure destructor is called once during clear, and won't be called
// again.
testing::MockFunction<void()> separator;
{
testing::InSequence s;
EXPECT_CALL(*derivedElement1, Destruct());
EXPECT_CALL(separator, Call());
EXPECT_CALL(*derivedElement1, Destruct()).Times(0);
}
list.replaceExistingElement<MockDerivedElementSubclass>(list.begin());
EXPECT_EQ(kMagicNumberToUseForSimpleDerivedElementTwo, derivedElement1->getValue());
separator.Call();
EXPECT_CALL(*derivedElement1, Destruct());
list.clear();
}
TEST(ListContainerTest, DestructorCalledOnceWhenErase)
{
ListContainer<DerivedElement> list(kCurrentLargestDerivedElementSize);
size_t size = 1;
MockDerivedElement* derivedElement1 = list.allocateAndConstruct<MockDerivedElement>();
EXPECT_EQ(size, list.size());
EXPECT_EQ(derivedElement1, list.front());
// Make sure destructor is called once during clear, and won't be called
// again.
testing::MockFunction<void()> separator;
{
testing::InSequence s;
EXPECT_CALL(*derivedElement1, Destruct());
EXPECT_CALL(separator, Call());
EXPECT_CALL(*derivedElement1, Destruct()).Times(0);
}
list.eraseAndInvalidateAllPointers(list.begin());
separator.Call();
}
TEST(ListContainerTest, SimpleIndexAccessNonDerivedElement)
{
ListContainer<NonDerivedElement> list;
size_t size = 3;
NonDerivedElement* nonDerivedElement1 = list.allocateAndConstruct<NonDerivedElement>();
NonDerivedElement* nonDerivedElement2 = list.allocateAndConstruct<NonDerivedElement>();
NonDerivedElement* nonDerivedElement3 = list.allocateAndConstruct<NonDerivedElement>();
EXPECT_EQ(size, list.size());
EXPECT_EQ(nonDerivedElement1, list.front());
EXPECT_EQ(nonDerivedElement3, list.back());
EXPECT_EQ(list.front(), list.elementAt(0));
EXPECT_EQ(nonDerivedElement2, list.elementAt(1));
EXPECT_EQ(list.back(), list.elementAt(2));
}
TEST(ListContainerTest, SimpleInsertionNonDerivedElement)
{
ListContainer<NonDerivedElement> list;
size_t size = 3;
NonDerivedElement* nonDerivedElement1 = list.allocateAndConstruct<NonDerivedElement>();
list.allocateAndConstruct<NonDerivedElement>();
NonDerivedElement* nonDerivedElement3 = list.allocateAndConstruct<NonDerivedElement>();
EXPECT_EQ(size, list.size());
EXPECT_EQ(nonDerivedElement1, list.front());
EXPECT_EQ(nonDerivedElement3, list.back());
}
TEST(ListContainerTest, SimpleInsertionAndClearNonDerivedElement)
{
ListContainer<NonDerivedElement> list;
EXPECT_TRUE(list.empty());
EXPECT_EQ(0u, list.size());
size_t size = 3;
NonDerivedElement* nonDerivedElement1 = list.allocateAndConstruct<NonDerivedElement>();
list.allocateAndConstruct<NonDerivedElement>();
NonDerivedElement* nonDerivedElement3 = list.allocateAndConstruct<NonDerivedElement>();
EXPECT_EQ(size, list.size());
EXPECT_EQ(nonDerivedElement1, list.front());
EXPECT_EQ(nonDerivedElement3, list.back());
EXPECT_FALSE(list.empty());
list.clear();
EXPECT_TRUE(list.empty());
EXPECT_EQ(0u, list.size());
}
TEST(ListContainerTest, SimpleInsertionClearAndInsertAgainNonDerivedElement)
{
ListContainer<NonDerivedElement> list;
EXPECT_TRUE(list.empty());
EXPECT_EQ(0u, list.size());
size_t size = 2;
NonDerivedElement* nonDerivedElementfront = list.allocateAndConstruct<NonDerivedElement>();
NonDerivedElement* nonDerivedElementback = list.allocateAndConstruct<NonDerivedElement>();
EXPECT_EQ(size, list.size());
EXPECT_EQ(nonDerivedElementfront, list.front());
EXPECT_EQ(nonDerivedElementback, list.back());
EXPECT_FALSE(list.empty());
list.clear();
EXPECT_TRUE(list.empty());
EXPECT_EQ(0u, list.size());
size = 3;
nonDerivedElementfront = list.allocateAndConstruct<NonDerivedElement>();
list.allocateAndConstruct<NonDerivedElement>();
nonDerivedElementback = list.allocateAndConstruct<NonDerivedElement>();
EXPECT_EQ(size, list.size());
EXPECT_EQ(nonDerivedElementfront, list.front());
EXPECT_EQ(nonDerivedElementback, list.back());
EXPECT_FALSE(list.empty());
}
// This test is used to test when there is more than one allocation needed
// for, ListContainer can still perform like normal vector.
TEST(ListContainerTest, SimpleInsertionTriggerMoreThanOneAllocationNonDerivedElement)
{
ListContainer<NonDerivedElement> list(sizeof(NonDerivedElement), 2);
std::vector<NonDerivedElement*> nonDerivedElementlist;
size_t size = 10;
for (size_t i = 0; i < size; ++i)
nonDerivedElementlist.push_back(list.allocateAndConstruct<NonDerivedElement>());
EXPECT_EQ(size, list.size());
ListContainer<NonDerivedElement>::Iterator iter = list.begin();
for (std::vector<NonDerivedElement*>::const_iterator nonderivedElementIter = nonDerivedElementlist.begin(); nonderivedElementIter != nonDerivedElementlist.end(); ++nonderivedElementIter) {
EXPECT_EQ(*nonderivedElementIter, *iter);
++iter;
}
}
TEST(ListContainerTest, CorrectAllocationSizeForMoreThanOneAllocationNonDerivedElement)
{
// Constructor sets the allocation size to 2. Every time ListContainer needs
// to allocate again, it doubles allocation size. In this test, 10 elements is
// needed, thus ListContainerShould allocate spaces 2, 4 and 8 elements.
ListContainer<NonDerivedElement> list(sizeof(NonDerivedElement), 2);
std::vector<NonDerivedElement*> nonDerivedElementlist;
size_t size = 10;
for (size_t i = 0; i < size; ++i) {
// Before asking for a new element, space available without another
// allocation follows.
switch (i) {
case 2:
case 6:
EXPECT_EQ(0u, list.availableSizeWithoutAnotherAllocationForTesting());
break;
case 1:
case 5:
EXPECT_EQ(1u, list.availableSizeWithoutAnotherAllocationForTesting());
break;
case 0:
case 4:
EXPECT_EQ(2u, list.availableSizeWithoutAnotherAllocationForTesting());
break;
case 3:
EXPECT_EQ(3u, list.availableSizeWithoutAnotherAllocationForTesting());
break;
case 9:
EXPECT_EQ(5u, list.availableSizeWithoutAnotherAllocationForTesting());
break;
case 8:
EXPECT_EQ(6u, list.availableSizeWithoutAnotherAllocationForTesting());
break;
case 7:
EXPECT_EQ(7u, list.availableSizeWithoutAnotherAllocationForTesting());
break;
default:
break;
}
nonDerivedElementlist.push_back(list.allocateAndConstruct<NonDerivedElement>());
// After asking for a new element, space available without another
// allocation follows.
switch (i) {
case 1:
case 5:
EXPECT_EQ(0u, list.availableSizeWithoutAnotherAllocationForTesting());
break;
case 0:
case 4:
EXPECT_EQ(1u, list.availableSizeWithoutAnotherAllocationForTesting());
break;
case 3:
EXPECT_EQ(2u, list.availableSizeWithoutAnotherAllocationForTesting());
break;
case 2:
EXPECT_EQ(3u, list.availableSizeWithoutAnotherAllocationForTesting());
break;
case 9:
EXPECT_EQ(4u, list.availableSizeWithoutAnotherAllocationForTesting());
break;
case 8:
EXPECT_EQ(5u, list.availableSizeWithoutAnotherAllocationForTesting());
break;
case 7:
EXPECT_EQ(6u, list.availableSizeWithoutAnotherAllocationForTesting());
break;
case 6:
EXPECT_EQ(7u, list.availableSizeWithoutAnotherAllocationForTesting());
break;
default:
break;
}
}
EXPECT_EQ(size, list.size());
ListContainer<NonDerivedElement>::Iterator iter = list.begin();
for (std::vector<NonDerivedElement*>::const_iterator nonderivedElementIter = nonDerivedElementlist.begin(); nonderivedElementIter != nonDerivedElementlist.end(); ++nonderivedElementIter) {
EXPECT_EQ(*nonderivedElementIter, *iter);
++iter;
}
}
TEST(ListContainerTest, SimpleIterationNonDerivedElement)
{
ListContainer<NonDerivedElement> list;
std::vector<NonDerivedElement*> nonDerivedElementlist;
size_t size = 10;
for (size_t i = 0; i < size; ++i)
nonDerivedElementlist.push_back(list.allocateAndConstruct<NonDerivedElement>());
EXPECT_EQ(size, list.size());
size_t numItersInList = 0;
{
std::vector<NonDerivedElement*>::const_iterator nonderivedElementIter = nonDerivedElementlist.begin();
for (ListContainer<NonDerivedElement>::Iterator iter = list.begin(); iter != list.end(); ++iter) {
EXPECT_EQ(*nonderivedElementIter, *iter);
++numItersInList;
++nonderivedElementIter;
}
}
size_t numItersInVector = 0;
{
ListContainer<NonDerivedElement>::Iterator iter = list.begin();
for (std::vector<NonDerivedElement*>::const_iterator nonderivedElementIter = nonDerivedElementlist.begin(); nonderivedElementIter != nonDerivedElementlist.end(); ++nonderivedElementIter) {
EXPECT_EQ(*nonderivedElementIter, *iter);
++numItersInVector;
++iter;
}
}
EXPECT_EQ(numItersInVector, numItersInList);
}
TEST(ListContainerTest, SimpleConstIteratorIterationNonDerivedElement)
{
ListContainer<NonDerivedElement> list;
std::vector<const NonDerivedElement*> nonDerivedElementlist;
size_t size = 10;
for (size_t i = 0; i < size; ++i)
nonDerivedElementlist.push_back(list.allocateAndConstruct<NonDerivedElement>());
EXPECT_EQ(size, list.size());
{
std::vector<const NonDerivedElement*>::const_iterator nonderivedElementIter = nonDerivedElementlist.begin();
for (ListContainer<NonDerivedElement>::ConstIterator iter = list.begin(); iter != list.end(); ++iter) {
EXPECT_TRUE(isConstNonDerivedElementPointer(*iter));
EXPECT_EQ(*nonderivedElementIter, *iter);
++nonderivedElementIter;
}
}
{
std::vector<const NonDerivedElement*>::const_iterator nonderivedElementIter = nonDerivedElementlist.begin();
for (ListContainer<NonDerivedElement>::Iterator iter = list.begin(); iter != list.end(); ++iter) {
EXPECT_FALSE(isConstNonDerivedElementPointer(*iter));
EXPECT_EQ(*nonderivedElementIter, *iter);
++nonderivedElementIter;
}
}
{
ListContainer<NonDerivedElement>::ConstIterator iter = list.begin();
for (std::vector<const NonDerivedElement*>::const_iterator nonderivedElementIter = nonDerivedElementlist.begin(); nonderivedElementIter != nonDerivedElementlist.end(); ++nonderivedElementIter) {
EXPECT_EQ(*nonderivedElementIter, *iter);
++iter;
}
}
}
TEST(ListContainerTest, SimpleReverseInsertionNonDerivedElement)
{
ListContainer<NonDerivedElement> list;
std::vector<NonDerivedElement*> nonDerivedElementlist;
size_t size = 10;
for (size_t i = 0; i < size; ++i)
nonDerivedElementlist.push_back(list.allocateAndConstruct<NonDerivedElement>());
EXPECT_EQ(size, list.size());
{
std::vector<NonDerivedElement*>::const_reverse_iterator nonderivedElementIter =
nonDerivedElementlist.rbegin();
for (ListContainer<NonDerivedElement>::ReverseIterator iter = list.rbegin(); iter != list.rend(); ++iter) {
EXPECT_EQ(*nonderivedElementIter, *iter);
++nonderivedElementIter;
}
}
{
ListContainer<NonDerivedElement>::ReverseIterator iter = list.rbegin();
for (std::vector<NonDerivedElement*>::reverse_iterator nonderivedElementIter = nonDerivedElementlist.rbegin(); nonderivedElementIter != nonDerivedElementlist.rend(); ++nonderivedElementIter) {
EXPECT_EQ(*nonderivedElementIter, *iter);
++iter;
}
}
}
TEST(ListContainerTest, SimpleDeletion)
{
ListContainer<DerivedElement> list(kCurrentLargestDerivedElementSize);
std::vector<SimpleDerivedElement*> simpleDerivedElementList;
int size = 10;
for (int i = 0; i < size; ++i) {
simpleDerivedElementList.push_back(list.allocateAndConstruct<SimpleDerivedElement>());
simpleDerivedElementList.back()->setValue(i);
}
EXPECT_EQ(static_cast<size_t>(size), list.size());
list.eraseAndInvalidateAllPointers(list.begin());
--size;
EXPECT_EQ(static_cast<size_t>(size), list.size());
int i = 1;
for (ListContainer<DerivedElement>::Iterator iter = list.begin(); iter != list.end(); ++iter) {
EXPECT_EQ(i, static_cast<SimpleDerivedElement*>(*iter)->getValue());
++i;
}
}
TEST(ListContainerTest, DeletionAllInAllocation)
{
const size_t kReserve = 10;
ListContainer<DerivedElement> list(kCurrentLargestDerivedElementSize, kReserve);
std::vector<SimpleDerivedElement*> simpleDerivedElementList;
// Add enough elements to cause another allocation.
for (size_t i = 0; i < kReserve + 1; ++i) {
simpleDerivedElementList.push_back(list.allocateAndConstruct<SimpleDerivedElement>());
simpleDerivedElementList.back()->setValue(static_cast<int>(i));
}
EXPECT_EQ(kReserve + 1, list.size());
// Remove everything in the first allocation.
for (size_t i = 0; i < kReserve; ++i)
list.eraseAndInvalidateAllPointers(list.begin());
EXPECT_EQ(1u, list.size());
// The last element is left.
SimpleDerivedElement* de = static_cast<SimpleDerivedElement*>(*list.begin());
EXPECT_EQ(static_cast<int>(kReserve), de->getValue());
// Remove the element from the 2nd allocation.
list.eraseAndInvalidateAllPointers(list.begin());
EXPECT_EQ(0u, list.size());
}
TEST(ListContainerTest, DeletionAllInAllocationReversed)
{
const size_t kReserve = 10;
ListContainer<DerivedElement> list(kCurrentLargestDerivedElementSize, kReserve);
std::vector<SimpleDerivedElement*> simpleDerivedElementList;
// Add enough elements to cause another allocation.
for (size_t i = 0; i < kReserve + 1; ++i) {
simpleDerivedElementList.push_back(list.allocateAndConstruct<SimpleDerivedElement>());
simpleDerivedElementList.back()->setValue(static_cast<int>(i));
}
EXPECT_EQ(kReserve + 1, list.size());
// Remove everything in the 2nd allocation.
auto it = list.begin();
for (size_t i = 0; i < kReserve; ++i)
++it;
list.eraseAndInvalidateAllPointers(it);
// The 2nd-last element is next, and the rest of the elements exist.
size_t i = kReserve - 1;
for (auto it = list.rbegin(); it != list.rend(); ++it) {
SimpleDerivedElement* de = static_cast<SimpleDerivedElement*>(*it);
EXPECT_EQ(static_cast<int>(i), de->getValue());
--i;
}
// Can forward iterate too.
i = 0;
for (auto it = list.begin(); it != list.end(); ++it) {
SimpleDerivedElement* de = static_cast<SimpleDerivedElement*>(*it);
EXPECT_EQ(static_cast<int>(i), de->getValue());
++i;
}
// Remove the last thing from the 1st allocation.
it = list.begin();
for (size_t i = 0; i < kReserve - 1; ++i)
++it;
list.eraseAndInvalidateAllPointers(it);
// The 2nd-last element is next, and the rest of the elements exist.
i = kReserve - 2;
for (auto it = list.rbegin(); it != list.rend(); ++it) {
SimpleDerivedElement* de = static_cast<SimpleDerivedElement*>(*it);
EXPECT_EQ(static_cast<int>(i), de->getValue());
--i;
}
// Can forward iterate too.
i = 0;
for (auto it = list.begin(); it != list.end(); ++it) {
SimpleDerivedElement* de = static_cast<SimpleDerivedElement*>(*it);
EXPECT_EQ(static_cast<int>(i), de->getValue());
++i;
}
}
TEST(ListContainerTest, SimpleIterationAndManipulation)
{
ListContainer<DerivedElement> list(kCurrentLargestDerivedElementSize);
std::vector<SimpleDerivedElement*> simpleDerivedElementList;
size_t size = 10;
for (size_t i = 0; i < size; ++i) {
SimpleDerivedElement* simpleDerivedElement = list.allocateAndConstruct<SimpleDerivedElement>();
simpleDerivedElementList.push_back(simpleDerivedElement);
}
EXPECT_EQ(size, list.size());
ListContainer<DerivedElement>::Iterator iter = list.begin();
for (int i = 0; i < 10; ++i) {
static_cast<SimpleDerivedElement*>(*iter)->setValue(i);
++iter;
}
int i = 0;
for (std::vector<SimpleDerivedElement*>::const_iterator simpleNonderivedElementIter =
simpleDerivedElementList.begin();
simpleNonderivedElementIter < simpleDerivedElementList.end(); ++simpleNonderivedElementIter) {
EXPECT_EQ(i, (*simpleNonderivedElementIter)->getValue());
++i;
}
}
TEST(ListContainerTest, SimpleManipulationWithIndexSimpleDerivedElement)
{
ListContainer<DerivedElement> list(kCurrentLargestDerivedElementSize);
std::vector<SimpleDerivedElement*> derivedElementlist;
int size = 10;
for (int i = 0; i < size; ++i)
derivedElementlist.push_back(list.allocateAndConstruct<SimpleDerivedElement>());
EXPECT_EQ(static_cast<size_t>(size), list.size());
for (int i = 0; i < size; ++i)
static_cast<SimpleDerivedElement*>(list.elementAt(i))->setValue(i);
int i = 0;
for (std::vector<SimpleDerivedElement*>::const_iterator derivedElementIter = derivedElementlist.begin(); derivedElementIter != derivedElementlist.end(); ++derivedElementIter, ++i)
EXPECT_EQ(i, (*derivedElementIter)->getValue());
}
TEST(ListContainerTest, SimpleManipulationWithIndexMoreThanOneAllocationSimpleDerivedElement)
{
ListContainer<DerivedElement> list(largestDerivedElementSize(), 2);
std::vector<SimpleDerivedElement*> derivedElementlist;
int size = 10;
for (int i = 0; i < size; ++i)
derivedElementlist.push_back(list.allocateAndConstruct<SimpleDerivedElement>());
EXPECT_EQ(static_cast<size_t>(size), list.size());
for (int i = 0; i < size; ++i)
static_cast<SimpleDerivedElement*>(list.elementAt(i))->setValue(i);
int i = 0;
for (std::vector<SimpleDerivedElement*>::const_iterator derivedElementIter = derivedElementlist.begin(); derivedElementIter != derivedElementlist.end(); ++derivedElementIter, ++i)
EXPECT_EQ(i, (*derivedElementIter)->getValue());
}
TEST(ListContainerTest, SimpleIterationAndReverseIterationWithIndexNonDerivedElement)
{
ListContainer<NonDerivedElement> list;
std::vector<NonDerivedElement*> nonDerivedElementlist;
size_t size = 10;
for (size_t i = 0; i < size; ++i)
nonDerivedElementlist.push_back(list.allocateAndConstruct<NonDerivedElement>());
EXPECT_EQ(size, list.size());
size_t i = 0;
for (ListContainer<NonDerivedElement>::Iterator iter = list.begin(); iter != list.end(); ++iter) {
EXPECT_EQ(i, iter.index());
++i;
}
i = 0;
for (ListContainer<NonDerivedElement>::ReverseIterator iter = list.rbegin(); iter != list.rend(); ++iter) {
EXPECT_EQ(i, iter.index());
++i;
}
}
// Increments an int when constructed (or the counter pointer is supplied) and
// decrements when destructed.
class InstanceCounter {
public:
InstanceCounter() : m_counter(nullptr) {}
explicit InstanceCounter(int* counter) { setCounter(counter); }
~InstanceCounter()
{
if (m_counter)
--*m_counter;
}
void setCounter(int* counter)
{
m_counter = counter;
++*m_counter;
}
private:
int* m_counter;
};
TEST(ListContainerTest, RemoveLastDestruction)
{
// We keep an explicit instance count to make sure that the destructors are
// indeed getting called.
int counter = 0;
ListContainer<InstanceCounter> list(sizeof(InstanceCounter), 1);
EXPECT_EQ(0, counter);
EXPECT_EQ(0u, list.size());
// We should be okay to add one and then go back to zero.
list.allocateAndConstruct<InstanceCounter>()->setCounter(&counter);
EXPECT_EQ(1, counter);
EXPECT_EQ(1u, list.size());
list.removeLast();
EXPECT_EQ(0, counter);
EXPECT_EQ(0u, list.size());
// We should also be okay to remove the last multiple times, as long as there
// are enough elements in the first place.
list.allocateAndConstruct<InstanceCounter>()->setCounter(&counter);
list.allocateAndConstruct<InstanceCounter>()->setCounter(&counter);
list.allocateAndConstruct<InstanceCounter>()->setCounter(&counter);
list.allocateAndConstruct<InstanceCounter>()->setCounter(&counter);
list.allocateAndConstruct<InstanceCounter>()->setCounter(&counter);
list.allocateAndConstruct<InstanceCounter>()->setCounter(&counter);
list.removeLast();
list.removeLast();
EXPECT_EQ(4, counter); // Leaves one in the last list.
EXPECT_EQ(4u, list.size());
list.removeLast();
EXPECT_EQ(3, counter); // Removes an inner list from before.
EXPECT_EQ(3u, list.size());
}
// TODO(jbroman): std::equal would work if ListContainer iterators satisfied the
// usual STL iterator constraints. We should fix that.
template <typename It1, typename It2>
bool Equal(It1 it1, const It1& end1, It2 it2)
{
for (; it1 != end1; ++it1, ++it2) {
if (!(*it1 == *it2))
return false;
}
return true;
}
TEST(ListContainerTest, RemoveLastIteration)
{
struct SmallStruct {
char dummy[16];
};
ListContainer<SmallStruct> list(sizeof(SmallStruct), 1);
std::vector<SmallStruct*> pointers;
// Utilities which keep these two lists in sync and check that their iteration
// order matches.
auto push = [&list, &pointers]()
{
pointers.push_back(list.allocateAndConstruct<SmallStruct>());
};
auto pop = [&list, &pointers]()
{
pointers.pop_back();
list.removeLast();
};
auto check_equal = [&list, &pointers]()
{
// They should be of the same size, and compare equal with all four kinds of
// iteration.
// Apparently Mac doesn't have vector::cbegin and vector::crbegin?
const auto& constPointers = pointers;
ASSERT_EQ(list.size(), pointers.size());
ASSERT_TRUE(Equal(list.begin(), list.end(), pointers.begin()));
ASSERT_TRUE(Equal(list.cbegin(), list.cend(), constPointers.begin()));
ASSERT_TRUE(Equal(list.rbegin(), list.rend(), pointers.rbegin()));
ASSERT_TRUE(Equal(list.crbegin(), list.crend(), constPointers.rbegin()));
};
check_equal(); // Initially empty.
push();
check_equal(); // One full inner list.
push();
check_equal(); // One full, one partially full.
push();
push();
check_equal(); // Two full, one partially full.
pop();
check_equal(); // Two full, one empty.
pop();
check_equal(); // One full, one partially full, one empty.
pop();
check_equal(); // One full, one empty.
push();
pop();
pop();
ASSERT_TRUE(list.empty());
check_equal(); // Empty.
}
TEST(ListContainerTest, AppendByMovingSameList)
{
ListContainer<SimpleDerivedElement> list(kCurrentLargestDerivedElementSize);
list.allocateAndConstruct<SimpleDerivedElementConstructMagicNumberOne>();
list.appendByMoving(list.front());
EXPECT_EQ(kMagicNumberToUseForSimpleDerivedElementOne, list.back()->getValue());
EXPECT_EQ(2u, list.size());
list.front()->setValue(kMagicNumberToUseForSimpleDerivedElementTwo);
EXPECT_EQ(kMagicNumberToUseForSimpleDerivedElementTwo, list.front()->getValue());
list.appendByMoving(list.front());
EXPECT_EQ(kMagicNumberToUseForSimpleDerivedElementTwo, list.back()->getValue());
EXPECT_EQ(3u, list.size());
}
TEST(ListContainerTest, AppendByMovingDoesNotDestruct)
{
ListContainer<DerivedElement> list1(kCurrentLargestDerivedElementSize);
ListContainer<DerivedElement> list2(kCurrentLargestDerivedElementSize);
MockDerivedElement* mde1 = list1.allocateAndConstruct<MockDerivedElement>();
// Make sure destructor isn't called during AppendByMoving.
list2.appendByMoving(mde1);
EXPECT_CALL(*mde1, Destruct()).Times(0);
testing::Mock::VerifyAndClearExpectations(mde1);
mde1 = static_cast<MockDerivedElement*>(list2.back());
EXPECT_CALL(*mde1, Destruct());
}
TEST(ListContainerTest, AppendByMovingReturnsMovedPointer)
{
ListContainer<SimpleDerivedElement> list1(kCurrentLargestDerivedElementSize);
ListContainer<SimpleDerivedElement> list2(kCurrentLargestDerivedElementSize);
SimpleDerivedElement* simpleElement = list1.allocateAndConstruct<SimpleDerivedElement>();
SimpleDerivedElement* movedElement1 = list2.appendByMoving(simpleElement);
EXPECT_EQ(list2.back(), movedElement1);
SimpleDerivedElement* movedElement2 = list1.appendByMoving(movedElement1);
EXPECT_EQ(list1.back(), movedElement2);
EXPECT_NE(movedElement1, movedElement2);
}
TEST(ListContainerTest, AppendByMovingReplacesSourceWithNewDerivedElement)
{
ListContainer<SimpleDerivedElementConstructMagicNumberOne> list1(kCurrentLargestDerivedElementSize);
ListContainer<SimpleDerivedElementConstructMagicNumberTwo> list2(kCurrentLargestDerivedElementSize);
list1.allocateAndConstruct<SimpleDerivedElementConstructMagicNumberOne>();
EXPECT_EQ(kMagicNumberToUseForSimpleDerivedElementOne,
list1.front()->getValue());
list2.appendByMoving(list1.front());
EXPECT_EQ(kMagicNumberToUseForSimpleDerivedElementOne,
list1.front()->getValue());
EXPECT_EQ(kMagicNumberToUseForSimpleDerivedElementOne,
list2.front()->getValue());
// Change the value of list2.front() to ensure the value is actually moved.
list2.back()->setValue(kMagicNumberToUseForSimpleDerivedElementThree);
list1.appendByMoving(list2.back());
EXPECT_EQ(kMagicNumberToUseForSimpleDerivedElementOne,
list1.front()->getValue());
EXPECT_EQ(kMagicNumberToUseForSimpleDerivedElementThree,
list1.back()->getValue());
EXPECT_EQ(kMagicNumberToUseForSimpleDerivedElementTwo,
list2.back()->getValue());
// AppendByMoving replaces the source element with a new derived element so
// we do not expect sizes to shrink after AppendByMoving is called.
EXPECT_EQ(2u, list1.size()); // One direct allocation and one AppendByMoving.
EXPECT_EQ(1u, list2.size()); // One AppendByMoving.
}
const size_t kLongCountForLongSimpleDerivedElement = 5;
class LongSimpleDerivedElement : public SimpleDerivedElement {
public:
~LongSimpleDerivedElement() override {}
void setAllValues(unsigned long value)
{
for (size_t i = 0; i < kLongCountForLongSimpleDerivedElement; i++)
values[i] = value;
}
bool areAllValuesEqualTo(size_t value) const
{
for (size_t i = 1; i < kLongCountForLongSimpleDerivedElement; i++) {
if (values[i] != values[0])
return false;
}
return true;
}
private:
unsigned long values[kLongCountForLongSimpleDerivedElement];
};
const unsigned long kMagicNumberToUseForLongSimpleDerivedElement = 2718ul;
class LongSimpleDerivedElementConstructMagicNumber : public LongSimpleDerivedElement {
public:
LongSimpleDerivedElementConstructMagicNumber()
{
setAllValues(kMagicNumberToUseForLongSimpleDerivedElement);
}
};
TEST(ListContainerTest, AppendByMovingLongAndSimpleDerivedElements)
{
static_assert(sizeof(LongSimpleDerivedElement) > sizeof(SimpleDerivedElement),
"LongSimpleDerivedElement should be larger than "
"SimpleDerivedElement's size.");
static_assert(sizeof(LongSimpleDerivedElement) <= kLargestDerivedElementSize,
"LongSimpleDerivedElement should be smaller than the maximum "
"DerivedElement size.");
ListContainer<SimpleDerivedElement> list(kCurrentLargestDerivedElementSize);
list.allocateAndConstruct<LongSimpleDerivedElementConstructMagicNumber>();
list.allocateAndConstruct<SimpleDerivedElementConstructMagicNumberOne>();
EXPECT_TRUE(static_cast<LongSimpleDerivedElement*>(list.front())->areAllValuesEqualTo(kMagicNumberToUseForLongSimpleDerivedElement));
EXPECT_EQ(kMagicNumberToUseForSimpleDerivedElementOne, list.back()->getValue());
// Test that moving a simple derived element actually moves enough data so
// that the LongSimpleDerivedElement at this location is entirely moved.
SimpleDerivedElement* simpleElement = list.back();
list.appendByMoving(list.front());
EXPECT_TRUE(static_cast<LongSimpleDerivedElement*>(list.back())->areAllValuesEqualTo(kMagicNumberToUseForLongSimpleDerivedElement));
EXPECT_EQ(kMagicNumberToUseForSimpleDerivedElementOne, simpleElement->getValue());
LongSimpleDerivedElement* longElement = static_cast<LongSimpleDerivedElement*>(list.back());
list.appendByMoving(simpleElement);
EXPECT_TRUE(longElement->areAllValuesEqualTo(kMagicNumberToUseForLongSimpleDerivedElement));
EXPECT_EQ(kMagicNumberToUseForSimpleDerivedElementOne, list.back()->getValue());
}
TEST(ListContainerTest, Swap)
{
ListContainer<SimpleDerivedElement> list1(kCurrentLargestDerivedElementSize);
list1.allocateAndConstruct<SimpleDerivedElementConstructMagicNumberOne>();
ListContainer<SimpleDerivedElement> list2(kCurrentLargestDerivedElementSize);
list2.allocateAndConstruct<SimpleDerivedElementConstructMagicNumberTwo>();
list2.allocateAndConstruct<SimpleDerivedElementConstructMagicNumberThree>();
SimpleDerivedElement* preSwapList1Front = list1.front();
EXPECT_EQ(kMagicNumberToUseForSimpleDerivedElementOne, list1.front()->getValue());
EXPECT_EQ(1u, list1.size());
EXPECT_EQ(kMagicNumberToUseForSimpleDerivedElementTwo, list2.front()->getValue());
EXPECT_EQ(kMagicNumberToUseForSimpleDerivedElementThree, list2.back()->getValue());
EXPECT_EQ(2u, list2.size());
list2.swap(list1);
EXPECT_EQ(kMagicNumberToUseForSimpleDerivedElementTwo, list1.front()->getValue());
EXPECT_EQ(kMagicNumberToUseForSimpleDerivedElementThree, list1.back()->getValue());
EXPECT_EQ(2u, list1.size());
EXPECT_EQ(kMagicNumberToUseForSimpleDerivedElementOne, list2.front()->getValue());
EXPECT_EQ(1u, list2.size());
// Ensure pointers are still valid after swapping.
EXPECT_EQ(preSwapList1Front, list2.front());
}
TEST(ListContainerTest, GetCapacityInBytes)
{
const int iterations = 500;
const size_t initialCapacity = 10;
const size_t upperBoundOnMinCapacity = initialCapacity;
// At time of writing, removing elements from the end can cause up to 7x the
// memory required to be consumed, in the worst case, since we can have up to
// two trailing inner lists that are empty (for 2*size + 4*size in unused
// memory, due to the exponential growth strategy).
const size_t maxWasteFactor = 8;
ListContainer<DerivedElement> list(largestDerivedElementSize(), initialCapacity);
// The capacity should grow with the list.
for (int i = 0; i < iterations; i++) {
size_t capacity = list.getCapacityInBytes();
ASSERT_GE(capacity, list.size() * largestDerivedElementSize());
ASSERT_LE(capacity,
std::max(list.size(),
upperBoundOnMinCapacity) * maxWasteFactor * largestDerivedElementSize());
list.allocateAndConstruct<DerivedElement1>();
}
// The capacity should shrink with the list.
for (int i = 0; i < iterations; i++) {
size_t capacity = list.getCapacityInBytes();
ASSERT_GE(capacity, list.size() * largestDerivedElementSize());
ASSERT_LE(capacity,
std::max(list.size(),
upperBoundOnMinCapacity) * maxWasteFactor * largestDerivedElementSize());
list.removeLast();
}
}
} // namespace
} // namespace blink
| 37.088561 | 202 | 0.713934 | [
"vector"
] |
abdf54ba08c6e5de98ad267dc00e9b625de0c179 | 2,164 | cpp | C++ | descompune/bogdan_30.cpp | palcu/rotopcoder | 01e61abb6b8549590403ae37f68941cbee8cb8b8 | [
"MIT"
] | 1 | 2018-04-25T11:33:47.000Z | 2018-04-25T11:33:47.000Z | descompune/bogdan_30.cpp | palcu/rotopcoder | 01e61abb6b8549590403ae37f68941cbee8cb8b8 | [
"MIT"
] | 1 | 2015-11-15T12:11:33.000Z | 2015-11-15T12:11:33.000Z | descompune/bogdan_30.cpp | palcu/rotopcoder | 01e61abb6b8549590403ae37f68941cbee8cb8b8 | [
"MIT"
] | 1 | 2018-04-25T11:33:48.000Z | 2018-04-25T11:33:48.000Z | /*
Bogdan Tirca
Problema Descompune
Complexitate: O(N^(PROP_LEN / WORD_LEN))
*/
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <cstring>
using namespace std;
#define INF (1 << 30)
#define PROP_LEN 100001
#define WORD_LEN 50
// Optimisations
#define OPT1 false
string prop;
int n;
vector <pair <string, int> > dict;
int dp[PROP_LEN], back[PROP_LEN];
int backSol[PROP_LEN];
int minCost;
vector <string> words;
void read() {
string cuv;
int cost;
ifstream fin("descompune.in");
fin >> prop;
fin >> n;
for (int i = 0; i < n; ++i) {
fin >> cuv >> cost;
dict.push_back(make_pair(cuv, cost));
}
}
void write() {
ofstream fout("descompune.out");
if (minCost == INF) {
fout << "-1\n";
} else {
for (int i = words.size() - 1; i >= 0; --i) {
fout << words[i] << " ";
}
fout << "\n" << minCost << "\n";
}
}
bool matchEnd(string &word, int right) {
int r1 = right, r2 = word.length() - 1;
for ( ;prop[r1] == word[r2] && r1 >= 0 && r2 >= 0; --r1, --r2);
return (r2 == -1);
}
void backt(int propPos) {
if (propPos == prop.length() - 1) {
// Solutie
if (minCost > dp[prop.length()]) {
minCost = dp[prop.length()];
memcpy(backSol, back, sizeof(int) * PROP_LEN);
}
} else {
for (int it = 0; it < dict.size(); ++it) {
pair<string, int> &word = dict[it];
int right = propPos + word.first.length();
int left = propPos + 1;
if (right < prop.length() && matchEnd(word.first, right)) {
if (OPT1 && dp[left] + word.second < dp[right + 1] || !OPT1) {
dp[right + 1] = dp[left] + word.second;
back[right + 1] = left;
backt(right);
}
}
}
}
}
void solve() {
minCost = INF;
for (int right = 1; right <= prop.length(); ++right) {
dp[right] = INF;
}
backt(-1);
// Reconstituim solutia de cost minim
if (minCost != INF) {
int left, right = prop.length();
while ((left = backSol[right]) != 0) {
words.push_back(prop.substr(left, right - left));
right = left;
}
words.push_back(prop.substr(0, right));
}
}
int main() {
read();
solve();
write();
return 0;
}
| 19.853211 | 67 | 0.561922 | [
"vector"
] |
abe7ba1ff9d2ca912a53e23a29922940d2443da2 | 137,057 | cpp | C++ | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/corelib/global/qglobal.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/corelib/global/qglobal.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/corelib/global/qglobal.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Copyright (C) 2016 Intel Corporation.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qplatformdefs.h"
#include "qstring.h"
#include "qvector.h"
#include "qlist.h"
#include "qthreadstorage.h"
#include "qdir.h"
#include "qdatetime.h"
#include "qoperatingsystemversion.h"
#include "qoperatingsystemversion_p.h"
#if defined(Q_OS_WIN) || defined(Q_OS_CYGWIN) || defined(Q_OS_WINRT)
#include "qoperatingsystemversion_win_p.h"
#endif
#include <private/qlocale_tools_p.h>
#include <qmutex.h>
#ifndef QT_NO_QOBJECT
#include <private/qthread_p.h>
#endif
#include <stdlib.h>
#include <limits.h>
#include <stdarg.h>
#include <string.h>
#ifndef QT_NO_EXCEPTIONS
# include <string>
# include <exception>
#endif
#include <errno.h>
#if defined(Q_CC_MSVC)
# include <crtdbg.h>
#endif
#ifdef Q_OS_WINRT
#include <Ws2tcpip.h>
#endif // Q_OS_WINRT
#if defined(Q_OS_VXWORKS) && defined(_WRS_KERNEL)
# include <envLib.h>
#endif
#if defined(Q_OS_ANDROID) && !defined(Q_OS_ANDROID_EMBEDDED)
#include <private/qjni_p.h>
#endif
#if defined(Q_OS_SOLARIS)
# include <sys/systeminfo.h>
#endif
#ifdef Q_OS_UNIX
#include <sys/utsname.h>
#include <private/qcore_unix_p.h>
#endif
#ifdef Q_OS_BSD4
#include <sys/sysctl.h>
#endif
#if defined(Q_OS_INTEGRITY)
extern "C" {
// Function mmap resides in libshm_client.a. To be able to link with it one needs
// to define symbols 'shm_area_password' and 'shm_area_name', because the library
// is meant to allow the application that links to it to use POSIX shared memory
// without full system POSIX.
# pragma weak shm_area_password
# pragma weak shm_area_name
char *shm_area_password = "dummy";
char *shm_area_name = "dummy";
}
#endif
#include "archdetect.cpp"
#ifdef qFatal
// the qFatal in this file are just redirections from elsewhere, so
// don't capture any context again
# undef qFatal
#endif
QT_BEGIN_NAMESPACE
#if !QT_DEPRECATED_SINCE(5, 0)
// Make sure they're defined to be exported
Q_CORE_EXPORT void *qMemCopy(void *dest, const void *src, size_t n);
Q_CORE_EXPORT void *qMemSet(void *dest, int c, size_t n);
#endif
// Statically check assumptions about the environment we're running
// in. The idea here is to error or warn if otherwise implicit Qt
// assumptions are not fulfilled on new hardware or compilers
// (if this list becomes too long, consider factoring into a separate file)
Q_STATIC_ASSERT_X(sizeof(int) == 4, "Qt assumes that int is 32 bits");
Q_STATIC_ASSERT_X(UCHAR_MAX == 255, "Qt assumes that char is 8 bits");
Q_STATIC_ASSERT_X(QT_POINTER_SIZE == sizeof(void *), "QT_POINTER_SIZE defined incorrectly");
/*!
\class QFlag
\inmodule QtCore
\brief The QFlag class is a helper data type for QFlags.
It is equivalent to a plain \c int, except with respect to
function overloading and type conversions. You should never need
to use this class in your applications.
\sa QFlags
*/
/*!
\fn QFlag::QFlag(int value)
Constructs a QFlag object that stores the given \a value.
*/
/*!
\fn QFlag::QFlag(uint value)
\since 5.3
Constructs a QFlag object that stores the given \a value.
*/
/*!
\fn QFlag::QFlag(short value)
\since 5.3
Constructs a QFlag object that stores the given \a value.
*/
/*!
\fn QFlag::QFlag(ushort value)
\since 5.3
Constructs a QFlag object that stores the given \a value.
*/
/*!
\fn QFlag::operator int() const
Returns the value stored by the QFlag object.
*/
/*!
\fn QFlag::operator uint() const
\since 5.3
Returns the value stored by the QFlag object.
*/
/*!
\class QFlags
\inmodule QtCore
\brief The QFlags class provides a type-safe way of storing
OR-combinations of enum values.
\ingroup tools
The QFlags<Enum> class is a template class, where Enum is an enum
type. QFlags is used throughout Qt for storing combinations of
enum values.
The traditional C++ approach for storing OR-combinations of enum
values is to use an \c int or \c uint variable. The inconvenience
with this approach is that there's no type checking at all; any
enum value can be OR'd with any other enum value and passed on to
a function that takes an \c int or \c uint.
Qt uses QFlags to provide type safety. For example, the
Qt::Alignment type is simply a typedef for
QFlags<Qt::AlignmentFlag>. QLabel::setAlignment() takes a
Qt::Alignment parameter, which means that any combination of
Qt::AlignmentFlag values, or 0, is legal:
\snippet code/src_corelib_global_qglobal.cpp 0
If you try to pass a value from another enum or just a plain
integer other than 0, the compiler will report an error. If you
need to cast integer values to flags in a untyped fashion, you can
use the explicit QFlags constructor as cast operator.
If you want to use QFlags for your own enum types, use
the Q_DECLARE_FLAGS() and Q_DECLARE_OPERATORS_FOR_FLAGS().
Example:
\snippet code/src_corelib_global_qglobal.cpp 1
You can then use the \c MyClass::Options type to store
combinations of \c MyClass::Option values.
\section1 Flags and the Meta-Object System
The Q_DECLARE_FLAGS() macro does not expose the flags to the meta-object
system, so they cannot be used by Qt Script or edited in Qt Designer.
To make the flags available for these purposes, the Q_FLAG() macro must
be used:
\snippet code/src_corelib_global_qglobal.cpp meta-object flags
\section1 Naming Convention
A sensible naming convention for enum types and associated QFlags
types is to give a singular name to the enum type (e.g., \c
Option) and a plural name to the QFlags type (e.g., \c Options).
When a singular name is desired for the QFlags type (e.g., \c
Alignment), you can use \c Flag as the suffix for the enum type
(e.g., \c AlignmentFlag).
\sa QFlag
*/
/*!
\typedef QFlags::Int
\since 5.0
Typedef for the integer type used for storage as well as for
implicit conversion. Either \c int or \c{unsigned int}, depending
on whether the enum's underlying type is signed or unsigned.
*/
/*!
\typedef QFlags::enum_type
Typedef for the Enum template type.
*/
/*!
\fn QFlags::QFlags(const QFlags &other)
Constructs a copy of \a other.
*/
/*!
\fn QFlags::QFlags(Enum flag)
Constructs a QFlags object storing the given \a flag.
*/
/*!
\fn QFlags::QFlags(Zero zero)
Constructs a QFlags object with no flags set. \a zero must be a
literal 0 value.
*/
/*!
\fn QFlags::QFlags(QFlag value)
Constructs a QFlags object initialized with the given integer \a
value.
The QFlag type is a helper type. By using it here instead of \c
int, we effectively ensure that arbitrary enum values cannot be
cast to a QFlags, whereas untyped enum values (i.e., \c int
values) can.
*/
/*!
\fn QFlags::QFlags(std::initializer_list<Enum> flags)
\since 5.4
Constructs a QFlags object initialized with all \a flags
combined using the bitwise OR operator.
\sa operator|=(), operator|()
*/
/*!
\fn QFlags &QFlags::operator=(const QFlags &other)
Assigns \a other to this object and returns a reference to this
object.
*/
/*!
\fn QFlags &QFlags::operator&=(int mask)
Performs a bitwise AND operation with \a mask and stores the
result in this QFlags object. Returns a reference to this object.
\sa operator&(), operator|=(), operator^=()
*/
/*!
\fn QFlags &QFlags::operator&=(uint mask)
\overload
*/
/*!
\fn QFlags &QFlags::operator&=(Enum mask)
\overload
*/
/*!
\fn QFlags &QFlags::operator|=(QFlags other)
Performs a bitwise OR operation with \a other and stores the
result in this QFlags object. Returns a reference to this object.
\sa operator|(), operator&=(), operator^=()
*/
/*!
\fn QFlags &QFlags::operator|=(Enum other)
\overload
*/
/*!
\fn QFlags &QFlags::operator^=(QFlags other)
Performs a bitwise XOR operation with \a other and stores the
result in this QFlags object. Returns a reference to this object.
\sa operator^(), operator&=(), operator|=()
*/
/*!
\fn QFlags &QFlags::operator^=(Enum other)
\overload
*/
/*!
\fn QFlags::operator Int() const
Returns the value stored in the QFlags object as an integer.
\sa Int
*/
/*!
\fn QFlags QFlags::operator|(QFlags other) const
Returns a QFlags object containing the result of the bitwise OR
operation on this object and \a other.
\sa operator|=(), operator^(), operator&(), operator~()
*/
/*!
\fn QFlags QFlags::operator|(Enum other) const
\overload
*/
/*!
\fn QFlags QFlags::operator^(QFlags other) const
Returns a QFlags object containing the result of the bitwise XOR
operation on this object and \a other.
\sa operator^=(), operator&(), operator|(), operator~()
*/
/*!
\fn QFlags QFlags::operator^(Enum other) const
\overload
*/
/*!
\fn QFlags QFlags::operator&(int mask) const
Returns a QFlags object containing the result of the bitwise AND
operation on this object and \a mask.
\sa operator&=(), operator|(), operator^(), operator~()
*/
/*!
\fn QFlags QFlags::operator&(uint mask) const
\overload
*/
/*!
\fn QFlags QFlags::operator&(Enum mask) const
\overload
*/
/*!
\fn QFlags QFlags::operator~() const
Returns a QFlags object that contains the bitwise negation of
this object.
\sa operator&(), operator|(), operator^()
*/
/*!
\fn bool QFlags::operator!() const
Returns \c true if no flag is set (i.e., if the value stored by the
QFlags object is 0); otherwise returns \c false.
*/
/*!
\fn bool QFlags::testFlag(Enum flag) const
\since 4.2
Returns \c true if the \a flag is set, otherwise \c false.
*/
/*!
\fn QFlags QFlags::setFlag(Enum flag, bool on)
\since 5.7
Sets the indicated \a flag if \a on is \c true or unsets it if
\a on is \c false. Returns a reference to this object.
*/
/*!
\macro Q_DISABLE_COPY(Class)
\relates QObject
Disables the use of copy constructors and assignment operators
for the given \a Class.
Instances of subclasses of QObject should not be thought of as
values that can be copied or assigned, but as unique identities.
This means that when you create your own subclass of QObject
(director or indirect), you should \e not give it a copy constructor
or an assignment operator. However, it may not enough to simply
omit them from your class, because, if you mistakenly write some code
that requires a copy constructor or an assignment operator (it's easy
to do), your compiler will thoughtfully create it for you. You must
do more.
The curious user will have seen that the Qt classes derived
from QObject typically include this macro in a private section:
\snippet code/src_corelib_global_qglobal.cpp 43
It declares a copy constructor and an assignment operator in the
private section, so that if you use them by mistake, the compiler
will report an error.
\snippet code/src_corelib_global_qglobal.cpp 44
But even this might not catch absolutely every case. You might be
tempted to do something like this:
\snippet code/src_corelib_global_qglobal.cpp 45
First of all, don't do that. Most compilers will generate code that
uses the copy constructor, so the privacy violation error will be
reported, but your C++ compiler is not required to generate code for
this statement in a specific way. It could generate code using
\e{neither} the copy constructor \e{nor} the assignment operator we
made private. In that case, no error would be reported, but your
application would probably crash when you called a member function
of \c{w}.
*/
/*!
\macro Q_DECLARE_FLAGS(Flags, Enum)
\relates QFlags
The Q_DECLARE_FLAGS() macro expands to
\snippet code/src_corelib_global_qglobal.cpp 2
\a Enum is the name of an existing enum type, whereas \a Flags is
the name of the QFlags<\e{Enum}> typedef.
See the QFlags documentation for details.
\sa Q_DECLARE_OPERATORS_FOR_FLAGS()
*/
/*!
\macro Q_DECLARE_OPERATORS_FOR_FLAGS(Flags)
\relates QFlags
The Q_DECLARE_OPERATORS_FOR_FLAGS() macro declares global \c
operator|() functions for \a Flags, which is of type QFlags<T>.
See the QFlags documentation for details.
\sa Q_DECLARE_FLAGS()
*/
/*!
\headerfile <QtGlobal>
\title Global Qt Declarations
\ingroup funclists
\brief The <QtGlobal> header file includes the fundamental global
declarations. It is included by most other Qt header files.
The global declarations include \l{types}, \l{functions} and
\l{macros}.
The type definitions are partly convenience definitions for basic
types (some of which guarantee certain bit-sizes on all platforms
supported by Qt), partly types related to Qt message handling. The
functions are related to generating messages, Qt version handling
and comparing and adjusting object values. And finally, some of
the declared macros enable programmers to add compiler or platform
specific code to their applications, while others are convenience
macros for larger operations.
\section1 Types
The header file declares several type definitions that guarantee a
specified bit-size on all platforms supported by Qt for various
basic types, for example \l qint8 which is a signed char
guaranteed to be 8-bit on all platforms supported by Qt. The
header file also declares the \l qlonglong type definition for \c
{long long int } (\c __int64 on Windows).
Several convenience type definitions are declared: \l qreal for \c
double or \c float, \l uchar for \c unsigned char, \l uint for \c unsigned
int, \l ulong for \c unsigned long and \l ushort for \c unsigned
short.
Finally, the QtMsgType definition identifies the various messages
that can be generated and sent to a Qt message handler;
QtMessageHandler is a type definition for a pointer to a function with
the signature
\c {void myMessageHandler(QtMsgType, const QMessageLogContext &, const char *)}.
QMessageLogContext class contains the line, file, and function the
message was logged at. This information is created by the QMessageLogger
class.
\section1 Functions
The <QtGlobal> header file contains several functions comparing
and adjusting an object's value. These functions take a template
type as argument: You can retrieve the absolute value of an object
using the qAbs() function, and you can bound a given object's
value by given minimum and maximum values using the qBound()
function. You can retrieve the minimum and maximum of two given
objects using qMin() and qMax() respectively. All these functions
return a corresponding template type; the template types can be
replaced by any other type.
Example:
\snippet code/src_corelib_global_qglobal.cpp 3
<QtGlobal> also contains functions that generate messages from the
given string argument: qDebug(), qInfo(), qWarning(), qCritical(),
and qFatal(). These functions call the message handler
with the given message.
Example:
\snippet code/src_corelib_global_qglobal.cpp 4
The remaining functions are qRound() and qRound64(), which both
accept a \c double or \c float value as their argument returning
the value rounded up to the nearest integer and 64-bit integer
respectively, the qInstallMessageHandler() function which installs
the given QtMessageHandler, and the qVersion() function which
returns the version number of Qt at run-time as a string.
\section1 Macros
The <QtGlobal> header file provides a range of macros (Q_CC_*)
that are defined if the application is compiled using the
specified platforms. For example, the Q_CC_SUN macro is defined if
the application is compiled using Forte Developer, or Sun Studio
C++. The header file also declares a range of macros (Q_OS_*)
that are defined for the specified platforms. For example,
Q_OS_UNIX which is defined for the Unix-based systems.
The purpose of these macros is to enable programmers to add
compiler or platform specific code to their application.
The remaining macros are convenience macros for larger operations:
The QT_TRANSLATE_NOOP() and QT_TR_NOOP() macros provide the
possibility of marking text for dynamic translation,
i.e. translation without changing the stored source text. The
Q_ASSERT() and Q_ASSERT_X() enables warning messages of various
level of refinement. The Q_FOREACH() and foreach() macros
implement Qt's foreach loop.
The Q_INT64_C() and Q_UINT64_C() macros wrap signed and unsigned
64-bit integer literals in a platform-independent way. The
Q_CHECK_PTR() macro prints a warning containing the source code's
file name and line number, saying that the program ran out of
memory, if the pointer is 0. The qPrintable() and qUtf8Printable()
macros represent an easy way of printing text.
Finally, the QT_POINTER_SIZE macro expands to the size of a
pointer in bytes, and the QT_VERSION and QT_VERSION_STR macros
expand to a numeric value or a string, respectively, specifying
Qt's version number, i.e the version the application is compiled
against.
\sa <QtAlgorithms>, QSysInfo
*/
/*!
\typedef qreal
\relates <QtGlobal>
Typedef for \c double unless Qt is configured with the
\c{-qreal float} option.
*/
/*! \typedef uchar
\relates <QtGlobal>
Convenience typedef for \c{unsigned char}.
*/
/*! \typedef ushort
\relates <QtGlobal>
Convenience typedef for \c{unsigned short}.
*/
/*! \typedef uint
\relates <QtGlobal>
Convenience typedef for \c{unsigned int}.
*/
/*! \typedef ulong
\relates <QtGlobal>
Convenience typedef for \c{unsigned long}.
*/
/*! \typedef qint8
\relates <QtGlobal>
Typedef for \c{signed char}. This type is guaranteed to be 8-bit
on all platforms supported by Qt.
*/
/*!
\typedef quint8
\relates <QtGlobal>
Typedef for \c{unsigned char}. This type is guaranteed to
be 8-bit on all platforms supported by Qt.
*/
/*! \typedef qint16
\relates <QtGlobal>
Typedef for \c{signed short}. This type is guaranteed to be
16-bit on all platforms supported by Qt.
*/
/*!
\typedef quint16
\relates <QtGlobal>
Typedef for \c{unsigned short}. This type is guaranteed to
be 16-bit on all platforms supported by Qt.
*/
/*! \typedef qint32
\relates <QtGlobal>
Typedef for \c{signed int}. This type is guaranteed to be 32-bit
on all platforms supported by Qt.
*/
/*!
\typedef quint32
\relates <QtGlobal>
Typedef for \c{unsigned int}. This type is guaranteed to
be 32-bit on all platforms supported by Qt.
*/
/*! \typedef qint64
\relates <QtGlobal>
Typedef for \c{long long int} (\c __int64 on Windows). This type
is guaranteed to be 64-bit on all platforms supported by Qt.
Literals of this type can be created using the Q_INT64_C() macro:
\snippet code/src_corelib_global_qglobal.cpp 5
\sa Q_INT64_C(), quint64, qlonglong
*/
/*!
\typedef quint64
\relates <QtGlobal>
Typedef for \c{unsigned long long int} (\c{unsigned __int64} on
Windows). This type is guaranteed to be 64-bit on all platforms
supported by Qt.
Literals of this type can be created using the Q_UINT64_C()
macro:
\snippet code/src_corelib_global_qglobal.cpp 6
\sa Q_UINT64_C(), qint64, qulonglong
*/
/*!
\typedef qintptr
\relates <QtGlobal>
Integral type for representing pointers in a signed integer (useful for
hashing, etc.).
Typedef for either qint32 or qint64. This type is guaranteed to
be the same size as a pointer on all platforms supported by Qt. On
a system with 32-bit pointers, qintptr is a typedef for qint32;
on a system with 64-bit pointers, qintptr is a typedef for
qint64.
Note that qintptr is signed. Use quintptr for unsigned values.
\sa qptrdiff, qint32, qint64
*/
/*!
\typedef quintptr
\relates <QtGlobal>
Integral type for representing pointers in an unsigned integer (useful for
hashing, etc.).
Typedef for either quint32 or quint64. This type is guaranteed to
be the same size as a pointer on all platforms supported by Qt. On
a system with 32-bit pointers, quintptr is a typedef for quint32;
on a system with 64-bit pointers, quintptr is a typedef for
quint64.
Note that quintptr is unsigned. Use qptrdiff for signed values.
\sa qptrdiff, quint32, quint64
*/
/*!
\typedef qptrdiff
\relates <QtGlobal>
Integral type for representing pointer differences.
Typedef for either qint32 or qint64. This type is guaranteed to be
the same size as a pointer on all platforms supported by Qt. On a
system with 32-bit pointers, quintptr is a typedef for quint32; on
a system with 64-bit pointers, quintptr is a typedef for quint64.
Note that qptrdiff is signed. Use quintptr for unsigned values.
\sa quintptr, qint32, qint64
*/
/*!
\enum QtMsgType
\relates <QtGlobal>
This enum describes the messages that can be sent to a message
handler (QtMessageHandler). You can use the enum to identify and
associate the various message types with the appropriate
actions.
\value QtDebugMsg
A message generated by the qDebug() function.
\value QtInfoMsg
A message generated by the qInfo() function.
\value QtWarningMsg
A message generated by the qWarning() function.
\value QtCriticalMsg
A message generated by the qCritical() function.
\value QtFatalMsg
A message generated by the qFatal() function.
\value QtSystemMsg
\c QtInfoMsg was added in Qt 5.5.
\sa QtMessageHandler, qInstallMessageHandler()
*/
/*! \typedef QFunctionPointer
\relates <QtGlobal>
This is a typedef for \c{void (*)()}, a pointer to a function that takes
no arguments and returns void.
*/
/*! \macro qint64 Q_INT64_C(literal)
\relates <QtGlobal>
Wraps the signed 64-bit integer \a literal in a
platform-independent way.
Example:
\snippet code/src_corelib_global_qglobal.cpp 8
\sa qint64, Q_UINT64_C()
*/
/*! \macro quint64 Q_UINT64_C(literal)
\relates <QtGlobal>
Wraps the unsigned 64-bit integer \a literal in a
platform-independent way.
Example:
\snippet code/src_corelib_global_qglobal.cpp 9
\sa quint64, Q_INT64_C()
*/
/*! \typedef qlonglong
\relates <QtGlobal>
Typedef for \c{long long int} (\c __int64 on Windows). This is
the same as \l qint64.
\sa qulonglong, qint64
*/
/*!
\typedef qulonglong
\relates <QtGlobal>
Typedef for \c{unsigned long long int} (\c{unsigned __int64} on
Windows). This is the same as \l quint64.
\sa quint64, qlonglong
*/
/*! \fn T qAbs(const T &value)
\relates <QtGlobal>
Compares \a value to the 0 of type T and returns the absolute
value. Thus if T is \e {double}, then \a value is compared to
\e{(double) 0}.
Example:
\snippet code/src_corelib_global_qglobal.cpp 10
*/
/*! \fn int qRound(double value)
\relates <QtGlobal>
Rounds \a value to the nearest integer.
Example:
\snippet code/src_corelib_global_qglobal.cpp 11A
*/
/*! \fn int qRound(float value)
\relates <QtGlobal>
Rounds \a value to the nearest integer.
Example:
\snippet code/src_corelib_global_qglobal.cpp 11B
*/
/*! \fn qint64 qRound64(double value)
\relates <QtGlobal>
Rounds \a value to the nearest 64-bit integer.
Example:
\snippet code/src_corelib_global_qglobal.cpp 12A
*/
/*! \fn qint64 qRound64(float value)
\relates <QtGlobal>
Rounds \a value to the nearest 64-bit integer.
Example:
\snippet code/src_corelib_global_qglobal.cpp 12B
*/
/*! \fn const T &qMin(const T &value1, const T &value2)
\relates <QtGlobal>
Returns the minimum of \a value1 and \a value2.
Example:
\snippet code/src_corelib_global_qglobal.cpp 13
\sa qMax(), qBound()
*/
/*! \fn const T &qMax(const T &value1, const T &value2)
\relates <QtGlobal>
Returns the maximum of \a value1 and \a value2.
Example:
\snippet code/src_corelib_global_qglobal.cpp 14
\sa qMin(), qBound()
*/
/*! \fn const T &qBound(const T &min, const T &value, const T &max)
\relates <QtGlobal>
Returns \a value bounded by \a min and \a max. This is equivalent
to qMax(\a min, qMin(\a value, \a max)).
Example:
\snippet code/src_corelib_global_qglobal.cpp 15
\sa qMin(), qMax()
*/
/*! \fn auto qOverload(T functionPointer)
\relates <QtGlobal>
\since 5.7
Returns a pointer to an overloaded function. The template
parameter is the list of the argument types of the function.
\a functionPointer is the pointer to the (member) function:
\snippet code/src_corelib_global_qglobal.cpp 52
If a member function is also const-overloaded \l qConstOverload and
\l qNonConstOverload need to be used.
qOverload() requires C++14 enabled. In C++11-only code, the helper
classes QOverload, QConstOverload, and QNonConstOverload can be used directly:
\snippet code/src_corelib_global_qglobal.cpp 53
\sa qConstOverload(), qNonConstOverload(), {Differences between String-Based
and Functor-Based Connections}
*/
/*! \fn auto qConstOverload(T memberFunctionPointer)
\relates <QtGlobal>
\since 5.7
Returns the \a memberFunctionPointer pointer to a constant member function:
\snippet code/src_corelib_global_qglobal.cpp 54
\sa qOverload, qNonConstOverload, {Differences between String-Based
and Functor-Based Connections}
*/
/*! \fn auto qNonConstOverload(T memberFunctionPointer)
\relates <QtGlobal>
\since 5.7
Returns the \a memberFunctionPointer pointer to a non-constant member function:
\snippet code/src_corelib_global_qglobal.cpp 54
\sa qOverload, qNonConstOverload, {Differences between String-Based
and Functor-Based Connections}
*/
/*!
\macro QT_VERSION_CHECK
\relates <QtGlobal>
Turns the major, minor and patch numbers of a version into an
integer, 0xMMNNPP (MM = major, NN = minor, PP = patch). This can
be compared with another similarly processed version id.
Example:
\snippet code/src_corelib_global_qglobal.cpp qt-version-check
\sa QT_VERSION
*/
/*!
\macro QT_VERSION
\relates <QtGlobal>
This macro expands a numeric value of the form 0xMMNNPP (MM =
major, NN = minor, PP = patch) that specifies Qt's version
number. For example, if you compile your application against Qt
4.1.2, the QT_VERSION macro will expand to 0x040102.
You can use QT_VERSION to use the latest Qt features where
available.
Example:
\snippet code/src_corelib_global_qglobal.cpp 16
\sa QT_VERSION_STR, qVersion()
*/
/*!
\macro QT_VERSION_STR
\relates <QtGlobal>
This macro expands to a string that specifies Qt's version number
(for example, "4.1.2"). This is the version against which the
application is compiled.
\sa qVersion(), QT_VERSION
*/
/*!
\relates <QtGlobal>
Returns the version number of Qt at run-time as a string (for
example, "4.1.2"). This may be a different version than the
version the application was compiled against.
\sa QT_VERSION_STR, QLibraryInfo::version()
*/
const char *qVersion() Q_DECL_NOTHROW
{
return QT_VERSION_STR;
}
bool qSharedBuild() Q_DECL_NOTHROW
{
#ifdef QT_SHARED
return true;
#else
return false;
#endif
}
/*****************************************************************************
System detection routines
*****************************************************************************/
/*!
\class QSysInfo
\inmodule QtCore
\brief The QSysInfo class provides information about the system.
\list
\li \l WordSize specifies the size of a pointer for the platform
on which the application is compiled.
\li \l ByteOrder specifies whether the platform is big-endian or
little-endian.
\endlist
Some constants are defined only on certain platforms. You can use
the preprocessor symbols Q_OS_WIN and Q_OS_MACOS to test that
the application is compiled under Windows or \macos.
\sa QLibraryInfo
*/
/*!
\enum QSysInfo::Sizes
This enum provides platform-specific information about the sizes of data
structures used by the underlying architecture.
\value WordSize The size in bits of a pointer for the platform on which
the application is compiled (32 or 64).
*/
/*!
\deprecated
\variable QSysInfo::WindowsVersion
\brief the version of the Windows operating system on which the
application is run.
*/
/*!
\deprecated
\fn QSysInfo::WindowsVersion QSysInfo::windowsVersion()
\since 4.4
Returns the version of the Windows operating system on which the
application is run, or WV_None if the operating system is not
Windows.
*/
/*!
\deprecated
\variable QSysInfo::MacintoshVersion
\brief the version of the Macintosh operating system on which
the application is run.
*/
/*!
\deprecated
\fn QSysInfo::MacVersion QSysInfo::macVersion()
Returns the version of Darwin (\macos or iOS) on which the
application is run, or MV_None if the operating system
is not a version of Darwin.
*/
/*!
\enum QSysInfo::Endian
\value BigEndian Big-endian byte order (also called Network byte order)
\value LittleEndian Little-endian byte order
\value ByteOrder Equals BigEndian or LittleEndian, depending on
the platform's byte order.
*/
/*!
\deprecated
\enum QSysInfo::WinVersion
This enum provides symbolic names for the various versions of the
Windows operating system. On Windows, the
QSysInfo::WindowsVersion variable gives the version of the system
on which the application is run.
MS-DOS-based versions:
\value WV_32s Windows 3.1 with Win 32s
\value WV_95 Windows 95
\value WV_98 Windows 98
\value WV_Me Windows Me
NT-based versions (note that each operating system version is only represented once rather than each Windows edition):
\value WV_NT Windows NT (operating system version 4.0)
\value WV_2000 Windows 2000 (operating system version 5.0)
\value WV_XP Windows XP (operating system version 5.1)
\value WV_2003 Windows Server 2003, Windows Server 2003 R2, Windows Home Server, Windows XP Professional x64 Edition (operating system version 5.2)
\value WV_VISTA Windows Vista, Windows Server 2008 (operating system version 6.0)
\value WV_WINDOWS7 Windows 7, Windows Server 2008 R2 (operating system version 6.1)
\value WV_WINDOWS8 Windows 8 (operating system version 6.2)
\value WV_WINDOWS8_1 Windows 8.1 (operating system version 6.3), introduced in Qt 5.2
\value WV_WINDOWS10 Windows 10 (operating system version 10.0), introduced in Qt 5.5
Alternatively, you may use the following macros which correspond directly to the Windows operating system version number:
\value WV_4_0 Operating system version 4.0, corresponds to Windows NT
\value WV_5_0 Operating system version 5.0, corresponds to Windows 2000
\value WV_5_1 Operating system version 5.1, corresponds to Windows XP
\value WV_5_2 Operating system version 5.2, corresponds to Windows Server 2003, Windows Server 2003 R2, Windows Home Server, and Windows XP Professional x64 Edition
\value WV_6_0 Operating system version 6.0, corresponds to Windows Vista and Windows Server 2008
\value WV_6_1 Operating system version 6.1, corresponds to Windows 7 and Windows Server 2008 R2
\value WV_6_2 Operating system version 6.2, corresponds to Windows 8
\value WV_6_3 Operating system version 6.3, corresponds to Windows 8.1, introduced in Qt 5.2
\value WV_10_0 Operating system version 10.0, corresponds to Windows 10, introduced in Qt 5.5
The following masks can be used for testing whether a Windows
version is MS-DOS-based or NT-based:
\value WV_DOS_based MS-DOS-based version of Windows
\value WV_NT_based NT-based version of Windows
\value WV_None Operating system other than Windows.
\omitvalue WV_CE
\omitvalue WV_CENET
\omitvalue WV_CE_5
\omitvalue WV_CE_6
\omitvalue WV_CE_based
\sa MacVersion
*/
/*!
\deprecated
\enum QSysInfo::MacVersion
This enum provides symbolic names for the various versions of the
Darwin operating system, covering both \macos and iOS. The
QSysInfo::MacintoshVersion variable gives the version of the
system on which the application is run.
\value MV_9 \macos 9
\value MV_10_0 \macos 10.0
\value MV_10_1 \macos 10.1
\value MV_10_2 \macos 10.2
\value MV_10_3 \macos 10.3
\value MV_10_4 \macos 10.4
\value MV_10_5 \macos 10.5
\value MV_10_6 \macos 10.6
\value MV_10_7 \macos 10.7
\value MV_10_8 \macos 10.8
\value MV_10_9 \macos 10.9
\value MV_10_10 \macos 10.10
\value MV_10_11 \macos 10.11
\value MV_10_12 \macos 10.12
\value MV_Unknown An unknown and currently unsupported platform
\value MV_CHEETAH Apple codename for MV_10_0
\value MV_PUMA Apple codename for MV_10_1
\value MV_JAGUAR Apple codename for MV_10_2
\value MV_PANTHER Apple codename for MV_10_3
\value MV_TIGER Apple codename for MV_10_4
\value MV_LEOPARD Apple codename for MV_10_5
\value MV_SNOWLEOPARD Apple codename for MV_10_6
\value MV_LION Apple codename for MV_10_7
\value MV_MOUNTAINLION Apple codename for MV_10_8
\value MV_MAVERICKS Apple codename for MV_10_9
\value MV_YOSEMITE Apple codename for MV_10_10
\value MV_ELCAPITAN Apple codename for MV_10_11
\value MV_SIERRA Apple codename for MV_10_12
\value MV_IOS iOS (any)
\value MV_IOS_4_3 iOS 4.3
\value MV_IOS_5_0 iOS 5.0
\value MV_IOS_5_1 iOS 5.1
\value MV_IOS_6_0 iOS 6.0
\value MV_IOS_6_1 iOS 6.1
\value MV_IOS_7_0 iOS 7.0
\value MV_IOS_7_1 iOS 7.1
\value MV_IOS_8_0 iOS 8.0
\value MV_IOS_8_1 iOS 8.1
\value MV_IOS_8_2 iOS 8.2
\value MV_IOS_8_3 iOS 8.3
\value MV_IOS_8_4 iOS 8.4
\value MV_IOS_9_0 iOS 9.0
\value MV_IOS_9_1 iOS 9.1
\value MV_IOS_9_2 iOS 9.2
\value MV_IOS_9_3 iOS 9.3
\value MV_IOS_10_0 iOS 10.0
\value MV_TVOS tvOS (any)
\value MV_TVOS_9_0 tvOS 9.0
\value MV_TVOS_9_1 tvOS 9.1
\value MV_TVOS_9_2 tvOS 9.2
\value MV_TVOS_10_0 tvOS 10.0
\value MV_WATCHOS watchOS (any)
\value MV_WATCHOS_2_0 watchOS 2.0
\value MV_WATCHOS_2_1 watchOS 2.1
\value MV_WATCHOS_2_2 watchOS 2.2
\value MV_WATCHOS_3_0 watchOS 3.0
\value MV_None Not a Darwin operating system
\sa WinVersion
*/
/*!
\macro Q_OS_DARWIN
\relates <QtGlobal>
Defined on Darwin-based operating systems such as \macos, iOS, watchOS, and tvOS.
*/
/*!
\macro Q_OS_MAC
\relates <QtGlobal>
Deprecated synonym for \c Q_OS_DARWIN. Do not use.
*/
/*!
\macro Q_OS_OSX
\relates <QtGlobal>
Deprecated synonym for \c Q_OS_MACOS. Do not use.
*/
/*!
\macro Q_OS_MACOS
\relates <QtGlobal>
Defined on \macos.
*/
/*!
\macro Q_OS_IOS
\relates <QtGlobal>
Defined on iOS.
*/
/*!
\macro Q_OS_WATCHOS
\relates <QtGlobal>
Defined on watchOS.
*/
/*!
\macro Q_OS_TVOS
\relates <QtGlobal>
Defined on tvOS.
*/
/*!
\macro Q_OS_WIN
\relates <QtGlobal>
Defined on all supported versions of Windows. That is, if
\l Q_OS_WIN32, \l Q_OS_WIN64, or \l Q_OS_WINRT is defined.
*/
/*!
\macro Q_OS_WIN32
\relates <QtGlobal>
Defined on 32-bit and 64-bit versions of Windows.
*/
/*!
\macro Q_OS_WIN64
\relates <QtGlobal>
Defined on 64-bit versions of Windows.
*/
/*!
\macro Q_OS_WINRT
\relates <QtGlobal>
Defined for Windows Runtime (Windows Store apps) on Windows 8, Windows RT,
and Windows Phone 8.
*/
/*!
\macro Q_OS_CYGWIN
\relates <QtGlobal>
Defined on Cygwin.
*/
/*!
\macro Q_OS_SOLARIS
\relates <QtGlobal>
Defined on Sun Solaris.
*/
/*!
\macro Q_OS_HPUX
\relates <QtGlobal>
Defined on HP-UX.
*/
/*!
\macro Q_OS_ULTRIX
\relates <QtGlobal>
Defined on DEC Ultrix.
*/
/*!
\macro Q_OS_LINUX
\relates <QtGlobal>
Defined on Linux.
*/
/*!
\macro Q_OS_ANDROID
\relates <QtGlobal>
Defined on Android.
*/
/*!
\macro Q_OS_FREEBSD
\relates <QtGlobal>
Defined on FreeBSD.
*/
/*!
\macro Q_OS_NETBSD
\relates <QtGlobal>
Defined on NetBSD.
*/
/*!
\macro Q_OS_OPENBSD
\relates <QtGlobal>
Defined on OpenBSD.
*/
/*!
\macro Q_OS_BSDI
\relates <QtGlobal>
Defined on BSD/OS.
*/
/*!
\macro Q_OS_IRIX
\relates <QtGlobal>
Defined on SGI Irix.
*/
/*!
\macro Q_OS_OSF
\relates <QtGlobal>
Defined on HP Tru64 UNIX.
*/
/*!
\macro Q_OS_SCO
\relates <QtGlobal>
Defined on SCO OpenServer 5.
*/
/*!
\macro Q_OS_UNIXWARE
\relates <QtGlobal>
Defined on UnixWare 7, Open UNIX 8.
*/
/*!
\macro Q_OS_AIX
\relates <QtGlobal>
Defined on AIX.
*/
/*!
\macro Q_OS_HURD
\relates <QtGlobal>
Defined on GNU Hurd.
*/
/*!
\macro Q_OS_DGUX
\relates <QtGlobal>
Defined on DG/UX.
*/
/*!
\macro Q_OS_RELIANT
\relates <QtGlobal>
Defined on Reliant UNIX.
*/
/*!
\macro Q_OS_DYNIX
\relates <QtGlobal>
Defined on DYNIX/ptx.
*/
/*!
\macro Q_OS_QNX
\relates <QtGlobal>
Defined on QNX Neutrino.
*/
/*!
\macro Q_OS_LYNX
\relates <QtGlobal>
Defined on LynxOS.
*/
/*!
\macro Q_OS_BSD4
\relates <QtGlobal>
Defined on Any BSD 4.4 system.
*/
/*!
\macro Q_OS_UNIX
\relates <QtGlobal>
Defined on Any UNIX BSD/SYSV system.
*/
/*!
\macro Q_CC_SYM
\relates <QtGlobal>
Defined if the application is compiled using Digital Mars C/C++
(used to be Symantec C++).
*/
/*!
\macro Q_CC_MSVC
\relates <QtGlobal>
Defined if the application is compiled using Microsoft Visual
C/C++, Intel C++ for Windows.
*/
/*!
\macro Q_CC_CLANG
\relates <QtGlobal>
Defined if the application is compiled using Clang.
*/
/*!
\macro Q_CC_BOR
\relates <QtGlobal>
Defined if the application is compiled using Borland/Turbo C++.
*/
/*!
\macro Q_CC_WAT
\relates <QtGlobal>
Defined if the application is compiled using Watcom C++.
*/
/*!
\macro Q_CC_GNU
\relates <QtGlobal>
Defined if the application is compiled using GNU C++.
*/
/*!
\macro Q_CC_COMEAU
\relates <QtGlobal>
Defined if the application is compiled using Comeau C++.
*/
/*!
\macro Q_CC_EDG
\relates <QtGlobal>
Defined if the application is compiled using Edison Design Group
C++.
*/
/*!
\macro Q_CC_OC
\relates <QtGlobal>
Defined if the application is compiled using CenterLine C++.
*/
/*!
\macro Q_CC_SUN
\relates <QtGlobal>
Defined if the application is compiled using Forte Developer, or
Sun Studio C++.
*/
/*!
\macro Q_CC_MIPS
\relates <QtGlobal>
Defined if the application is compiled using MIPSpro C++.
*/
/*!
\macro Q_CC_DEC
\relates <QtGlobal>
Defined if the application is compiled using DEC C++.
*/
/*!
\macro Q_CC_HPACC
\relates <QtGlobal>
Defined if the application is compiled using HP aC++.
*/
/*!
\macro Q_CC_USLC
\relates <QtGlobal>
Defined if the application is compiled using SCO OUDK and UDK.
*/
/*!
\macro Q_CC_CDS
\relates <QtGlobal>
Defined if the application is compiled using Reliant C++.
*/
/*!
\macro Q_CC_KAI
\relates <QtGlobal>
Defined if the application is compiled using KAI C++.
*/
/*!
\macro Q_CC_INTEL
\relates <QtGlobal>
Defined if the application is compiled using Intel C++ for Linux,
Intel C++ for Windows.
*/
/*!
\macro Q_CC_HIGHC
\relates <QtGlobal>
Defined if the application is compiled using MetaWare High C/C++.
*/
/*!
\macro Q_CC_PGI
\relates <QtGlobal>
Defined if the application is compiled using Portland Group C++.
*/
/*!
\macro Q_CC_GHS
\relates <QtGlobal>
Defined if the application is compiled using Green Hills
Optimizing C++ Compilers.
*/
/*!
\macro Q_PROCESSOR_ALPHA
\relates <QtGlobal>
Defined if the application is compiled for Alpha processors.
\sa QSysInfo::buildCpuArchitecture()
*/
/*!
\macro Q_PROCESSOR_ARM
\relates <QtGlobal>
Defined if the application is compiled for ARM processors. Qt currently
supports three optional ARM revisions: \l Q_PROCESSOR_ARM_V5, \l
Q_PROCESSOR_ARM_V6, and \l Q_PROCESSOR_ARM_V7.
\sa QSysInfo::buildCpuArchitecture()
*/
/*!
\macro Q_PROCESSOR_ARM_V5
\relates <QtGlobal>
Defined if the application is compiled for ARMv5 processors. The \l
Q_PROCESSOR_ARM macro is also defined when Q_PROCESSOR_ARM_V5 is defined.
\sa QSysInfo::buildCpuArchitecture()
*/
/*!
\macro Q_PROCESSOR_ARM_V6
\relates <QtGlobal>
Defined if the application is compiled for ARMv6 processors. The \l
Q_PROCESSOR_ARM and \l Q_PROCESSOR_ARM_V5 macros are also defined when
Q_PROCESSOR_ARM_V6 is defined.
\sa QSysInfo::buildCpuArchitecture()
*/
/*!
\macro Q_PROCESSOR_ARM_V7
\relates <QtGlobal>
Defined if the application is compiled for ARMv7 processors. The \l
Q_PROCESSOR_ARM, \l Q_PROCESSOR_ARM_V5, and \l Q_PROCESSOR_ARM_V6 macros
are also defined when Q_PROCESSOR_ARM_V7 is defined.
\sa QSysInfo::buildCpuArchitecture()
*/
/*!
\macro Q_PROCESSOR_AVR32
\relates <QtGlobal>
Defined if the application is compiled for AVR32 processors.
\sa QSysInfo::buildCpuArchitecture()
*/
/*!
\macro Q_PROCESSOR_BLACKFIN
\relates <QtGlobal>
Defined if the application is compiled for Blackfin processors.
\sa QSysInfo::buildCpuArchitecture()
*/
/*!
\macro Q_PROCESSOR_IA64
\relates <QtGlobal>
Defined if the application is compiled for IA-64 processors. This includes
all Itanium and Itanium 2 processors.
\sa QSysInfo::buildCpuArchitecture()
*/
/*!
\macro Q_PROCESSOR_MIPS
\relates <QtGlobal>
Defined if the application is compiled for MIPS processors. Qt currently
supports seven MIPS revisions: \l Q_PROCESSOR_MIPS_I, \l
Q_PROCESSOR_MIPS_II, \l Q_PROCESSOR_MIPS_III, \l Q_PROCESSOR_MIPS_IV, \l
Q_PROCESSOR_MIPS_V, \l Q_PROCESSOR_MIPS_32, and \l Q_PROCESSOR_MIPS_64.
\sa QSysInfo::buildCpuArchitecture()
*/
/*!
\macro Q_PROCESSOR_MIPS_I
\relates <QtGlobal>
Defined if the application is compiled for MIPS-I processors. The \l
Q_PROCESSOR_MIPS macro is also defined when Q_PROCESSOR_MIPS_I is defined.
\sa QSysInfo::buildCpuArchitecture()
*/
/*!
\macro Q_PROCESSOR_MIPS_II
\relates <QtGlobal>
Defined if the application is compiled for MIPS-II processors. The \l
Q_PROCESSOR_MIPS and \l Q_PROCESSOR_MIPS_I macros are also defined when
Q_PROCESSOR_MIPS_II is defined.
\sa QSysInfo::buildCpuArchitecture()
*/
/*!
\macro Q_PROCESSOR_MIPS_32
\relates <QtGlobal>
Defined if the application is compiled for MIPS32 processors. The \l
Q_PROCESSOR_MIPS, \l Q_PROCESSOR_MIPS_I, and \l Q_PROCESSOR_MIPS_II macros
are also defined when Q_PROCESSOR_MIPS_32 is defined.
\sa QSysInfo::buildCpuArchitecture()
*/
/*!
\macro Q_PROCESSOR_MIPS_III
\relates <QtGlobal>
Defined if the application is compiled for MIPS-III processors. The \l
Q_PROCESSOR_MIPS, \l Q_PROCESSOR_MIPS_I, and \l Q_PROCESSOR_MIPS_II macros
are also defined when Q_PROCESSOR_MIPS_III is defined.
\sa QSysInfo::buildCpuArchitecture()
*/
/*!
\macro Q_PROCESSOR_MIPS_IV
\relates <QtGlobal>
Defined if the application is compiled for MIPS-IV processors. The \l
Q_PROCESSOR_MIPS, \l Q_PROCESSOR_MIPS_I, \l Q_PROCESSOR_MIPS_II, and \l
Q_PROCESSOR_MIPS_III macros are also defined when Q_PROCESSOR_MIPS_IV is
defined.
\sa QSysInfo::buildCpuArchitecture()
*/
/*!
\macro Q_PROCESSOR_MIPS_V
\relates <QtGlobal>
Defined if the application is compiled for MIPS-V processors. The \l
Q_PROCESSOR_MIPS, \l Q_PROCESSOR_MIPS_I, \l Q_PROCESSOR_MIPS_II, \l
Q_PROCESSOR_MIPS_III, and \l Q_PROCESSOR_MIPS_IV macros are also defined
when Q_PROCESSOR_MIPS_V is defined.
\sa QSysInfo::buildCpuArchitecture()
*/
/*!
\macro Q_PROCESSOR_MIPS_64
\relates <QtGlobal>
Defined if the application is compiled for MIPS64 processors. The \l
Q_PROCESSOR_MIPS, \l Q_PROCESSOR_MIPS_I, \l Q_PROCESSOR_MIPS_II, \l
Q_PROCESSOR_MIPS_III, \l Q_PROCESSOR_MIPS_IV, and \l Q_PROCESSOR_MIPS_V
macros are also defined when Q_PROCESSOR_MIPS_64 is defined.
\sa QSysInfo::buildCpuArchitecture()
*/
/*!
\macro Q_PROCESSOR_POWER
\relates <QtGlobal>
Defined if the application is compiled for POWER processors. Qt currently
supports two Power variants: \l Q_PROCESSOR_POWER_32 and \l
Q_PROCESSOR_POWER_64.
\sa QSysInfo::buildCpuArchitecture()
*/
/*!
\macro Q_PROCESSOR_POWER_32
\relates <QtGlobal>
Defined if the application is compiled for 32-bit Power processors. The \l
Q_PROCESSOR_POWER macro is also defined when Q_PROCESSOR_POWER_32 is
defined.
\sa QSysInfo::buildCpuArchitecture()
*/
/*!
\macro Q_PROCESSOR_POWER_64
\relates <QtGlobal>
Defined if the application is compiled for 64-bit Power processors. The \l
Q_PROCESSOR_POWER macro is also defined when Q_PROCESSOR_POWER_64 is
defined.
\sa QSysInfo::buildCpuArchitecture()
*/
/*!
\macro Q_PROCESSOR_S390
\relates <QtGlobal>
Defined if the application is compiled for S/390 processors. Qt supports
one optional variant of S/390: Q_PROCESSOR_S390_X.
\sa QSysInfo::buildCpuArchitecture()
*/
/*!
\macro Q_PROCESSOR_S390_X
\relates <QtGlobal>
Defined if the application is compiled for S/390x processors. The \l
Q_PROCESSOR_S390 macro is also defined when Q_PROCESSOR_S390_X is defined.
\sa QSysInfo::buildCpuArchitecture()
*/
/*!
\macro Q_PROCESSOR_SH
\relates <QtGlobal>
Defined if the application is compiled for SuperH processors. Qt currently
supports one SuperH revision: \l Q_PROCESSOR_SH_4A.
\sa QSysInfo::buildCpuArchitecture()
*/
/*!
\macro Q_PROCESSOR_SH_4A
\relates <QtGlobal>
Defined if the application is compiled for SuperH 4A processors. The \l
Q_PROCESSOR_SH macro is also defined when Q_PROCESSOR_SH_4A is defined.
\sa QSysInfo::buildCpuArchitecture()
*/
/*!
\macro Q_PROCESSOR_SPARC
\relates <QtGlobal>
Defined if the application is compiled for SPARC processors. Qt currently
supports one optional SPARC revision: \l Q_PROCESSOR_SPARC_V9.
\sa QSysInfo::buildCpuArchitecture()
*/
/*!
\macro Q_PROCESSOR_SPARC_V9
\relates <QtGlobal>
Defined if the application is compiled for SPARC V9 processors. The \l
Q_PROCESSOR_SPARC macro is also defined when Q_PROCESSOR_SPARC_V9 is
defined.
\sa QSysInfo::buildCpuArchitecture()
*/
/*!
\macro Q_PROCESSOR_X86
\relates <QtGlobal>
Defined if the application is compiled for x86 processors. Qt currently
supports two x86 variants: \l Q_PROCESSOR_X86_32 and \l Q_PROCESSOR_X86_64.
\sa QSysInfo::buildCpuArchitecture()
*/
/*!
\macro Q_PROCESSOR_X86_32
\relates <QtGlobal>
Defined if the application is compiled for 32-bit x86 processors. This
includes all i386, i486, i586, and i686 processors. The \l Q_PROCESSOR_X86
macro is also defined when Q_PROCESSOR_X86_32 is defined.
\sa QSysInfo::buildCpuArchitecture()
*/
/*!
\macro Q_PROCESSOR_X86_64
\relates <QtGlobal>
Defined if the application is compiled for 64-bit x86 processors. This
includes all AMD64, Intel 64, and other x86_64/x64 processors. The \l
Q_PROCESSOR_X86 macro is also defined when Q_PROCESSOR_X86_64 is defined.
\sa QSysInfo::buildCpuArchitecture()
*/
/*!
\macro QT_DISABLE_DEPRECATED_BEFORE
\relates <QtGlobal>
This macro can be defined in the project file to disable functions deprecated in
a specified version of Qt or any earlier version. The default version number is 5.0,
meaning that functions deprecated in or before Qt 5.0 will not be included.
Examples:
When using a future release of Qt 5, set QT_DISABLE_DEPRECATED_BEFORE=0x050100 to
disable functions deprecated in Qt 5.1 and earlier. In any release, set
QT_DISABLE_DEPRECATED_BEFORE=0x000000 to enable any functions, including the ones
deprecated in Qt 5.0
\sa QT_DEPRECATED_WARNINGS
*/
/*!
\macro QT_DEPRECATED_WARNINGS
\relates <QtGlobal>
If this macro is defined, the compiler will generate warnings if API declared as
deprecated by Qt is used.
\sa QT_DISABLE_DEPRECATED_BEFORE
*/
#if defined(QT_BUILD_QMAKE)
// needed to bootstrap qmake
static const unsigned int qt_one = 1;
const int QSysInfo::ByteOrder = ((*((unsigned char *) &qt_one) == 0) ? BigEndian : LittleEndian);
#endif
#if defined(Q_OS_MAC)
QT_BEGIN_INCLUDE_NAMESPACE
#include "private/qcore_mac_p.h"
#include "qnamespace.h"
QT_END_INCLUDE_NAMESPACE
#if QT_DEPRECATED_SINCE(5, 9)
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
QSysInfo::MacVersion QSysInfo::macVersion()
{
const auto version = QOperatingSystemVersion::current();
#if defined(Q_OS_OSX)
return QSysInfo::MacVersion(Q_MV_OSX(version.majorVersion(), version.minorVersion()));
#elif defined(Q_OS_IOS)
return QSysInfo::MacVersion(Q_MV_IOS(version.majorVersion(), version.minorVersion()));
#elif defined(Q_OS_TVOS)
return QSysInfo::MacVersion(Q_MV_TVOS(version.majorVersion(), version.minorVersion()));
#elif defined(Q_OS_WATCHOS)
return QSysInfo::MacVersion(Q_MV_WATCHOS(version.majorVersion(), version.minorVersion()));
#else
return QSysInfo::MV_Unknown;
#endif
}
const QSysInfo::MacVersion QSysInfo::MacintoshVersion = QSysInfo::macVersion();
QT_WARNING_POP
#endif
#ifdef Q_OS_DARWIN
static const char *osVer_helper(QOperatingSystemVersion version = QOperatingSystemVersion::current())
{
#ifdef Q_OS_MACOS
if (version.majorVersion() == 10) {
switch (version.minorVersion()) {
case 9:
return "Mavericks";
case 10:
return "Yosemite";
case 11:
return "El Capitan";
case 12:
return "Sierra";
case 13:
return "High Sierra";
}
}
// unknown, future version
#else
Q_UNUSED(version);
#endif
return 0;
}
#endif
#elif defined(Q_OS_WIN) || defined(Q_OS_CYGWIN) || defined(Q_OS_WINRT)
QT_BEGIN_INCLUDE_NAMESPACE
#include "qt_windows.h"
QT_END_INCLUDE_NAMESPACE
# ifndef QT_BOOTSTRAPPED
class QWindowsSockInit
{
public:
QWindowsSockInit();
~QWindowsSockInit();
int version;
};
QWindowsSockInit::QWindowsSockInit()
: version(0)
{
//### should we try for 2.2 on all platforms ??
WSAData wsadata;
// IPv6 requires Winsock v2.0 or better.
if (WSAStartup(MAKEWORD(2,0), &wsadata) != 0) {
qWarning("QTcpSocketAPI: WinSock v2.0 initialization failed.");
} else {
version = 0x20;
}
}
QWindowsSockInit::~QWindowsSockInit()
{
WSACleanup();
}
Q_GLOBAL_STATIC(QWindowsSockInit, winsockInit)
# endif // QT_BOOTSTRAPPED
#if QT_DEPRECATED_SINCE(5, 9)
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
QSysInfo::WinVersion QSysInfo::windowsVersion()
{
const auto version = QOperatingSystemVersion::current();
if (version.majorVersion() == 6 && version.minorVersion() == 1)
return QSysInfo::WV_WINDOWS7;
if (version.majorVersion() == 6 && version.minorVersion() == 2)
return QSysInfo::WV_WINDOWS8;
if (version.majorVersion() == 6 && version.minorVersion() == 3)
return QSysInfo::WV_WINDOWS8_1;
if (version.majorVersion() == 10 && version.minorVersion() == 0)
return QSysInfo::WV_WINDOWS10;
return QSysInfo::WV_NT_based;
}
const QSysInfo::WinVersion QSysInfo::WindowsVersion = QSysInfo::windowsVersion();
QT_WARNING_POP
#endif
static QString winSp_helper()
{
const auto osv = qWindowsVersionInfo();
const qint16 major = osv.wServicePackMajor;
if (major) {
QString sp = QStringLiteral(" SP ") + QString::number(major);
const qint16 minor = osv.wServicePackMinor;
if (minor)
sp += QLatin1Char('.') + QString::number(minor);
return sp;
}
return QString();
}
static const char *osVer_helper(QOperatingSystemVersion version = QOperatingSystemVersion::current())
{
Q_UNUSED(version);
const OSVERSIONINFOEX osver = qWindowsVersionInfo();
const bool workstation = osver.wProductType == VER_NT_WORKSTATION;
#define Q_WINVER(major, minor) (major << 8 | minor)
switch (Q_WINVER(osver.dwMajorVersion, osver.dwMinorVersion)) {
case Q_WINVER(6, 1):
return workstation ? "7" : "Server 2008 R2";
case Q_WINVER(6, 2):
return workstation ? "8" : "Server 2012";
case Q_WINVER(6, 3):
return workstation ? "8.1" : "Server 2012 R2";
case Q_WINVER(10, 0):
return workstation ? "10" : "Server 2016";
}
#undef Q_WINVER
// unknown, future version
return 0;
}
#endif
#if defined(Q_OS_UNIX)
# if (defined(Q_OS_LINUX) && !defined(Q_OS_ANDROID)) || defined(Q_OS_FREEBSD)
# define USE_ETC_OS_RELEASE
struct QUnixOSVersion
{
// from /etc/os-release older /etc/lsb-release // redhat /etc/redhat-release // debian /etc/debian_version
QString productType; // $ID $DISTRIB_ID // single line file containing: // Debian
QString productVersion; // $VERSION_ID $DISTRIB_RELEASE // <Vendor_ID release Version_ID> // single line file <Release_ID/sid>
QString prettyName; // $PRETTY_NAME $DISTRIB_DESCRIPTION
};
static QString unquote(const char *begin, const char *end)
{
if (*begin == '"') {
Q_ASSERT(end[-1] == '"');
return QString::fromLatin1(begin + 1, end - begin - 2);
}
return QString::fromLatin1(begin, end - begin);
}
static QByteArray getEtcFileContent(const char *filename)
{
// we're avoiding QFile here
int fd = qt_safe_open(filename, O_RDONLY);
if (fd == -1)
return QByteArray();
QT_STATBUF sbuf;
if (QT_FSTAT(fd, &sbuf) == -1) {
qt_safe_close(fd);
return QByteArray();
}
QByteArray buffer(sbuf.st_size, Qt::Uninitialized);
buffer.resize(qt_safe_read(fd, buffer.data(), sbuf.st_size));
qt_safe_close(fd);
return buffer;
}
static bool readEtcFile(QUnixOSVersion &v, const char *filename,
const QByteArray &idKey, const QByteArray &versionKey, const QByteArray &prettyNameKey)
{
QByteArray buffer = getEtcFileContent(filename);
if (buffer.isEmpty())
return false;
const char *ptr = buffer.constData();
const char *end = buffer.constEnd();
const char *eol;
QByteArray line;
for ( ; ptr != end; ptr = eol + 1) {
// find the end of the line after ptr
eol = static_cast<const char *>(memchr(ptr, '\n', end - ptr));
if (!eol)
eol = end - 1;
line.setRawData(ptr, eol - ptr);
if (line.startsWith(idKey)) {
ptr += idKey.length();
v.productType = unquote(ptr, eol);
continue;
}
if (line.startsWith(prettyNameKey)) {
ptr += prettyNameKey.length();
v.prettyName = unquote(ptr, eol);
continue;
}
if (line.startsWith(versionKey)) {
ptr += versionKey.length();
v.productVersion = unquote(ptr, eol);
continue;
}
}
return true;
}
static bool readEtcOsRelease(QUnixOSVersion &v)
{
return readEtcFile(v, "/etc/os-release", QByteArrayLiteral("ID="),
QByteArrayLiteral("VERSION_ID="), QByteArrayLiteral("PRETTY_NAME="));
}
static bool readEtcLsbRelease(QUnixOSVersion &v)
{
bool ok = readEtcFile(v, "/etc/lsb-release", QByteArrayLiteral("DISTRIB_ID="),
QByteArrayLiteral("DISTRIB_RELEASE="), QByteArrayLiteral("DISTRIB_DESCRIPTION="));
if (ok && (v.prettyName.isEmpty() || v.prettyName == v.productType)) {
// some distributions have redundant information for the pretty name,
// so try /etc/<lowercasename>-release
// we're still avoiding QFile here
QByteArray distrorelease = "/etc/" + v.productType.toLatin1().toLower() + "-release";
int fd = qt_safe_open(distrorelease, O_RDONLY);
if (fd != -1) {
QT_STATBUF sbuf;
if (QT_FSTAT(fd, &sbuf) != -1 && sbuf.st_size > v.prettyName.length()) {
// file apparently contains interesting information
QByteArray buffer(sbuf.st_size, Qt::Uninitialized);
buffer.resize(qt_safe_read(fd, buffer.data(), sbuf.st_size));
v.prettyName = QString::fromLatin1(buffer.trimmed());
}
qt_safe_close(fd);
}
}
// some distributions have a /etc/lsb-release file that does not provide the values
// we are looking for, i.e. DISTRIB_ID, DISTRIB_RELEASE and DISTRIB_DESCRIPTION.
// Assuming that neither DISTRIB_ID nor DISTRIB_RELEASE were found, or contained valid values,
// returning false for readEtcLsbRelease will allow further /etc/<lowercasename>-release parsing.
return ok && !(v.productType.isEmpty() && v.productVersion.isEmpty());
}
#if defined(Q_OS_LINUX)
static QByteArray getEtcFileFirstLine(const char *fileName)
{
QByteArray buffer = getEtcFileContent(fileName);
if (buffer.isEmpty())
return QByteArray();
const char *ptr = buffer.constData();
int eol = buffer.indexOf("\n");
return QByteArray(ptr, eol).trimmed();
}
static bool readEtcRedHatRelease(QUnixOSVersion &v)
{
// /etc/redhat-release analysed should be a one line file
// the format of its content is <Vendor_ID release Version>
// i.e. "Red Hat Enterprise Linux Workstation release 6.5 (Santiago)"
QByteArray line = getEtcFileFirstLine("/etc/redhat-release");
if (line.isEmpty())
return false;
v.prettyName = QString::fromLatin1(line);
const char keyword[] = "release ";
int releaseIndex = line.indexOf(keyword);
v.productType = QString::fromLatin1(line.mid(0, releaseIndex)).remove(QLatin1Char(' '));
int spaceIndex = line.indexOf(' ', releaseIndex + strlen(keyword));
v.productVersion = QString::fromLatin1(line.mid(releaseIndex + strlen(keyword),
spaceIndex > -1 ? spaceIndex - releaseIndex - int(strlen(keyword)) : -1));
return true;
}
static bool readEtcDebianVersion(QUnixOSVersion &v)
{
// /etc/debian_version analysed should be a one line file
// the format of its content is <Release_ID/sid>
// i.e. "jessie/sid"
QByteArray line = getEtcFileFirstLine("/etc/debian_version");
if (line.isEmpty())
return false;
v.productType = QStringLiteral("Debian");
v.productVersion = QString::fromLatin1(line);
return true;
}
#endif
static bool findUnixOsVersion(QUnixOSVersion &v)
{
if (readEtcOsRelease(v))
return true;
if (readEtcLsbRelease(v))
return true;
#if defined(Q_OS_LINUX)
if (readEtcRedHatRelease(v))
return true;
if (readEtcDebianVersion(v))
return true;
#endif
return false;
}
# endif // USE_ETC_OS_RELEASE
#endif // Q_OS_UNIX
#if defined(Q_OS_ANDROID) && !defined(Q_OS_ANDROID_EMBEDDED)
static const char *osVer_helper(QOperatingSystemVersion)
{
/* Data:
Cupcake
Donut
Eclair
Eclair
Eclair
Froyo
Gingerbread
Gingerbread
Honeycomb
Honeycomb
Honeycomb
Ice Cream Sandwich
Ice Cream Sandwich
Jelly Bean
Jelly Bean
Jelly Bean
KitKat
KitKat
Lollipop
Lollipop
Marshmallow
Nougat
Nougat
Oreo
*/
static const char versions_string[] =
"\0"
"Cupcake\0"
"Donut\0"
"Eclair\0"
"Froyo\0"
"Gingerbread\0"
"Honeycomb\0"
"Ice Cream Sandwich\0"
"Jelly Bean\0"
"KitKat\0"
"Lollipop\0"
"Marshmallow\0"
"Nougat\0"
"Oreo\0"
"\0";
static const int versions_indices[] = {
0, 0, 0, 1, 9, 15, 15, 15,
22, 28, 28, 40, 40, 40, 50, 50,
69, 69, 69, 80, 80, 87, 87, 96,
108, 108, 115, -1
};
static const int versions_count = (sizeof versions_indices) / (sizeof versions_indices[0]);
// https://source.android.com/source/build-numbers.html
// https://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels
const int sdk_int = QJNIObjectPrivate::getStaticField<jint>("android/os/Build$VERSION", "SDK_INT");
return &versions_string[versions_indices[qBound(0, sdk_int, versions_count - 1)]];
}
#endif
/*!
\since 5.4
Returns the architecture of the CPU that Qt was compiled for, in text
format. Note that this may not match the actual CPU that the application is
running on if there's an emulation layer or if the CPU supports multiple
architectures (like x86-64 processors supporting i386 applications). To
detect that, use currentCpuArchitecture().
Values returned by this function are stable and will not change over time,
so applications can rely on the returned value as an identifier, except
that new CPU types may be added over time.
Typical returned values are (note: list not exhaustive):
\list
\li "arm"
\li "arm64"
\li "i386"
\li "ia64"
\li "mips"
\li "mips64"
\li "power"
\li "power64"
\li "sparc"
\li "sparcv9"
\li "x86_64"
\endlist
\sa QSysInfo::buildAbi(), QSysInfo::currentCpuArchitecture()
*/
QString QSysInfo::buildCpuArchitecture()
{
return QStringLiteral(ARCH_PROCESSOR);
}
/*!
\since 5.4
Returns the architecture of the CPU that the application is running on, in
text format. Note that this function depends on what the OS will report and
may not detect the actual CPU architecture if the OS hides that information
or is unable to provide it. For example, a 32-bit OS running on a 64-bit
CPU is usually unable to determine the CPU is actually capable of running
64-bit programs.
Values returned by this function are mostly stable: an attempt will be made
to ensure that they stay constant over time and match the values returned
by QSysInfo::builldCpuArchitecture(). However, due to the nature of the
operating system functions being used, there may be discrepancies.
Typical returned values are (note: list not exhaustive):
\list
\li "arm"
\li "arm64"
\li "i386"
\li "ia64"
\li "mips"
\li "mips64"
\li "power"
\li "power64"
\li "sparc"
\li "sparcv9"
\li "x86_64"
\endlist
\sa QSysInfo::buildAbi(), QSysInfo::buildCpuArchitecture()
*/
QString QSysInfo::currentCpuArchitecture()
{
#if defined(Q_OS_WIN)
// We don't need to catch all the CPU architectures in this function;
// only those where the host CPU might be different than the build target
// (usually, 64-bit platforms).
SYSTEM_INFO info;
GetNativeSystemInfo(&info);
switch (info.wProcessorArchitecture) {
# ifdef PROCESSOR_ARCHITECTURE_AMD64
case PROCESSOR_ARCHITECTURE_AMD64:
return QStringLiteral("x86_64");
# endif
# ifdef PROCESSOR_ARCHITECTURE_IA32_ON_WIN64
case PROCESSOR_ARCHITECTURE_IA32_ON_WIN64:
# endif
case PROCESSOR_ARCHITECTURE_IA64:
return QStringLiteral("ia64");
}
#elif defined(Q_OS_DARWIN) && !defined(Q_OS_MACOS)
// iOS-based OSes do not return the architecture on uname(2)'s result.
return buildCpuArchitecture();
#elif defined(Q_OS_UNIX)
long ret = -1;
struct utsname u;
# if defined(Q_OS_SOLARIS)
// We need a special call for Solaris because uname(2) on x86 returns "i86pc" for
// both 32- and 64-bit CPUs. Reference:
// http://docs.oracle.com/cd/E18752_01/html/816-5167/sysinfo-2.html#REFMAN2sysinfo-2
// http://fxr.watson.org/fxr/source/common/syscall/systeminfo.c?v=OPENSOLARIS
// http://fxr.watson.org/fxr/source/common/conf/param.c?v=OPENSOLARIS;im=10#L530
if (ret == -1)
ret = sysinfo(SI_ARCHITECTURE_64, u.machine, sizeof u.machine);
# endif
if (ret == -1)
ret = uname(&u);
// we could use detectUnixVersion() above, but we only need a field no other function does
if (ret != -1) {
// the use of QT_BUILD_INTERNAL here is simply to ensure all branches build
// as we don't often build on some of the less common platforms
# if defined(Q_PROCESSOR_ARM) || defined(QT_BUILD_INTERNAL)
if (strcmp(u.machine, "aarch64") == 0)
return QStringLiteral("arm64");
if (strncmp(u.machine, "armv", 4) == 0)
return QStringLiteral("arm");
# endif
# if defined(Q_PROCESSOR_POWER) || defined(QT_BUILD_INTERNAL)
// harmonize "powerpc" and "ppc" to "power"
if (strncmp(u.machine, "ppc", 3) == 0)
return QLatin1String("power") + QLatin1String(u.machine + 3);
if (strncmp(u.machine, "powerpc", 7) == 0)
return QLatin1String("power") + QLatin1String(u.machine + 7);
if (strcmp(u.machine, "Power Macintosh") == 0)
return QLatin1String("power");
# endif
# if defined(Q_PROCESSOR_SPARC) || defined(QT_BUILD_INTERNAL)
// Solaris sysinfo(2) (above) uses "sparcv9", but uname -m says "sun4u";
// Linux says "sparc64"
if (strcmp(u.machine, "sun4u") == 0 || strcmp(u.machine, "sparc64") == 0)
return QStringLiteral("sparcv9");
if (strcmp(u.machine, "sparc32") == 0)
return QStringLiteral("sparc");
# endif
# if defined(Q_PROCESSOR_X86) || defined(QT_BUILD_INTERNAL)
// harmonize all "i?86" to "i386"
if (strlen(u.machine) == 4 && u.machine[0] == 'i'
&& u.machine[2] == '8' && u.machine[3] == '6')
return QStringLiteral("i386");
if (strcmp(u.machine, "amd64") == 0) // Solaris
return QStringLiteral("x86_64");
# endif
return QString::fromLatin1(u.machine);
}
#endif
return buildCpuArchitecture();
}
/*!
\since 5.4
Returns the full architecture string that Qt was compiled for. This string
is useful for identifying different, incompatible builds. For example, it
can be used as an identifier to request an upgrade package from a server.
The values returned from this function are kept stable as follows: the
mandatory components of the result will not change in future versions of
Qt, but optional suffixes may be added.
The returned value is composed of three or more parts, separated by dashes
("-"). They are:
\table
\header \li Component \li Value
\row \li CPU Architecture \li The same as QSysInfo::buildCpuArchitecture(), such as "arm", "i386", "mips" or "x86_64"
\row \li Endianness \li "little_endian" or "big_endian"
\row \li Word size \li Whether it's a 32- or 64-bit application. Possible values are:
"llp64" (Windows 64-bit), "lp64" (Unix 64-bit), "ilp32" (32-bit)
\row \li (Optional) ABI \li Zero or more components identifying different ABIs possible in this architecture.
Currently, Qt has optional ABI components for ARM and MIPS processors: one
component is the main ABI (such as "eabi", "o32", "n32", "o64"); another is
whether the calling convention is using hardware floating point registers ("hardfloat"
is present).
Additionally, if Qt was configured with \c{-qreal float}, the ABI option tag "qreal_float"
will be present. If Qt was configured with another type as qreal, that type is present after
"qreal_", with all characters other than letters and digits escaped by an underscore, followed
by two hex digits. For example, \c{-qreal long double} becomes "qreal_long_20double".
\endtable
\sa QSysInfo::buildCpuArchitecture()
*/
QString QSysInfo::buildAbi()
{
#ifdef Q_COMPILER_UNICODE_STRINGS
// ARCH_FULL is a concatenation of strings (incl. ARCH_PROCESSOR), which breaks
// QStringLiteral on MSVC. Since the concatenation behavior we want is specified
// the same C++11 paper as the Unicode strings, we'll use that macro and hope
// that Microsoft implements the new behavior when they add support for Unicode strings.
return QStringLiteral(ARCH_FULL);
#else
return QLatin1String(ARCH_FULL);
#endif
}
static QString unknownText()
{
return QStringLiteral("unknown");
}
/*!
\since 5.4
Returns the type of the operating system kernel Qt was compiled for. It's
also the kernel the application is running on, unless the host operating
system is running a form of compatibility or virtualization layer.
Values returned by this function are stable and will not change over time,
so applications can rely on the returned value as an identifier, except
that new OS kernel types may be added over time.
On Windows, this function returns the type of Windows kernel, like "winnt".
On Unix systems, it returns the same as the output of \c{uname
-s} (lowercased).
\note This function may return surprising values: it returns "linux"
for all operating systems running Linux (including Android), "qnx" for all
operating systems running QNX, "freebsd" for
Debian/kFreeBSD, and "darwin" for \macos and iOS. For information on the type
of product the application is running on, see productType().
\sa QFileSelector, kernelVersion(), productType(), productVersion(), prettyProductName()
*/
QString QSysInfo::kernelType()
{
#if defined(Q_OS_WIN)
return QStringLiteral("winnt");
#elif defined(Q_OS_UNIX)
struct utsname u;
if (uname(&u) == 0)
return QString::fromLatin1(u.sysname).toLower();
#endif
return unknownText();
}
/*!
\since 5.4
Returns the release version of the operating system kernel. On Windows, it
returns the version of the NT kernel. On Unix systems, including
Android and \macos, it returns the same as the \c{uname -r}
command would return.
If the version could not be determined, this function may return an empty
string.
\sa kernelType(), productType(), productVersion(), prettyProductName()
*/
QString QSysInfo::kernelVersion()
{
#ifdef Q_OS_WIN
const auto osver = QOperatingSystemVersion::current();
return QString::number(osver.majorVersion()) + QLatin1Char('.') + QString::number(osver.minorVersion())
+ QLatin1Char('.') + QString::number(osver.microVersion());
#else
struct utsname u;
if (uname(&u) == 0)
return QString::fromLatin1(u.release);
return QString();
#endif
}
/*!
\since 5.4
Returns the product name of the operating system this application is
running in. If the application is running on some sort of emulation or
virtualization layer (such as WINE on a Unix system), this function will
inspect the emulation / virtualization layer.
Values returned by this function are stable and will not change over time,
so applications can rely on the returned value as an identifier, except
that new OS types may be added over time.
\b{Linux and Android note}: this function returns "android" for Linux
systems running Android userspace, notably when using the Bionic library.
For all other Linux systems, regardless of C library being used, it tries
to determine the distribution name and returns that. If determining the
distribution name failed, it returns "unknown".
\b{\macos note}: this function returns "osx" for all \macos systems,
regardless of Apple naming convention. The returned string will be updated
for Qt 6. Note that this function erroneously returned "macos" for \macos
10.12 in Qt versions 5.6.2, 5.7.1, and 5.8.0.
\b{Darwin, iOS, tvOS, and watchOS note}: this function returns "ios" for
iOS systems, "tvos" for tvOS systems, "watchos" for watchOS systems, and
"darwin" in case the system could not be determined.
\b{FreeBSD note}: this function returns "debian" for Debian/kFreeBSD and
"unknown" otherwise.
\b{Windows note}: this function "winrt" for WinRT builds, and "windows"
for normal desktop builds.
For other Unix-type systems, this function usually returns "unknown".
\sa QFileSelector, kernelType(), kernelVersion(), productVersion(), prettyProductName()
*/
QString QSysInfo::productType()
{
// similar, but not identical to QFileSelectorPrivate::platformSelectors
#if defined(Q_OS_WINRT)
return QStringLiteral("winrt");
#elif defined(Q_OS_WIN)
return QStringLiteral("windows");
#elif defined(Q_OS_QNX)
return QStringLiteral("qnx");
#elif defined(Q_OS_ANDROID)
return QStringLiteral("android");
#elif defined(Q_OS_IOS)
return QStringLiteral("ios");
#elif defined(Q_OS_TVOS)
return QStringLiteral("tvos");
#elif defined(Q_OS_WATCHOS)
return QStringLiteral("watchos");
#elif defined(Q_OS_MACOS)
// ### Qt6: remove fallback
# if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
return QStringLiteral("macos");
# else
return QStringLiteral("osx");
# endif
#elif defined(Q_OS_DARWIN)
return QStringLiteral("darwin");
#elif defined(USE_ETC_OS_RELEASE) // Q_OS_UNIX
QUnixOSVersion unixOsVersion;
findUnixOsVersion(unixOsVersion);
if (!unixOsVersion.productType.isEmpty())
return unixOsVersion.productType;
#endif
return unknownText();
}
/*!
\since 5.4
Returns the product version of the operating system in string form. If the
version could not be determined, this function returns "unknown".
It will return the Android, iOS, \macos, Windows full-product
versions on those systems.
Typical returned values are (note: list not exhaustive):
\list
\li "2016.09" (Amazon Linux AMI 2016.09)
\li "7.1" (Android Nougat)
\li "25" (Fedora 25)
\li "10.1" (iOS 10.1)
\li "10.12" (macOS Sierra)
\li "10.0" (tvOS 10)
\li "16.10" (Ubuntu 16.10)
\li "3.1" (watchOS 3.1)
\li "7 SP 1" (Windows 7 Service Pack 1)
\li "8.1" (Windows 8.1)
\li "10" (Windows 10)
\li "Server 2016" (Windows Server 2016)
\endlist
On Linux systems, it will try to determine the distribution version and will
return that. This is also done on Debian/kFreeBSD, so this function will
return Debian version in that case.
In all other Unix-type systems, this function always returns "unknown".
\note The version string returned from this function is not guaranteed to
be orderable. On Linux, the version of
the distribution may jump unexpectedly, please refer to the distribution's
documentation for versioning practices.
\sa kernelType(), kernelVersion(), productType(), prettyProductName()
*/
QString QSysInfo::productVersion()
{
#if defined(Q_OS_ANDROID) || defined(Q_OS_DARWIN)
const auto version = QOperatingSystemVersion::current();
return QString::number(version.majorVersion()) + QLatin1Char('.') + QString::number(version.minorVersion());
#elif defined(Q_OS_WIN)
const char *version = osVer_helper();
if (version) {
const QLatin1Char spaceChar(' ');
return QString::fromLatin1(version).remove(spaceChar).toLower() + winSp_helper().remove(spaceChar).toLower();
}
// fall through
#elif defined(USE_ETC_OS_RELEASE) // Q_OS_UNIX
QUnixOSVersion unixOsVersion;
findUnixOsVersion(unixOsVersion);
if (!unixOsVersion.productVersion.isEmpty())
return unixOsVersion.productVersion;
#endif
// fallback
return unknownText();
}
/*!
\since 5.4
Returns a prettier form of productType() and productVersion(), containing
other tokens like the operating system type, codenames and other
information. The result of this function is suitable for displaying to the
user, but not for long-term storage, as the string may change with updates
to Qt.
If productType() is "unknown", this function will instead use the
kernelType() and kernelVersion() functions.
\sa kernelType(), kernelVersion(), productType(), productVersion()
*/
QString QSysInfo::prettyProductName()
{
#if (defined(Q_OS_ANDROID) && !defined(Q_OS_ANDROID_EMBEDDED)) || defined(Q_OS_DARWIN) || defined(Q_OS_WIN)
const auto version = QOperatingSystemVersion::current();
const char *name = osVer_helper(version);
if (name)
return version.name() + QLatin1Char(' ') + QLatin1String(name)
# if defined(Q_OS_WIN)
+ winSp_helper()
# endif
+ QLatin1String(" (") + QString::number(version.majorVersion())
+ QLatin1Char('.') + QString::number(version.minorVersion())
+ QLatin1Char(')');
else
return version.name() + QLatin1Char(' ')
+ QString::number(version.majorVersion()) + QLatin1Char('.')
+ QString::number(version.minorVersion());
#elif defined(Q_OS_HAIKU)
return QLatin1String("Haiku ") + productVersion();
#elif defined(Q_OS_UNIX)
# ifdef USE_ETC_OS_RELEASE
QUnixOSVersion unixOsVersion;
findUnixOsVersion(unixOsVersion);
if (!unixOsVersion.prettyName.isEmpty())
return unixOsVersion.prettyName;
# endif
struct utsname u;
if (uname(&u) == 0)
return QString::fromLatin1(u.sysname) + QLatin1Char(' ') + QString::fromLatin1(u.release);
#endif
return unknownText();
}
#ifndef QT_BOOTSTRAPPED
/*!
\since 5.6
Returns this machine's host name, if one is configured. Note that hostnames
are not guaranteed to be globally unique, especially if they were
configured automatically.
This function does not guarantee the returned host name is a Fully
Qualified Domain Name (FQDN). For that, use QHostInfo to resolve the
returned name to an FQDN.
This function returns the same as QHostInfo::localHostName().
\sa QHostInfo::localDomainName
*/
QString QSysInfo::machineHostName()
{
#if defined(Q_OS_LINUX)
// gethostname(3) on Linux just calls uname(2), so do it ourselves
// and avoid a memcpy
struct utsname u;
if (uname(&u) == 0)
return QString::fromLocal8Bit(u.nodename);
#else
# ifdef Q_OS_WIN
// Important: QtNetwork depends on machineHostName() initializing ws2_32.dll
winsockInit();
# endif
char hostName[512];
if (gethostname(hostName, sizeof(hostName)) == -1)
return QString();
hostName[sizeof(hostName) - 1] = '\0';
return QString::fromLocal8Bit(hostName);
#endif
return QString();
}
#endif // QT_BOOTSTRAPPED
/*!
\macro void Q_ASSERT(bool test)
\relates <QtGlobal>
Prints a warning message containing the source code file name and
line number if \a test is \c false.
Q_ASSERT() is useful for testing pre- and post-conditions
during development. It does nothing if \c QT_NO_DEBUG was defined
during compilation.
Example:
\snippet code/src_corelib_global_qglobal.cpp 17
If \c b is zero, the Q_ASSERT statement will output the following
message using the qFatal() function:
\snippet code/src_corelib_global_qglobal.cpp 18
\sa Q_ASSERT_X(), qFatal(), {Debugging Techniques}
*/
/*!
\macro void Q_ASSERT_X(bool test, const char *where, const char *what)
\relates <QtGlobal>
Prints the message \a what together with the location \a where,
the source file name and line number if \a test is \c false.
Q_ASSERT_X is useful for testing pre- and post-conditions during
development. It does nothing if \c QT_NO_DEBUG was defined during
compilation.
Example:
\snippet code/src_corelib_global_qglobal.cpp 19
If \c b is zero, the Q_ASSERT_X statement will output the following
message using the qFatal() function:
\snippet code/src_corelib_global_qglobal.cpp 20
\sa Q_ASSERT(), qFatal(), {Debugging Techniques}
*/
/*!
\macro void Q_ASSUME(bool expr)
\relates <QtGlobal>
\since 5.0
Causes the compiler to assume that \a expr is \c true. This macro is useful
for improving code generation, by providing the compiler with hints about
conditions that it would not otherwise know about. However, there is no
guarantee that the compiler will actually use those hints.
This macro could be considered a "lighter" version of \l{Q_ASSERT()}. While
Q_ASSERT will abort the program's execution if the condition is \c false,
Q_ASSUME will tell the compiler not to generate code for those conditions.
Therefore, it is important that the assumptions always hold, otherwise
undefined behaviour may occur.
If \a expr is a constantly \c false condition, Q_ASSUME will tell the compiler
that the current code execution cannot be reached. That is, Q_ASSUME(false)
is equivalent to Q_UNREACHABLE().
In debug builds the condition is enforced by an assert to facilitate debugging.
\note Q_LIKELY() tells the compiler that the expression is likely, but not
the only possibility. Q_ASSUME tells the compiler that it is the only
possibility.
\sa Q_ASSERT(), Q_UNREACHABLE(), Q_LIKELY()
*/
/*!
\macro void Q_UNREACHABLE()
\relates <QtGlobal>
\since 5.0
Tells the compiler that the current point cannot be reached by any
execution, so it may optimize any code paths leading here as dead code, as
well as code continuing from here.
This macro is useful to mark impossible conditions. For example, given the
following enum:
\snippet code/src_corelib_global_qglobal.cpp qunreachable-enum
One can write a switch table like so:
\snippet code/src_corelib_global_qglobal.cpp qunreachable-switch
The advantage of inserting Q_UNREACHABLE() at that point is that the
compiler is told not to generate code for a shape variable containing that
value. If the macro is missing, the compiler will still generate the
necessary comparisons for that value. If the case label were removed, some
compilers could produce a warning that some enum values were not checked.
By using this macro in impossible conditions, code coverage may be improved
as dead code paths may be eliminated.
In debug builds the condition is enforced by an assert to facilitate debugging.
\sa Q_ASSERT(), Q_ASSUME(), qFatal()
*/
/*!
\macro void Q_FALLTHROUGH()
\relates <QtGlobal>
\since 5.8
Can be used in switch statements at the end of case block to tell the compiler
and other developers that that the lack of a break statement is intentional.
This is useful since a missing break statement is often a bug, and some
compilers can be configured to emit warnings when one is not found.
\sa Q_UNREACHABLE()
*/
/*!
\macro void Q_CHECK_PTR(void *pointer)
\relates <QtGlobal>
If \a pointer is 0, prints a message containing the source
code's file name and line number, saying that the program ran out
of memory and aborts program execution. It throws \c std::bad_alloc instead
if exceptions are enabled.
Q_CHECK_PTR does nothing if \c QT_NO_DEBUG and \c QT_NO_EXCEPTIONS were
defined during compilation. Therefore you must not use Q_CHECK_PTR to check
for successful memory allocations because the check will be disabled in
some cases.
Example:
\snippet code/src_corelib_global_qglobal.cpp 21
\sa qWarning(), {Debugging Techniques}
*/
/*!
\fn T *q_check_ptr(T *pointer)
\relates <QtGlobal>
Uses Q_CHECK_PTR on \a pointer, then returns \a pointer.
This can be used as an inline version of Q_CHECK_PTR.
*/
/*!
\macro const char* Q_FUNC_INFO()
\relates <QtGlobal>
Expands to a string that describe the function the macro resides in. How this string looks
more specifically is compiler dependent. With GNU GCC it is typically the function signature,
while with other compilers it might be the line and column number.
Q_FUNC_INFO can be conveniently used with qDebug(). For example, this function:
\snippet code/src_corelib_global_qglobal.cpp 22
when instantiated with the integer type, will with the GCC compiler produce:
\tt{const TInputType& myMin(const TInputType&, const TInputType&) [with TInputType = int] was called with value1: 3 value2: 4}
If this macro is used outside a function, the behavior is undefined.
*/
/*!
\internal
The Q_CHECK_PTR macro calls this function if an allocation check
fails.
*/
void qt_check_pointer(const char *n, int l) Q_DECL_NOTHROW
{
// make separate printing calls so that the first one may flush;
// the second one could want to allocate memory (fputs prints a
// newline and stderr auto-flushes).
fputs("Out of memory", stderr);
fprintf(stderr, " in %s, line %d\n", n, l);
std::terminate();
}
/*
\internal
Allows you to throw an exception without including <new>
Called internally from Q_CHECK_PTR on certain OS combinations
*/
void qBadAlloc()
{
QT_THROW(std::bad_alloc());
}
#ifndef QT_NO_EXCEPTIONS
/*
\internal
Allows you to call std::terminate() without including <exception>.
Called internally from QT_TERMINATE_ON_EXCEPTION
*/
Q_NORETURN void qTerminate() Q_DECL_NOTHROW
{
std::terminate();
}
#endif
/*
The Q_ASSERT macro calls this function when the test fails.
*/
void qt_assert(const char *assertion, const char *file, int line) Q_DECL_NOTHROW
{
QMessageLogger(file, line, nullptr).fatal("ASSERT: \"%s\" in file %s, line %d", assertion, file, line);
}
/*
The Q_ASSERT_X macro calls this function when the test fails.
*/
void qt_assert_x(const char *where, const char *what, const char *file, int line) Q_DECL_NOTHROW
{
QMessageLogger(file, line, nullptr).fatal("ASSERT failure in %s: \"%s\", file %s, line %d", where, what, file, line);
}
/*
Dijkstra's bisection algorithm to find the square root of an integer.
Deliberately not exported as part of the Qt API, but used in both
qsimplerichtext.cpp and qgfxraster_qws.cpp
*/
Q_CORE_EXPORT unsigned int qt_int_sqrt(unsigned int n)
{
// n must be in the range 0...UINT_MAX/2-1
if (n >= (UINT_MAX>>2)) {
unsigned int r = 2 * qt_int_sqrt(n / 4);
unsigned int r2 = r + 1;
return (n >= r2 * r2) ? r2 : r;
}
uint h, p= 0, q= 1, r= n;
while (q <= n)
q <<= 2;
while (q != 1) {
q >>= 2;
h= p + q;
p >>= 1;
if (r >= h) {
p += q;
r -= h;
}
}
return p;
}
void *qMemCopy(void *dest, const void *src, size_t n) { return memcpy(dest, src, n); }
void *qMemSet(void *dest, int c, size_t n) { return memset(dest, c, n); }
// In the C runtime on all platforms access to the environment is not thread-safe. We
// add thread-safety for the Qt wrappers.
static QBasicMutex environmentMutex;
// getenv is declared as deprecated in VS2005. This function
// makes use of the new secure getenv function.
/*!
\relates <QtGlobal>
Returns the value of the environment variable with name \a
varName. To get the variable string, use QByteArray::constData().
To convert the data to a QString use QString::fromLocal8Bit().
\note qgetenv() was introduced because getenv() from the standard
C library was deprecated in VC2005 (and later versions). qgetenv()
uses the new replacement function in VC, and calls the standard C
library's implementation on all other platforms.
\warning Don't use qgetenv on Windows if the content may contain
non-US-ASCII characters, like file paths.
\sa qputenv(), qEnvironmentVariableIsSet(), qEnvironmentVariableIsEmpty()
*/
QByteArray qgetenv(const char *varName)
{
QMutexLocker locker(&environmentMutex);
#if defined(_MSC_VER) && _MSC_VER >= 1400
size_t requiredSize = 0;
QByteArray buffer;
getenv_s(&requiredSize, 0, 0, varName);
if (requiredSize == 0)
return buffer;
buffer.resize(int(requiredSize));
getenv_s(&requiredSize, buffer.data(), requiredSize, varName);
// requiredSize includes the terminating null, which we don't want.
Q_ASSERT(buffer.endsWith('\0'));
buffer.chop(1);
return buffer;
#else
return QByteArray(::getenv(varName));
#endif
}
/*!
\relates <QtGlobal>
\since 5.1
Returns whether the environment variable \a varName is empty.
Equivalent to
\code
qgetenv(varName).isEmpty()
\endcode
except that it's potentially much faster, and can't throw exceptions.
\sa qgetenv(), qEnvironmentVariableIsSet()
*/
bool qEnvironmentVariableIsEmpty(const char *varName) Q_DECL_NOEXCEPT
{
QMutexLocker locker(&environmentMutex);
#if defined(_MSC_VER) && _MSC_VER >= 1400
// we provide a buffer that can only hold the empty string, so
// when the env.var isn't empty, we'll get an ERANGE error (buffer
// too small):
size_t dummy;
char buffer = '\0';
return getenv_s(&dummy, &buffer, 1, varName) != ERANGE;
#else
const char * const value = ::getenv(varName);
return !value || !*value;
#endif
}
/*!
\relates <QtGlobal>
\since 5.5
Returns the numerical value of the environment variable \a varName.
If \a ok is not null, sets \c{*ok} to \c true or \c false depending
on the success of the conversion.
Equivalent to
\code
qgetenv(varName).toInt(ok, 0)
\endcode
except that it's much faster, and can't throw exceptions.
\note there's a limit on the length of the value, which is sufficient for
all valid values of int, not counting leading zeroes or spaces. Values that
are too long will either be truncated or this function will set \a ok to \c
false.
\sa qgetenv(), qEnvironmentVariableIsSet()
*/
int qEnvironmentVariableIntValue(const char *varName, bool *ok) Q_DECL_NOEXCEPT
{
static const int NumBinaryDigitsPerOctalDigit = 3;
static const int MaxDigitsForOctalInt =
(std::numeric_limits<uint>::digits + NumBinaryDigitsPerOctalDigit - 1) / NumBinaryDigitsPerOctalDigit;
QMutexLocker locker(&environmentMutex);
#if defined(_MSC_VER) && _MSC_VER >= 1400
// we provide a buffer that can hold any int value:
char buffer[MaxDigitsForOctalInt + 2]; // +1 for NUL +1 for optional '-'
size_t dummy;
if (getenv_s(&dummy, buffer, sizeof buffer, varName) != 0) {
if (ok)
*ok = false;
return 0;
}
#else
const char * const buffer = ::getenv(varName);
if (!buffer || strlen(buffer) > MaxDigitsForOctalInt + 2) {
if (ok)
*ok = false;
return 0;
}
#endif
bool ok_ = true;
const char *endptr;
const qlonglong value = qstrtoll(buffer, &endptr, 0, &ok_);
if (int(value) != value || *endptr != '\0') { // this is the check in QByteArray::toInt(), keep it in sync
if (ok)
*ok = false;
return 0;
} else if (ok) {
*ok = ok_;
}
return int(value);
}
/*!
\relates <QtGlobal>
\since 5.1
Returns whether the environment variable \a varName is set.
Equivalent to
\code
!qgetenv(varName).isNull()
\endcode
except that it's potentially much faster, and can't throw exceptions.
\sa qgetenv(), qEnvironmentVariableIsEmpty()
*/
bool qEnvironmentVariableIsSet(const char *varName) Q_DECL_NOEXCEPT
{
QMutexLocker locker(&environmentMutex);
#if defined(_MSC_VER) && _MSC_VER >= 1400
size_t requiredSize = 0;
(void)getenv_s(&requiredSize, 0, 0, varName);
return requiredSize != 0;
#else
return ::getenv(varName) != 0;
#endif
}
/*!
\relates <QtGlobal>
This function sets the \a value of the environment variable named
\a varName. It will create the variable if it does not exist. It
returns 0 if the variable could not be set.
Calling qputenv with an empty value removes the environment variable on
Windows, and makes it set (but empty) on Unix. Prefer using qunsetenv()
for fully portable behavior.
\note qputenv() was introduced because putenv() from the standard
C library was deprecated in VC2005 (and later versions). qputenv()
uses the replacement function in VC, and calls the standard C
library's implementation on all other platforms.
\sa qgetenv()
*/
bool qputenv(const char *varName, const QByteArray& value)
{
QMutexLocker locker(&environmentMutex);
#if defined(_MSC_VER) && _MSC_VER >= 1400
return _putenv_s(varName, value.constData()) == 0;
#elif (defined(_POSIX_VERSION) && (_POSIX_VERSION-0) >= 200112L) || defined(Q_OS_HAIKU)
// POSIX.1-2001 has setenv
return setenv(varName, value.constData(), true) == 0;
#else
QByteArray buffer(varName);
buffer += '=';
buffer += value;
char* envVar = qstrdup(buffer.constData());
int result = putenv(envVar);
if (result != 0) // error. we have to delete the string.
delete[] envVar;
return result == 0;
#endif
}
/*!
\relates <QtGlobal>
This function deletes the variable \a varName from the environment.
Returns \c true on success.
\since 5.1
\sa qputenv(), qgetenv()
*/
bool qunsetenv(const char *varName)
{
QMutexLocker locker(&environmentMutex);
#if defined(_MSC_VER) && _MSC_VER >= 1400
return _putenv_s(varName, "") == 0;
#elif (defined(_POSIX_VERSION) && (_POSIX_VERSION-0) >= 200112L) || defined(Q_OS_BSD4) || defined(Q_OS_HAIKU)
// POSIX.1-2001, BSD and Haiku have unsetenv
return unsetenv(varName) == 0;
#elif defined(Q_CC_MINGW)
// On mingw, putenv("var=") removes "var" from the environment
QByteArray buffer(varName);
buffer += '=';
return putenv(buffer.constData()) == 0;
#else
// Fallback to putenv("var=") which will insert an empty var into the
// environment and leak it
QByteArray buffer(varName);
buffer += '=';
char *envVar = qstrdup(buffer.constData());
return putenv(envVar) == 0;
#endif
}
#if defined(Q_OS_ANDROID) && !defined(Q_OS_ANDROID_EMBEDDED) && (__ANDROID_API__ < 21)
typedef QThreadStorage<QJNIObjectPrivate> AndroidRandomStorage;
Q_GLOBAL_STATIC(AndroidRandomStorage, randomTLS)
#elif defined(Q_OS_UNIX) && !defined(QT_NO_THREAD) && defined(_POSIX_THREAD_SAFE_FUNCTIONS) && (_POSIX_THREAD_SAFE_FUNCTIONS - 0 > 0)
# if defined(Q_OS_INTEGRITY) && defined(__GHS_VERSION_NUMBER) && (__GHS_VERSION_NUMBER < 500)
// older versions of INTEGRITY used a long instead of a uint for the seed.
typedef long SeedStorageType;
# else
typedef uint SeedStorageType;
# endif
typedef QThreadStorage<SeedStorageType *> SeedStorage;
Q_GLOBAL_STATIC(SeedStorage, randTLS) // Thread Local Storage for seed value
#endif
/*!
\relates <QtGlobal>
\since 4.2
Thread-safe version of the standard C++ \c srand() function.
Sets the argument \a seed to be used to generate a new random number sequence of
pseudo random integers to be returned by qrand().
The sequence of random numbers generated is deterministic per thread. For example,
if two threads call qsrand(1) and subsequently call qrand(), the threads will get
the same random number sequence.
\sa qrand()
*/
void qsrand(uint seed)
{
#if defined(Q_OS_ANDROID) && !defined(Q_OS_ANDROID_EMBEDDED) && (__ANDROID_API__ < 21)
if (randomTLS->hasLocalData()) {
randomTLS->localData().callMethod<void>("setSeed", "(J)V", jlong(seed));
return;
}
QJNIObjectPrivate random("java/util/Random",
"(J)V",
jlong(seed));
if (!random.isValid()) {
srand(seed);
return;
}
randomTLS->setLocalData(random);
#elif defined(Q_OS_UNIX) && !defined(QT_NO_THREAD) && defined(_POSIX_THREAD_SAFE_FUNCTIONS) && (_POSIX_THREAD_SAFE_FUNCTIONS - 0 > 0)
SeedStorage *seedStorage = randTLS();
if (seedStorage) {
SeedStorageType *pseed = seedStorage->localData();
if (!pseed)
seedStorage->setLocalData(pseed = new SeedStorageType);
*pseed = seed;
} else {
//global static seed storage should always exist,
//except after being deleted by QGlobalStaticDeleter.
//But since it still can be called from destructor of another
//global static object, fallback to srand(seed)
srand(seed);
}
#else
// On Windows srand() and rand() already use Thread-Local-Storage
// to store the seed between calls
// this is also valid for QT_NO_THREAD
srand(seed);
#endif
}
/*!
\relates <QtGlobal>
\since 4.2
Thread-safe version of the standard C++ \c rand() function.
Returns a value between 0 and \c RAND_MAX (defined in \c <cstdlib> and
\c <stdlib.h>), the next number in the current sequence of pseudo-random
integers.
Use \c qsrand() to initialize the pseudo-random number generator with
a seed value.
\sa qsrand()
*/
int qrand()
{
#if defined(Q_OS_ANDROID) && !defined(Q_OS_ANDROID_EMBEDDED) && (__ANDROID_API__ < 21)
AndroidRandomStorage *randomStorage = randomTLS();
if (!randomStorage)
return rand();
if (randomStorage->hasLocalData()) {
return randomStorage->localData().callMethod<jint>("nextInt",
"(I)I",
RAND_MAX);
}
QJNIObjectPrivate random("java/util/Random",
"(J)V",
jlong(1));
if (!random.isValid())
return rand();
randomStorage->setLocalData(random);
return random.callMethod<jint>("nextInt", "(I)I", RAND_MAX);
#elif defined(Q_OS_UNIX) && !defined(QT_NO_THREAD) && defined(_POSIX_THREAD_SAFE_FUNCTIONS) && (_POSIX_THREAD_SAFE_FUNCTIONS - 0 > 0)
SeedStorage *seedStorage = randTLS();
if (seedStorage) {
SeedStorageType *pseed = seedStorage->localData();
if (!pseed) {
seedStorage->setLocalData(pseed = new SeedStorageType);
*pseed = 1;
}
return rand_r(pseed);
} else {
//global static seed storage should always exist,
//except after being deleted by QGlobalStaticDeleter.
//But since it still can be called from destructor of another
//global static object, fallback to rand()
return rand();
}
#else
// On Windows srand() and rand() already use Thread-Local-Storage
// to store the seed between calls
// this is also valid for QT_NO_THREAD
return rand();
#endif
}
/*!
\macro forever
\relates <QtGlobal>
This macro is provided for convenience for writing infinite
loops.
Example:
\snippet code/src_corelib_global_qglobal.cpp 31
It is equivalent to \c{for (;;)}.
If you're worried about namespace pollution, you can disable this
macro by adding the following line to your \c .pro file:
\snippet code/src_corelib_global_qglobal.cpp 32
\sa Q_FOREVER
*/
/*!
\macro Q_FOREVER
\relates <QtGlobal>
Same as \l{forever}.
This macro is available even when \c no_keywords is specified
using the \c .pro file's \c CONFIG variable.
\sa foreach()
*/
/*!
\macro foreach(variable, container)
\relates <QtGlobal>
This macro is used to implement Qt's \c foreach loop. The \a
variable parameter is a variable name or variable definition; the
\a container parameter is a Qt container whose value type
corresponds to the type of the variable. See \l{The foreach
Keyword} for details.
If you're worried about namespace pollution, you can disable this
macro by adding the following line to your \c .pro file:
\snippet code/src_corelib_global_qglobal.cpp 33
\note Since Qt 5.7, the use of this macro is discouraged. It will
be removed in a future version of Qt. Please use C++11 range-for,
possibly with qAsConst(), as needed.
\sa qAsConst()
*/
/*!
\macro Q_FOREACH(variable, container)
\relates <QtGlobal>
Same as foreach(\a variable, \a container).
This macro is available even when \c no_keywords is specified
using the \c .pro file's \c CONFIG variable.
\note Since Qt 5.7, the use of this macro is discouraged. It will
be removed in a future version of Qt. Please use C++11 range-for,
possibly with qAsConst(), as needed.
\sa qAsConst()
*/
/*!
\fn qAsConst(T &t)
\relates <QtGlobal>
\since 5.7
Returns \a t cast to \c{const T}.
This function is a Qt implementation of C++17's std::as_const(),
a cast function like std::move(). But while std::move() turns
lvalues into rvalues, this function turns non-const lvalues into
const lvalues. Like std::as_const(), it doesn't work on rvalues,
because it cannot be efficiently implemented for rvalues without
leaving dangling references.
Its main use in Qt is to prevent implicitly-shared Qt containers
from detaching:
\code
QString s = ...;
for (QChar ch : s) // detaches 's' (performs a deep-copy if 's' was shared)
process(ch);
for (QChar ch : qAsConst(s)) // ok, no detach attempt
process(ch);
\endcode
Of course, in this case, you could (and probably should) have declared
\c s as \c const in the first place:
\code
const QString s = ...;
for (QChar ch : s) // ok, no detach attempt on const objects
process(ch);
\endcode
but often that is not easily possible.
It is important to note that qAsConst() does not copy its argument,
it just performs a \c{const_cast<const T&>(t)}. This is also the reason
why it is designed to fail for rvalues: The returned reference would go
stale too soon. So while this works (but detaches the returned object):
\code
for (QChar ch : funcReturningQString())
process(ch); // OK, the returned object is kept alive for the loop's duration
\endcode
this would not:
\code
for (QChar ch : qAsConst(funcReturningQString()))
process(ch); // ERROR: ch is copied from deleted memory
\endcode
To prevent this construct from compiling (and failing at runtime), qAsConst() has
a second, deleted, overload which binds to rvalues.
*/
/*!
\fn qAsConst(const T &&t)
\relates <QtGlobal>
\since 5.7
\overload
This overload is deleted to prevent a dangling reference in code like
\code
for (QChar ch : qAsConst(funcReturningQString()))
process(ch); // ERROR: ch is copied from deleted memory
\endcode
*/
/*!
\macro QT_TR_NOOP(sourceText)
\relates <QtGlobal>
Marks the string literal \a sourceText for dynamic translation in
the current context (class), i.e the stored \a sourceText will not
be altered.
The macro expands to \a sourceText.
Example:
\snippet code/src_corelib_global_qglobal.cpp 34
The macro QT_TR_NOOP_UTF8() is identical except that it tells lupdate
that the source string is encoded in UTF-8. Corresponding variants
exist in the QT_TRANSLATE_NOOP() family of macros, too.
\sa QT_TRANSLATE_NOOP(), {Internationalization with Qt}
*/
/*!
\macro QT_TRANSLATE_NOOP(context, sourceText)
\relates <QtGlobal>
Marks the string literal \a sourceText for dynamic translation in
the given \a context; i.e, the stored \a sourceText will not be
altered. The \a context is typically a class and also needs to
be specified as string literal.
The macro expands to \a sourceText.
Example:
\snippet code/src_corelib_global_qglobal.cpp 35
\sa QT_TR_NOOP(), QT_TRANSLATE_NOOP3(), {Internationalization with Qt}
*/
/*!
\macro QT_TRANSLATE_NOOP3(context, sourceText, comment)
\relates <QtGlobal>
\since 4.4
Marks the string literal \a sourceText for dynamic translation in the
given \a context and with \a comment, i.e the stored \a sourceText will
not be altered. The \a context is typically a class and also needs to
be specified as string literal. The string literal \a comment
will be available for translators using e.g. Qt Linguist.
The macro expands to anonymous struct of the two string
literals passed as \a sourceText and \a comment.
Example:
\snippet code/src_corelib_global_qglobal.cpp 36
\sa QT_TR_NOOP(), QT_TRANSLATE_NOOP(), {Internationalization with Qt}
*/
/*!
\fn QString qtTrId(const char *id, int n = -1)
\relates <QtGlobal>
\reentrant
\since 4.6
\brief The qtTrId function finds and returns a translated string.
Returns a translated string identified by \a id.
If no matching string is found, the id itself is returned. This
should not happen under normal conditions.
If \a n >= 0, all occurrences of \c %n in the resulting string
are replaced with a decimal representation of \a n. In addition,
depending on \a n's value, the translation text may vary.
Meta data and comments can be passed as documented for QObject::tr().
In addition, it is possible to supply a source string template like that:
\tt{//% <C string>}
or
\tt{\\begincomment% <C string> \\endcomment}
Example:
\snippet code/src_corelib_global_qglobal.cpp qttrid
Creating QM files suitable for use with this function requires passing
the \c -idbased option to the \c lrelease tool.
\warning This method is reentrant only if all translators are
installed \e before calling this method. Installing or removing
translators while performing translations is not supported. Doing
so will probably result in crashes or other undesirable behavior.
\sa QObject::tr(), QCoreApplication::translate(), {Internationalization with Qt}
*/
/*!
\macro QT_TRID_NOOP(id)
\relates <QtGlobal>
\since 4.6
\brief The QT_TRID_NOOP macro marks an id for dynamic translation.
The only purpose of this macro is to provide an anchor for attaching
meta data like to qtTrId().
The macro expands to \a id.
Example:
\snippet code/src_corelib_global_qglobal.cpp qttrid_noop
\sa qtTrId(), {Internationalization with Qt}
*/
/*!
\macro Q_LIKELY(expr)
\relates <QtGlobal>
\since 4.8
\brief Hints to the compiler that the enclosed condition, \a expr, is
likely to evaluate to \c true.
Use of this macro can help the compiler to optimize the code.
Example:
\snippet code/src_corelib_global_qglobal.cpp qlikely
\sa Q_UNLIKELY()
*/
/*!
\macro Q_UNLIKELY(expr)
\relates <QtGlobal>
\since 4.8
\brief Hints to the compiler that the enclosed condition, \a expr, is
likely to evaluate to \c false.
Use of this macro can help the compiler to optimize the code.
Example:
\snippet code/src_corelib_global_qglobal.cpp qunlikely
\sa Q_LIKELY()
*/
/*!
\macro QT_POINTER_SIZE
\relates <QtGlobal>
Expands to the size of a pointer in bytes (4 or 8). This is
equivalent to \c sizeof(void *) but can be used in a preprocessor
directive.
*/
/*!
\macro QABS(n)
\relates <QtGlobal>
\obsolete
Use qAbs(\a n) instead.
\sa QMIN(), QMAX()
*/
/*!
\macro QMIN(x, y)
\relates <QtGlobal>
\obsolete
Use qMin(\a x, \a y) instead.
\sa QMAX(), QABS()
*/
/*!
\macro QMAX(x, y)
\relates <QtGlobal>
\obsolete
Use qMax(\a x, \a y) instead.
\sa QMIN(), QABS()
*/
/*!
\macro const char *qPrintable(const QString &str)
\relates <QtGlobal>
Returns \a str as a \c{const char *}. This is equivalent to
\a{str}.toLocal8Bit().constData().
The char pointer will be invalid after the statement in which
qPrintable() is used. This is because the array returned by
QString::toLocal8Bit() will fall out of scope.
\note qDebug(), qInfo(), qWarning(), qCritical(), qFatal() expect
%s arguments to be UTF-8 encoded, while qPrintable() converts to
local 8-bit encoding. Therefore qUtf8Printable() should be used
for logging strings instead of qPrintable().
\sa qUtf8Printable()
*/
/*!
\macro const char *qUtf8Printable(const QString &str)
\relates <QtGlobal>
\since 5.4
Returns \a str as a \c{const char *}. This is equivalent to
\a{str}.toUtf8().constData().
The char pointer will be invalid after the statement in which
qUtf8Printable() is used. This is because the array returned by
QString::toUtf8() will fall out of scope.
Example:
\snippet code/src_corelib_global_qglobal.cpp 37
\sa qPrintable(), qDebug(), qInfo(), qWarning(), qCritical(), qFatal()
*/
/*!
\macro const wchar_t *qUtf16Printable(const QString &str)
\relates <QtGlobal>
\since 5.7
Returns \a str as a \c{const ushort *}, but cast to a \c{const wchar_t *}
to avoid warnings. This is equivalent to \a{str}.utf16() plus some casting.
The only useful thing you can do with the return value of this macro is to
pass it to QString::asprintf() for use in a \c{%ls} conversion. In particular,
the return value is \e{not} a valid \c{const wchar_t*}!
In general, the pointer will be invalid after the statement in which
qUtf16Printable() is used. This is because the pointer may have been
obtained from a temporary expression, which will fall out of scope.
Example:
\snippet code/src_corelib_global_qglobal.cpp qUtf16Printable
\sa qPrintable(), qDebug(), qInfo(), qWarning(), qCritical(), qFatal()
*/
/*!
\macro Q_DECLARE_TYPEINFO(Type, Flags)
\relates <QtGlobal>
You can use this macro to specify information about a custom type
\a Type. With accurate type information, Qt's \l{Container Classes}
{generic containers} can choose appropriate storage methods and
algorithms.
\a Flags can be one of the following:
\list
\li \c Q_PRIMITIVE_TYPE specifies that \a Type is a POD (plain old
data) type with no constructor or destructor, or else a type where
every bit pattern is a valid object and memcpy() creates a valid
independent copy of the object.
\li \c Q_MOVABLE_TYPE specifies that \a Type has a constructor
and/or a destructor but can be moved in memory using \c
memcpy(). Note: despite the name, this has nothing to do with move
constructors or C++ move semantics.
\li \c Q_COMPLEX_TYPE (the default) specifies that \a Type has
constructors and/or a destructor and that it may not be moved
in memory.
\endlist
Example of a "primitive" type:
\snippet code/src_corelib_global_qglobal.cpp 38
An example of a non-POD "primitive" type is QUuid: Even though
QUuid has constructors (and therefore isn't POD), every bit
pattern still represents a valid object, and memcpy() can be used
to create a valid independent copy of a QUuid object.
Example of a movable type:
\snippet code/src_corelib_global_qglobal.cpp 39
*/
/*!
\macro Q_UNUSED(name)
\relates <QtGlobal>
Indicates to the compiler that the parameter with the specified
\a name is not used in the body of a function. This can be used to
suppress compiler warnings while allowing functions to be defined
with meaningful parameter names in their signatures.
*/
struct QInternal_CallBackTable {
QVector<QList<qInternalCallback> > callbacks;
};
Q_GLOBAL_STATIC(QInternal_CallBackTable, global_callback_table)
bool QInternal::registerCallback(Callback cb, qInternalCallback callback)
{
if (cb >= 0 && cb < QInternal::LastCallback) {
QInternal_CallBackTable *cbt = global_callback_table();
cbt->callbacks.resize(cb + 1);
cbt->callbacks[cb].append(callback);
return true;
}
return false;
}
bool QInternal::unregisterCallback(Callback cb, qInternalCallback callback)
{
if (cb >= 0 && cb < QInternal::LastCallback) {
if (global_callback_table.exists()) {
QInternal_CallBackTable *cbt = global_callback_table();
return (bool) cbt->callbacks[cb].removeAll(callback);
}
}
return false;
}
bool QInternal::activateCallbacks(Callback cb, void **parameters)
{
Q_ASSERT_X(cb >= 0, "QInternal::activateCallback()", "Callback id must be a valid id");
if (!global_callback_table.exists())
return false;
QInternal_CallBackTable *cbt = &(*global_callback_table);
if (cbt && cb < cbt->callbacks.size()) {
QList<qInternalCallback> callbacks = cbt->callbacks[cb];
bool ret = false;
for (int i=0; i<callbacks.size(); ++i)
ret |= (callbacks.at(i))(parameters);
return ret;
}
return false;
}
/*!
\macro Q_BYTE_ORDER
\relates <QtGlobal>
This macro can be used to determine the byte order your system
uses for storing data in memory. i.e., whether your system is
little-endian or big-endian. It is set by Qt to one of the macros
Q_LITTLE_ENDIAN or Q_BIG_ENDIAN. You normally won't need to worry
about endian-ness, but you might, for example if you need to know
which byte of an integer or UTF-16 character is stored in the
lowest address. Endian-ness is important in networking, where
computers with different values for Q_BYTE_ORDER must pass data
back and forth.
Use this macro as in the following examples.
\snippet code/src_corelib_global_qglobal.cpp 40
\sa Q_BIG_ENDIAN, Q_LITTLE_ENDIAN
*/
/*!
\macro Q_LITTLE_ENDIAN
\relates <QtGlobal>
This macro represents a value you can compare to the macro
Q_BYTE_ORDER to determine the endian-ness of your system. In a
little-endian system, the least significant byte is stored at the
lowest address. The other bytes follow in increasing order of
significance.
\snippet code/src_corelib_global_qglobal.cpp 41
\sa Q_BYTE_ORDER, Q_BIG_ENDIAN
*/
/*!
\macro Q_BIG_ENDIAN
\relates <QtGlobal>
This macro represents a value you can compare to the macro
Q_BYTE_ORDER to determine the endian-ness of your system. In a
big-endian system, the most significant byte is stored at the
lowest address. The other bytes follow in decreasing order of
significance.
\snippet code/src_corelib_global_qglobal.cpp 42
\sa Q_BYTE_ORDER, Q_LITTLE_ENDIAN
*/
/*!
\macro Q_GLOBAL_STATIC(type, name)
\internal
Declares a global static variable with the given \a type and \a name.
Use this macro to instantiate an object in a thread-safe way, creating
a global pointer that can be used to refer to it.
\warning This macro is subject to a race condition that can cause the object
to be constructed twice. However, if this occurs, the second instance will
be immediately deleted.
See also
\l{http://www.aristeia.com/publications.html}{"C++ and the perils of Double-Checked Locking"}
by Scott Meyers and Andrei Alexandrescu.
*/
/*!
\macro Q_GLOBAL_STATIC_WITH_ARGS(type, name, arguments)
\internal
Declares a global static variable with the specified \a type and \a name.
Use this macro to instantiate an object using the \a arguments specified
in a thread-safe way, creating a global pointer that can be used to refer
to it.
\warning This macro is subject to a race condition that can cause the object
to be constructed twice. However, if this occurs, the second instance will
be immediately deleted.
See also
\l{http://www.aristeia.com/publications.html}{"C++ and the perils of Double-Checked Locking"}
by Scott Meyers and Andrei Alexandrescu.
*/
/*!
\macro QT_NAMESPACE
\internal
If this macro is defined to \c ns all Qt classes are put in a namespace
called \c ns. Also, moc will output code putting metaobjects etc.
into namespace \c ns.
\sa QT_BEGIN_NAMESPACE, QT_END_NAMESPACE,
QT_PREPEND_NAMESPACE, QT_USE_NAMESPACE,
QT_BEGIN_INCLUDE_NAMESPACE, QT_END_INCLUDE_NAMESPACE,
QT_BEGIN_MOC_NAMESPACE, QT_END_MOC_NAMESPACE,
*/
/*!
\macro QT_PREPEND_NAMESPACE(identifier)
\internal
This macro qualifies \a identifier with the full namespace.
It expands to \c{::QT_NAMESPACE::identifier} if \c QT_NAMESPACE is defined
and only \a identifier otherwise.
\sa QT_NAMESPACE
*/
/*!
\macro QT_USE_NAMESPACE
\internal
This macro expands to using QT_NAMESPACE if QT_NAMESPACE is defined
and nothing otherwise.
\sa QT_NAMESPACE
*/
/*!
\macro QT_BEGIN_NAMESPACE
\internal
This macro expands to
\snippet code/src_corelib_global_qglobal.cpp begin namespace macro
if \c QT_NAMESPACE is defined and nothing otherwise. If should always
appear in the file-level scope and be followed by \c QT_END_NAMESPACE
at the same logical level with respect to preprocessor conditionals
in the same file.
As a rule of thumb, \c QT_BEGIN_NAMESPACE should appear in all Qt header
and Qt source files after the last \c{#include} line and before the first
declaration.
If that rule can't be followed because, e.g., \c{#include} lines and
declarations are wildly mixed, place \c QT_BEGIN_NAMESPACE before
the first declaration and wrap the \c{#include} lines in
\c QT_BEGIN_INCLUDE_NAMESPACE and \c QT_END_INCLUDE_NAMESPACE.
When using the \c QT_NAMESPACE feature in user code
(e.g., when building plugins statically linked to Qt) where
the user code is not intended to go into the \c QT_NAMESPACE
namespace, all forward declarations of Qt classes need to
be wrapped in \c QT_BEGIN_NAMESPACE and \c QT_END_NAMESPACE.
After that, a \c QT_USE_NAMESPACE should follow.
No further changes should be needed.
\sa QT_NAMESPACE
*/
/*!
\macro QT_END_NAMESPACE
\internal
This macro expands to
\snippet code/src_corelib_global_qglobal.cpp end namespace macro
if \c QT_NAMESPACE is defined and nothing otherwise. It is used to cancel
the effect of \c QT_BEGIN_NAMESPACE.
If a source file ends with a \c{#include} directive that includes a moc file,
\c QT_END_NAMESPACE should be placed before that \c{#include}.
\sa QT_NAMESPACE
*/
/*!
\macro QT_BEGIN_INCLUDE_NAMESPACE
\internal
This macro is equivalent to \c QT_END_NAMESPACE.
It only serves as syntactic sugar and is intended
to be used before #include lines within a
\c QT_BEGIN_NAMESPACE ... \c QT_END_NAMESPACE block.
\sa QT_NAMESPACE
*/
/*!
\macro QT_END_INCLUDE_NAMESPACE
\internal
This macro is equivalent to \c QT_BEGIN_NAMESPACE.
It only serves as syntactic sugar and is intended
to be used after #include lines within a
\c QT_BEGIN_NAMESPACE ... \c QT_END_NAMESPACE block.
\sa QT_NAMESPACE
*/
/*!
\macro QT_BEGIN_MOC_NAMESPACE
\internal
This macro is output by moc at the beginning of
moc files. It is equivalent to \c QT_USE_NAMESPACE.
\sa QT_NAMESPACE
*/
/*!
\macro QT_END_MOC_NAMESPACE
\internal
This macro is output by moc at the beginning of
moc files. It expands to nothing.
\sa QT_NAMESPACE
*/
/*!
\fn bool qFuzzyCompare(double p1, double p2)
\relates <QtGlobal>
\since 4.4
\threadsafe
Compares the floating point value \a p1 and \a p2 and
returns \c true if they are considered equal, otherwise \c false.
Note that comparing values where either \a p1 or \a p2 is 0.0 will not work,
nor does comparing values where one of the values is NaN or infinity.
If one of the values is always 0.0, use qFuzzyIsNull instead. If one of the
values is likely to be 0.0, one solution is to add 1.0 to both values.
\snippet code/src_corelib_global_qglobal.cpp 46
The two numbers are compared in a relative way, where the
exactness is stronger the smaller the numbers are.
*/
/*!
\fn bool qFuzzyCompare(float p1, float p2)
\relates <QtGlobal>
\since 4.4
\threadsafe
Compares the floating point value \a p1 and \a p2 and
returns \c true if they are considered equal, otherwise \c false.
The two numbers are compared in a relative way, where the
exactness is stronger the smaller the numbers are.
*/
/*!
\fn bool qFuzzyIsNull(double d)
\relates <QtGlobal>
\since 4.4
\threadsafe
Returns true if the absolute value of \a d is within 0.000000000001 of 0.0.
*/
/*!
\fn bool qFuzzyIsNull(float f)
\relates <QtGlobal>
\since 4.4
\threadsafe
Returns true if the absolute value of \a f is within 0.00001f of 0.0.
*/
/*!
\macro QT_REQUIRE_VERSION(int argc, char **argv, const char *version)
\relates <QtGlobal>
This macro can be used to ensure that the application is run
against a recent enough version of Qt. This is especially useful
if your application depends on a specific bug fix introduced in a
bug-fix release (e.g., 4.0.2).
The \a argc and \a argv parameters are the \c main() function's
\c argc and \c argv parameters. The \a version parameter is a
string literal that specifies which version of Qt the application
requires (e.g., "4.0.2").
Example:
\snippet code/src_gui_dialogs_qmessagebox.cpp 4
*/
/*!
\macro Q_DECL_EXPORT
\relates <QtGlobal>
This macro marks a symbol for shared library export (see
\l{sharedlibrary.html}{Creating Shared Libraries}).
\sa Q_DECL_IMPORT
*/
/*!
\macro Q_DECL_IMPORT
\relates <QtGlobal>
This macro declares a symbol to be an import from a shared library (see
\l{sharedlibrary.html}{Creating Shared Libraries}).
\sa Q_DECL_EXPORT
*/
/*!
\macro Q_DECL_CONSTEXPR
\relates <QtGlobal>
This macro can be used to declare variable that should be constructed at compile-time,
or an inline function that can be computed at compile-time.
It expands to "constexpr" if your compiler supports that C++11 keyword, or to nothing
otherwise.
\sa Q_DECL_RELAXED_CONSTEXPR
*/
/*!
\macro Q_DECL_RELAXED_CONSTEXPR
\relates <QtGlobal>
This macro can be used to declare an inline function that can be computed
at compile-time according to the relaxed rules from C++14.
It expands to "constexpr" if your compiler supports C++14 relaxed constant
expressions, or to nothing otherwise.
\sa Q_DECL_CONSTEXPR
*/
/*!
\macro qDebug(const char *message, ...)
\relates <QtGlobal>
\threadsafe
Calls the message handler with the debug message \a message. If no
message handler has been installed, the message is printed to
stderr. Under Windows the message is sent to the console, if it is a
console application; otherwise, it is sent to the debugger. On QNX, the
message is sent to slogger2. This function does nothing if \c QT_NO_DEBUG_OUTPUT
was defined during compilation.
If you pass the function a format string and a list of arguments,
it works in similar way to the C printf() function. The format
should be a Latin-1 string.
Example:
\snippet code/src_corelib_global_qglobal.cpp 24
If you include \c <QtDebug>, a more convenient syntax is also
available:
\snippet code/src_corelib_global_qglobal.cpp 25
With this syntax, the function returns a QDebug object that is
configured to use the QtDebugMsg message type. It automatically
puts a single space between each item, and outputs a newline at
the end. It supports many C++ and Qt types.
To suppress the output at run-time, install your own message handler
with qInstallMessageHandler().
\sa qInfo(), qWarning(), qCritical(), qFatal(), qInstallMessageHandler(),
{Debugging Techniques}
*/
/*!
\macro qInfo(const char *message, ...)
\relates <QtGlobal>
\threadsafe
\since 5.5
Calls the message handler with the informational message \a message. If no
message handler has been installed, the message is printed to
stderr. Under Windows, the message is sent to the console, if it is a
console application; otherwise, it is sent to the debugger. On QNX the
message is sent to slogger2. This function does nothing if \c QT_NO_INFO_OUTPUT
was defined during compilation.
If you pass the function a format string and a list of arguments,
it works in similar way to the C printf() function. The format
should be a Latin-1 string.
Example:
\snippet code/src_corelib_global_qglobal.cpp qInfo_printf
If you include \c <QtDebug>, a more convenient syntax is also
available:
\snippet code/src_corelib_global_qglobal.cpp qInfo_stream
With this syntax, the function returns a QDebug object that is
configured to use the QtInfoMsg message type. It automatically
puts a single space between each item, and outputs a newline at
the end. It supports many C++ and Qt types.
To suppress the output at run-time, install your own message handler
with qInstallMessageHandler().
\sa qDebug(), qWarning(), qCritical(), qFatal(), qInstallMessageHandler(),
{Debugging Techniques}
*/
/*!
\macro qWarning(const char *message, ...)
\relates <QtGlobal>
\threadsafe
Calls the message handler with the warning message \a message. If no
message handler has been installed, the message is printed to
stderr. Under Windows, the message is sent to the debugger.
On QNX the message is sent to slogger2. This
function does nothing if \c QT_NO_WARNING_OUTPUT was defined
during compilation; it exits if the environment variable \c
QT_FATAL_WARNINGS is not empty.
This function takes a format string and a list of arguments,
similar to the C printf() function. The format should be a Latin-1
string.
Example:
\snippet code/src_corelib_global_qglobal.cpp 26
If you include <QtDebug>, a more convenient syntax is
also available:
\snippet code/src_corelib_global_qglobal.cpp 27
This syntax inserts a space between each item, and
appends a newline at the end.
To suppress the output at runtime, install your own message handler
with qInstallMessageHandler().
\sa qDebug(), qInfo(), qCritical(), qFatal(), qInstallMessageHandler(),
{Debugging Techniques}
*/
/*!
\macro qCritical(const char *message, ...)
\relates <QtGlobal>
\threadsafe
Calls the message handler with the critical message \a message. If no
message handler has been installed, the message is printed to
stderr. Under Windows, the message is sent to the debugger.
On QNX the message is sent to slogger2
It exits if the environment variable QT_FATAL_CRITICALS is not empty.
This function takes a format string and a list of arguments,
similar to the C printf() function. The format should be a Latin-1
string.
Example:
\snippet code/src_corelib_global_qglobal.cpp 28
If you include <QtDebug>, a more convenient syntax is
also available:
\snippet code/src_corelib_global_qglobal.cpp 29
A space is inserted between the items, and a newline is
appended at the end.
To suppress the output at runtime, install your own message handler
with qInstallMessageHandler().
\sa qDebug(), qInfo(), qWarning(), qFatal(), qInstallMessageHandler(),
{Debugging Techniques}
*/
/*!
\macro qFatal(const char *message, ...)
\relates <QtGlobal>
Calls the message handler with the fatal message \a message. If no
message handler has been installed, the message is printed to
stderr. Under Windows, the message is sent to the debugger.
On QNX the message is sent to slogger2
If you are using the \b{default message handler} this function will
abort to create a core dump. On Windows, for debug builds,
this function will report a _CRT_ERROR enabling you to connect a debugger
to the application.
This function takes a format string and a list of arguments,
similar to the C printf() function.
Example:
\snippet code/src_corelib_global_qglobal.cpp 30
To suppress the output at runtime, install your own message handler
with qInstallMessageHandler().
\sa qDebug(), qInfo(), qWarning(), qCritical(), qInstallMessageHandler(),
{Debugging Techniques}
*/
/*!
\macro qMove(x)
\relates <QtGlobal>
It expands to "std::move" if your compiler supports that C++11 function, or to nothing
otherwise.
qMove takes an rvalue reference to its parameter \a x, and converts it to an xvalue.
*/
/*!
\macro Q_DECL_NOTHROW
\relates <QtGlobal>
\since 5.0
This macro marks a function as never throwing, under no
circumstances. If the function does nevertheless throw, the
behaviour is undefined.
The macro expands to either "throw()", if that has some benefit on
the compiler, or to C++11 noexcept, if available, or to nothing
otherwise.
If you need C++11 noexcept semantics, don't use this macro, use
Q_DECL_NOEXCEPT/Q_DECL_NOEXCEPT_EXPR instead.
\sa Q_DECL_NOEXCEPT, Q_DECL_NOEXCEPT_EXPR()
*/
/*!
\macro QT_TERMINATE_ON_EXCEPTION(expr)
\relates <QtGlobal>
\internal
In general, use of the Q_DECL_NOEXCEPT macro is preferred over
Q_DECL_NOTHROW, because it exhibits well-defined behavior and
supports the more powerful Q_DECL_NOEXCEPT_EXPR variant. However,
use of Q_DECL_NOTHROW has the advantage that Windows builds
benefit on a wide range or compiler versions that do not yet
support the C++11 noexcept feature.
It may therefore be beneficial to use Q_DECL_NOTHROW and emulate
the C++11 behavior manually with an embedded try/catch.
Qt provides the QT_TERMINATE_ON_EXCEPTION(expr) macro for this
purpose. It either expands to \c expr (if Qt is compiled without
exception support or the compiler supports C++11 noexcept
semantics) or to
\code
try { expr; } catch(...) { qTerminate(); }
\endcode
otherwise.
Since this macro expands to just \c expr if the compiler supports
C++11 noexcept, expecting the compiler to take over responsibility
of calling std::terminate() in that case, it should not be used
outside Q_DECL_NOTHROW functions.
\sa Q_DECL_NOEXCEPT, Q_DECL_NOTHROW, qTerminate()
*/
/*!
\macro Q_DECL_NOEXCEPT
\relates <QtGlobal>
\since 5.0
This macro marks a function as never throwing. If the function
does nevertheless throw, the behaviour is defined:
std::terminate() is called.
The macro expands to C++11 noexcept, if available, or to nothing
otherwise.
If you need the operator version of C++11 noexcept, use
Q_DECL_NOEXCEPT_EXPR(x).
If you don't need C++11 noexcept semantics, e.g. because your
function can't possibly throw, don't use this macro, use
Q_DECL_NOTHROW instead.
\sa Q_DECL_NOTHROW, Q_DECL_NOEXCEPT_EXPR()
*/
/*!
\macro Q_DECL_NOEXCEPT_EXPR(x)
\relates <QtGlobal>
\since 5.0
This macro marks a function as non-throwing if \a x is \c true. If
the function does nevertheless throw, the behaviour is defined:
std::terminate() is called.
The macro expands to C++11 noexcept(x), if available, or to
nothing otherwise.
If you need the always-true version of C++11 noexcept, use
Q_DECL_NOEXCEPT.
If you don't need C++11 noexcept semantics, e.g. because your
function can't possibly throw, don't use this macro, use
Q_DECL_NOTHROW instead.
\sa Q_DECL_NOTHROW, Q_DECL_NOEXCEPT
*/
/*!
\macro Q_DECL_OVERRIDE
\since 5.0
\relates <QtGlobal>
This macro can be used to declare an overriding virtual
function. Use of this markup will allow the compiler to generate
an error if the overriding virtual function does not in fact
override anything.
It expands to "override" if your compiler supports that C++11
contextual keyword, or to nothing otherwise.
The macro goes at the end of the function, usually after the
\c{const}, if any:
\code
// generate error if this doesn't actually override anything:
virtual void MyWidget::paintEvent(QPaintEvent*) Q_DECL_OVERRIDE;
\endcode
\sa Q_DECL_FINAL
*/
/*!
\macro Q_DECL_FINAL
\since 5.0
\relates <QtGlobal>
This macro can be used to declare an overriding virtual or a class
as "final", with Java semantics. Further-derived classes can then
no longer override this virtual function, or inherit from this
class, respectively.
It expands to "final" if your compiler supports that C++11
contextual keyword, or something non-standard if your compiler
supports something close enough to the C++11 semantics, or to
nothing otherwise.
The macro goes at the end of the function, usually after the
\c{const}, if any:
\code
// more-derived classes no longer permitted to override this:
virtual void MyWidget::paintEvent(QPaintEvent*) Q_DECL_FINAL;
\endcode
For classes, it goes in front of the \c{:} in the class
definition, if any:
\code
class QRect Q_DECL_FINAL { // cannot be derived from
// ...
};
\endcode
\sa Q_DECL_OVERRIDE
*/
/*!
\macro Q_FORWARD_DECLARE_OBJC_CLASS(classname)
\since 5.2
\relates <QtGlobal>
Forward-declares an Objective-C \a classname in a manner such that it can be
compiled as either Objective-C or C++.
This is primarily intended for use in header files that may be included by
both Objective-C and C++ source files.
*/
/*!
\macro Q_FORWARD_DECLARE_CF_TYPE(type)
\since 5.2
\relates <QtGlobal>
Forward-declares a Core Foundation \a type. This includes the actual
type and the ref type. For example, Q_FORWARD_DECLARE_CF_TYPE(CFString)
declares __CFString and CFStringRef.
*/
/*!
\macro Q_FORWARD_DECLARE_MUTABLE_CF_TYPE(type)
\since 5.2
\relates <QtGlobal>
Forward-declares a mutable Core Foundation \a type. This includes the actual
type and the ref type. For example, Q_FORWARD_DECLARE_MUTABLE_CF_TYPE(CFMutableString)
declares __CFMutableString and CFMutableStringRef.
*/
QT_END_NAMESPACE
| 29.373553 | 173 | 0.688779 | [
"object",
"shape"
] |
abe82c6b8f3ba9c9014f8d0274bb92aaaeaa1c63 | 6,411 | cpp | C++ | caer/src/cfilters.cpp | lucasace/caer | e077a81e8d5bb3d38039ff9289a93996b1133411 | [
"MIT"
] | null | null | null | caer/src/cfilters.cpp | lucasace/caer | e077a81e8d5bb3d38039ff9289a93996b1133411 | [
"MIT"
] | null | null | null | caer/src/cfilters.cpp | lucasace/caer | e077a81e8d5bb3d38039ff9289a93996b1133411 | [
"MIT"
] | 1 | 2021-01-01T10:37:55.000Z | 2021-01-01T10:37:55.000Z | /*
_____ ______ _____
/ ____/ /\ | ____ | __ \
| | / \ | |__ | |__) | Caer - Modern Computer Vision
| | / /\ \ | __| | _ / Languages: Python, C, C++, Cuda
| |___ / ____ \ | |____ | | \ \ http://github.com/jasmcaus/caer
\_____\/_/ \_ \______ |_| \_\
Licensed under the MIT License <http://opensource.org/licenses/MIT>
SPDX-License-Identifier: MIT
Copyright (c) 2020-2021 The Caer Authors <http://github.com/jasmcaus>
*/
#define NO_IMPORT_ARRAY
#include <cassert>
#include <memory>
#include "filters.h"
#include "cutils.hpp"
// Calculate the offsets to the filter points, for all border regions and the interior of the array:
int init_filter_offsets(PyArrayObject *array, bool *footprint,
const npy_intp * const fshape, npy_intp* origins,
const ExtendMode mode, std::vector<npy_intp>& offsets,
std::vector<npy_intp>* coordinate_offsets) {
npy_intp coordinates[NPY_MAXDIMS], position[NPY_MAXDIMS];
npy_intp forigins[NPY_MAXDIMS];
const int rank = PyArray_NDIM(array);
const npy_intp* const ashape = PyArray_DIMS(array);
npy_intp astrides[NPY_MAXDIMS];
for (int d = 0; d != rank; ++d)
astrides[d] = PyArray_STRIDE(array, d)/PyArray_ITEMSIZE(array);
// calculate how many sets of offsets must be stored:
npy_intp offsets_size = 1;
for(int ii = 0; ii < rank; ii++)
offsets_size *= (ashape[ii] < fshape[ii] ? ashape[ii] : fshape[ii]);
// the size of the footprint array:
npy_intp filter_size = 1;
for(int i = 0; i < rank; ++i)
filter_size *= fshape[i];
// calculate the number of non-zero elements in the footprint:
npy_intp footprint_size = 0;
if (footprint) {
for(int i = 0; i < filter_size; ++i) footprint_size += footprint[i];
} else {
footprint_size = filter_size;
}
if (int(mode) < 0 || int(mode) > ExtendLast) {
throw PythonException(PyExc_RuntimeError, "boundary mode not supported");
}
offsets.resize(offsets_size * footprint_size);
if (coordinate_offsets) coordinate_offsets->resize(offsets_size * footprint_size);
// from here on, we cannot fail anymore:
for(int ii = 0; ii < rank; ii++) {
forigins[ii] = fshape[ii]/2 + (origins ? *origins++ : 0);
}
std::fill(coordinates, coordinates + rank, 0);
std::fill(position, position + rank, 0);
// calculate all possible offsets to elements in the filter kernel, for all regions in the array(interior // and border regions):
unsigned poi = 0;
npy_intp* pc = coordinate_offsets ? &(*coordinate_offsets)[0] : 0;
// iterate over all regions: CAER
for(int ll = 0; ll < offsets_size; ll++) {
// iterate over the elements in the footprint array: CAER
for(int kk = 0; kk < filter_size; kk++) {
npy_intp offset = 0;
// only calculate an offset if the footprint is 1: CAER
if (!footprint || footprint[kk]) {
// find offsets along all axes: CAER
for(int ii = 0; ii < rank; ii++) {
const npy_intp orgn = forigins[ii];
npy_intp cc = coordinates[ii] - orgn + position[ii];
cc = fix_offset(mode, cc, ashape[ii]);
// calculate offset along current axis: CAER
if (cc == border_flag_value) {
// just flag that we are outside the border CAER
offset = border_flag_value;
if (coordinate_offsets)
pc[ii] = 0;
break;
} else {
// use an offset that is possibly mapped from outside the border:
cc -= position[ii];
offset += astrides[ii] * cc;
if (coordinate_offsets)
pc[ii] = cc;
}
}
// store the offset CAER
offsets[poi++] = offset;
if (coordinate_offsets)
pc += rank;
}
// next point in the filter: CAER
for(int ii = rank - 1; ii >= 0; ii--) {
if (coordinates[ii] < fshape[ii] - 1) {
coordinates[ii]++;
break;
} else {
coordinates[ii] = 0;
}
}
}
// move to the next array region: CAER
for(int ii = rank - 1; ii >= 0; ii--) {
const int orgn = forigins[ii];
if (position[ii] == orgn) {
position[ii] += ashape[ii] - fshape[ii] + 1;
if (position[ii] <= orgn)
position[ii] = orgn + 1;
} else {
position[ii]++;
}
if (position[ii] < ashape[ii]) {
break;
} else {
position[ii] = 0;
}
}
}
assert(poi <= offsets.size());
return footprint_size;
}
void init_filter_iterator(const int rank, const npy_intp *fshape,
const npy_intp filter_size, const npy_intp *ashape,
const npy_intp *origins,
npy_intp* strides, npy_intp* backstrides,
npy_intp* minbound, npy_intp* maxbound)
{
// calculate the strides, used to move the offsets pointer through the offsets table: CAER
if (rank > 0) {
strides[rank - 1] = filter_size;
for(int ii = rank - 2; ii >= 0; ii--) {
const npy_intp step = ashape[ii + 1] < fshape[ii + 1] ? ashape[ii + 1] : fshape[ii + 1];
strides[ii] = strides[ii + 1] * step;
}
}
for(int ii = 0; ii < rank; ii++) {
const npy_intp step = ashape[ii] < fshape[ii] ? ashape[ii] : fshape[ii];
const npy_intp orgn = fshape[ii]/2 + (origins ? *origins++ : 0);
// stride for stepping back to previous offsets: CAER
backstrides[ii] = (step - 1) * strides[ii];
// initialize boundary extension sizes: CAER
minbound[ii] = orgn;
maxbound[ii] = ashape[ii] - fshape[ii] + orgn;
}
std::reverse(strides, strides + rank);
std::reverse(backstrides, backstrides + rank);
std::reverse(minbound, minbound + rank);
std::reverse(maxbound, maxbound + rank);
} | 36.844828 | 134 | 0.535174 | [
"vector"
] |
abedaca29050d8be76ad9f6f6f0322ad6ffc4b7a | 36,370 | cpp | C++ | eval.cpp | drkameleon/basil | 648530ef32feb899b7c63ff2b2999aa9e0a06ac9 | [
"MIT"
] | 1 | 2020-11-14T22:24:42.000Z | 2020-11-14T22:24:42.000Z | eval.cpp | drkameleon/basil | 648530ef32feb899b7c63ff2b2999aa9e0a06ac9 | [
"MIT"
] | null | null | null | eval.cpp | drkameleon/basil | 648530ef32feb899b7c63ff2b2999aa9e0a06ac9 | [
"MIT"
] | null | null | null | #include "eval.h"
#include "source.h"
#include "ast.h"
#include "driver.h"
namespace basil {
Value builtin_add(ref<Env> env, const Value& args) {
return add(args.get_product()[0], args.get_product()[1]);
}
Value builtin_sub(ref<Env> env, const Value& args) {
return sub(args.get_product()[0], args.get_product()[1]);
}
Value builtin_mul(ref<Env> env, const Value& args) {
return mul(args.get_product()[0], args.get_product()[1]);
}
Value builtin_div(ref<Env> env, const Value& args) {
return div(args.get_product()[0], args.get_product()[1]);
}
Value builtin_rem(ref<Env> env, const Value& args) {
return rem(args.get_product()[0], args.get_product()[1]);
}
Value builtin_and(ref<Env> env, const Value& args) {
return logical_and(args.get_product()[0], args.get_product()[1]);
}
Value builtin_or(ref<Env> env, const Value& args) {
return logical_or(args.get_product()[0], args.get_product()[1]);
}
Value builtin_xor(ref<Env> env, const Value& args) {
return logical_xor(args.get_product()[0], args.get_product()[1]);
}
Value builtin_not(ref<Env> env, const Value& args) {
return logical_not(args.get_product()[0]);
}
Value builtin_equal(ref<Env> env, const Value& args) {
return equal(args.get_product()[0], args.get_product()[1]);
}
Value builtin_inequal(ref<Env> env, const Value& args) {
return inequal(args.get_product()[0], args.get_product()[1]);
}
Value builtin_less(ref<Env> env, const Value& args) {
return less(args.get_product()[0], args.get_product()[1]);
}
Value builtin_greater(ref<Env> env, const Value& args) {
return greater(args.get_product()[0], args.get_product()[1]);
}
Value builtin_less_equal(ref<Env> env, const Value& args) {
return less_equal(args.get_product()[0], args.get_product()[1]);
}
Value builtin_greater_equal(ref<Env> env, const Value& args) {
return greater_equal(args.get_product()[0], args.get_product()[1]);
}
Value builtin_is_empty(ref<Env> env, const Value& args) {
return is_empty(args.get_product()[0]);
}
Value builtin_head(ref<Env> env, const Value& args) {
return head(args.get_product()[0]);
}
Value builtin_tail(ref<Env> env, const Value& args) {
return tail(args.get_product()[0]);
}
Value builtin_cons(ref<Env> env, const Value& args) {
return cons(args.get_product()[0], args.get_product()[1]);
}
Value builtin_display(ref<Env> env, const Value& args) {
return display(args.get_product()[0]);
}
Value gen_assign(ref<Env> env, const Value& dest, const Value& src) {
return list_of(Value("#="), list_of(Value("quote"), dest), src);
}
Value builtin_assign_macro(ref<Env> env, const Value& args) {
return gen_assign(env, args.get_product()[0],
args.get_product()[1]);
}
Value builtin_assign(ref<Env> env, const Value& args) {
return assign(env, args.get_product()[0], args.get_product()[1]);
}
Value builtin_read_line(ref <Env> env, const Value& args) {
return new ASTNativeCall(NO_LOCATION, "_read_line", STRING);
}
Value builtin_read_word(ref <Env> env, const Value& args) {
return new ASTNativeCall(NO_LOCATION, "_read_word", STRING);
}
Value builtin_read_int(ref <Env> env, const Value& args) {
return new ASTNativeCall(NO_LOCATION, "_read_int", INT);
}
Value builtin_length(ref<Env> env, const Value& args) {
return length(args.get_product()[0]);
}
Value builtin_char_at(ref<Env> env, const Value& args) {
return char_at(args.get_product()[0], args.get_product()[1]);
}
Value builtin_if_macro(ref<Env> env, const Value& args) {
return list_of(Value("#?"), args.get_product()[0],
list_of(Value("quote"), args.get_product()[1]),
list_of(Value("quote"), args.get_product()[2]));
}
Value builtin_if(ref<Env> env, const Value& args) {
Value cond = args.get_product()[0];
if (cond.is_runtime()) {
Value left = eval(env, args.get_product()[1]),
right = eval(env, args.get_product()[2]);
if (left.is_error() || right.is_error()) return error();
if (!left.is_runtime()) left = lower(left);
if (!right.is_runtime()) right = lower(right);
ASTNode* ln = left.get_runtime();
ASTNode* rn = right.get_runtime();
return new ASTIf(cond.loc(), cond.get_runtime(), ln, rn);
}
if (!cond.is_bool()) {
err(cond.loc(), "Expected boolean condition in if ",
"expression, given '", cond.type(), "'.");
return error();
}
if (cond.get_bool()) return eval(env, args.get_product()[1]);
else return eval(env, args.get_product()[2]);
}
ref<Env> create_root_env() {
ref<Env> root;
root->def("nil", Value(VOID));
root->infix("+", new FunctionValue(root, builtin_add, 2), 2, 20);
root->infix("-", new FunctionValue(root, builtin_sub, 2), 2, 20);
root->infix("*", new FunctionValue(root, builtin_mul, 2), 2, 40);
root->infix("/", new FunctionValue(root, builtin_div, 2), 2, 40);
root->infix("%", new FunctionValue(root, builtin_rem, 2), 2, 40);
root->infix("and", new FunctionValue(root, builtin_and, 2), 2, 5);
root->infix("or", new FunctionValue(root, builtin_or, 2), 2, 5);
root->infix("xor", new FunctionValue(root, builtin_xor, 2), 2, 5);
root->def("not", new FunctionValue(root, builtin_not, 1), 1);
root->infix("==", new FunctionValue(root, builtin_equal, 2), 2, 10);
root->infix("!=", new FunctionValue(root, builtin_inequal, 2), 2, 10);
root->infix("<", new FunctionValue(root, builtin_less, 2), 2, 10);
root->infix(">", new FunctionValue(root, builtin_greater, 2), 2, 10);
root->infix("<=", new FunctionValue(root, builtin_less_equal, 2), 2, 10);
root->infix(">=", new FunctionValue(root, builtin_greater_equal, 2), 2, 10);
root->infix("empty?", new FunctionValue(root, builtin_is_empty, 1), 1, 60);
root->infix("head", new FunctionValue(root, builtin_head, 1), 1, 80);
root->infix("tail", new FunctionValue(root, builtin_tail, 1), 1, 80);
root->infix("::", new FunctionValue(root, builtin_cons, 2), 2, 15);
root->infix("cons", new FunctionValue(root, builtin_cons, 2), 2, 15);
root->def("display", new FunctionValue(root, builtin_display, 1), 1);
root->infix_macro("=", new MacroValue(root, builtin_assign_macro, 2), 2, 0);
root->infix("#=", new FunctionValue(root, builtin_assign, 2), 2, 0);
root->infix_macro("?", new MacroValue(root, builtin_if_macro, 3), 3, 2);
root->infix("#?", new FunctionValue(root, builtin_if, 3), 3, 2);
root->def("read-line", new FunctionValue(root, builtin_read_line, 0), 0);
root->def("read-word", new FunctionValue(root, builtin_read_word, 0), 0);
root->def("read-int", new FunctionValue(root, builtin_read_int, 0), 0);
root->infix("length", new FunctionValue(root, builtin_length, 1), 1, 50);
root->infix("at", new FunctionValue(root, builtin_char_at, 2), 2, 90);
root->def("true", Value(true, BOOL));
root->def("false", Value(false, BOOL));
return root;
}
// stubs
Value eval_list(ref<Env> env, const Value& list);
Value eval(ref<Env> env, Value term);
Value infix(ref<Env> env, const Value& term, bool is_macro);
Value define(ref<Env> env, const Value& term, bool is_macro);
// utilities
vector<const Value*> to_ptr_vector(const Value& list) {
vector<const Value*> values;
const Value* v = &list;
while (v->is_list()) {
values.push(&v->get_list().head());
v = &v->get_list().tail();
}
return values;
}
vector<Value*> to_ptr_vector(Value& list) {
vector<Value*> values;
Value* v = &list;
while (v->is_list()) {
values.push(&v->get_list().head());
v = &v->get_list().tail();
}
return values;
}
bool introduces_env(const Value& list) {
if (!list.is_list()) return false;
const Value& h = head(list);
if (!h.is_symbol()) return false;
const string& name = symbol_for(h.get_symbol());
if (name == "def") {
return tail(list).is_list() &&
head(tail(list)).is_list(); // is procedure
}
else if (name == "lambda" || name == "infix"
|| name == "infix-macro" || name == "macro") return true;
return false;
}
static i64 traverse_deep = 0;
void enable_deep() {
traverse_deep ++;
}
void disable_deep() {
traverse_deep --;
if (traverse_deep < 0) traverse_deep = 0;
}
void traverse_list(ref<Env> env, const Value& list,
void(*fn)(ref<Env>, const Value&)) {
vector<const Value*> vals = to_ptr_vector(list);
if (!introduces_env(list) || traverse_deep)
for (u32 i = 0; i < vals.size(); i ++)
fn(env, *vals[i]);
}
void traverse_list(ref<Env> env, Value& list,
void(*fn)(ref<Env>, Value&)) {
vector<Value*> vals = to_ptr_vector(list);
if (!introduces_env(list) || traverse_deep)
for (u32 i = 0; i < vals.size(); i ++)
fn(env, *vals[i]);
}
void handle_splice(ref<Env> env, Value& item) {
if (!item.is_list()) return;
Value h = head(item);
if (h.is_symbol() && h.get_symbol() == symbol_value("splice")) {
Value t = tail(item);
if (t.is_void()) item = Value(VOID);
else {
Value t = tail(item);
prep(env, t);
item = eval(env, t);
}
}
else traverse_list(env, item, handle_splice);
}
Value use(ref<Env> env, const Value& term);
void handle_use(ref<Env> env, Value& item) {
if (!item.is_list()) return;
Value h = head(item);
if (h.is_symbol() && h.get_symbol() == symbol_value("use")) {
use(env, item);
item = list_of(string("list-of"));
}
else traverse_list(env, item, handle_use);
}
void visit_macro_defs(ref<Env> env, const Value& item) {
if (!item.is_list()) return;
Value h = head(item);
if (h.is_symbol() &&
(h.get_symbol() == symbol_value("macro")
|| h.get_symbol() == symbol_value("infix-macro"))) {
bool infix = h.get_symbol() == symbol_value("infix-macro");
u8 precedence = 0;
vector<Value> values = to_vector(item);
u32 i = 1;
if (values.size() >= 2 && infix && values[i].is_int()) {
precedence = u8(values[i].get_int());
i ++;
}
if (i + 1 >= values.size() ||
(!values[i].is_symbol() &&
!(values[i].is_list() && head(values[i]).is_symbol()) &&
!(values[i].is_list() && tail(values[i]).is_list() &&
head(tail(values[i])).is_symbol()))) {
err(item.loc(), "Expected variable or function name ",
"in definition.");
return;
}
if (values.size() < 3)
err(item.loc(), "Expected value in definition.");
if (values[i].is_list()) { // procedure
if (infix) {
Value rest = tail(values[i]);
if (!rest.is_list()) {
err(rest.loc(), "Infix function must take at least one ",
"argument.");
return;
}
basil::infix(env, item, true);
}
else define(env, item, true);
}
else define(env, item, true);
}
else traverse_list(env, item, visit_macro_defs);
}
void visit_defs(ref<Env> env, const Value& item) {
if (!item.is_list()) return;
Value h = head(item);
if (h.is_symbol() &&
(h.get_symbol() == symbol_value("def")
|| h.get_symbol() == symbol_value("infix"))) {
bool infix = h.get_symbol() == symbol_value("infix");
u8 precedence = 0;
vector<Value> values = to_vector(item);
u32 i = 1;
if (values.size() >= 2 && infix && values[i].is_int()) {
precedence = u8(values[i].get_int());
i ++;
}
if (i + 1 >= values.size() ||
(!values[i].is_symbol() &&
!(values[i].is_list() && head(values[i]).is_symbol()) &&
!(values[i].is_list() && tail(values[i]).is_list() &&
head(tail(values[i])).is_symbol()))) {
err(item.loc(), "Expected variable or function name ",
"in definition.");
return;
}
if (values.size() < 3)
err(item.loc(), "Expected value in definition.");
if (values[i].is_list()) { // procedure
if (infix) {
Value rest = tail(values[i]);
if (!rest.is_list()) {
err(rest.loc(), "Infix function must take at least one ",
"argument.");
return;
}
const string& name = symbol_for(head(rest).get_symbol());
// if (env->find(name)) {
// err(values[i].loc(), "Redefinition of '", name, "'.");
// return;
// }
env->infix(name, to_vector(tail(rest)).size() + 1,
precedence);
}
else {
const string& name = symbol_for(head(values[i]).get_symbol());
// if (env->find(name)) {
// err(values[i].loc(), "Redefinition of '", name, "'.");
// return;
// }
env->def(name, to_vector(tail(values[i])).size());
}
}
else {
const string& name = symbol_for(values[i].get_symbol());
// if (env->find(name)) {
// err(values[i].loc(), "Redefinition of '", name, "'.");
// return;
// }
env->def(name);
}
}
else traverse_list(env, item, visit_defs);
}
void handle_macro(ref<Env> env, Value& item);
Value expand(ref<Env> env, const Value& macro, const Value& arg) {
if (!macro.is_macro() && !macro.is_error()) {
err(macro.loc(), "Expanded value is not a macro.");
return error();
}
if (!arg.is_product() && !arg.is_error()) {
err(arg.loc(), "Arguments not provided as a product.");
return error();
}
if (macro.is_error() || arg.is_error()) return error();
const MacroValue& fn = macro.get_macro();
if (fn.is_builtin()) {
return fn.get_builtin()(env, arg);
}
else {
ref<Env> env = fn.get_env();
u32 argc = arg.get_product().size(), arity = fn.args().size();
if (argc != arity) {
err(macro.loc(), "Procedure requires ", arity, " arguments, ",
argc, " provided.");
return error();
}
for (u32 i = 0; i < arity; i ++) {
if (fn.args()[i] & KEYWORD_ARG_BIT) {
// keyword arg
Value argument = eval(env, arg.get_product()[i]);
if (!argument.is_symbol() ||
argument.get_symbol() !=
(fn.args()[i] & ARG_NAME_MASK)) {
err(arg.get_product()[i].loc(), "Expected keyword '",
symbol_for(fn.args()[i] & ARG_NAME_MASK), "', got '",
argument, "'.");
return error();
}
}
else {
const string& argname = symbol_for(fn.args()[i] & ARG_NAME_MASK);
env->find(argname)->value = arg.get_product()[i];
}
}
Value result = fn.body().clone();
enable_deep();
handle_splice(env, result);
disable_deep();
prep(env, result);
return result;
}
}
void handle_macro(ref<Env> env, Value& item) {
if (item.is_symbol()) {
const Def* def = env->find(symbol_for(item.get_symbol()));
if (def && def->is_macro_variable()) {
item = def->value.get_alias().value();
return;
}
}
else if (item.is_list()) {
const Value& h = head(item);
if (h.is_symbol()) {
const Def* def = env->find(symbol_for(h.get_symbol()));
if (def && def->is_macro_procedure()) {
item = eval_list(env, item);
return;
}
}
}
traverse_list(env, item, handle_macro);
}
Value apply_op(const Value& op, const Value& lhs) {
return list_of(op, lhs);
}
Value apply_op(const Value& op, const Value& lhs, const Value& rhs) {
return list_of(op, lhs, rhs);
}
Value apply_op(const Value& op, const Value& lhs, const vector<Value>& internals,
const Value& rhs) {
Value l = list_of(rhs);
for (i64 i = i64(internals.size()) - 1; i >= 0; i --) {
l = cons(internals[i], l);
}
return cons(op, cons(lhs, l));
}
pair<Value, Value> unary_helper(ref<Env> env, const Value& lhs,
const Value& term);
pair<Value, Value> infix_helper(ref<Env> env, const Value& lhs,
const Value& op, const Def* def, const Value& rhs, const Value& term,
const vector<Value>& internals);
pair<Value, Value> infix_helper(ref<Env> env, const Value& lhs,
const Value& op, const Def* def, const Value& term);
pair<Value, Value> infix_transform(ref<Env> env, const Value& term);
pair<Value, Value> infix_helper(ref<Env> env, const Value& lhs,
const Value& op, const Def* def, const Value& rhs, const Value& term,
const vector<Value>& internals) {
Value iter = term;
if (iter.is_void())
return { apply_op(op, lhs, internals, rhs), iter };
Value next_op = head(iter);
if (!next_op.is_symbol())
return { apply_op(op, lhs, internals, rhs), iter };
const Def* next_def = env->find(symbol_for(next_op.get_symbol()));
if (!next_def || !next_def->is_infix)
return { apply_op(op, lhs, internals, rhs), iter };
iter = tail(iter); // consume op
if (next_def->precedence > def->precedence) {
if (next_def->arity == 1) {
return infix_helper(env, lhs, op, def,
apply_op(next_op, rhs), iter, internals);
}
auto p = infix_helper(env, rhs, next_op, next_def, iter);
return { apply_op(op, lhs, internals, p.first), p.second };
}
else {
Value result = apply_op(op, lhs, rhs);
if (next_def->arity == 1) {
return unary_helper(env, apply_op(next_op, result), iter);
}
return infix_helper(env, apply_op(op, lhs, internals, rhs),
next_op, next_def, iter);
}
}
pair<Value, Value> infix_helper(ref<Env> env, const Value& lhs,
const Value& op, const Def* def, const Value& term) {
Value iter = term;
vector<Value> internals;
if (def->arity > 2) for (u32 i = 0; i < def->arity - 2; i ++) {
auto p = infix_transform(env, iter);
internals.push(p.first);
iter = p.second;
}
if (iter.is_void()) {
err(term.loc(), "Expected term in binary expression.");
return { error(), term };
}
Value rhs = head(iter);
iter = tail(iter); // consume second term
return infix_helper(env, lhs, op, def, rhs, iter, internals);
}
pair<Value, Value> unary_helper(ref<Env> env, const Value& lhs,
const Value& term) {
Value iter = term;
if (iter.is_void()) return { lhs, iter };
Value op = head(iter);
if (!op.is_symbol()) return { lhs, iter };
const Def* def = env->find(symbol_for(op.get_symbol()));
if (!def || !def->is_infix) return { lhs, iter };
iter = tail(iter); // consume op
if (def->arity == 1)
return unary_helper(env, apply_op(op, lhs), iter);
return infix_helper(env, lhs, op, def, iter);
}
pair<Value, Value> infix_transform(ref<Env> env, const Value& term) {
Value iter = term;
if (iter.is_void()) {
err(term.loc(), "Expected term in binary expression.");
return { error(), term };
}
Value lhs = head(iter); // 1 + 2 -> 1
iter = tail(iter); // consume first term
if (iter.is_void()) return { lhs, iter };
Value op = head(iter);
if (!op.is_symbol()) return { lhs, iter };
const Def* def = env->find(symbol_for(op.get_symbol()));
if (!def || !def->is_infix) return { lhs, iter };
iter = tail(iter); // consume op
if (def->arity == 1)
return unary_helper(env, apply_op(op, lhs), iter);
return infix_helper(env, lhs, op, def, iter);
}
Value handle_infix(ref<Env> env, const Value& term) {
vector<Value> infix_exprs;
Value iter = term;
while (iter.is_list()) {
auto p = infix_transform(env, iter);
infix_exprs.push(p.first); // next s-expr
iter = p.second; // move past it in source list
}
Value result = list_of(infix_exprs);
return result;
}
void apply_infix(ref<Env> env, Value& item);
void apply_infix_at(ref<Env> env, Value& item, u32 depth) {
Value* iter = &item;
while (depth && iter->is_list()) {
iter = &iter->get_list().tail();
depth --;
}
*iter = handle_infix(env, *iter);
traverse_list(env, *iter, apply_infix);
}
void apply_infix(ref<Env> env, Value& item) {
Value orig = item.clone();
if (!item.is_list()) return;
Value h = head(item);
if (h.is_symbol()) {
const string& name = symbol_for(h.get_symbol());
if (name == "macro" || name == "infix"
|| name == "infix-macro" || name == "lambda"
|| name == "quote" || name == "splice") return;
else if (name == "def") {
if (tail(item).is_list() && head(tail(item)).is_symbol())
apply_infix_at(env, item, 2);
}
else if (name == "if" || name == "do" || name == "list-of")
apply_infix_at(env, item, 1);
else {
silence_errors();
Value proc = eval(env, h);
unsilence_errors();
if (proc.is_function()) apply_infix_at(env, item, 1);
else apply_infix_at(env, item, 0);
}
}
else apply_infix_at(env, item, 0);
}
void prep(ref<Env> env, Value& term) {
handle_splice(env, term);
handle_use(env, term);
visit_macro_defs(env, term);
handle_macro(env, term);
visit_defs(env, term);
apply_infix(env, term);
handle_macro(env, term);
visit_defs(env, term);
}
// definition stuff
Value define(ref<Env> env, const Value& term, bool is_macro) {
vector<Value> values = to_vector(term);
// visit_defs already does some error-checking, so we
// don't need to check the number of values or their types
// exhaustively.
if (values[1].is_symbol()) { // variable
const string& name = symbol_for(values[1].get_symbol());
if (is_macro) {
env->def_macro(name, Value(new AliasValue(values[2])));
return Value(VOID);
}
else {
Value init = eval(env, values[2]);
if (env->is_runtime())
init = lower(init);
env->def(name, init);
if (init.is_runtime())
return new ASTDefine(values[0].loc(), env,
values[1].get_symbol(), init.get_runtime());
return Value(VOID);
}
}
else if (values[1].is_list()) { // procedure
const string& name = symbol_for(head(values[1]).get_symbol());
Env env_descendant(env);
ref<Env> function_env(env_descendant);
vector<Value> args = to_vector(tail(values[1]));
vector<u64> argnames;
for (const Value& v : args) {
if (v.is_symbol()) {
argnames.push(v.get_symbol());
function_env->def(symbol_for(v.get_symbol()));
}
else if (v.is_list() && head(v).is_symbol()
&& symbol_for(head(v).get_symbol()) == "quote") {
argnames.push(eval(env, v).get_symbol() | KEYWORD_ARG_BIT);
}
else {
err(v.loc(), "Only symbols and quoted symbols are permitted ",
"within an argument list.");
return error();
}
}
vector<Value> body;
for (u32 i = 2; i < values.size(); i ++) body.push(values[i]);
Value body_term = cons(Value("do"), list_of(body));
if (is_macro) {
Value mac(new MacroValue(function_env, argnames, body_term));
env->def_macro(name, mac, argnames.size());
}
else {
prep(function_env, body_term);
Value func(new FunctionValue(function_env, argnames, body_term,
symbol_value(name)));
env->def(name, func, argnames.size());
}
return Value(VOID);
}
else {
err(values[1].loc(), "First parameter to definition must be ",
"a symbol (for variable or alias) or list (for procedure ",
"or macro).");
return error();
}
}
Value infix(ref<Env> env, const Value& term, bool is_macro) {
vector<Value> values = to_vector(term);
u8 precedence = 0;
u32 i = 1;
if (values[i].is_int()) { // precedence
precedence = (u8)values[i].get_int();
i ++;
}
if (i + 1 >= values.size()) {
err(values[0].loc(), "Expected argument list and body in ",
"infix definition.");
return error();
}
if (!values[i].is_list()) {
err(values[i].loc(), "Expected name and argument list for ",
"infix definition.");
return error();
}
if (!head(tail(values[i])).is_symbol()) {
err(tail(values[i]).loc(), "Expected name for infix definition.");
return error();
}
const string& name = symbol_for(head(tail(values[i])).get_symbol());
vector<Value> args;
args.push(head(values[i]));
Value v = tail(tail(values[i]));
while (v.is_list()) {
args.push(head(v));
v = tail(v);
}
if (args.size() == 0) {
err(values[i].loc(), "Expected argument list in infix ",
"definition.");
return error();
}
i ++;
Env env_descendant(env);
ref<Env> function_env(env_descendant);
vector<u64> argnames;
for (const Value& v : args) {
if (v.is_symbol()) {
argnames.push(v.get_symbol());
function_env->def(symbol_for(v.get_symbol()));
}
else if (v.is_list() && head(v).is_symbol()
&& symbol_for(head(v).get_symbol()) == "quote"
&& head(tail(v)).is_symbol()) {
argnames.push(eval(env, v).get_symbol() | KEYWORD_ARG_BIT);
}
else {
err(v.loc(), "Only symbols and quoted symbols are permitted ",
"within an argument list.");
return error();
}
}
vector<Value> body;
for (; i < values.size(); i ++) body.push(values[i]);
Value body_term = cons(Value("do"), list_of(body));
if (is_macro) {
Value mac(new MacroValue(function_env, argnames, body_term));
env->infix_macro(name, mac, argnames.size(), precedence);
return Value(VOID);
}
else {
prep(function_env, body_term);
Value func(new FunctionValue(function_env, argnames, body_term,
symbol_value(name)));
env->infix(name, func, argnames.size(), precedence);
return Value(VOID);
}
}
Value lambda(ref<Env> env, const Value& term) {
vector<Value> values = to_vector(term);
if (values.size() < 3) {
err(values[0].loc(), "Expected argument list and body in ",
"lambda expression.");
return error();
}
if (!values[1].is_list()) {
err(values[1].loc(), "Expected argument list in lambda ",
"expression.");
return error();
}
Env env_descendant(env);
ref<Env> function_env(env_descendant);
vector<Value> args = to_vector(values[1]);
vector<u64> argnames;
for (const Value& v : args) {
if (v.is_symbol()) {
argnames.push(v.get_symbol());
function_env->def(symbol_for(v.get_symbol()));
}
else {
err(v.loc(), "Only symbols are permitted ",
"within a lambda's argument list.");
return error();
}
}
vector<Value> body;
for (u32 i = 2; i < values.size(); i ++) body.push(values[i]);
Value body_term = list_of(body);
prep(function_env, body_term);
return Value(new FunctionValue(function_env, argnames,
cons(Value("do"), body_term)));
}
Value do_block(ref<Env> env, const Value& term) {
const Value& todo = tail(term);
const Value* v = &todo;
vector<Value> values;
bool runtime = false;
while (v->is_list()) {
values.push(eval(env, v->get_list().head()));
if (values.back().is_runtime()) runtime = true;
v = &v->get_list().tail();
}
if (values.size() == 0) return Value(VOID);
if (runtime) {
vector<ASTNode*> nodes;
for (Value& v : values) if (!v.is_runtime()) {
v = lower(v);
if (v.is_error()) return v;
}
for (Value& v : values) nodes.push(v.get_runtime());
return new ASTBlock(term.loc(), nodes);
}
return values.back();
}
u64 get_keyword(const Value& v) {
if (v.is_symbol()) return v.get_symbol();
else if (v.is_list() && head(v).is_symbol()
&& head(v).get_symbol() == symbol_value("quote")
&& tail(v).is_list() && head(tail(v)).is_symbol())
return head(tail(v)).get_symbol();
return 0;
}
bool is_keyword(const Value& v, const string& word) {
if (v.is_symbol()) return v.get_symbol() == symbol_value(word);
else if (v.is_list() && head(v).is_symbol()
&& head(v).get_symbol() == symbol_value("quote")
&& tail(v).is_list() && head(tail(v)).is_symbol())
return head(tail(v)).get_symbol() == symbol_value(word);
return false;
}
Value if_expr(ref<Env> env, const Value& term) {
Value params = tail(term);
prep(env, params);
Value cond, if_true, if_false;
bool has_else = false;
vector<Value> if_true_vals, if_false_vals;
if (!params.is_list()) {
err(term.loc(), "Expected condition in if expression.");
return error();
}
cond = head(params);
params = tail(params);
while (params.is_list() && !(is_keyword(head(params), "else")
|| is_keyword(head(params), "elif"))) {
if_true_vals.push(head(params));
params = tail(params);
}
if_true = cons(Value("do"), list_of(if_true_vals));
if (!params.is_list()) {
if_false = list_of(Value("list-of"));
}
else if (get_keyword(head(params)) == symbol_value("elif")) {
if_false = if_expr(env, params);
return list_of(Value("#?"),
cond,
list_of(Value("quote"), if_true),
list_of(Value("quote"), if_false));
}
else {
params = tail(params);
while (params.is_list()) {
if_false_vals.push(head(params));
params = tail(params);
}
if_false = cons(Value("do"), list_of(if_false_vals));
}
return list_of(Value("#?"),
cond,
list_of(Value("quote"), if_true),
list_of(Value("quote"), if_false));
}
bool is_quoted_symbol(const Value& val) {
return val.is_list() && tail(val).is_list()
&& head(val).is_symbol() && head(val).get_symbol() == symbol_value("quote")
&& head(tail(val)).is_symbol();
}
void find_assigns(ref<Env> env, const Value& term,
set<u64>& dests) {
if (!term.is_list()) return;
Value h = head(term);
if (h.is_symbol() && h.get_symbol() == symbol_value("#=")) {
if (tail(term).is_list() && is_quoted_symbol(head(tail(term)))) {
u64 sym = eval(env, head(tail(term))).get_symbol();
Def* def = env->find(symbol_for(sym));
if (def) dests.insert(sym);
}
}
if (!introduces_env(term)) {
const Value* v = &term;
while (v->is_list()) {
find_assigns(env, v->get_list().head(), dests);
v = &v->get_list().tail();
}
}
}
Value while_stmt(ref<Env> env, const Value& term) {
vector<Value> values = to_vector(term);
if (values.size() < 3) {
err(term.loc(), "Incorrect number of arguments for while ",
"statement. Expected condition and body.");
return error();
}
Value body = cons(Value("do"), tail(tail(term)));
set<u64> dests;
find_assigns(env, head(tail(term)), dests);
find_assigns(env, body, dests);
vector<ASTNode*> nodes;
for (u64 u : dests) {
Def* def = env->find(symbol_for(u));
if (!def->value.is_runtime()) {
Value new_value = lower(def->value);
nodes.push(
new ASTDefine(new_value.loc(), env, u, new_value.get_runtime()));
def->value = new_value;
}
}
Value cond = eval(env, head(tail(term)));
if (cond.is_error()) return error();
if (!cond.is_runtime()) cond = lower(cond);
body = eval(env, body);
if (body.is_error()) return error();
if (!body.is_runtime()) body = lower(body);
nodes.push(new ASTWhile(term.loc(), cond.get_runtime(),
body.get_runtime()));
return nodes.size() == 1 ? nodes[0] : new ASTBlock(term.loc(), nodes);
}
Value list_of(ref<Env> env, const Value& term) {
Value items = tail(term);
const Value* v = &items;
vector<Value> vals;
while (v->is_list()) {
vals.push(eval(env, v->get_list().head()));
v = &v->get_list().tail();
}
return list_of(vals);
}
struct CompilationUnit {
Source source;
ref<Env> env;
};
static map<string, CompilationUnit> modules;
Value use(ref<Env> env, const Value& term) {
if (!tail(term).is_list() || !head(tail(term)).is_symbol()) {
err(tail(term).loc(), "Expected symbol in use expression, given '",
tail(term), "'.");
return error();
}
Value h = head(tail(term));
string path = symbol_for(h.get_symbol());
path += ".bl";
ref<Env> module;
auto it = modules.find(path);
if (it != modules.end()) {
module = it->second.env;
}
else {
CompilationUnit unit { Source((const char*)path.raw()), {} };
if (!unit.source.begin().peek()) {
err(h.loc(), "Could not load source file at path '", path, "'.");
return error();
}
module = unit.env = load(unit.source);
if (error_count()) return error();
for (const auto& p : *module) {
if (env->find(p.first)) {
err(term.loc(), "Module '", symbol_for(h.get_symbol()),
"' redefines '", p.first, "' in the current environment.");
return error();
}
}
modules.put(path, unit);
}
env->import(module);
return Value(VOID);
}
Value eval_list(ref<Env> env, const Value& term) {
Value h = head(term);
if (h.is_symbol()) {
const string& name = symbol_for(h.get_symbol());
if (name == "quote") return head(tail(term)).clone();
else if (name == "def") return define(env, term, false);
else if (name == "infix") return infix(env, term, false);
else if (name == "macro") return define(env, term, true);
else if (name == "infix-macro") return infix(env, term, true);
else if (name == "lambda") return lambda(env, term);
else if (name == "do") return do_block(env, term);
else if (name == "if") return eval(env, if_expr(env, term));
else if (name == "list-of") return list_of(env, term);
else if (name == "use") return use(env, term);
else if (name == "while") return while_stmt(env, term);
}
Value first = eval(env, h);
if (first.is_macro()) {
vector<Value> args;
const Value* v = &term.get_list().tail();
u32 i = 0;
while (v->is_list()) {
if (i < first.get_macro().arity()
&& first.get_macro().args()[i] & KEYWORD_ARG_BIT
&& v->get_list().head().is_symbol())
args.push(list_of(Value("quote"), v->get_list().head()));
else args.push(v->get_list().head());
v = &v->get_list().tail();
i ++;
}
if (args.size() != first.get_macro().arity()) {
err(term.loc(), "Macro procedure expects ",
first.get_macro().arity(), " arguments, ",
args.size(), " provided.");
return error();
}
return expand(env, first, Value(new ProductValue(args)));
}
else if (first.is_function()) {
vector<Value> args;
Value args_term = tail(term);
const Value* v = &args_term;
u32 i = 0;
while (v->is_list()) {
if (i < first.get_function().arity()
&& first.get_function().args()[i] & KEYWORD_ARG_BIT
&& v->get_list().head().is_symbol()) {
args.push(v->get_list().head()); // leave keywords quoted
}
else args.push(eval(env, v->get_list().head()));
v = &v->get_list().tail();
i ++;
}
if (args.size() != first.get_function().arity()) {
err(term.loc(), "Procedure expects ",
first.get_function().arity(), " arguments, ",
args.size(), " provided.");
return error();
}
return call(env, first, Value(new ProductValue(args)));
}
else if (first.is_runtime() &&
first.get_runtime()->type()->kind() == KIND_FUNCTION) {
vector<Value> args;
Value args_term = tail(term);
const Value* v = &args_term;
u32 i = 0;
while (v->is_list()) {
args.push(eval(env, v->get_list().head()));
v = &v->get_list().tail();
i ++;
}
const FunctionType* fntype = (const FunctionType*)first.get_runtime()->type();
const ProductType* args_type = (const ProductType*)fntype->arg();
if (args.size() != args_type->count()) {
err(term.loc(), "Procedure expects ",
args_type->count(), " arguments, ",
args.size(), " provided.");
return error();
}
return call(env, first, Value(new ProductValue(args)));
}
if (tail(term).is_void()) return first;
err(term.loc(), "Could not evaluate list '", term, "'.");
return error();
}
Value eval(ref<Env> env, Value term) {
if (term.is_list()) return eval_list(env, term);
else if (term.is_int()) return term;
else if (term.is_string()) return term;
else if (term.is_symbol()) {
const string& name = symbol_for(term.get_symbol());
const Def* def = env->find(name);
if (def && def->is_macro_variable())
return def->value.get_alias().value();
else if (def) {
if (def->value.is_runtime())
return new ASTVar(term.loc(), env, term.get_symbol());
return def->value;
}
else {
err(term.loc(), "Undefined variable '", name, "'.");
return error();
}
}
err(term.loc(), "Could not evaluate term '", term, "'.");
return error();
}
} | 31.847636 | 83 | 0.597608 | [
"vector"
] |
743c1481213f57dc14b93616f381d3c2d8540007 | 3,842 | cpp | C++ | src/mongo/db/catalog/create_collection.cpp | EdwardPrentice/wrongo | 1e7c9136f5fab7040b5bd5df51b4946876625c88 | [
"Apache-2.0"
] | 12 | 2020-04-27T21:31:57.000Z | 2020-12-13T13:25:06.000Z | src/mongo/db/catalog/create_collection.cpp | EdwardPrentice/wrongo | 1e7c9136f5fab7040b5bd5df51b4946876625c88 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/catalog/create_collection.cpp | EdwardPrentice/wrongo | 1e7c9136f5fab7040b5bd5df51b4946876625c88 | [
"Apache-2.0"
] | 4 | 2021-03-27T14:40:25.000Z | 2022-03-19T20:52:41.000Z | /**
* Copyright (C) 2015 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/db/catalog/create_collection.h"
#include "mongo/bson/bsonobj.h"
#include "mongo/db/concurrency/write_conflict_exception.h"
#include "mongo/db/curop.h"
#include "mongo/db/db_raii.h"
#include "mongo/db/namespace_string.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/ops/insert.h"
#include "mongo/db/repl/replication_coordinator_global.h"
namespace mongo {
Status createCollection(OperationContext* txn,
const std::string& dbName,
const BSONObj& cmdObj,
const BSONObj& idIndex) {
BSONObjIterator it(cmdObj);
// Extract ns from first cmdObj element.
BSONElement firstElt = it.next();
uassert(15888, "must pass name of collection to create", firstElt.valuestrsafe()[0] != '\0');
Status status = userAllowedCreateNS(dbName, firstElt.valuestr());
if (!status.isOK()) {
return status;
}
NamespaceString nss(dbName, firstElt.valuestrsafe());
// Build options object from remaining cmdObj elements.
BSONObjBuilder optionsBuilder;
while (it.more()) {
optionsBuilder.append(it.next());
}
BSONObj options = optionsBuilder.obj();
uassert(14832,
"specify size:<n> when capped is true",
!options["capped"].trueValue() || options["size"].isNumber() ||
options.hasField("$nExtents"));
MONGO_WRITE_CONFLICT_RETRY_LOOP_BEGIN {
ScopedTransaction transaction(txn, MODE_IX);
Lock::DBLock dbXLock(txn->lockState(), dbName, MODE_X);
OldClientContext ctx(txn, nss.ns());
if (txn->writesAreReplicated() &&
!repl::getGlobalReplicationCoordinator()->canAcceptWritesFor(nss)) {
return Status(ErrorCodes::NotMaster,
str::stream() << "Not primary while creating collection " << nss.ns());
}
WriteUnitOfWork wunit(txn);
// Create collection.
const bool createDefaultIndexes = true;
status = userCreateNS(txn, ctx.db(), nss.ns(), options, createDefaultIndexes, idIndex);
if (!status.isOK()) {
return status;
}
wunit.commit();
}
MONGO_WRITE_CONFLICT_RETRY_LOOP_END(txn, "create", nss.ns());
return Status::OK();
}
} // namespace mongo
| 39.608247 | 97 | 0.672306 | [
"object"
] |
74426251cd255ed2b688811172392419401fa2b7 | 638 | cpp | C++ | src/Main.cpp | wibbe/ascii-icon | 095632d90e94df579bb20170bd1400b10fd48e3a | [
"MIT"
] | null | null | null | src/Main.cpp | wibbe/ascii-icon | 095632d90e94df579bb20170bd1400b10fd48e3a | [
"MIT"
] | null | null | null | src/Main.cpp | wibbe/ascii-icon | 095632d90e94df579bb20170bd1400b10fd48e3a | [
"MIT"
] | null | null | null |
#include "ASCIIcon.hpp"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
static const std::vector<asciicon::Layer> chevronIcon = {
{
0x5a5a5aff,
{
"· · · · · · · · · · · ·",
"· · · 1 2 · · · · · · ·",
"· · · A # # · · · · · ·",
"· · · · # # # · · · · ·",
"· · · · · # # # · · · ·",
"· · · · · · 9 # 3 · · ·",
"· · · · · · 8 # 4 · · ·",
"· · · · · # # # · · · ·",
"· · · · # # # · · · · ·",
"· · · 7 # # · · · · · ·",
"· · · 6 5 · · · · · · ·",
"· · · · · · · · · · · ·",
}
}
};
int main(int argc, char * argv[])
{
return 0;
} | 21.266667 | 57 | 0.266458 | [
"vector"
] |
74459ca6243445d5ecea8f58ecf7213ebffa81e8 | 8,407 | cpp | C++ | interface/src/raypick/PickScriptingInterface.cpp | amantley/blendshapes | 3f5820266762f9962d9bb5bd91912272005e4f02 | [
"Apache-2.0"
] | null | null | null | interface/src/raypick/PickScriptingInterface.cpp | amantley/blendshapes | 3f5820266762f9962d9bb5bd91912272005e4f02 | [
"Apache-2.0"
] | null | null | null | interface/src/raypick/PickScriptingInterface.cpp | amantley/blendshapes | 3f5820266762f9962d9bb5bd91912272005e4f02 | [
"Apache-2.0"
] | null | null | null | //
// Created by Sam Gondelman 10/20/2017
// Copyright 2017 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include "PickScriptingInterface.h"
#include <QVariant>
#include "GLMHelpers.h"
#include <PickManager.h>
#include "StaticRayPick.h"
#include "JointRayPick.h"
#include "MouseRayPick.h"
#include "StylusPick.h"
#include <ScriptEngine.h>
unsigned int PickScriptingInterface::createPick(const PickQuery::PickType type, const QVariant& properties) {
switch (type) {
case PickQuery::PickType::Ray:
return createRayPick(properties);
case PickQuery::PickType::Stylus:
return createStylusPick(properties);
default:
return PickManager::INVALID_PICK_ID;
}
}
/**jsdoc
* A set of properties that can be passed to {@link Picks.createPick} to create a new Ray Pick.
* @typedef {object} Picks.RayPickProperties
* @property {boolean} [enabled=false] If this Pick should start enabled or not. Disabled Picks do not updated their pick results.
* @property {number} [filter=Picks.PICK_NOTHING] The filter for this Pick to use, constructed using filter flags combined using bitwise OR.
* @property {number} [maxDistance=0.0] The max distance at which this Pick will intersect. 0.0 = no max. < 0.0 is invalid.
* @property {string} [joint] Only for Joint or Mouse Ray Picks. If "Mouse", it will create a Ray Pick that follows the system mouse, in desktop or HMD.
* If "Avatar", it will create a Joint Ray Pick that follows your avatar's head. Otherwise, it will create a Joint Ray Pick that follows the given joint, if it
* exists on your current avatar.
* @property {Vec3} [posOffset=Vec3.ZERO] Only for Joint Ray Picks. A local joint position offset, in meters. x = upward, y = forward, z = lateral
* @property {Vec3} [dirOffset=Vec3.UP] Only for Joint Ray Picks. A local joint direction offset. x = upward, y = forward, z = lateral
* @property {Vec3} [position] Only for Static Ray Picks. The world-space origin of the ray.
* @property {Vec3} [direction=-Vec3.UP] Only for Static Ray Picks. The world-space direction of the ray.
*/
unsigned int PickScriptingInterface::createRayPick(const QVariant& properties) {
QVariantMap propMap = properties.toMap();
bool enabled = false;
if (propMap["enabled"].isValid()) {
enabled = propMap["enabled"].toBool();
}
PickFilter filter = PickFilter();
if (propMap["filter"].isValid()) {
filter = PickFilter(propMap["filter"].toUInt());
}
float maxDistance = 0.0f;
if (propMap["maxDistance"].isValid()) {
maxDistance = propMap["maxDistance"].toFloat();
}
if (propMap["joint"].isValid()) {
std::string jointName = propMap["joint"].toString().toStdString();
if (jointName != "Mouse") {
// x = upward, y = forward, z = lateral
glm::vec3 posOffset = Vectors::ZERO;
if (propMap["posOffset"].isValid()) {
posOffset = vec3FromVariant(propMap["posOffset"]);
}
glm::vec3 dirOffset = Vectors::UP;
if (propMap["dirOffset"].isValid()) {
dirOffset = vec3FromVariant(propMap["dirOffset"]);
}
return DependencyManager::get<PickManager>()->addPick(PickQuery::Ray, std::make_shared<JointRayPick>(jointName, posOffset, dirOffset, filter, maxDistance, enabled));
} else {
return DependencyManager::get<PickManager>()->addPick(PickQuery::Ray, std::make_shared<MouseRayPick>(filter, maxDistance, enabled));
}
} else if (propMap["position"].isValid()) {
glm::vec3 position = vec3FromVariant(propMap["position"]);
glm::vec3 direction = -Vectors::UP;
if (propMap["direction"].isValid()) {
direction = vec3FromVariant(propMap["direction"]);
}
return DependencyManager::get<PickManager>()->addPick(PickQuery::Ray, std::make_shared<StaticRayPick>(position, direction, filter, maxDistance, enabled));
}
return PickManager::INVALID_PICK_ID;
}
/**jsdoc
* A set of properties that can be passed to {@link Picks.createPick} to create a new Stylus Pick.
* @typedef {object} Picks.StylusPickProperties
* @property {number} [hand=-1] An integer. 0 == left, 1 == right. Invalid otherwise.
* @property {boolean} [enabled=false] If this Pick should start enabled or not. Disabled Picks do not updated their pick results.
* @property {number} [filter=Picks.PICK_NOTHING] The filter for this Pick to use, constructed using filter flags combined using bitwise OR.
* @property {number} [maxDistance=0.0] The max distance at which this Pick will intersect. 0.0 = no max. < 0.0 is invalid.
*/
unsigned int PickScriptingInterface::createStylusPick(const QVariant& properties) {
QVariantMap propMap = properties.toMap();
bilateral::Side side = bilateral::Side::Invalid;
{
QVariant handVar = propMap["hand"];
if (handVar.isValid()) {
side = bilateral::side(handVar.toInt());
}
}
bool enabled = false;
if (propMap["enabled"].isValid()) {
enabled = propMap["enabled"].toBool();
}
PickFilter filter = PickFilter();
if (propMap["filter"].isValid()) {
filter = PickFilter(propMap["filter"].toUInt());
}
float maxDistance = 0.0f;
if (propMap["maxDistance"].isValid()) {
maxDistance = propMap["maxDistance"].toFloat();
}
return DependencyManager::get<PickManager>()->addPick(PickQuery::Stylus, std::make_shared<StylusPick>(side, filter, maxDistance, enabled));
}
void PickScriptingInterface::enablePick(unsigned int uid) {
DependencyManager::get<PickManager>()->enablePick(uid);
}
void PickScriptingInterface::disablePick(unsigned int uid) {
DependencyManager::get<PickManager>()->disablePick(uid);
}
void PickScriptingInterface::removePick(unsigned int uid) {
DependencyManager::get<PickManager>()->removePick(uid);
}
QVariantMap PickScriptingInterface::getPrevPickResult(unsigned int uid) {
QVariantMap result;
auto pickResult = DependencyManager::get<PickManager>()->getPrevPickResult(uid);
if (pickResult) {
result = pickResult->toVariantMap();
}
return result;
}
void PickScriptingInterface::setPrecisionPicking(unsigned int uid, bool precisionPicking) {
DependencyManager::get<PickManager>()->setPrecisionPicking(uid, precisionPicking);
}
void PickScriptingInterface::setIgnoreItems(unsigned int uid, const QScriptValue& ignoreItems) {
DependencyManager::get<PickManager>()->setIgnoreItems(uid, qVectorQUuidFromScriptValue(ignoreItems));
}
void PickScriptingInterface::setIncludeItems(unsigned int uid, const QScriptValue& includeItems) {
DependencyManager::get<PickManager>()->setIncludeItems(uid, qVectorQUuidFromScriptValue(includeItems));
}
bool PickScriptingInterface::isLeftHand(unsigned int uid) {
return DependencyManager::get<PickManager>()->isLeftHand(uid);
}
bool PickScriptingInterface::isRightHand(unsigned int uid) {
return DependencyManager::get<PickManager>()->isRightHand(uid);
}
bool PickScriptingInterface::isMouse(unsigned int uid) {
return DependencyManager::get<PickManager>()->isMouse(uid);
}
QScriptValue pickTypesToScriptValue(QScriptEngine* engine, const PickQuery::PickType& pickType) {
return pickType;
}
void pickTypesFromScriptValue(const QScriptValue& object, PickQuery::PickType& pickType) {
pickType = static_cast<PickQuery::PickType>(object.toUInt16());
}
void PickScriptingInterface::registerMetaTypes(QScriptEngine* engine) {
QScriptValue pickTypes = engine->newObject();
auto metaEnum = QMetaEnum::fromType<PickQuery::PickType>();
for (int i = 0; i < PickQuery::PickType::NUM_PICK_TYPES; ++i) {
pickTypes.setProperty(metaEnum.key(i), metaEnum.value(i));
}
engine->globalObject().setProperty("PickType", pickTypes);
qScriptRegisterMetaType(engine, pickTypesToScriptValue, pickTypesFromScriptValue);
}
unsigned int PickScriptingInterface::getPerFrameTimeBudget() const {
return DependencyManager::get<PickManager>()->getPerFrameTimeBudget();
}
void PickScriptingInterface::setPerFrameTimeBudget(unsigned int numUsecs) {
DependencyManager::get<PickManager>()->setPerFrameTimeBudget(numUsecs);
}
| 40.418269 | 177 | 0.703105 | [
"object"
] |
744d0260befe80ea6b1c635d98116b8f14fddab4 | 1,260 | cpp | C++ | src/sf2cute/generator_item.cpp | gocha/sf2cc | b42f23c75667d414ac024858f5303fb7dc17e0fd | [
"Zlib"
] | 31 | 2016-07-20T23:23:17.000Z | 2022-03-12T13:23:06.000Z | src/sf2cute/generator_item.cpp | gocha/sf2cc | b42f23c75667d414ac024858f5303fb7dc17e0fd | [
"Zlib"
] | 6 | 2017-09-18T02:16:29.000Z | 2020-08-30T13:24:39.000Z | src/sf2cute/generator_item.cpp | gocha/sf2cc | b42f23c75667d414ac024858f5303fb7dc17e0fd | [
"Zlib"
] | 7 | 2016-11-03T03:27:06.000Z | 2021-06-07T11:02:56.000Z | /// @file
/// SoundFont 2 Generator class implementation.
///
/// @author gocha <https://github.com/gocha>
#include <sf2cute/generator_item.hpp>
#include <array>
#include <utility>
namespace sf2cute {
/// Constructs a new SFGeneratorItem.
SFGeneratorItem::SFGeneratorItem() :
op_(SFGenerator(0)),
amount_(0) {
}
/// Constructs a new SFGeneratorItem using the specified properties.
SFGeneratorItem::SFGeneratorItem(SFGenerator op, GenAmountType amount) :
op_(std::move(op)),
amount_(std::move(amount)) {
}
/// Indicates a SFGenerator object is "less than" the other one.
bool SFGeneratorItem::Compare(const SFGenerator & x, const SFGenerator & y) noexcept {
std::array<SFGenerator, 2> firstElements{ SFGenerator::kKeyRange, SFGenerator::kVelRange };
std::array<SFGenerator, 2> lastElements{ SFGenerator::kSampleID, SFGenerator::kInstrument };
if (x == y) {
return false;
}
for (const SFGenerator & first : firstElements) {
if (x == first) {
return true;
}
else if (y == first) {
return false;
}
}
for (const SFGenerator & last : lastElements) {
if (x == last) {
return false;
}
else if (y == last) {
return true;
}
}
return x < y;
}
} // namespace sf2cute
| 22.5 | 94 | 0.659524 | [
"object"
] |
744fa6b8f93234ecce4a2ccc803cd0f7b3740f4f | 5,465 | cc | C++ | thirdparty/github/fairinternal/postman/postman/cc/server.cc | RomanGaraev/diplomacy_searchbot | bf3f38e5a68bfd3c6fa58e47351fcae3eed88557 | [
"MIT"
] | 32 | 2021-05-04T17:05:19.000Z | 2022-03-21T07:56:53.000Z | thirdparty/github/fairinternal/postman/postman/cc/server.cc | RomanGaraev/diplomacy_searchbot | bf3f38e5a68bfd3c6fa58e47351fcae3eed88557 | [
"MIT"
] | 3 | 2022-01-22T19:44:10.000Z | 2022-03-02T23:20:52.000Z | thirdparty/github/fairinternal/postman/postman/cc/server.cc | facebookresearch/diplomacy_searchbot | 44d6f3272be7567060ba7d0e41f4e44b1bb8b5ca | [
"MIT"
] | 10 | 2021-05-07T11:51:29.000Z | 2022-02-18T18:29:57.000Z | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <chrono>
#include <deque>
#include <future>
#include <memory>
#include <mutex>
#include <optional>
#include <stdexcept>
#include <thread>
#include <ATen/ATen.h>
#include "postman/serialization.h"
#include "postman/server.h"
#include "postman/blocking_counter.h"
#include "postman/computationqueue.h"
#include "postman/exceptions.h"
#include <nest.h>
namespace postman {
grpc::Status Server::ServiceImpl::bind(const std::string &name,
Function &&function) {
functions_.insert({name, std::move(function)});
return grpc::Status::OK;
}
grpc::Status Server::ServiceImpl::Call(
grpc::ServerContext *context,
grpc::ServerReaderWriter<CallResponse, CallRequest> *stream) {
CallRequest call_req;
while (stream->Read(&call_req)) {
CallResponse call_resp;
try {
auto it = functions_.find(call_req.function());
if (it == functions_.end())
throw std::runtime_error("AttributeError: No such function '" +
call_req.function() + "'");
TensorNest result = it->second(
detail::nest_proto_to_tensornest(call_req.mutable_inputs()));
detail::fill_proto_from_tensornest(call_resp.mutable_outputs(), result);
} catch (const QueueClosed &e) {
break;
} catch (const std::runtime_error &e) {
std::cerr << "Error in " << call_req.function() << ": " << e.what()
<< std::endl;
call_resp.mutable_error()->set_message(e.what());
} catch (const std::exception &e) {
std::cerr << "Error in " << call_req.function() << ": " << e.what()
<< std::endl;
return grpc::Status(grpc::INTERNAL, e.what());
}
stream->Write(call_resp);
}
return grpc::Status::OK;
}
void Server::run() {
if (server_) throw std::runtime_error("Server already running");
int port;
grpc::ServerBuilder builder;
builder.SetMaxReceiveMessageSize(-1); // Unlimited.
builder.AddChannelArgument(GRPC_ARG_ALLOW_REUSEPORT, 0);
builder.AddListeningPort(address_, grpc::InsecureServerCredentials(), &port);
builder.RegisterService(&service_);
server_ = builder.BuildAndStart();
if (!server_)
throw std::runtime_error(
"Failed to run server. Maybe the port is already used?");
if (port == 0) throw std::runtime_error("Failed to bind to port");
port_.store(port);
running_.store(true);
}
void Server::wait() {
if (!server_) throw std::runtime_error("Server not running");
server_->Wait();
}
void Server::stop() {
if (!server_) throw std::runtime_error("Server not running");
running_.store(false);
server_->Shutdown(std::chrono::system_clock::now());
}
void Server::bind(const std::string &name, Function &&function) {
service_.bind(name, std::move(function));
}
void Server::bind_queue(const std::string &name,
std::shared_ptr<ComputationQueue> queue) {
bind(name, [queue(queue)](const TensorNest &inputs) mutable {
int64_t index;
auto future = queue->compute(inputs, &index);
if (future.wait_for(std::chrono::seconds(5)) != std::future_status::ready)
throw TimeoutError("Compute timeout reached.");
TensorNest outputs = [&]() {
try {
return future.get();
} catch (const std::future_error &e) {
if (queue->closed() && e.code() == std::future_errc::broken_promise)
throw QueueClosed(e.what());
throw;
}
}();
return outputs.map([index](const at::Tensor &t) { return t[index]; });
});
}
void Server::bind_queue_batched(const std::string &name,
std::shared_ptr<ComputationQueue> queue) {
bind(name, [queue(queue)](const TensorNest &inputs) mutable {
// TODO: Add some shape testing.
int64_t batch_size = inputs.front().size(0);
std::vector<int64_t> indices(batch_size);
std::vector<std::shared_future<TensorNest>> futures;
for (int64_t i = 0; i < batch_size; ++i) {
futures.push_back(queue->compute(
inputs.map([i](const at::Tensor &t) { return t[i]; }), &indices[i]));
}
std::vector<TensorNest> outputs;
for (int64_t i = 0; i < batch_size; ++i) {
try {
outputs.push_back(futures[i].get().map(
[index(indices[i])](const at::Tensor &t) { return t[index]; }));
} catch (const std::future_error &e) {
if (queue->closed() && e.code() == std::future_errc::broken_promise)
throw QueueClosed(e.what());
throw;
}
}
// TODO: This incurs extra memcopies. We could also write everything to a
// buffer here and give that to the protobuf library directly.
nest::Nest<std::vector<at::Tensor>> zipped = TensorNest::zip(outputs);
return zipped.map(
[](const std::vector<at::Tensor> &v) { return at::stack(v); });
});
}
} // namespace postman
| 31.228571 | 79 | 0.64172 | [
"shape",
"vector"
] |
7452d9eb9b86dc2a21690e2f854ad4cee6350546 | 2,679 | cpp | C++ | src/caffe/layers/resize_layer.cpp | leon-liangwu/caffe-maskyolo | 9c4d82f072cb60e60ff91900920ef67687cf7be1 | [
"Intel",
"BSD-2-Clause"
] | 1 | 2020-01-10T09:54:38.000Z | 2020-01-10T09:54:38.000Z | src/caffe/layers/resize_layer.cpp | leon-liangwu/caffe-maskyolo | 9c4d82f072cb60e60ff91900920ef67687cf7be1 | [
"Intel",
"BSD-2-Clause"
] | null | null | null | src/caffe/layers/resize_layer.cpp | leon-liangwu/caffe-maskyolo | 9c4d82f072cb60e60ff91900920ef67687cf7be1 | [
"Intel",
"BSD-2-Clause"
] | null | null | null | #include <vector>
#include "caffe/filler.hpp"
#include "caffe/layer.hpp"
#include "caffe/layers/resize_layer.hpp"
#include "caffe/util/math_functions.hpp"
namespace caffe {
template <typename Dtype>
void ResizeLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
// Configure the kernel size, padding, stride, and inputs.
ResizeParameter resize_param = this->layer_param_.resize_param();
bool is_pyramid_test = resize_param.is_pyramid_test();
if (is_pyramid_test == false) {
CHECK(resize_param.has_height()) << "output height is required ";
CHECK(resize_param.has_width()) << "output width is required ";
this->out_height_ = resize_param.height();
this->out_width_ = resize_param.width();
}
else {
CHECK(resize_param.has_out_height_scale()) << "output height scale is required ";
CHECK(resize_param.has_out_width_scale()) << "output width scale is required ";
int in_height = bottom[0]->height();
int in_width = bottom[0]->width();
this->out_height_ = int(resize_param.out_height_scale() * in_height);
this->out_width_ = int(resize_param.out_width_scale() * in_width);
}
for (int i = 0; i<4; i++) {
this->locs_.push_back(new Blob<Dtype>);
}
}
template <typename Dtype>
void ResizeLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
ResizeParameter resize_param = this->layer_param_.resize_param();
bool is_pyramid_test = resize_param.is_pyramid_test();
if (is_pyramid_test == false) {
this->out_height_ = resize_param.height();
this->out_width_ = resize_param.width();
}
else {
int in_height = bottom[0]->height();
int in_width = bottom[0]->width();
this->out_height_ = int(resize_param.out_height_scale() * in_height);
this->out_width_ = int(resize_param.out_width_scale() * in_width);
}
this->out_num_ = bottom[0]->num();
this->out_channels_ = bottom[0]->channels();
top[0]->Reshape(out_num_, out_channels_, out_height_, out_width_);
for (int i = 0; i<4; ++i) {
this->locs_[i]->Reshape(1, 1, out_height_, out_width_);
}
}
template <typename Dtype>
void ResizeLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
}
template <typename Dtype>
void ResizeLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
}
#ifdef CPU_ONLY
STUB_GPU(ResizeLayer);
#endif
INSTANTIATE_CLASS(ResizeLayer);
REGISTER_LAYER_CLASS(Resize);
} // namespace caffe | 33.911392 | 87 | 0.681224 | [
"vector"
] |
7456178a327d5f5586b4b5303d73831faade06ff | 19,664 | cpp | C++ | src/gpu/simulated_device_enumeration.cpp | olifre/htcondor | e1299614fbdcad113a206270f3940e2e8777c2bd | [
"Apache-2.0"
] | 217 | 2015-01-08T04:49:42.000Z | 2022-03-27T10:11:58.000Z | src/gpu/simulated_device_enumeration.cpp | olifre/htcondor | e1299614fbdcad113a206270f3940e2e8777c2bd | [
"Apache-2.0"
] | 185 | 2015-05-03T13:26:31.000Z | 2022-03-28T03:08:59.000Z | src/gpu/simulated_device_enumeration.cpp | olifre/htcondor | e1299614fbdcad113a206270f3940e2e8777c2bd | [
"Apache-2.0"
] | 133 | 2015-02-11T09:17:45.000Z | 2022-03-31T07:28:54.000Z | #include <time.h>
#include <string.h>
#include <string>
#include <vector>
#include <set>
// For pi_dynlink.h
#ifdef WIN32
#define WIN32_LEAN_AND_MEAN
#define NOSERVICE
#define NOMCX
#define NOIME
#include <Windows.h>
#endif
#include "pi_dynlink.h"
#include "nvml_stub.h"
#include "cuda_header_doc.h"
#include "cuda_device_enumeration.h"
int sim_index = 0;
int sim_device_count = 0;
//From Dumbo.
//DetectedGPUs="GPU-c4a646d7, GPU-6a96bd13"
//CUDACoresPerCU=64
//CUDADriverVersion=11.20
//CUDAMaxSupportedVersion=11020
//GPU_6a96bd13Capability=7.5
//GPU_6a96bd13ClockMhz=1770.00
//GPU_6a96bd13ComputeUnits=72
//GPU_6a96bd13DeviceName="TITAN RTX"
//GPU_6a96bd13DevicePciBusId="0000:AF:00.0"
//GPU_6a96bd13DeviceUuid="6a96bd13-70bc-6494-6d62-1b77a9a7f29f"
//GPU_6a96bd13ECCEnabled=false
//GPU_6a96bd13GlobalMemoryMb=24220
//GPU_c4a646d7Capability=7.0
//GPU_c4a646d7ClockMhz=1380.00
//GPU_c4a646d7ComputeUnits=80
//GPU_c4a646d7DeviceName="Tesla V100-PCIE-16GB"
//GPU_c4a646d7DevicePciBusId="0000:3B:00.0"
//GPU_c4a646d7DeviceUuid="c4a646d7-aa14-1dd1-f1b0-57288cda864d"
//GPU_c4a646d7ECCEnabled=true
//GPU_c4a646d7GlobalMemoryMb=16160
//From Igor, MIG capable GPU and 7 MIG devices enumerated by 9.1.0
//DetectedGPUs=GPU-cb91fc08, GPU-MIG-3167, GPU-MIG-5bc6, GPU-MIG-5daa, GPU-MIG-9654, GPU-MIG-987e, GPU-MIG-c1df, GPU-MIG-e84b
//CUDADriverVersion=11.40
//CUDAMaxSupportedVersion=11040
//GPU_MIG_3167DeviceUuid="MIG-3167cf3e-b048-5a67-8134-a2610532c94e"
//GPU_MIG_3167GlobalMemoryMb=4861
//GPU_MIG_5bc6DeviceUuid="MIG-5bc689c8-e6d8-5f8c-b51e-35a01df05f5f"
//GPU_MIG_5bc6GlobalMemoryMb=4861
//GPU_MIG_5daaDeviceUuid="MIG-5daab7d7-3e0a-5b76-bf22-8bc5fc94a3e6"
//GPU_MIG_5daaGlobalMemoryMb=4861
//GPU_MIG_9654DeviceUuid="MIG-9654dd54-5c9f-54be-adf0-55269caad1f2"
//GPU_MIG_9654GlobalMemoryMb=4861
//GPU_MIG_987eDeviceUuid="MIG-987e0eb2-08b2-55ca-9663-89eaaf68156a"
//GPU_MIG_987eGlobalMemoryMb=3512
//GPU_MIG_c1dfDeviceUuid="MIG-c1df38f3-a7ad-5465-8941-f0260e698979"
//GPU_MIG_c1dfGlobalMemoryMb=4861
//GPU_MIG_e84bDeviceUuid="MIG-e84b0b57-e50c-50df-a261-bc0a05671e0a"
//GPU_MIG_e84bGlobalMemoryMb=4861
//GPU_cb91fc08Capability=8.0
//GPU_cb91fc08DeviceName="NVIDIA A100-SXM4-40GB MIG 1g.5gb"
//GPU_cb91fc08DevicePciBusId="0000:00:04.0"
//GPU_cb91fc08DeviceUuid="cb91fc08-a9a0-9087-ce0c-5d09d5f00f03"
//GPU_cb91fc08ECCEnabled=true
//GPU_cb91fc08GlobalMemoryMb=4864
// From gpulab2004 4 A100's
//CUDADriverVersion = 11.2
//CUDAMaxSupportedVersion = 11020
//GPU_124d06a7DevicePciBusId = "0000:01:00.0"
//GPU_124d06a7DeviceUuid = "124d06a7-6642-3962-9afa-c86c31b9a7e6"
//GPU_20e62ffcDevicePciBusId = "0000:C1:00.0"
//GPU_20e62ffcDeviceUuid = "20e62ffc-155e-49ad-04e1-ffacfc109ce3"
//GPU_8f9c2d75DevicePciBusId = "0000:81:00.0"
//GPU_8f9c2d75DeviceUuid = "8f9c2d75-1b7d-5026-b177-283d13ddbb90"
//GPU_c6cfdc9cDevicePciBusId = "0000:41:00.0"
//GPU_c6cfdc9cDeviceUuid = "c6cfdc9c-63df-c5b3-3605-7bc4b2545434"
//CUDACapability = 8.0
//CUDADeviceName = "A100-SXM4-40GB"
//CUDAECCEnabled = true
//CUDAGlobalMemoryMb = 40536
// 8 A100's from AWS (nested), one in MIG mode
//DetectedGPUs="GPU-8aa54555, MIG-0caf1ce3-fcd4-59da-8564-764000e3ace9, MIG-207f657b-6f50-5c1a-94f0-01d07ff4cdb0, GPU-775e454e, GPU-d79a3765, GPU-a6e658d5, GPU-c73e918e, GPU-e627fc34, GPU-5368a050, GPU-5d2744da"
//Common=[ DriverVersion=11.40; MaxSupportedVersion=11040; ]
//GPU_5368a050=[ id="GPU-5368a050"; Capability=8.0; ClockMhz=1410.00; CoresPerCU=64; DeviceName="NVIDIA A100-SXM4-40GB"; DevicePciBusId="0000:A0:1C.0"; DeviceUuid="GPU-5368a050-ed79-fab9-5cba-0d37c5f12c81"; DieTempC=28; ECCEnabled=true; EccErrorsDoubleBit=0; EccErrorsSingleBit=0; GlobalMemoryMb=40536; PowerUsage_mw=52603; ]
//GPU_5d2744da=[ id="GPU-5d2744da"; Capability=8.0; ClockMhz=1410.00; CoresPerCU=64; DeviceName="NVIDIA A100-SXM4-40GB"; DevicePciBusId="0000:A0:1D.0"; DeviceUuid="GPU-5d2744da-c329-024c-6477-17d879625691"; DieTempC=27; ECCEnabled=true; EccErrorsDoubleBit=0; EccErrorsSingleBit=0; GlobalMemoryMb=40536; PowerUsage_mw=49850; ]
//GPU_775e454e=[ id="GPU-775e454e"; Capability=8.0; ClockMhz=1410.00; CoresPerCU=64; DeviceName="NVIDIA A100-SXM4-40GB"; DevicePciBusId="0000:10:1D.0"; DeviceUuid="GPU-775e454e-c504-a1bb-22c6-3db1b940058d"; DieTempC=25; ECCEnabled=true; EccErrorsDoubleBit=0; EccErrorsSingleBit=0; GlobalMemoryMb=40536; PowerUsage_mw=49049; ]
//GPU_a6e658d5=[ id="GPU-a6e658d5"; Capability=8.0; ClockMhz=1410.00; CoresPerCU=64; DeviceName="NVIDIA A100-SXM4-40GB"; DevicePciBusId="0000:20:1D.0"; DeviceUuid="GPU-a6e658d5-41c2-c7e4-6f66-912a14127670"; DieTempC=27; ECCEnabled=true; EccErrorsDoubleBit=0; EccErrorsSingleBit=0; GlobalMemoryMb=40536; PowerUsage_mw=50891; ]
//GPU_c73e918e=[ id="GPU-c73e918e"; Capability=8.0; ClockMhz=1410.00; CoresPerCU=64; DeviceName="NVIDIA A100-SXM4-40GB"; DevicePciBusId="0000:90:1C.0"; DeviceUuid="GPU-c73e918e-cc34-67c5-bc49-1aa14ccaa76e"; DieTempC=27; ECCEnabled=true; EccErrorsDoubleBit=0; EccErrorsSingleBit=0; GlobalMemoryMb=40536; PowerUsage_mw=54073; ]
//GPU_d79a3765=[ id="GPU-d79a3765"; Capability=8.0; ClockMhz=1410.00; CoresPerCU=64; DeviceName="NVIDIA A100-SXM4-40GB"; DevicePciBusId="0000:20:1C.0"; DeviceUuid="GPU-d79a3765-a737-9880-9f25-c901ef668a0b"; DieTempC=27; ECCEnabled=true; EccErrorsDoubleBit=0; EccErrorsSingleBit=0; GlobalMemoryMb=40536; PowerUsage_mw=53276; ]
//GPU_e627fc34=[ id="GPU-e627fc34"; Capability=8.0; ClockMhz=1410.00; CoresPerCU=64; DeviceName="NVIDIA A100-SXM4-40GB"; DevicePciBusId="0000:90:1D.0"; DeviceUuid="GPU-e627fc34-bc78-bc31-d502-b26fad63dea8"; DieTempC=26; ECCEnabled=true; EccErrorsDoubleBit=0; EccErrorsSingleBit=0; GlobalMemoryMb=40536; PowerUsage_mw=52970; ]
//GPU_8aa54555=[ id="GPU-8aa54555"; Capability=8.0; ClockMhz=1410.00; ComputeUnits=42; CoresPerCU=64; DeviceName="NVIDIA A100-SXM4-40GB MIG 3g.20gb"; DevicePciBusId="0000:10:1C.0"; DeviceUuid="8aa54555-90e8-79b7-e5f8-e4b2b3e8fcfe"; DieTempC=25; ECCEnabled=true; EccErrorsDoubleBit=0; EccErrorsSingleBit=0; GlobalMemoryMb=20096; PowerUsage_mw=40055; ]
//MIG_0caf1ce3_fcd4_59da_8564_764000e3ace9=[ id="MIG-0caf1ce3-fcd4-59da-8564-764000e3ace9"; ComputeUnits=42; DeviceUuid="MIG-0caf1ce3-fcd4-59da-8564-764000e3ace9"; GlobalMemoryMb=20086; ]
//MIG_207f657b_6f50_5c1a_94f0_01d07ff4cdb0=[ id="MIG-207f657b-6f50-5c1a-94f0-01d07ff4cdb0"; ComputeUnits=42; DeviceUuid="MIG-207f657b-6f50-5c1a-94f0-01d07ff4cdb0"; GlobalMemoryMb=20082; ]
//
// tables of simulated cuda devices, so we can test HTCondor startd and starter without
// actually having a GPU.
//
struct _simulated_cuda_device {
const char * name;
int SM; // capability 0xMm (hexidecimal notation), M = SM Major version, and m = SM minor version
int clockRate;
int multiProcessorCount;
int ECCEnabled;
size_t totalGlobalMem;
};
struct _simulated_mig_devices {
unsigned int migCount;
unsigned int migMode; // MIG configuration, here are a limited number of partitioning schemes
struct {
int memory;
} inst[7];
};
struct _simulated_cuda_config {
int driverVer;
int deviceCount;
const struct _simulated_cuda_device * device;
const struct _simulated_mig_devices * mig;
};
static const struct _simulated_cuda_device GeForceGT330 = { "GeForce GT 330", 0x12, 1340*1000, 12, 0, 1024*1024*1024 };
static const struct _simulated_cuda_device GeForceGTX480 = { "GeForce GTX 480", 0x20, 1400*1000, 15, 0, 1536*1024*1024 };
static const struct _simulated_cuda_device TeslaV100 = { "Tesla V100-PCIE-16GB", 0x70, 1380*1000, 80, 1, (size_t)24220*1024*1024 };
static const struct _simulated_cuda_device TitanRTX = { "TITAN RTX", 0x75, 1770*1000, 72, 0, (size_t)24220*1024*1024 };
static const struct _simulated_cuda_device A100 = { "A100-SXM4-40GB", 0x80, 1410*1000, 42, 1, (size_t)40536*1024*1204 };
static const struct _simulated_cuda_device A100Mig1g = { "NVIDIA A100-SXM4-40GB MIG 1g.5gb", 0x80, 1410*1000, 42, 1, (size_t)4864*1024*1204 };
static const struct _simulated_cuda_device A100Mig3g = { "NVIDIA A100-SXM4-40GB MIG 3g.20gb", 0x80, 1410*1000, 42, 1, (size_t)20096*1024*1204 };
static const struct _simulated_mig_devices Mig3g20 = { 2, 3, {20086, 20082, 0, 0, 0, 0, 0} };
static const struct _simulated_mig_devices Mig1g5 = { 7, 1, {4861, 4861, 4861, 4861, 4861, 4861, 4861} };
static const struct _simulated_cuda_config aSimConfig[] = {
{6000, 1, &GeForceGT330, NULL }, // 0
{4020, 2, &GeForceGTX480, NULL }, // 1
// from dumbo
{11020, 1, &TeslaV100, NULL }, // 2
{11020, 1, &TitanRTX, NULL }, // 3
// mig capable devices
{11020, 1, &A100, NULL }, // 4 (not in mig mode)
{11020, 1, &A100Mig3g, &Mig3g20 }, // 5 (interpolated)
{11040, 1, &A100Mig1g, &Mig1g5 }, // 6 (from Igor)
{11040, 1, &A100Mig3g, &Mig3g20 }, // 7 (from AWS)
};
const int sim_index_max = (int)(sizeof(aSimConfig)/sizeof(aSimConfig[0]));
cudaError_t CUDACALL sim_cudaGetDeviceCount(int* pdevs) {
*pdevs = 0;
if (sim_index < 0 || sim_index > sim_index_max)
return cudaErrorInvalidValue;
if (sim_index == sim_index_max) { // simulate N one of each device
*pdevs = sim_index_max * (sim_device_count?sim_device_count:1);
} else if (sim_device_count) {
*pdevs = sim_device_count;
} else {
*pdevs = aSimConfig[sim_index].deviceCount;
}
return cudaSuccess;
}
cudaError_t CUDACALL sim_cudaDriverGetVersion(int* pver) {
if (sim_index < 0 || sim_index > sim_index_max)
return cudaErrorInvalidValue;
int ix = sim_index < sim_index_max ? sim_index : 0;
*pver = aSimConfig[ix].driverVer;
return cudaSuccess;
}
static unsigned char* sim_makeuuid(int devID, unsigned int migID=0x34) {
static unsigned char uuid[16] = {0xa1,0x22,0x33,0x34, 0x44,0x45, 0x56,0x67, 0x89,0x9a, 0xab,0xbc,0xcd,0xde,0xef,0xf0 };
uuid[0] = (unsigned char)(((devID*0x11) + 0xa0) & 0xFF);
uuid[3] = (unsigned char)(migID & 0xFF);
return uuid;
}
cudaError_t CUDACALL sim_getBasicProps(int devID, BasicProps * p) {
if (sim_index < 0 || sim_index > sim_index_max)
return cudaErrorNoDevice;
const struct _simulated_cuda_device * dev;
if (sim_index == sim_index_max) { // simulate N one of each device
int iter = (sim_device_count ? sim_device_count : 1);
dev = aSimConfig[devID/iter].device;
} else {
int cDevs = sim_device_count ? sim_device_count : aSimConfig[sim_index].deviceCount;
if (devID < 0 || devID >= cDevs)
return cudaErrorInvalidDevice;
dev = aSimConfig[sim_index].device;
}
p->name = dev->name;
p->setUUIDFromBuffer( sim_makeuuid(devID) );
sprintf(p->pciId, "0000:%02x:00.0", devID + 0x40);
p->ccMajor = (dev->SM & 0xF0) >> 4;
p->ccMinor = (dev->SM & 0x0F);
p->multiProcessorCount = dev->multiProcessorCount;
p->clockRate = dev->clockRate;
p->totalGlobalMem = dev->totalGlobalMem;
p->ECCEnabled = dev->ECCEnabled;
return cudaSuccess;
}
int sim_jitter = 0;
nvmlReturn_t sim_nvmlInit(void) { sim_jitter = (int)(time(NULL) % 10); return NVML_SUCCESS; }
nvmlReturn_t sim_nvmlDeviceGetFanSpeed(nvmlDevice_t dev, unsigned int * pval) { *pval = 9+sim_jitter+(int)(size_t)dev; return NVML_SUCCESS; }
nvmlReturn_t sim_nvmlDeviceGetPowerUsage(nvmlDevice_t dev, unsigned int * pval) { *pval = 29+sim_jitter+(int)(size_t)dev; return NVML_SUCCESS; }
nvmlReturn_t sim_nvmlDeviceGetTemperature(nvmlDevice_t dev, nvmlTemperatureSensors_t /*sensor*/, unsigned int * pval) { *pval = 89+sim_jitter+(int)(size_t)dev; return NVML_SUCCESS;}
nvmlReturn_t sim_nvmlDeviceGetTotalEccErrors(nvmlDevice_t /*dev*/, nvmlMemoryErrorType_t /*met*/, nvmlEccCounterType_t /*mec*/, unsigned long long * pval) { *pval = 0; /*sim_jitter-1+(int)dev;*/ return NVML_SUCCESS; }
inline nvmlDevice_t sim_index_to_nvmldev(unsigned int simindex, unsigned int migindex=0x34) {
size_t mask = 0x100 + (migindex * (size_t)0x1000);
return (nvmlDevice_t)(((size_t)(simindex)) | mask);
}
inline unsigned int nvmldev_to_sim_index(nvmlDevice_t device) {
return (unsigned int)((size_t)(device) & 0xFF);
}
inline unsigned int nvmldev_to_mig_index(nvmlDevice_t device) {
return (unsigned int)((((size_t)(device)) / 0x1000) & 0xFF);
}
inline unsigned int nvmldev_is_mig(nvmlDevice_t device) {
return nvmldev_to_mig_index(device) < 8;
}
nvmlReturn_t
sim_nvmlDeviceGetHandleByIndex(unsigned int devID, nvmlDevice_t * pdev) {
if (devID < 0 || devID > (unsigned int)sim_index_max) {
return NVML_ERROR_NOT_FOUND;
}
* pdev = sim_index_to_nvmldev(devID);
return NVML_SUCCESS;
}
nvmlReturn_t
sim_nvmlDeviceGetHandleByUUID(const char * uuid, nvmlDevice_t * pdev) {
unsigned int devID=0, migID=0;
if( sscanf(uuid, "%02x2233%02x-4445-5667-899aabbccddeeff0", & devID, &migID) != 2 ) {
return NVML_ERROR_NOT_FOUND;
}
devID = (devID & 0x0F);
if (migID == 0x34) { // is this a MIG uuid?
migID = 0;
} else if (migID > 7) {
return NVML_ERROR_NOT_FOUND;
}
* pdev = sim_index_to_nvmldev(devID, migID);
return NVML_SUCCESS;
};
nvmlReturn_t
sim_findNVMLDeviceHandle(const std::string & uuid, nvmlDevice_t * device) {
return nvmlDeviceGetHandleByUUID( uuid.c_str(), device );
}
nvmlReturn_t
sim_nvmlDeviceGetCount (unsigned int * count) {
int num = 0;
if (sim_cudaGetDeviceCount(&num) == cudaSuccess) {
*count = (unsigned int)num;
return NVML_SUCCESS;
}
return NVML_ERROR_NOT_SUPPORTED;
}
// given an nvml device handle, return the config entry for that device
static nvmlReturn_t sim_getconfig(nvmlDevice_t device, const struct _simulated_cuda_config *& config) {
config = nullptr;
int ix = sim_index; // assume all devices are of type sim_index
int devID = nvmldev_to_sim_index(device);
if (sim_index < 0 || sim_index > sim_index_max)
return NVML_ERROR_NOT_SUPPORTED;
if (sim_index == sim_index_max) { // simulating one of each device
ix = devID;
} else {
int cDevs = sim_device_count ? sim_device_count : aSimConfig[sim_index].deviceCount;
if (devID < 0 || devID >= cDevs)
return NVML_ERROR_NOT_FOUND;
}
// now ix is the index into the simulated devices table,
if (ix < 0 || ix >= sim_index_max) {
return NVML_ERROR_NOT_SUPPORTED;
}
config = &aSimConfig[ix];
return NVML_SUCCESS;
}
nvmlReturn_t
sim_nvmlDeviceGetMaxMigDeviceCount(nvmlDevice_t device, unsigned int * count ) {
const struct _simulated_cuda_config * config = nullptr;
nvmlReturn_t ret = sim_getconfig(device, config);
if (ret != NVML_SUCCESS) { return ret; }
if ( ! config->mig) {
if (config->driverVer < 10000) {
return NVML_ERROR_NOT_SUPPORTED;
} else {
*count = 0;
return NVML_SUCCESS;
}
}
* count = config->mig->migCount;
return NVML_SUCCESS;
}
nvmlReturn_t
sim_nvmlDeviceGetMigDeviceHandleByIndex(nvmlDevice_t device, unsigned int index, nvmlDevice_t* migDevice ) {
const struct _simulated_cuda_config * config = nullptr;
nvmlReturn_t ret = sim_getconfig(device, config);
if (ret != NVML_SUCCESS) { return ret; }
if ( ! config->mig || nvmldev_is_mig(device)) { return NVML_ERROR_NOT_SUPPORTED; }
if (index >= config->mig->migCount) { return NVML_ERROR_NOT_FOUND; }
int devID = nvmldev_to_sim_index(device);
* migDevice = sim_index_to_nvmldev(devID, index);
return NVML_SUCCESS;
}
nvmlReturn_t
sim_nvmlDeviceGetUUID(nvmlDevice_t device, char *buf, unsigned int bufsize ) {
const struct _simulated_cuda_config * config = nullptr;
nvmlReturn_t ret = sim_getconfig(device, config);
if (ret != NVML_SUCCESS) { return ret; }
int devID = nvmldev_to_sim_index(device);
std::string bogus_uuid;
if (nvmldev_is_mig(device)) {
unsigned int migID = nvmldev_to_mig_index(device);
// first turn the uuid into a string.
char uuidbuf[NVML_DEVICE_UUID_V2_BUFFER_SIZE];
// then turn that into a nvml "uuid" which is really a string containing a uuid and prefix/suffix
if (config->driverVer >= 11040) {
bogus_uuid = "MIG-";
print_uuid(uuidbuf, NVML_DEVICE_UUID_V2_BUFFER_SIZE, sim_makeuuid(devID, migID));
bogus_uuid += uuidbuf;
} else {
bogus_uuid = "MIG-GPU-";
print_uuid(uuidbuf, NVML_DEVICE_UUID_V2_BUFFER_SIZE, sim_makeuuid(devID));
bogus_uuid += uuidbuf;
sprintf(uuidbuf, "/%d/0", migID);
bogus_uuid += uuidbuf;
}
} else {
// first turn the uuid into a string.
char uuidbuf[NVML_DEVICE_UUID_V2_BUFFER_SIZE];
print_uuid(uuidbuf, NVML_DEVICE_UUID_V2_BUFFER_SIZE, sim_makeuuid(devID));
bogus_uuid = "GPU-";
bogus_uuid += uuidbuf;
}
strncpy(buf, bogus_uuid.c_str(), bufsize-1);
buf[bufsize - 1] = 0;
return NVML_SUCCESS;
}
nvmlReturn_t
sim_nvmlDeviceGetName(nvmlDevice_t device, char *buf, unsigned int bufsize) {
const struct _simulated_cuda_config * config = nullptr;
nvmlReturn_t ret = sim_getconfig(device, config);
if (ret != NVML_SUCCESS) { return ret; }
int devID = nvmldev_to_sim_index(device);
if (nvmldev_is_mig(device)) {
// TODO: is driver 470 different than driver 450 ?
// strcpy(buf, config->device->name);
return NVML_ERROR_NOT_FOUND;
} else {
strcpy(buf, config->device->name);
}
return NVML_SUCCESS;
}
nvmlReturn_t
sim_nvmlDeviceGetMemoryInfo(nvmlDevice_t device, nvmlMemory_t * memory ) {
const struct _simulated_cuda_config * config = nullptr;
nvmlReturn_t ret = sim_getconfig(device, config);
if (ret != NVML_SUCCESS) { return ret; }
int devID = nvmldev_to_sim_index(device);
if (nvmldev_is_mig(device)) {
memory->total = config->mig->inst[nvmldev_to_mig_index(device)].memory * (size_t)(1024*1024);
} else {
memory->total = config->device->totalGlobalMem;
}
memory->free = memory->total;
memory->used = 0;
return NVML_SUCCESS;
}
nvmlReturn_t
sim_nvmlDeviceGetEccMode( nvmlDevice_t device, nvmlEnableState_t* current, nvmlEnableState_t* pending ) {
const struct _simulated_cuda_config * config = nullptr;
nvmlReturn_t ret = sim_getconfig(device, config);
if (ret != NVML_SUCCESS) { return ret; }
int devID = nvmldev_to_sim_index(device);
int enabled = 0;
if (nvmldev_is_mig(device)) { // TODO: per MIG ecc?
enabled = config->device->ECCEnabled;
} else {
enabled = config->device->ECCEnabled;
}
* current = enabled ? NVML_FEATURE_ENABLED : NVML_FEATURE_DISABLED;
return NVML_SUCCESS;
}
nvmlReturn_t
sim_nvmlDeviceGetMaxClockInfo( nvmlDevice_t device, nvmlClockType_t /*ct*/, unsigned int * clock ) {
const struct _simulated_cuda_config * config = nullptr;
nvmlReturn_t ret = sim_getconfig(device, config);
if (ret != NVML_SUCCESS) { return ret; }
int devID = nvmldev_to_sim_index(device);
int clockRate = 0;
if (nvmldev_is_mig(device)) { // TODO: per MIG ecc?
clockRate = config->device->clockRate;
} else {
clockRate = config->device->clockRate;
}
// table in Khz, but NVML wants MHz
* clock = clockRate / 1000;
return NVML_SUCCESS;
}
void
setSimulatedCUDAFunctionPointers() {
getBasicProps = sim_getBasicProps;
cuDeviceGetCount = sim_cudaGetDeviceCount;
cudaDriverGetVersion = sim_cudaDriverGetVersion;
}
bool
setSimulatedNVMLFunctionPointers() {
nvmlInit = sim_nvmlInit;
nvmlShutdown = sim_nvmlInit;
nvmlDeviceGetFanSpeed = sim_nvmlDeviceGetFanSpeed;
nvmlDeviceGetPowerUsage = sim_nvmlDeviceGetPowerUsage;
nvmlDeviceGetTemperature = sim_nvmlDeviceGetTemperature;
nvmlDeviceGetTotalEccErrors = sim_nvmlDeviceGetTotalEccErrors;
nvmlDeviceGetHandleByUUID = sim_nvmlDeviceGetHandleByUUID;
nvmlDeviceGetHandleByIndex = sim_nvmlDeviceGetHandleByIndex;
nvmlDeviceGetUUID = sim_nvmlDeviceGetUUID;
findNVMLDeviceHandle = sim_findNVMLDeviceHandle;
if (sim_index > 1) { // for later versions of the runtime, enable MIG
nvmlDeviceGetCount = sim_nvmlDeviceGetCount;
nvmlDeviceGetName = sim_nvmlDeviceGetName;
nvmlDeviceGetMemoryInfo = sim_nvmlDeviceGetMemoryInfo;
nvmlDeviceGetEccMode = sim_nvmlDeviceGetEccMode;
nvmlDeviceGetMaxClockInfo = sim_nvmlDeviceGetMaxClockInfo;
nvmlDeviceGetMaxMigDeviceCount = sim_nvmlDeviceGetMaxMigDeviceCount;
nvmlDeviceGetMigDeviceHandleByIndex = sim_nvmlDeviceGetMigDeviceHandleByIndex;
}
return sim_index > 1;
}
| 42.37931 | 350 | 0.759357 | [
"vector"
] |
7463b9bd475e9ce1d669590466c415b6a129ffaa | 138,861 | cpp | C++ | tests/src/test_BamRecordImplVariableData.cpp | bio-nim/pbbam | d3bf59e90865ef3b39bf50f19fd846db42bb0fe1 | [
"BSD-3-Clause-Clear"
] | null | null | null | tests/src/test_BamRecordImplVariableData.cpp | bio-nim/pbbam | d3bf59e90865ef3b39bf50f19fd846db42bb0fe1 | [
"BSD-3-Clause-Clear"
] | null | null | null | tests/src/test_BamRecordImplVariableData.cpp | bio-nim/pbbam | d3bf59e90865ef3b39bf50f19fd846db42bb0fe1 | [
"BSD-3-Clause-Clear"
] | null | null | null | // Author: Derek Barnett
#include <pbbam/BamRecordImpl.h>
#include <cstddef>
#include <cstdint>
#include <algorithm>
#include <iterator>
#include <string>
#include <utility>
#include <vector>
#include <gtest/gtest.h>
#include <pbbam/BamTagCodec.h>
#include <pbbam/SamTagCodec.h>
#include <pbbam/Tag.h>
#include <pbbam/TagCollection.h>
#include "../src/MemoryUtils.h"
using namespace PacBio;
using namespace PacBio::BAM;
// NOTE: this file has a *TON* of tests. Probably overkill, but I wanted to check
// every possible combination of variable data, and then manipulate each
// element within each combo to shrink & expand.
namespace BamRecordImplVariableDataTests {
static void CheckRawData(const BamRecordImpl& bam)
{
// ensure raw data (lengths at least) matches API-facing data
const uint32_t expectedNameBytes = bam.Name().size() + 1; // include NULL term
const uint32_t expectedNameNulls = 4 - (expectedNameBytes % 4);
const uint32_t expectedNameLength = expectedNameBytes + expectedNameNulls;
const uint32_t expectedNumCigarOps = bam.CigarData().size();
const int32_t expectedSeqLength = bam.Sequence().length();
const size_t expectedTagsLength = BamTagCodec::Encode(bam.Tags()).size();
// Name CIGAR Sequence Quals Tags
// l_qname + (n_cigar * 4) + (l_qseq+1)/2 + l_qseq + <encoded length>
const int expectedTotalDataLength = expectedNameLength + (expectedNumCigarOps * 4) +
(expectedSeqLength + 1) / 2 + expectedSeqLength +
expectedTagsLength;
const auto& rawData = PacBio::BAM::BamRecordMemory::GetRawData(bam);
ASSERT_TRUE(static_cast<bool>(rawData));
EXPECT_EQ(expectedNameNulls, rawData->core.l_extranul);
EXPECT_EQ(expectedNameLength, rawData->core.l_qname);
EXPECT_EQ(expectedNumCigarOps, rawData->core.n_cigar);
EXPECT_EQ(expectedSeqLength, rawData->core.l_qseq);
EXPECT_EQ(expectedTotalDataLength, rawData->l_data);
}
} // namespace BamRecordImplVariableDataTests
TEST(BAM_BamRecordImplVarData, default_construction_all_data_is_empty_and_valid)
{
BamRecordImpl bam;
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, default_construction_tags_are_empty)
{
BamRecordImpl bam;
bam.Tags(TagCollection());
EXPECT_EQ(0, bam.Tags().size());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_add_tags)
{
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Tags(tags);
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
}
TEST(BAM_BamRecordImplVarData, can_add_tags_then_overwrite_with_longer_tags)
{
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
TagCollection longerTags;
longerTags["HX"] = std::string("1abc75");
longerTags["HX"].Modifier(TagModifier::HEX_STRING);
longerTags["CA"] = std::vector<uint8_t>({34, 5, 125});
longerTags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Tags(tags);
bam.Tags(longerTags);
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
}
TEST(BAM_BamRecordImplVarData, can_add_tags_then_overwrite_with_shorter_tags)
{
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
TagCollection longerTags;
longerTags["HX"] = std::string("1abc75");
longerTags["HX"].Modifier(TagModifier::HEX_STRING);
longerTags["CA"] = std::vector<uint8_t>({34, 5, 125});
longerTags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Tags(longerTags);
bam.Tags(tags);
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
}
TEST(BAM_BamRecordImplVarData, can_add_tags_then_overwrite_with_empty_tags)
{
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Tags(tags);
bam.Tags(TagCollection());
EXPECT_EQ(0, bam.Tags().size());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, default_construction_cigar_is_empty)
{
BamRecordImpl bam;
bam.CigarData(std::string());
EXPECT_EQ(0, bam.CigarData().size());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_cigar_from_cigar_object)
{
Cigar cigar;
cigar.push_back(CigarOperation('=', 100));
BamRecordImpl bam;
bam.CigarData(cigar);
EXPECT_EQ(cigar, bam.CigarData());
EXPECT_TRUE("100=" == bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_cigar_from_cigar_string)
{
const std::string cigar = "100=";
BamRecordImpl bam;
bam.CigarData(cigar);
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_cigar_then_overwrite_with_longer_cigar)
{
const std::string cigar = "100=";
const std::string longerCigar = "100=10D100=10I100X";
BamRecordImpl bam;
bam.CigarData(cigar);
bam.CigarData(longerCigar);
EXPECT_EQ(longerCigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_cigar_then_overwrite_with_shorter_cigar)
{
const std::string cigar = "100=";
const std::string longerCigar = "100=10D100=10I100X";
BamRecordImpl bam;
bam.CigarData(longerCigar);
bam.CigarData(cigar);
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_cigar_then_overwrite_with_empty_cigar)
{
const std::string cigar = "100=";
const std::string empty;
BamRecordImpl bam;
bam.CigarData(cigar);
bam.CigarData(empty);
EXPECT_EQ(empty, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_cigar_tag)
{
const std::string cigar = "100=";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.CigarData(cigar);
bam.Tags(tags);
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_cigar_tag_with_empty_cigar_string)
{
const std::string cigar = "100=";
const std::string empty;
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.CigarData(cigar);
bam.Tags(tags);
bam.CigarData(empty);
EXPECT_EQ(empty, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_cigar_tag_with_empty_cigar)
{
const std::string cigar = "100=";
BamRecordImpl bam;
bam.CigarData(cigar);
bam.Tags(TagCollection());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
EXPECT_EQ(0, bam.Tags().size());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_cigar_tag_then_overwrite_with_longer_cigar)
{
const std::string cigar = "100=";
const std::string longerCigar = "100=10D100=10I100X";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.CigarData(cigar);
bam.Tags(tags);
bam.CigarData(longerCigar);
EXPECT_EQ(longerCigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_cigar_tag_then_overwrite_with_shorter_cigar)
{
const std::string cigar = "100=";
const std::string longerCigar = "100=10D100=10I100X";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.CigarData(longerCigar);
bam.Tags(tags);
bam.CigarData(cigar);
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_cigar_tag_then_overwrite_with_empty_cigar)
{
const std::string cigar = "100=";
const std::string empty;
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.CigarData(cigar);
bam.Tags(tags);
bam.CigarData(empty);
EXPECT_EQ(empty, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_cigar_tag_then_overwrite_with_longer_tag_collection)
{
const std::string cigar = "100=";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
TagCollection longerTags;
longerTags["HX"] = std::string("1abc75");
longerTags["HX"].Modifier(TagModifier::HEX_STRING);
longerTags["CA"] = std::vector<uint8_t>({34, 5, 125});
longerTags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.CigarData(cigar);
bam.Tags(tags);
bam.Tags(longerTags);
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_cigar_tag_then_overwrite_with_shorter_tag_collection)
{
const std::string cigar = "100=";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
TagCollection longerTags;
longerTags["HX"] = std::string("1abc75");
longerTags["HX"].Modifier(TagModifier::HEX_STRING);
longerTags["CA"] = std::vector<uint8_t>({34, 5, 125});
longerTags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.CigarData(cigar);
bam.Tags(longerTags);
bam.Tags(tags);
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_cigar_tag_then_overwrite_with_empty_tag_collection)
{
const std::string cigar = "100=";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
BamRecordImpl bam;
bam.CigarData(cigar);
bam.Tags(tags);
bam.Tags(TagCollection());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
EXPECT_EQ(0, bam.Tags().size());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_with_both_empty)
{
BamRecordImpl bam;
bam.SetSequenceAndQualities(std::string(), std::string());
EXPECT_EQ(0, bam.Sequence().size());
EXPECT_EQ(0, bam.Qualities().Fastq().size());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_with_both_normal)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_with_empty_qual)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities;
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_preencoded)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const size_t encodedLength = (sequence.size() + 1) / 2;
char* encoded = static_cast<char*>(std::calloc(encodedLength, sizeof(char)));
char* e = encoded;
uint8_t nucleotideCode{};
bool useHighWord = true;
for (char i : sequence) {
switch (i) {
case 'A':
nucleotideCode = 1;
break;
case 'C':
nucleotideCode = 2;
break;
case 'G':
nucleotideCode = 4;
break;
case 'T':
nucleotideCode = 8;
break;
default:
EXPECT_FALSE(true);
break;
}
// pack the nucleotide code
if (useHighWord) {
*e = nucleotideCode << 4;
useHighWord = false;
} else {
*e |= nucleotideCode;
++e;
useHighWord = true;
}
}
BamRecordImpl bam;
bam.SetPreencodedSequenceAndQualities(encoded, sequence.size(), qualities.c_str());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
BamRecordImplVariableDataTests::CheckRawData(bam);
free(encoded);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_preencoded_with_empty_qual)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities;
const auto encodedLength = (sequence.size() + 1) / 2;
auto* encoded = static_cast<char*>(std::calloc(encodedLength, sizeof(char)));
auto* e = encoded;
uint8_t nucleotideCode{};
bool useHighWord = true;
for (char i : sequence) {
switch (i) {
case 'A':
nucleotideCode = 1;
break;
case 'C':
nucleotideCode = 2;
break;
case 'G':
nucleotideCode = 4;
break;
case 'T':
nucleotideCode = 8;
break;
default:
EXPECT_FALSE(true);
break;
}
// pack the nucleotide code
if (useHighWord) {
*e = nucleotideCode << 4;
useHighWord = false;
} else {
*e |= nucleotideCode;
++e;
useHighWord = true;
}
}
BamRecordImpl bam;
bam.SetPreencodedSequenceAndQualities(encoded, sequence.size(), qualities.c_str());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
BamRecordImplVariableDataTests::CheckRawData(bam);
free(encoded);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_overwrite_with_longer_seq_and_qual)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string shortSeq = "ACGT";
const std::string shortQual = "?]?]";
BamRecordImpl bam;
bam.SetSequenceAndQualities(shortSeq, shortQual);
bam.SetSequenceAndQualities(sequence, qualities);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_overwrite_with_longer_seq_only)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities;
const std::string shortSeq = "ACGT";
const std::string shortQual = "?]?]";
BamRecordImpl bam;
bam.SetSequenceAndQualities(shortSeq, shortQual);
bam.SetSequenceAndQualities(sequence, qualities);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_overwrite_with_shorter_seq_and_qual)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string shortSeq = "ACGT";
const std::string shortQual = "?]?]";
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.SetSequenceAndQualities(shortSeq, shortQual);
EXPECT_EQ(shortSeq, bam.Sequence());
EXPECT_EQ(shortQual, bam.Qualities().Fastq());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_overwrite_with_shorter_seq_only)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string shortSeq = "ACGT";
const std::string shortQual;
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.SetSequenceAndQualities(shortSeq, shortQual);
EXPECT_EQ(shortSeq, bam.Sequence());
EXPECT_EQ(shortQual, bam.Qualities().Fastq());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_overwrite_with_empty_seq_)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string empty;
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.SetSequenceAndQualities(empty, empty);
EXPECT_EQ(empty, bam.Sequence());
EXPECT_EQ(empty, bam.Qualities().Fastq());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_tags)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.Tags(tags);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_empty_seq_qual_then_tags)
{
const std::string sequence;
const std::string qualities;
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.Tags(tags);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_with_empty_qual_then_tags)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities;
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.Tags(tags);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_empty_tags)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.Tags(TagCollection());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(0, bam.Tags().size());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_tags_then_longer_seq_qual)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string shortSeq = "ACGT";
const std::string shortQual = "?]?]";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.SetSequenceAndQualities(shortSeq, shortQual);
bam.Tags(tags);
bam.SetSequenceAndQualities(sequence, qualities);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_tags_then_longer_seq_qual_with_empty_qual)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities;
const std::string shortSeq = "ACGT";
const std::string shortQual = "?]?]";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.SetSequenceAndQualities(shortSeq, shortQual);
bam.Tags(tags);
bam.SetSequenceAndQualities(sequence, qualities);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_tags_then_shorter_seq_qual)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string shortSeq = "ACGT";
const std::string shortQual = "?]?]";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.Tags(tags);
bam.SetSequenceAndQualities(shortSeq, shortQual);
EXPECT_EQ(shortSeq, bam.Sequence());
EXPECT_EQ(shortQual, bam.Qualities().Fastq());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_tags_then_shorter_seq_qual_with_empty_qual)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string shortSeq = "ACGT";
const std::string shortQual;
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.Tags(tags);
bam.SetSequenceAndQualities(shortSeq, shortQual);
EXPECT_EQ(shortSeq, bam.Sequence());
EXPECT_EQ(shortQual, bam.Qualities().Fastq());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_tags_then_empty_seq)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string empty;
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.Tags(tags);
bam.SetSequenceAndQualities(empty, empty);
EXPECT_EQ(empty, bam.Sequence());
EXPECT_EQ(empty, bam.Qualities().Fastq());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_tags_then_longer_tags)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
TagCollection longerTags;
longerTags["HX"] = std::string("1abc75");
longerTags["HX"].Modifier(TagModifier::HEX_STRING);
longerTags["CA"] = std::vector<uint8_t>({34, 5, 125});
longerTags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.Tags(tags);
bam.Tags(longerTags);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_tags_then_shorter_tags)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
TagCollection longerTags;
longerTags["HX"] = std::string("1abc75");
longerTags["HX"].Modifier(TagModifier::HEX_STRING);
longerTags["CA"] = std::vector<uint8_t>({34, 5, 125});
longerTags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.Tags(longerTags);
bam.Tags(tags);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_tags_then_empty_tags)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.Tags(tags);
bam.Tags(TagCollection());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(0, bam.Tags().size());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_cigar)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_empty_seq_qual_then_cigar)
{
const std::string sequence;
const std::string qualities;
const std::string cigar = "100=";
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_and_empty_qual_then_cigar)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities;
const std::string cigar = "100=";
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_empty_cigar)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar;
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_cigar_then_overwrite_with_longer_seq_qual)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string shortSeq = "ACGT";
const std::string shortQual = "?]?]";
BamRecordImpl bam;
bam.SetSequenceAndQualities(shortSeq, shortQual);
bam.CigarData(cigar);
bam.SetSequenceAndQualities(sequence, qualities);
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_seq_qual_then_cigar_then_overwrite_with_longer_seq_empty_qual)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities;
const std::string cigar = "100=";
const std::string shortSeq = "ACGT";
const std::string shortQual = "?]?]";
BamRecordImpl bam;
bam.SetSequenceAndQualities(shortSeq, shortQual);
bam.CigarData(cigar);
bam.SetSequenceAndQualities(sequence, qualities);
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_cigar_then_overwrite_with_shorter_seq_qual)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string shortSeq = "ACGT";
const std::string shortQual = "?]?]";
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.SetSequenceAndQualities(shortSeq, shortQual);
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
EXPECT_EQ(shortSeq, bam.Sequence());
EXPECT_EQ(shortQual, bam.Qualities().Fastq());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_seq_qual_then_cigar_then_overwrite_with_shorter_seq_empty_qual)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string shortSeq = "ACGT";
const std::string shortQual;
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.SetSequenceAndQualities(shortSeq, shortQual);
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
EXPECT_EQ(shortSeq, bam.Sequence());
EXPECT_EQ(shortQual, bam.Qualities().Fastq());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_cigar_then_overwrite_with_empty_seq)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string empty;
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.SetSequenceAndQualities(empty, empty);
EXPECT_EQ(empty, bam.Sequence());
EXPECT_EQ(empty, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_cigar_then_overwrite_with_longer_cigar)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string longerCigar = "100=10D100=10I100X";
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.CigarData(longerCigar);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(longerCigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_cigar_then_overwrite_with_shorter_cigar)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string longerCigar = "100=10D100=10I100X";
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(longerCigar);
bam.CigarData(cigar);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_cigar_then_overwrite_with_empty_cigar)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string empty;
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.CigarData(empty);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(empty, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_cigar_then_tag)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(tags);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_cigar_then_tag_with_empty_seq_qual)
{
const std::string sequence;
const std::string qualities;
const std::string cigar = "100=";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(tags);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_cigar_then_tag_with_empty_qual)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities;
const std::string cigar = "100=";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(tags);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_cigar_then_tag_with_empty_cigar)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar;
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(tags);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_cigar_then_tag_with_empty_tag)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(TagCollection());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
EXPECT_EQ(0, bam.Tags().size());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_seq_qual_then_cigar_then_tag_then_overwrite_with_longer_seq_qual)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string shortSeq = "ACGT";
const std::string shortQual = "?]?]";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.SetSequenceAndQualities(shortSeq, shortQual);
bam.CigarData(cigar);
bam.Tags(tags);
bam.SetSequenceAndQualities(sequence, qualities);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_seq_qual_then_cigar_then_tag_then_overwrite_with_longer_seq_only)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities;
const std::string cigar = "100=";
const std::string shortSeq = "ACGT";
const std::string shortQual = "?]?]";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.SetSequenceAndQualities(shortSeq, shortQual);
bam.CigarData(cigar);
bam.Tags(tags);
bam.SetSequenceAndQualities(sequence, qualities);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_seq_qual_then_cigar_then_tag_then_overwrite_with_shorter_seq_qual)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string shortSeq = "ACGT";
const std::string shortQual = "?]?]";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(tags);
bam.SetSequenceAndQualities(shortSeq, shortQual);
EXPECT_EQ(shortSeq, bam.Sequence());
EXPECT_EQ(shortQual, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_seq_qual_then_cigar_then_tag_then_overwrite_with_shorter_seq_only)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string shortSeq = "ACGT";
const std::string shortQual;
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(tags);
bam.SetSequenceAndQualities(shortSeq, shortQual);
EXPECT_EQ(shortSeq, bam.Sequence());
EXPECT_EQ(shortQual, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_cigar_then_tag_then_overwrite_with_empty_seq)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string empty;
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(tags);
bam.SetSequenceAndQualities(empty, empty);
EXPECT_EQ(empty, bam.Sequence());
EXPECT_EQ(empty, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_seq_qual_then_cigar_then_tag_then_overwrite_with_longer_cigar)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string longerCigar = "100=10D100=10I100X";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(tags);
bam.CigarData(longerCigar);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(longerCigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_seq_qual_then_cigar_then_tag_then_overwrite_with_shorter_cigar)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string longerCigar = "100=10D100=10I100X";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(longerCigar);
bam.Tags(tags);
bam.CigarData(cigar);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_cigar_then_tag_then_overwrite_with_empty_cigar)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string empty;
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(tags);
bam.CigarData(empty);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(empty, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_cigar_then_tag_then_overwrite_with_longer_tags)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
TagCollection longerTags;
longerTags["HX"] = std::string("1abc75");
longerTags["HX"].Modifier(TagModifier::HEX_STRING);
longerTags["CA"] = std::vector<uint8_t>({34, 5, 125});
longerTags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(tags);
bam.Tags(longerTags);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_seq_qual_then_cigar_then_tag_then_overwrite_with_shorter_tags)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
TagCollection longerTags;
longerTags["HX"] = std::string("1abc75");
longerTags["HX"].Modifier(TagModifier::HEX_STRING);
longerTags["CA"] = std::vector<uint8_t>({34, 5, 125});
longerTags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(longerTags);
bam.Tags(tags);
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_seq_qual_then_cigar_then_tag_then_overwrite_with_empty_tags)
{
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(tags);
bam.Tags(TagCollection());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
EXPECT_EQ(0, bam.Tags().size());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_with_empty_name)
{
BamRecordImpl bam;
bam.Name(std::string());
EXPECT_EQ(0, bam.Name().size());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_with_name_only)
{
const std::string readName = "foo";
BamRecordImpl bam;
bam.Name(readName);
EXPECT_EQ(readName, bam.Name());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_overwrite_with_longer_name)
{
const std::string readName = "foo";
const std::string longerName = "this is a long read name";
BamRecordImpl bam;
bam.Name(readName);
bam.Name(longerName);
EXPECT_EQ(longerName, bam.Name());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_overwrite_with_shorter_name)
{
const std::string readName = "foo";
const std::string longerName = "this is a long read name";
BamRecordImpl bam;
bam.Name(longerName);
bam.Name(readName);
EXPECT_EQ(readName, bam.Name());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_overwrite_with_empty_name)
{
const std::string readName = "foo";
const std::string emptyName;
BamRecordImpl bam;
bam.Name(readName);
bam.Name(emptyName);
EXPECT_EQ(emptyName, bam.Name());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_tag)
{
const std::string readName = "foo";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.Tags(tags);
EXPECT_EQ(readName, bam.Name());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_empty_name_then_tag)
{
const std::string readName;
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.Tags(tags);
EXPECT_EQ(readName, bam.Name());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_empty_tag)
{
const std::string readName = "foo";
BamRecordImpl bam;
bam.Name(readName);
bam.Tags(TagCollection());
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(0, bam.Tags().size());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_tag_then_overwrite_with_longer_name)
{
const std::string readName = "foo";
const std::string longerName = "this is a long read name";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.Tags(tags);
bam.Name(longerName);
EXPECT_EQ(longerName, bam.Name());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_tag_then_overwrite_with_shorter_name)
{
const std::string readName = "foo";
const std::string longerName = "this is a long read name";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(longerName);
bam.Tags(tags);
bam.Name(readName);
EXPECT_EQ(readName, bam.Name());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_tag_then_overwrite_with_empty_name)
{
const std::string readName = "foo";
const std::string empty;
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.Tags(tags);
bam.Name(empty);
EXPECT_EQ(empty, bam.Name());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_tag_then_overwrite_with_longer_tags)
{
const std::string readName = "foo";
TagCollection longerTags;
longerTags["HX"] = std::string("1abc75");
longerTags["HX"].Modifier(TagModifier::HEX_STRING);
longerTags["CA"] = std::vector<uint8_t>({34, 5, 125});
longerTags["XY"] = int32_t{-42};
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
BamRecordImpl bam;
bam.Name(readName);
bam.Tags(tags);
bam.Tags(longerTags);
EXPECT_EQ(readName, bam.Name());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_tag_then_overwrite_with_shorter_tags)
{
const std::string readName = "foo";
TagCollection longerTags;
longerTags["HX"] = std::string("1abc75");
longerTags["HX"].Modifier(TagModifier::HEX_STRING);
longerTags["CA"] = std::vector<uint8_t>({34, 5, 125});
longerTags["XY"] = int32_t{-42};
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
BamRecordImpl bam;
bam.Name(readName);
bam.Tags(longerTags);
bam.Tags(tags);
EXPECT_EQ(readName, bam.Name());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_tag_then_overwrite_with_empty_tags)
{
const std::string readName = "foo";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.Tags(tags);
bam.Tags(TagCollection());
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(0, bam.Tags().size());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_cigar)
{
const std::string readName = "foo";
const std::string cigar = "100=";
BamRecordImpl bam;
bam.Name(readName);
bam.CigarData(cigar);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_empty_name_then_cigar)
{
const std::string readName;
const std::string cigar = "100=";
BamRecordImpl bam;
bam.Name(readName);
bam.CigarData(cigar);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_empty_name_then_empty_cigar)
{
const std::string readName = "foo";
const std::string cigar;
BamRecordImpl bam;
bam.Name(readName);
bam.CigarData(cigar);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_cigar_then_overwrite_with_longer_name)
{
const std::string readName = "foo";
const std::string cigar = "100=";
const std::string longerName = "this is a long read name";
BamRecordImpl bam;
bam.Name(readName);
bam.CigarData(cigar);
bam.Name(longerName);
EXPECT_EQ(longerName, bam.Name());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_cigar_then_overwrite_with_shorter_name)
{
const std::string readName = "foo";
const std::string cigar = "100=";
const std::string longerName = "this is a long read name";
BamRecordImpl bam;
bam.Name(longerName);
bam.CigarData(cigar);
bam.Name(readName);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_cigar_then_overwrite_with_empty_name)
{
const std::string readName = "foo";
const std::string cigar = "100=";
const std::string empty;
BamRecordImpl bam;
bam.Name(readName);
bam.CigarData(cigar);
bam.Name(empty);
EXPECT_EQ(empty, bam.Name());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_cigar_then_overwrite_with_longer_cigar)
{
const std::string readName = "foo";
const std::string cigar = "100=";
const std::string longerCigar = "100=10D100=10I100X";
BamRecordImpl bam;
bam.Name(readName);
bam.CigarData(cigar);
bam.CigarData(longerCigar);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(longerCigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_cigar_then_overwrite_with_shorter_cigar)
{
const std::string readName = "foo";
const std::string cigar = "100=";
const std::string longerCigar = "100=10D100=10I100X";
BamRecordImpl bam;
bam.Name(readName);
bam.CigarData(longerCigar);
bam.CigarData(cigar);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_cigar_then_overwrite_with_empty_cigar)
{
const std::string readName = "foo";
const std::string cigar = "100=";
const std::string empty;
BamRecordImpl bam;
bam.Name(readName);
bam.CigarData(cigar);
bam.CigarData(empty);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(empty, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_cigar_then_tag)
{
const std::string readName = "foo";
const std::string cigar = "100=";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.CigarData(cigar);
bam.Tags(tags);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_empty_name_then_cigar_then_tag)
{
const std::string readName;
const std::string cigar = "100=";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.CigarData(cigar);
bam.Tags(tags);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_empty_cigar_then_tag)
{
const std::string readName = "foo";
const std::string cigar;
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.CigarData(cigar);
bam.Tags(tags);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_cigar_then_empty_tag)
{
const std::string readName = "foo";
const std::string cigar = "100=";
BamRecordImpl bam;
bam.Name(readName);
bam.CigarData(cigar);
bam.Tags(TagCollection());
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
EXPECT_EQ(0, bam.Tags().size());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_cigar_then_tag_then_overwrite_with_longer_name)
{
const std::string readName = "foo";
const std::string cigar = "100=";
const std::string longerName = "this is a long read name";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.CigarData(cigar);
bam.Tags(tags);
bam.Name(longerName);
EXPECT_EQ(longerName, bam.Name());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_cigar_then_tag_then_overwrite_with_shorter_name)
{
const std::string readName = "foo";
const std::string cigar = "100=";
const std::string longerName = "this is a long read name";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(longerName);
bam.CigarData(cigar);
bam.Tags(tags);
bam.Name(readName);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_cigar_then_tag_then_overwrite_with_empty_name)
{
const std::string readName = "foo";
const std::string cigar = "100=";
const std::string empty;
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.CigarData(cigar);
bam.Tags(tags);
bam.Name(empty);
EXPECT_EQ(empty, bam.Name());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_cigar_then_tag_then_overwrite_with_longer_cigar)
{
const std::string readName = "foo";
const std::string cigar = "100=";
const std::string longerCigar = "100=10D100=10I100X";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.CigarData(cigar);
bam.Tags(tags);
bam.CigarData(longerCigar);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(longerCigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_cigar_then_tag_then_overwrite_with_shorter_cigar)
{
const std::string readName = "foo";
const std::string cigar = "100=";
const std::string longerCigar = "100=10D100=10I100X";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.CigarData(longerCigar);
bam.Tags(tags);
bam.CigarData(cigar);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_cigar_then_tag_then_overwrite_with_empty_cigar)
{
const std::string readName = "foo";
const std::string cigar = "100=";
const std::string empty;
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.CigarData(cigar);
bam.Tags(tags);
bam.CigarData(empty);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(empty, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_cigar_then_tag_then_overwrite_with_longer_tag)
{
const std::string readName = "foo";
const std::string cigar = "100=";
TagCollection longerTags;
longerTags["HX"] = std::string("1abc75");
longerTags["HX"].Modifier(TagModifier::HEX_STRING);
longerTags["CA"] = std::vector<uint8_t>({34, 5, 125});
longerTags["XY"] = int32_t{-42};
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
BamRecordImpl bam;
bam.Name(readName);
bam.CigarData(cigar);
bam.Tags(tags);
bam.Tags(longerTags);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_cigar_then_tag_then_overwrite_with_shorter_tag)
{
const std::string readName = "foo";
const std::string cigar = "100=";
TagCollection longerTags;
longerTags["HX"] = std::string("1abc75");
longerTags["HX"].Modifier(TagModifier::HEX_STRING);
longerTags["CA"] = std::vector<uint8_t>({34, 5, 125});
longerTags["XY"] = int32_t{-42};
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
BamRecordImpl bam;
bam.Name(readName);
bam.CigarData(cigar);
bam.Tags(longerTags);
bam.Tags(tags);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_cigar_then_tag_then_overwrite_with_empty_tag)
{
const std::string readName = "foo";
const std::string cigar = "100=";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.CigarData(cigar);
bam.Tags(tags);
bam.Tags(TagCollection());
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
EXPECT_EQ(0, bam.Tags().size());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_seq_qual)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_empty_seq_qual)
{
const std::string readName = "foo";
const std::string sequence;
const std::string qualities;
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_empty_seq_only)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities;
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_seq_qual_then_overwrite_with_longer_name)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string longerName = "this is a long read name";
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.Name(longerName);
EXPECT_EQ(longerName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_seq_qual_then_overwrite_with_shorter_name)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string longerName = "this is a long read name";
BamRecordImpl bam;
bam.Name(longerName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.Name(readName);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_seq_qual_then_overwrite_with_empty_name)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string empty;
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.Name(empty);
EXPECT_EQ(empty, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_seq_qual_then_overwrite_with_longer_seq_qual)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string shortSeq = "ACGT";
const std::string shortQual = "?]?]";
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(shortSeq, shortQual);
bam.SetSequenceAndQualities(sequence, qualities);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_seq_qual_then_overwrite_with_longer_seq_only)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities;
const std::string shortSeq = "ACGT";
const std::string shortQual = "?]?]";
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(shortSeq, shortQual);
bam.SetSequenceAndQualities(sequence, qualities);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_seq_qual_then_overwrite_with_shorter_seq_qual)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string shortSeq = "ACGT";
const std::string shortQual = "?]?]";
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.SetSequenceAndQualities(shortSeq, shortQual);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(shortSeq, bam.Sequence());
EXPECT_EQ(shortQual, bam.Qualities().Fastq());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_seq_qual_then_overwrite_with_shorter_seq_only)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string shortSeq = "ACGT";
const std::string shortQual;
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.SetSequenceAndQualities(shortSeq, shortQual);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(shortSeq, bam.Sequence());
EXPECT_EQ(shortQual, bam.Qualities().Fastq());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_seq_qual_then_overwrite_with_empty_seq)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string empty;
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.SetSequenceAndQualities(empty, empty);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(empty, bam.Sequence());
EXPECT_EQ(empty, bam.Qualities().Fastq());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_seq_qual_then_tag)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.Tags(tags);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_empty_name_then_seq_qual_then_tag)
{
const std::string readName;
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.Tags(tags);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_empty_seq_qual_then_tag)
{
const std::string readName = "foo";
const std::string sequence;
const std::string qualities;
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.Tags(tags);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_seq_only_then_tag)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities;
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.Tags(tags);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_seq_qual_then_empty_tag)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.Tags(TagCollection());
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(0, bam.Tags().size());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_seq_qual_then_tag_then_overwrite_with_longer_name)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string longerName = "this is a long read name";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.Tags(tags);
bam.Name(longerName);
EXPECT_EQ(longerName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_seq_qual_then_tag_then_overwrite_with_shorter_name)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string longerName = "this is a long read name";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(longerName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.Tags(tags);
bam.Name(readName);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_seq_qual_then_tag_then_overwrite_with_empty_name)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string empty;
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.Tags(tags);
bam.Name(empty);
EXPECT_EQ(empty, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_name_then_seq_qual_then_tag_then_overwrite_with_longer_seq_qual)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string shortSeq = "ACGT";
const std::string shortQual = "?]?]";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(shortSeq, shortQual);
bam.Tags(tags);
bam.SetSequenceAndQualities(sequence, qualities);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_name_then_seq_qual_then_tag_then_overwrite_with_longer_seq_only)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities;
const std::string shortSeq = "ACGT";
const std::string shortQual = "?]?]";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(shortSeq, shortQual);
bam.Tags(tags);
bam.SetSequenceAndQualities(sequence, qualities);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_name_then_seq_qual_then_tag_then_overwrite_with_shorter_seq_qual)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string shortSeq = "ACGT";
const std::string shortQual = "?]?]";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.Tags(tags);
bam.SetSequenceAndQualities(shortSeq, shortQual);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(shortSeq, bam.Sequence());
EXPECT_EQ(shortQual, bam.Qualities().Fastq());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_name_then_seq_qual_then_tag_then_overwrite_with_shorter_seq_only)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string shortSeq = "ACGT";
const std::string shortQual;
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.Tags(tags);
bam.SetSequenceAndQualities(shortSeq, shortQual);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(shortSeq, bam.Sequence());
EXPECT_EQ(shortQual, bam.Qualities().Fastq());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_seq_qual_then_tag_then_overwrite_with_empty_seq)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string empty;
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.Tags(tags);
bam.SetSequenceAndQualities(empty, empty);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(empty, bam.Sequence());
EXPECT_EQ(empty, bam.Qualities().Fastq());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_seq_qual_then_tag_then_overwrite_with_longer_tag)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
TagCollection longerTags;
longerTags["HX"] = std::string("1abc75");
longerTags["HX"].Modifier(TagModifier::HEX_STRING);
longerTags["CA"] = std::vector<uint8_t>({34, 5, 125});
longerTags["XY"] = int32_t{-42};
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.Tags(tags);
bam.Tags(longerTags);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_seq_qual_then_tag_then_overwrite_with_shorter_tag)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
TagCollection longerTags;
longerTags["HX"] = std::string("1abc75");
longerTags["HX"].Modifier(TagModifier::HEX_STRING);
longerTags["CA"] = std::vector<uint8_t>({34, 5, 125});
longerTags["XY"] = int32_t{-42};
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.Tags(longerTags);
bam.Tags(tags);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_seq_qual_then_tag_then_overwrite_with_empty_tag)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.Tags(tags);
bam.Tags(TagCollection());
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(0, bam.Tags().size());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_seq_qual_then_cigar)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_empty_name_then_seq_qual_then_cigar)
{
const std::string readName;
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_empty_seq_qual_then_cigar)
{
const std::string readName = "foo";
const std::string sequence;
const std::string qualities;
const std::string cigar = "100=";
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_seq_only_then_cigar)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities;
const std::string cigar = "100=";
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_seq_qual_then_empty_cigar)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar;
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_name_then_seq_qual_then_cigar_then_overwrite_with_longer_name)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string longerName = "this is a long read name";
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Name(longerName);
EXPECT_EQ(longerName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_name_then_seq_qual_then_cigar_then_overwrite_with_shorter_name)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string longerName = "this is a long read name";
BamRecordImpl bam;
bam.Name(longerName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Name(readName);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_seq_qual_then_cigar_then_overwrite_with_empty_name)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string empty;
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Name(empty);
EXPECT_EQ(empty, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_name_then_seq_qual_then_cigar_then_overwrite_with_longer_seq_qual)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string shortSeq = "ACGT";
const std::string shortQual = "?]?]";
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(shortSeq, shortQual);
bam.CigarData(cigar);
bam.SetSequenceAndQualities(sequence, qualities);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_name_then_seq_qual_then_cigar_then_overwrite_with_longer_seq_only)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities;
const std::string cigar = "100=";
const std::string shortSeq = "ACGT";
const std::string shortQual = "?]?]";
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(shortSeq, shortQual);
bam.CigarData(cigar);
bam.SetSequenceAndQualities(sequence, qualities);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_name_then_seq_qual_then_cigar_then_overwrite_with_shorter_seq_qual)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string shortSeq = "ACGT";
const std::string shortQual = "?]?]";
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.SetSequenceAndQualities(shortSeq, shortQual);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(shortSeq, bam.Sequence());
EXPECT_EQ(shortQual, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_name_then_seq_qual_then_cigar_then_overwrite_with_shorter_seq_only)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string shortSeq = "ACGT";
const std::string shortQual;
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.SetSequenceAndQualities(shortSeq, shortQual);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(shortSeq, bam.Sequence());
EXPECT_EQ(shortQual, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_seq_qual_then_cigar_then_overwrite_with_empty_seq)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string empty;
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.SetSequenceAndQualities(empty, empty);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(empty, bam.Sequence());
EXPECT_EQ(empty, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_name_then_seq_qual_then_cigar_then_overwrite_with_longer_cigar)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string longerCigar = "100=10D100=10I100X";
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.CigarData(longerCigar);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(longerCigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_name_then_seq_qual_then_cigar_then_overwrite_with_shorter_cigar)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string longerCigar = "100=10D100=10I100X";
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(longerCigar);
bam.CigarData(cigar);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_name_then_seq_qual_then_cigar_then_overwrite_with_empty_cigar)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string empty;
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.CigarData(empty);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(empty, bam.CigarData().ToStdString());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
TEST(BAM_BamRecordImplVarData, can_set_name_then_seq_qual_then_cigar_then_tag)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(tags);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_empty_name_then_seq_qual_then_cigar_then_tag)
{
const std::string readName;
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(tags);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_empty_seq_qual_then_cigar_then_tag)
{
const std::string readName = "foo";
const std::string sequence;
const std::string qualities;
const std::string cigar = "100=";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(tags);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_empty_seq_only_then_cigar_then_tag)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities;
const std::string cigar = "100=";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(tags);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_seq_qual_then_empty_cigar_then_tag)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar;
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(tags);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData, can_set_name_then_seq_qual_then_cigar_then_empty_tag)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(TagCollection());
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
EXPECT_EQ(0, bam.Tags().size());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_name_then_seq_qual_then_cigar_then_tag_then_overwrite_with_longer_name)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string longerName = "this is a long read name";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(tags);
bam.Name(longerName);
EXPECT_EQ(longerName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_name_then_seq_qual_then_cigar_then_tag_then_overwrite_with_shorter_name)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string longerName = "this is a long read name";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(longerName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(tags);
bam.Name(readName);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_name_then_seq_qual_then_cigar_then_tag_then_overwrite_with_empty_name)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string empty;
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(tags);
bam.Name(empty);
EXPECT_EQ(empty, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_name_then_seq_qual_then_cigar_then_tag_then_overwrite_with_longer_seq_qual)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string shortSeq = "ACGT";
const std::string shortQual = "?]?]";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(shortSeq, shortQual);
bam.CigarData(cigar);
bam.Tags(tags);
bam.SetSequenceAndQualities(sequence, qualities);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_name_then_seq_qual_then_cigar_then_tag_then_overwrite_with_longer_seq_only)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities;
const std::string cigar = "100=";
const std::string shortSeq = "ACGT";
const std::string shortQual = "?]?]";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(shortSeq, shortQual);
bam.CigarData(cigar);
bam.Tags(tags);
bam.SetSequenceAndQualities(sequence, qualities);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_name_then_seq_qual_then_cigar_then_tag_then_overwrite_with_shorter_seq_qual)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string shortSeq = "ACGT";
const std::string shortQual = "?]?]";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(tags);
bam.SetSequenceAndQualities(shortSeq, shortQual);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(shortSeq, bam.Sequence());
EXPECT_EQ(shortQual, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_name_then_seq_qual_then_cigar_then_tag_then_overwrite_with_shorter_seq_only)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string shortSeq = "ACGT";
const std::string shortQual;
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(tags);
bam.SetSequenceAndQualities(shortSeq, shortQual);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(shortSeq, bam.Sequence());
EXPECT_EQ(shortQual, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_name_then_seq_qual_then_cigar_then_tag_then_overwrite_with_empty_seq)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string empty;
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(tags);
bam.SetSequenceAndQualities(empty, empty);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(empty, bam.Sequence());
EXPECT_EQ(empty, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_name_then_seq_qual_then_cigar_then_tag_then_overwrite_with_longer_cigar)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string longerCigar = "100=10D100=10I100X";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(tags);
bam.CigarData(longerCigar);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(longerCigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_name_then_seq_qual_then_cigar_then_tag_then_overwrite_with_shorter_cigar)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string longerCigar = "100=10D100=10I100X";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(longerCigar);
bam.Tags(tags);
bam.CigarData(cigar);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_name_then_seq_qual_then_cigar_then_tag_then_overwrite_with_empty_cigar)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
const std::string empty;
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(tags);
bam.CigarData(empty);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(empty, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_name_then_seq_qual_then_cigar_then_tag_then_overwrite_with_longer_tag)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
TagCollection longerTags;
longerTags["HX"] = std::string("1abc75");
longerTags["HX"].Modifier(TagModifier::HEX_STRING);
longerTags["CA"] = std::vector<uint8_t>({34, 5, 125});
longerTags["XY"] = int32_t{-42};
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(tags);
bam.Tags(longerTags);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
expected.append("\t");
expected.append("XY:i:-42");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_name_then_seq_qual_then_cigar_then_tag_then_overwrite_with_shorter_tag)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
TagCollection longerTags;
longerTags["HX"] = std::string("1abc75");
longerTags["HX"].Modifier(TagModifier::HEX_STRING);
longerTags["CA"] = std::vector<uint8_t>({34, 5, 125});
longerTags["XY"] = int32_t{-42};
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(longerTags);
bam.Tags(tags);
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
std::string expected;
expected.append("CA:B:C,34,5,125");
expected.append("\t");
expected.append("HX:H:1abc75");
const std::string sam = SamTagCodec::Encode(bam.Tags());
EXPECT_EQ(expected, sam);
BamRecordImplVariableDataTests::CheckRawData(bam);
}
TEST(BAM_BamRecordImplVarData,
can_set_name_then_seq_qual_then_cigar_then_tag_then_overwrite_with_empty_tag)
{
const std::string readName = "foo";
const std::string sequence = "ACGTACGTACGT";
const std::string qualities = "?]?]?]?]?]?]";
const std::string cigar = "100=";
TagCollection tags;
tags["HX"] = std::string("1abc75");
tags["HX"].Modifier(TagModifier::HEX_STRING);
tags["CA"] = std::vector<uint8_t>({34, 5, 125});
tags["XY"] = int32_t{-42};
BamRecordImpl bam;
bam.Name(readName);
bam.SetSequenceAndQualities(sequence, qualities);
bam.CigarData(cigar);
bam.Tags(tags);
bam.Tags(TagCollection());
EXPECT_EQ(readName, bam.Name());
EXPECT_EQ(sequence, bam.Sequence());
EXPECT_EQ(qualities, bam.Qualities().Fastq());
EXPECT_EQ(cigar, bam.CigarData().ToStdString());
EXPECT_EQ(0, bam.Tags().size());
BamRecordImplVariableDataTests::CheckRawData(bam);
}
| 30.41862 | 100 | 0.674379 | [
"vector"
] |
746a4afa87327fd2aaa66c05cbc9b3e58d409e1c | 5,499 | cpp | C++ | test/test_xcoordinate.cpp | SylvainCorlay/xframe | ceb346b7be28cc0aea2ea91aa99533eed6e99bb3 | [
"BSD-3-Clause"
] | 176 | 2017-09-25T20:21:49.000Z | 2019-10-03T20:09:38.000Z | test/test_xcoordinate.cpp | vishalbelsare/xframe | 24d65f462cb9345c0814264dc449c5552c2592bb | [
"BSD-3-Clause"
] | 53 | 2017-09-29T06:52:58.000Z | 2019-06-27T08:20:35.000Z | test/test_xcoordinate.cpp | vishalbelsare/xframe | 24d65f462cb9345c0814264dc449c5552c2592bb | [
"BSD-3-Clause"
] | 20 | 2017-09-25T20:21:50.000Z | 2019-06-29T01:43:02.000Z | /***************************************************************************
* Copyright (c) Johan Mabille, Sylvain Corlay, Wolf Vollprecht and *
* Martin Renou *
* Copyright (c) QuantStack *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#include "gtest/gtest.h"
#include "test_fixture.hpp"
namespace xf
{
using slabel_type = std::vector<fstring>;
using ilabel_type = std::vector<int>;
TEST(xcoordinate, constructor)
{
auto c1 = make_test_coordinate();
using map_type = typename std::decay_t<decltype(c1)>::map_type;
map_type m;
m["abscissa"] = make_test_saxis();
m["ordinate"] = make_test_iaxis();
auto c2 = coordinate(m);
auto c3 = coordinate(std::move(m));
EXPECT_EQ(c1, c2);
EXPECT_EQ(c1, c3);
EXPECT_FALSE(c1 != c2);
decltype(c1) c4 = {{ fstring("abscissa"), make_test_saxis() }, { fstring("ordinate"), make_test_iaxis() }};
EXPECT_EQ(c1, c4);
decltype(c1) c5 = {{"abscissa", make_test_saxis()}, {"ordinate", make_test_iaxis()}};
EXPECT_EQ(c1, c5);
auto c6 = coordinate({{"abscissa", make_test_saxis()}, {"ordinate", make_test_iaxis() }});
EXPECT_EQ(c1, c6);
}
TEST(xcoordinate, size)
{
auto c1 = make_test_coordinate();
EXPECT_EQ(2u, c1.size());
EXPECT_FALSE(c1.empty());
decltype(c1) c2;
EXPECT_EQ(0u, c2.size());
EXPECT_TRUE(c2.empty());
}
TEST(xcoordinate, contains)
{
auto c = make_test_coordinate();
EXPECT_TRUE(c.contains("abscissa"));
EXPECT_FALSE(c.contains("humidity"));
}
TEST(xcoordinate, access)
{
auto c = make_test_coordinate();
EXPECT_EQ(c["abscissa"]["a"], 0u);
EXPECT_EQ(c["abscissa"]["c"], 1u);
EXPECT_EQ(c["abscissa"]["d"], 2u);
EXPECT_EQ(c["ordinate"][1], 0u);
EXPECT_EQ(c["ordinate"][2], 1u);
EXPECT_EQ(c["ordinate"][4], 2u);
EXPECT_EQ(c[std::make_pair("abscissa", fstring("a"))], 0u);
EXPECT_EQ(c[std::make_pair("abscissa", fstring("c"))], 1u);
EXPECT_EQ(c[std::make_pair("abscissa", fstring("d"))], 2u);
EXPECT_EQ(c[std::make_pair("ordinate", 1)], 0u);
EXPECT_EQ(c[std::make_pair("ordinate", 2)], 1u);
EXPECT_EQ(c[std::make_pair("ordinate", 4)], 2u);
}
TEST(xcoordinate, iterator)
{
auto c = make_test_coordinate();
auto iter = c.begin();
EXPECT_EQ((iter->second)["d"], 2u);
++iter;
EXPECT_EQ((iter->second)[2], 1u);
++iter;
EXPECT_EQ(iter, c.end());
}
TEST(xcoordinate, find)
{
auto c = make_test_coordinate();
auto iter = c.find("abscissa");
EXPECT_EQ((iter->second)["d"], 2u);
auto iter2 = c.find("not_here");
EXPECT_EQ(iter2, c.end());
}
TEST(xcoordinate, key_iterator)
{
auto c = make_test_coordinate();
auto iter = c.key_begin();
EXPECT_EQ(*iter, "abscissa");
++iter;
EXPECT_EQ(*iter, "ordinate");
++iter;
EXPECT_EQ(iter, c.key_end());
}
TEST(xcoordinate, merge)
{
auto coord_res = make_merge_coordinate();
auto c1 = make_test_coordinate();
decltype(c1) cres1;
auto res1 = broadcast_coordinates<join::outer>(cres1, c1, c1);
EXPECT_TRUE(res1.m_same_dimensions);
EXPECT_TRUE(res1.m_same_labels);
EXPECT_EQ(c1, cres1);
auto c2 = make_test_coordinate3();
decltype(c2) cres2;
auto res2 = broadcast_coordinates<join::outer>(cres2, c1, c2);
EXPECT_FALSE(res2.m_same_dimensions);
EXPECT_FALSE(res2.m_same_labels);
EXPECT_EQ(cres2, coord_res);
}
TEST(xcoordinate, merge_axis_default)
{
auto coord_res = make_merge_coordinate2();
auto c1 = make_test_coordinate3();
auto c2 = make_test_coordinate4();
decltype(c1) cres1;
broadcast_coordinates<join::outer>(cres1, c1, c2);
EXPECT_EQ(cres1, coord_res);
decltype(c1) cres2;
broadcast_coordinates<join::outer>(cres2, c2, c1);
EXPECT_EQ(cres1, cres2);
}
TEST(xcoordinate, intersect)
{
auto c1 = make_test_coordinate();
auto c2 = make_test_coordinate3();
auto coord_res = make_intersect_coordinate();
auto cres = c1;
auto res = broadcast_coordinates<join::inner>(cres, c2);
EXPECT_FALSE(res.m_same_dimensions);
EXPECT_FALSE(res.m_same_labels);
EXPECT_EQ(cres, coord_res);
}
TEST(xcoordinate, intersect_axis_default)
{
auto c1 = make_test_coordinate3();
auto c2 = make_test_coordinate4();
auto coord_res = make_intersect_coordinate2();
decltype(c1) cres1;
broadcast_coordinates<join::inner>(cres1, c1, c2);
EXPECT_EQ(cres1, coord_res);
decltype(c1) cres2;
broadcast_coordinates<join::inner>(cres2, c2, c1);
EXPECT_EQ(cres2, coord_res);
}
}
| 31.603448 | 115 | 0.544099 | [
"vector"
] |
746a63b45f2f2b47ba648f7f79cfa1d23b2c3f61 | 7,405 | cpp | C++ | src/lib/ZControl.cpp | otrojota/ZScreens | c1f47cbcd063f2cd31f9fb7c595d64b829798e11 | [
"MIT"
] | null | null | null | src/lib/ZControl.cpp | otrojota/ZScreens | c1f47cbcd063f2cd31f9fb7c595d64b829798e11 | [
"MIT"
] | null | null | null | src/lib/ZControl.cpp | otrojota/ZScreens | c1f47cbcd063f2cd31f9fb7c595d64b829798e11 | [
"MIT"
] | null | null | null | #include "ZControl.h"
#include "ZCompoundControl.h"
#include "ZApp.h"
ZLinkedList *ZControl::factoriesLL() {
static ZLinkedList *ll = new ZLinkedList();
return ll;
}
int ZControl::registerFactory(const char *type, ZControlFactory factory) {
ZControlFactoryDeclaration *data = new ZControlFactoryDeclaration();
data->controlType = type;
data->factory = factory;
factoriesLL()->add(data);
}
void ZControl::showFactories() {
if (!factoriesLL()->length()) {
Serial.println("No ZControls Factories");
} else {
Serial.println("ZControl Factories:");
for (int i=0; i<factoriesLL()->length(); i++) {
ZControlFactoryDeclaration *data = (ZControlFactoryDeclaration *)factoriesLL()->get(i);
Serial.print(" -- "); Serial.println(data->controlType);
}
}
}
ZControl *ZControl::create(const char *id, JsonObject def) {
const char *type = def["type"];
int i = 0, n = factoriesLL()->length();
ZControlFactoryDeclaration *found = NULL;
while (i < n) {
ZControlFactoryDeclaration *data = (ZControlFactoryDeclaration *)factoriesLL()->get(i);
if (!strcmp(data->controlType, type)) {
found = data;
break;
}
i++;
}
if (!found) {
Serial.print("ZControl type '"); Serial.print(type); Serial.println("' Not found");
while(1) sleep(100);
}
return (found->factory)(id, def);
}
void ZControl::parseFontUsage(JsonObject def, const char *jsonAttributeName, ZFontUsage &fontUsage) {
fontUsage.name[0] = 0;
fontUsage.number = -1;
fontUsage.textSize = 1;
fontUsage.isValid = false;
if (!def.containsKey(jsonAttributeName)) return;
JsonObject fDef = def[jsonAttributeName];
if (fDef.containsKey("name")) {strcpy(fontUsage.name, (const char *)fDef["name"]); fontUsage.isValid = true;}
else if (fDef.containsKey("number")) {fontUsage.number = fDef["number"]; fontUsage.isValid = true;}
else {
Serial.println("Invalid font usage. Expected name or number in object");
while(1) sleep(100);
}
if (fDef.containsKey("size")) fontUsage.textSize = fDef["size"];
}
int ZControl::parseTextAlign(const char *ta) {
if (!strcmp(ta, "TL")) return TL_DATUM;
if (!strcmp(ta, "TC")) return TC_DATUM;
if (!strcmp(ta, "TR")) return TR_DATUM;
if (!strcmp(ta, "ML")) return ML_DATUM;
if (!strcmp(ta, "CL")) return CL_DATUM;
if (!strcmp(ta, "MC")) return MC_DATUM;
if (!strcmp(ta, "CC")) return CC_DATUM;
if (!strcmp(ta, "MR")) return MR_DATUM;
if (!strcmp(ta, "CR")) return CR_DATUM;
if (!strcmp(ta, "BL")) return BL_DATUM;
if (!strcmp(ta, "BC")) return BC_DATUM;
if (!strcmp(ta, "BR")) return TR_DATUM;
Serial.println("Invalid textAlign");
while(1) sleep(100);
}
ZControl::ZControl(const char *_id, int _x, int _y, int _w, int _h) {
strcpy(id, _id);
x = _x; y = _y; w = _w; h = _h;
valid = false;
visible = true;
container = NULL;
theme = NULL;
tindex = -1;
}
ZControl::ZControl(const char *_id, JsonObject def):ZControl(_id, (int)def["pos"][0], (int)def["pos"][1], (int)def["pos"][2], (int)def["pos"][3]) {
if (def.containsKey("theme")) theme = def["theme"];
if (def.containsKey("tindex")) tindex = def["tindex"];
}
void ZControl::init(ZApp *_app, ZCompoundControl *_container) {
app = _app;
container = _container;
}
// Todo: Add container scrolling (xOffset, yOffset) and some other (future) transformations
int ZControl::zx() {return x;}
int ZControl::zy() {return y;}
int ZControl::zw() {return w;}
int ZControl::zh() {return h;}
int ZControl::zAbsX() {return container?container->zAbsX() + zx():zx();}
int ZControl::zAbsY() {return container?container->zAbsY() + zy():zy();}
void ZControl::draw() {
valid = true;
}
bool ZControl::isValid() {return valid;}
bool ZControl::isFinal() {return true;}
bool ZControl::isModified() {return !isValid();}
void ZControl::invalidate() {
valid = false;
if (container) container->setModified();
}
ZScreen *ZControl::getScreen() {
ZControl *c = this;
while(c->container) c = c->container;
return (ZScreen *)c;
}
ZTheme ZControl::getTheme() {
if (theme) return ZApp::getTheme(theme);
if (container) return container->getTheme();
return app->theme;
}
ZControl *ZControl::getControl(char *_id) {
if (!strcmp(_id, id)) return this;
return NULL;
}
void ZControl::clear() {
app->tft->fillRect(zx(), zy(), zw(), zh(), getTheme().mainBackground);
}
ZControlType ZControl::getControlTypeFromStyleName(char *styleNMame) {
if (!strcmp("primary", styleNMame)) return Z_PRIMARY;
if (!strcmp("secondary", styleNMame)) return Z_SECONDARY;
if (!strcmp("success", styleNMame)) return Z_SUCCESS;
if (!strcmp("danger", styleNMame)) return Z_DANGER;
if (!strcmp("warning", styleNMame)) return Z_WARNING;
if (!strcmp("info", styleNMame)) return Z_INFO;
if (!strcmp("light", styleNMame)) return Z_LIGHT;
if (!strcmp("dark", styleNMame)) return Z_DARK;
return Z_ERROR;
}
ZColorScheme ZControl::getColorSchemeForType(enum ZControlType type) {
int bk, fg, bd;
ZTheme theme = getTheme();
switch(type) {
case Z_PRIMARY:
return {.background = theme.primaryBackground, .foreground = theme.primaryForeground, .border = theme.primaryBorder};
case Z_SECONDARY:
return {.background = theme.secondaryBackground, .foreground = theme.secondaryForeground, .border = theme.secondaryBorder};
break;
case Z_SUCCESS:
return {.background = theme.successBackground, .foreground = theme.successForeground, .border = theme.successBorder};
break;
case Z_DANGER:
return {.background = theme.dangerBackground, .foreground = theme.dangerForeground, .border = theme.dangerBorder};
break;
case Z_WARNING:
return {.background = theme.warningBackground, .foreground = theme.warningForeground, .border = theme.warningBorder};
break;
case Z_INFO:
return {.background = theme.infoBackground, .foreground = theme.infoForeground, .border = theme.infoBorder};
break;
case Z_LIGHT:
return {.background = theme.lightBackground, .foreground = theme.lightForeground, .border = theme.lightBorder};
break;
case Z_DARK:
return {.background = theme.darkBackground, .foreground = theme.darkForeground, .border = theme.darkBorder};
break;
}
}
ZControl *ZControl::getControlAt(int x, int y) {
if (x >= this->zAbsX() && x <= (this->zAbsX() + this->zw()) && y >= this->zAbsY() && y <= (this->zAbsY() + this->zh())) return this;
return NULL;
}
bool ZControl::triggerEvent(const char *eventName, ZEventData eventData) {
return container->triggerEvent(this, eventName, eventData);
}
void ZControl::touchDown(int x, int y) {}
void ZControl::touchUp(int x, int y) {}
void ZControl::touchStartMove(int x, int y) {}
void ZControl::touchMove(int x0, int y0, int x, int y) {}
void ZControl::touchEndMove(int x0, int y0, int x, int y) {}
void ZControl::show() {visible = true; invalidate();}
void ZControl::hide() {visible = false; invalidate();}
void ZControl::setVisible(bool v) {visible = v; invalidate();}
bool ZControl::isVisible() {return visible;}
bool ZControl::isFocusable() {return tindex >0 && visible;}
bool ZControl::hasFocus() {return container && tindex > 0 && container->activeTindex == tindex;}
void ZControl::tabInfo(bool left, bool ok, bool right) {
if (left && container) container->doTabLeft();
if (right && container) container->doTabRight();
} | 36.840796 | 147 | 0.673329 | [
"object"
] |
746a7568c4875bf00fdec9363f46bae6c67dcd7a | 4,528 | hpp | C++ | ad_map_access/impl/include/ad/map/access/Operation.hpp | seowwj/map | 2afacd50e1b732395c64b1884ccfaeeca0040ee7 | [
"MIT"
] | null | null | null | ad_map_access/impl/include/ad/map/access/Operation.hpp | seowwj/map | 2afacd50e1b732395c64b1884ccfaeeca0040ee7 | [
"MIT"
] | null | null | null | ad_map_access/impl/include/ad/map/access/Operation.hpp | seowwj/map | 2afacd50e1b732395c64b1884ccfaeeca0040ee7 | [
"MIT"
] | 1 | 2020-10-27T11:09:30.000Z | 2020-10-27T11:09:30.000Z | // ----------------- BEGIN LICENSE BLOCK ---------------------------------
//
// Copyright (C) 2018-2020 Intel Corporation
//
// SPDX-License-Identifier: MIT
//
// ----------------- END LICENSE BLOCK -----------------------------------
#pragma once
#include <memory>
#include "ad/map/access/MapMetaDataValidInputRange.hpp"
#include "ad/map/access/Store.hpp"
#include "ad/map/config/PointOfInterest.hpp"
#include "ad/map/intersection/IntersectionType.hpp"
#include "ad/map/lane/Types.hpp"
#include "ad/map/route/Types.hpp"
/** @brief namespace ad */
namespace ad {
/** @brief namespace map */
namespace map {
namespace point {
class CoordinateTransform;
} // namespace point
/** @brief namespace access */
namespace access {
/**
* @brief checks if the given MapMetaData is valid
*
* The metaData is valid if it's within valid input range.
*/
inline bool isValid(MapMetaData const &metaData, bool const logErrors = true)
{
bool isValidInputRange = withinValidInputRange(metaData, logErrors) && (metaData.trafficType != TrafficType::INVALID);
if (!isValidInputRange && logErrors)
{
spdlog::error("withinValidInputRange(::ad::map::access::MapMetaData)>> {} not valid", metaData);
}
return isValidInputRange;
}
/**
* @brief get the coordinate transformation object
*/
std::shared_ptr<point::CoordinateTransform> getCoordinateTransform();
/**
* @brief initialize singleton with given configuration file
*
* The configuration file specifies all available maps, see ConfigFileHandler for details of the semantics
* @return true if initialization was successful (i.e. config file exists or singleton was already initialized)
* @return false if config file doesn't exist or the singleton was already initialized with a different config file
*/
bool init(std::string const &configFileName);
/**
* @brief initialize singleton with OpenDRIVE content
*
* @return true if initialization was successful (i.e. map content was valid or singleton was already initialized)
* @return false if map content was invalid or the singleton was already initialized with a different config file
*/
bool initFromOpenDriveContent(std::string const &openDriveContent,
double const overlapMargin,
intersection::IntersectionType const defaultIntersectionType,
landmark::TrafficLightType const defaultTrafficLightType
= landmark::TrafficLightType::SOLID_RED_YELLOW_GREEN);
/**
* @brief initialize singleton with given store
*
* No map files will be read. The store has to be filled by other means.
*/
bool init(Store::Ptr store);
/**
* @brief remove all loaded maps and configuration
*/
void cleanup();
/**
* @brief set the current ENU reference point
*
* @param[in] point the geo point defining the reference point
*/
void setENUReferencePoint(point::GeoPoint const &point);
/**
* @brief get the current ENU reference point set in the map
*
* @returns Set ENU reference point in Geo coordinates
*/
point::GeoPoint getENUReferencePoint();
/**
* @brief check if ENU Reference Point is set
*/
bool isENUReferencePointSet();
/**
* @brief get points of interest in the surrounding of a given geoPoint
*
* @param[in] geoPoint GeoPoint to be used to query the POIs
* @param[in] radius radius to be use for the query
*
* @returns the list with the PointOfInterest within the queried region.
*/
std::vector<config::PointOfInterest> getPointsOfInterest(point::GeoPoint const &geoPoint,
physics::Distance const &radius);
/**
* @brief get all points of interest
*
* @returns the complete list of PointOfInterest currently available
*/
std::vector<config::PointOfInterest> const &getPointsOfInterest();
/**
* @brief get a certain point of interest if exists
*
* Calls getPointsOfInterest() and searches for the point with the given name.
*
* @param[in] name the name of the POI to query
* @param[out] poi the found PointOfInterest
*
* @returns \c true if the PointOfInterest with the given \a name if exits
*/
bool getPointOfInterest(std::string const &name, config::PointOfInterest &poi);
/**
* @returns \c true if the map is a left hand traffic map
*/
bool isLeftHandedTraffic();
/**
* @returns \c true if the map is a left hand traffic map
*/
bool isRightHandedTraffic();
/**
* @returns reference to the map store object
*/
Store &getStore();
} // namespace access
} // namespace map
} // namespace ad
| 30.186667 | 120 | 0.696334 | [
"object",
"vector"
] |
746cbb7cc331104cae2ca32fa4bfafad70d65450 | 10,099 | hpp | C++ | src/parser/parser.hpp | alohaeee/-orrosion | 7529cf9fb2d15f4d67a45013bd90760bc9c8f579 | [
"MIT"
] | null | null | null | src/parser/parser.hpp | alohaeee/-orrosion | 7529cf9fb2d15f4d67a45013bd90760bc9c8f579 | [
"MIT"
] | null | null | null | src/parser/parser.hpp | alohaeee/-orrosion | 7529cf9fb2d15f4d67a45013bd90760bc9c8f579 | [
"MIT"
] | null | null | null | #ifndef CORROSION_SRC_PARSER_PARSER_HPP_
#define CORROSION_SRC_PARSER_PARSER_HPP_
#include "utility/std_incl.hpp"
#include "ast/ast.hpp"
#include "ast/assoc_prec.hpp"
#include "parse_session.hpp"
#include "token_stream.hpp"
#include "ast/token_tree.hpp"
using namespace corrosion::ast;
namespace corrosion
{
enum Restriction
{
NO_RESTRICT = 0,
STMT_EXPR = 1 << 0,
NO_STRUCT_LITERAL = 1 << 1
};
struct TokenCursorFrame
{
ast::data::Delim delim;
DelimSpan span;
bool openDelim;
TreeCursor cursor;
bool closeDelim;
TokenCursorFrame(data::Delim delim, DelimSpan&& span, TreeCursor&& stream) : openDelim{ delim.isEmpty() },
closeDelim{ delim.isEmpty() },
delim{ delim },
span{ span },
cursor{ stream }
{
}
};
struct TokenCursor
{
TokenCursor(TokenCursorFrame&& frame) : frame{ frame }
{
}
Token next()
{
while (true)
{
TreeAndJoint tree{ Token{}, IsJoint::NotJoint };
if (!this->frame.openDelim)
{
this->frame.openDelim = true;
tree = { TokenTree::openTT(this->frame.span, this->frame.delim), IsJoint::NotJoint };
}
else if (auto next_tree = this->frame.cursor.nextWithJoint();next_tree)
{
tree = next_tree.value();
}
else if (!this->frame.closeDelim)
{
this->frame.closeDelim = true;
tree = { TokenTree::closeTT(this->frame.span, this->frame.delim), IsJoint::NotJoint };
}
else if (stack.size())
{
this->frame = this->stack.back();
this->stack.pop_back();
continue;
}
else
{
return Token{ TokenKind::Eof };
}
if (tree.first.isToken())
{
return tree.first.getToken();
}
else
{
auto delim = tree.first.getDelimited();
this->stack.push_back(this->frame);
this->frame = TokenCursorFrame{ delim.kind, std::move(delim.span),
std::move(delim.stream) };
}
}
}
TokenCursorFrame frame;
std::vector<TokenCursorFrame> stack{};
};
class Parser
{
private:
Token nextToken()
{
return tokenCursor.next();
}
public:
Parser(std::shared_ptr<ParseSession>& sess, TokenStream&& stream) : session(sess),
tokenCursor(TokenCursorFrame{
data::Delim{ data::Delim::NoDelim },
DelimSpan::Dummy(), std::move(stream) })
{
shift();
}
void shiftWith(Token&& nextTok)
{
if (this->prevToken.kind == TokenKind::Eof)
{
this->session->criticalSpan(nextTok.span,
"attempted to bump the parser past EOF (may be stuck in a loop)");
}
this->prevToken = std::move(this->token);
this->token = nextTok;
CR_DEBUG_LOG_TRACE("token:{}", token.printable());
this->expectedTokens.clear();
}
void shift()
{
auto next_tok = nextToken();
shiftWith(std::move(next_tok));
}
/// Checks if the next token is `tok`, and returns `true` if so.
///
/// This method will automatically add `tok` to `expected_tokens` if `tok` is not
/// encountered.
bool check(TokenKind kind, TokenData&& data = data::Empty{})
{
auto is_present = this->token.kind == kind && this->token.data == data;
if (!is_present)
{
this->expectedTokens.emplace_back(kind, data);
}
return is_present;
}
bool checkOrExpected(bool ok, TokenKind kind, const TokenData& data = data::Empty{})
{
if (ok)
{
return true;
}
expectedTokens.emplace_back(kind, data);
return false;
}
bool checkPath()
{
return checkOrExpected(token.isPathStart(), token.kind, token.data);
}
bool checkKeyword(SymType sym)
{
return token.isKeyword(sym);
}
/// Consumes a token 'tok' if it exists. Returns whether the given token was present.
bool eat(TokenKind kind, TokenData&& data = data::Empty{})
{
auto is_present = check(kind, std::move(data));
if (is_present)
{
this->shift();
}
return is_present;
}
bool eatKeyword(SymType sym)
{
if (this->checkKeyword(sym))
{
this->shift();
return true;
}
return false;
}
std::optional<Label> eatLabel()
{
if (auto ident = token.lifetime();ident)
{
this->shift();
return Label{ ident.value() };
}
return std::nullopt;
}
Token lookahead(std::size_t n)
{
auto tree = tokenCursor.frame.cursor.lookahead(n);
if (tree)
{
if (tree->first.isToken())
{
return tree->first.getToken();
}
else
{
auto delim = tree->first.getDelimited();
return Token{ TokenKind::OpenDelim, delim.span.close, delim.kind };
}
}
return Token{ TokenKind::CloseDelim, tokenCursor.frame.span.close, tokenCursor.frame.delim };
}
/// Is the given keyword `kw` followed by a non-reserved identifier?
bool isKwFollowedByIdent(SymType kw)
{
return token.isKeyword(kw) && !lookahead(1).isKeyword();
}
Mutability parseMutability()
{
if (eatKeyword(kw::Mut))
{
return Mutability::Mut;
}
return Mutability::Not;
}
Ident parseIdent()
{
if (token.isIdent())
{
auto ident = Ident{ token.getData<data::Ident>().symbol, token.span };
this->shift();
return ident;
}
session->criticalSpan(token.span, "trying to eat ident, but find: ");
return Ident{};
}
Const parseConstness()
{
if(eatKeyword(kw::Const))
{
return Const{prevToken.span,Const::Yes};
}
else
{
return Const{std::nullopt, Const::No};
}
};
void expect(TokenKind kind, TokenData&& data = data::Empty{})
{
if (check(kind,std::move(data)))
{
this->shift();
return;
}
if (expectedTokens.size() == 1)
{
Span span = token.span;
if (token.kind == TokenKind::Eof)
{
span = prevToken.span;
}
session->criticalSpan(span,
fmt::format("expected token: {}", Token{ kind, {}, data }.printable()));
}
else
{
std::string msg;
for (auto &&[kind, data]: expectedTokens)
{
msg += (fmt::format("'{}' or ", Token{ kind, {}, data }.printable()));
}
msg.pop_back();
msg.pop_back();
msg.pop_back();
session->criticalSpan(token.span, fmt::format("expected: {}", msg));
}
}
template<typename Re>
Re withRes(Restriction res, std::function<Re(Parser&)> func)
{
auto old = this->restrictions;
this->restrictions = res;
auto result = std::invoke(func, *this);
this->restrictions = old;
return result;
}
template<typename Re>
Re withRes(Restriction res, std::function<Re()> func)
{
auto old = this->restrictions;
this->restrictions = res;
auto result = std::invoke(func);
this->restrictions = old;
return result;
}
inline void printAst(std::vector<Stmt>& stmts)
{
#ifdef CR_ENABLE_LOG_AST
CR_LOG_AST("![AST in file: {}]", session->file().path().string());
for(auto&stmt: stmts)
{
stmt.printer(0);
}
Log::getAstLogger()->flush();
#endif
}
/* EXPR */
bool exprIsComplete(Pointer<Expr>& e);
Pointer<Expr> parseExpr();
inline Pointer<Expr> parseExprRes(Restriction res);
inline Pointer<Expr> parseAssocExpr();
Pointer<Expr> parseAssocExprWith(std::size_t minPrec, Pointer<Expr> lhs);
bool shouldContinueAsAssocExpr(Pointer<Expr>& e);
std::optional<AssocOp> checkAssocOp();
Pointer<Expr> parsePrefixRangeExpr();
Pointer<Expr> parsePrefixExpr();
Pointer<Expr> parseDotOrCallExpr();
Pointer<Expr> parseDotOrCallExprWith(Pointer<Expr>& e, Span lo);
Pointer<Expr> parseBottomExpr();
Spanned<Pointer<Expr>> parsePrefixExprCommon(Span lo);
Pointer<Expr> parseUnaryExpr(Span lo, UnOpKind op);
Pointer<Expr> parseLitExpr();
Pointer<Expr> parseLitMaybeMinus();
Pointer<Expr> parseCondExpr();
Pointer<Expr> parseWhileExpr(std::optional<Label> optLabel, Span lo);
Pointer<Expr> parseLoopExpr(std::optional<Label> optLabel, Span lo);
Pointer<Expr> parseTupleParensExpr();
Pointer<Expr> parseBlockExpr(std::optional<Label> optLabel, Span lo);
Pointer<Expr> parseArrayOrRepeatExpr();
Pointer<Expr> parseStartPathExpr();
Pointer<Expr> parseReturnExpr();
Pointer<Expr> parseBreakExpr();
Pointer<Expr> parseForExpr(std::optional<Label> optLabel, Span lo);
Pointer<Expr> parseIfExpr();
Pointer<Expr> parseElseExpr();
Pointer<Expr> parseLabeledExpr(Label label);
Pointer<Expr> parseFnCallExpr(Pointer<Expr>& e, Span lo);
Pointer<Expr> parseIndexExpr(Pointer<Expr>& e, Span lo);
AnonConst parseAnonConstExpr();
/* STMT */
Pointer<Block> parseBlockCommon();
std::optional<Stmt> parseStmtWithoutRecovery();
Pointer<Local> parseLocal();
std::optional<Stmt> parseFullStmt();
/* PATTERNS */
inline Pointer<Pat> parsePat();
Pointer<Pat> parseTopPat(bool gateOr);
Pointer<Pat> parsePatWithOr(bool gateOr);
Pointer<Pat> parsePatWithRangePat(bool allowRangePat);
PatKind::Ref parsePatDeref();
PatKind::Paren parsePatParen();
PatKind::Ident parsePatIdentRef();
PatKind::Ident parsePatIdent(BindingMode bindingMode);
Pointer<Pat> parseFnParamPat();
/* Types */
Pointer<Ty> parseTy();
Ty::KindUnion parseArrayTy();
Pointer<Ty> parseRetTy();
/* Items */
Pointer<Item> parseItemCommon();
std::tuple<Ident,Pointer<Ty>, Pointer<Expr>> parseItemGlobal(std::optional<Mutability> m);
std::optional<ItemInfo> parseItemKind(Span lo);
bool checkFnFrontMatter();
std::tuple<Ident,FnSig,Generics,Pointer<Block>> parseFn();
Pointer<FnDecl> parseFnDecl();
std::vector<Param> parseFnParams();
Param parseParamGeneral(bool firstParam);
std::optional<Param> parseSelfParam();
Pointer<Block> parseFnBody();
/* Path */
Path parsePath();
void parsePathSegments(std::vector<PathSegment>& segments);
Ident parsePathSegmentIdent();
//diagnistics
bool checkNoChainedComparison(Pointer<Expr> innerOp, Spanned<AssocOp>&& outerOp);
std::shared_ptr<ParseSession> session;
/// The current token.
Token token{};
/// The previous token.
Token prevToken{};
std::vector<std::pair<TokenKind, TokenData>> expectedTokens{};
TokenCursor tokenCursor;
Restriction restrictions = NO_RESTRICT;
//Item root;
};
}
#endif //CORROSION_SRC_PARSER_PARSER_HPP_
| 25.310777 | 108 | 0.65155 | [
"vector"
] |
7471d702894a39818e337d4d482ddfcb1b8fb2c1 | 3,519 | cpp | C++ | 517-gq1C.cpp | AndrewWayne/OI_Learning | 0fe8580066704c8d120a131f6186fd7985924dd4 | [
"MIT"
] | null | null | null | 517-gq1C.cpp | AndrewWayne/OI_Learning | 0fe8580066704c8d120a131f6186fd7985924dd4 | [
"MIT"
] | null | null | null | 517-gq1C.cpp | AndrewWayne/OI_Learning | 0fe8580066704c8d120a131f6186fd7985924dd4 | [
"MIT"
] | null | null | null | /*
* Author: xiaohei_AWM
* Date: 10.2
* Motto: Face to the weakness, expect for the strength.
*/
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<ctime>
#include<utility>
#include<functional>
#include<cmath>
#include<vector>
#include<assert.h>
using namespace std;
#define reg register
#define endfile fclose(stdin);fclose(stdout);
typedef long long ll;
typedef unsigned long long ull;
typedef double db;
typedef std::pair<int,int> pii;
typedef std::pair<ll,ll> pll;
namespace IO{
char buf[1<<15],*S,*T;
inline char gc(){
if (S==T){
T=(S=buf)+fread(buf,1,1<<15,stdin);
if (S==T)return EOF;
}
return *S++;
}
inline int read(){
reg int x;reg bool f;reg char c;
for(f=0;(c=gc())<'0'||c>'9';f=c=='-');
for(x=c^'0';(c=gc())>='0'&&c<='9';x=(x<<3)+(x<<1)+(c^'0'));
return f?-x:x;
}
inline ll readll(){
reg ll x;reg bool f;reg char c;
for(f=0;(c=gc())<'0'||c>'9';f=c=='-');
for(x=c^'0';(c=gc())>='0'&&c<='9';x=(x<<3)+(x<<1)+(c^'0'));
return f?-x:x;
}
}
using namespace IO;
const long long llINF = 9223372036854775807;
const int INF = 2147483647;
const int maxn = 52;
const int MOD = 1e9 + 7;
int n, p, c[maxn];
int f[maxn][maxn][maxn];// f[i][ob][ow]表示取了i个点,ob个奇方案数黑点,ow个奇方案数白点
ll power_two[maxn];
ll Mod(int x){
while(x >= MOD) x -= MOD;
return x;
}
int main(){
n = read(), p = read();
for(int i = 1; i <= n; i++) c[i] = read();
power_two[0] = 1;
for(int i = 1; i <= 50; i++) power_two[i] = ((ll)power_two[i-1] * 2)% MOD;
if(c[1] == 1 || c[1] == -1) f[1][1][0] = 1;//一开始可以染一个黑点,只有一个点,一定是奇数点
if(c[1] == 0 || c[1] == -1) f[1][0][1] = 1;//一开始可以染一个白点
for(int i = 2; i <= n; i++){
for(int ob = 0; ob <= i; ob++){
for(int ow = 0; ow <= i; ow++){//枚举目标状态
if(ob + ow > i) break;
int e = i - ow - ob;//偶点数量
if(ob > 0){//可以染奇黑点/偶白点
ll val = 0;
if(c[i] == 1 || c[i] == -1){
if(ow > 0) val = power_two[ow-1];
else val = 1;//必须有偶数个奇白连过去,当奇数白为零,就自力更生唯一
val = ((val * f[i-1][ob-1][ow]) % MOD * power_two[i - ow - 1]) % MOD;
}
if(e > 0 && (c[i] == -1 || c[i] == 0))
val += (power_two[ob-1] * f[i-1][ob][ow]) % MOD * power_two[i - ob - 1] % MOD;
val %= MOD;
f[i][ob][ow] = (val + f[i][ob][ow]) % MOD;
}
if(ow > 0){//可以染偶黑/奇白
ll val = 0;
if(c[i] == 0 || c[i] == -1){
if(ob > 0) val = power_two[ob - 1];
else val = 1;
val = ((val * f[i-1][ob][ow-1]) % MOD * power_two[i - ob - 1]) % MOD;
}
if(e > 0 && (c[i] == 1 || c[i] == -1))
val += (power_two[ow-1] * f[i-1][ob][ow]) % MOD * power_two[i - ow - 1] % MOD;
val %= MOD;
f[i][ob][ow] = (val + f[i][ob][ow]) % MOD;
}
}
}
}
int ans = 0;//统计答案
for(int j = 0; j <= n; j++)
for(int k = 0; k <= n; k++){
if(j + k > n) break;
if(((j+k) & 1) == p){
ans = Mod(ans + f[n][j][k]);
}
}
printf("%d\n", ans);
return 0;
}
| 31.990909 | 102 | 0.418301 | [
"vector"
] |
7472cbb9b25f10786cef4ba52b1f9c0c2b95eafd | 5,530 | cpp | C++ | DemoDevice/src/AY_DemoDev.cpp | aykutkes2/P1001 | 93a425f55cac89b107377a8fe9263a858c497ba4 | [
"BSD-2-Clause"
] | null | null | null | DemoDevice/src/AY_DemoDev.cpp | aykutkes2/P1001 | 93a425f55cac89b107377a8fe9263a858c497ba4 | [
"BSD-2-Clause"
] | null | null | null | DemoDevice/src/AY_DemoDev.cpp | aykutkes2/P1001 | 93a425f55cac89b107377a8fe9263a858c497ba4 | [
"BSD-2-Clause"
] | null | null | null | //#include "pch.h"
#undef UNICODE
#include <stdio.h>
#include <time.h>
//#include <windows.h>
#include <AY_Memory.h>
#include <AY_DemoDev.h>
AY_DEVINFO DevLevel1[4096];
AY_DEVINFO DevRemote[256];
Ui16 DevRemoteTOut[256];
AY_DEVINFO **pDevInfos[15];///< total 4096 * (15+1) = 65536 devices supported
/*
*
*/
int AY_Demo_RemoteDevTimeoutTest(void) {
int i;
for (i = 0; i < 256; i++) {
if (DevRemoteTOut[i]) {
DevRemoteTOut[i] --;
if (DevRemoteTOut[i] == 0) {
DevRemote[i].DevF.Full_ = 0;
}
}
}
return 1;
}
/*
*
*/
int AY_Demo_UpdateDevInfo(AY_DEVINFO *pDeInf, Ui08 *pComp, Ui08 Comp) {
switch (Comp) {
case _DEVINFOALL:
*pDeInf = *((AY_DEVINFO *)pComp);
pDeInf->DevF.Full_ = 1;
printf("AYDEV--> _DEVINFOALL \n");
break;
case _DEV_FLG:
pDeInf->DevF = *((AY_DEVFLAGs *)pComp);
pDeInf->DevF.Full_ = 1;
printf("AYDEV--> _DEV_FLG \n");
break;
case _DEV_UDPH:
pDeInf->UDP_Hdr = *((udp_headerAll *)pComp);
pDeInf->DevF.Full_ = 1;
printf("AYDEV--> _DEV_UDPH \n");
break;
case _DEV_SSK:
memcpy(&pDeInf->Sessionkey[0], ((Ui08 *)pComp), 16);
pDeInf->DevF.Full_ = 1;
printf("AYDEV--> _DEV_SSK \n");
break;
case _DEV_READ:
pDeInf->DevRead = *((AY_DeviceRead *)pComp);
pDeInf->DevF.Full_ = 1;
printf("AYDEV--> _DEV_READ \n");
break;
case _DEV_READ_ALL:
memset(pDeInf, 0, sizeof(AY_DEVINFO));
pDeInf->DevRead = *((AY_DeviceRead *)pComp);
pDeInf->DevF.Full_ = 1;
printf("AYDEV--> _DEV_READ_ALL \n");
break;
case _DEV_SNDCNT:
pDeInf->SendCnt = *((Ui32 *)pComp);
pDeInf->DevF.Full_ = 1;
printf("AYDEV--> _DEV_SNDCNT \n");
break;
case _DEV_RDCNT:
pDeInf->ReadCnt = *((Ui32 *)pComp);
pDeInf->DevF.Full_ = 1;
printf("AYDEV--> _DEV_RDCNT \n");
break;
case _DEV_ERRCNT:
pDeInf->ErrCnt = *((Ui32 *)pComp);
pDeInf->DevF.Full_ = 1;
printf("AYDEV--> _DEV_ERRCNT \n");
break;
case _DEV_DELCNTS:
pDeInf->SendCnt = 0;
pDeInf->ReadCnt = 0;
pDeInf->ErrCnt = 0;
pDeInf->DevF.Full_ = 1;
printf("AYDEV--> _DEV_DELCNTS \n");
break;
case _DEV_DELETE:
memset(pDeInf, 0, sizeof(AY_DEVINFO));
break;
default:
printf("AYDEV--> Undefined Object \n");
break;
};
return 1;
}
/*
*
*/
int AY_Demo_AddDevToList(Ui08 *pComp, Ui32 DevNo, Ui08 Comp) {
Ui32 i;
Ui16 j,k;
AY_DEVINFO *pDeInf;
//=======================================================================================================//
if ((DevNo & 0xFFFFFF) > 65535) {
return -1;
}
else if ((DevNo & 0xFF000000)&& ((DevNo& 0xFFFFFF) < 0x000101)) {
k = 0;
DevNo &= 0xFFFFFF;
if (DevNo == 256) {///< find empty slot
pDeInf = &DevRemote[0];
for (i = 0; i < 256; i++) {
if (!pDeInf->DevF.Full_) {
k = i;
break;
}
}
if (i == 256) {///< all full, find oldest and use it
j = 0xFFFF;
for (i = 0; i < 256; i++) {
if (DevRemoteTOut[i] < j) {
j = DevRemoteTOut[i];
k = i;
}
}
}
pDeInf = &DevRemote[k];
pDeInf->DevF.Full_ = 1;
memset(pDeInf, 0, sizeof(AY_DEVINFO));
DevRemoteTOut[k] = DEV_REMOTE_TIMEOUT;
printf("AYDEV--> New Device Remote Added DevNo=%d \n", (k+1));
}
else {
k = DevNo;
pDeInf = &DevRemote[k];
DevRemoteTOut[k] = DEV_REMOTE_TIMEOUT;
printf("AYDEV--> Device Remote Found DevNo=%d \n", DevNo);
}
i = k;
}
else if (DevNo < 4096) {
pDeInf = &DevLevel1[0];
i = DevNo;
printf("AYDEV--> New Device Level 1 created DevNo=%d \n", DevNo);
}
else {
i = DevNo - 4096;
pDeInf = *pDevInfos[(i >> 12)];
i = (i & 0xFFF);
if (pDeInf == 0) {
pDeInf = (AY_DEVINFO *)_AY_MallocMemory(sizeof(DevLevel1));
memset(pDeInf, 0, sizeof(DevLevel1));
printf("AYDEV--> New Device List %d created DevNo=%d \n", ((DevNo >> 12)+2), DevNo);
}
}
//=======================================================================================================//
if (Comp < _DEV_LASTCOMP) {
AY_Demo_UpdateDevInfo(&pDeInf[i], pComp, Comp);
}
//=======================================================================================================//
return 1;
}
/*
*
*/
AY_DEVINFO *pAY_FindDevInfoByDevNo(Ui32 DevNo) {
Ui32 i;
AY_DEVINFO *pDeInf;
if ((DevNo & 0xFFFFFF) > 65535) {
return 0;
}
else if ((DevNo & 0xFF000000) && ((DevNo & 0xFFFFFF) < 0x000101)) {
DevNo &= 0xFFFFFF;
pDeInf = &DevRemote[DevNo];
}
else if (DevNo < 4096 ) {
pDeInf = &DevLevel1[DevNo];
}
else {
i = DevNo - 4096;
pDeInf = *pDevInfos[(i >> 12)];
i = (i & 0xFFF);
pDeInf += i;
}
return pDeInf;
}
/*
*
*/
AY_DEVINFO *pAY_FindLocDevInfoByIP(Ui32 LocIP) {
Ui32 i;
AY_DEVINFO *pDeInf;
for (i = 0; i < 65536; i++) {
pDeInf = pAY_FindDevInfoByDevNo(i);
if (pDeInf) {
if (pDeInf->DevF.Full_) {
if (pDeInf->DevRead._LocalIp == LocIP) {
return pDeInf;
}
}
}
}
return 0;///< not found
}
/*
*
*/
AY_DEVINFO *pAY_FindRmtDevInfoByMAC(Ui08 *pMac, Ui08 SrcDst) {
Ui32 i;
AY_DEVINFO *pDeInf;
Ui08 *pM;
for (i = 0; i < 256; i++) {
pDeInf = pAY_FindDevInfoByDevNo(i+0xFF000000);
if (pDeInf) {
if (pDeInf->DevF.Full_) {
if (SrcDst == 0) {///< SRC
pM = (Ui08 *)&pDeInf->UDP_Hdr._ethHeader.src;
}
else {///< DST
pM = (Ui08 *)&pDeInf->UDP_Hdr._ethHeader.src;
}
if( memcmp(pM, pMac,sizeof(uip_eth_addr)) == 0){
return pDeInf;
}
}
}
}
return 0;///< not found
}
| 23.432203 | 109 | 0.540325 | [
"object"
] |
7473080d9f8053e2ce3580aeb98ac91d3bc67685 | 34,879 | cpp | C++ | src/realsense_ingestor.cpp | open-edge-insights/video-ingestion | 189f50c73df6a2879de278f1232f14f291c8e6cf | [
"MIT"
] | 7 | 2021-05-11T04:28:28.000Z | 2022-03-29T00:39:39.000Z | src/realsense_ingestor.cpp | open-edge-insights/video-ingestion | 189f50c73df6a2879de278f1232f14f291c8e6cf | [
"MIT"
] | 1 | 2022-02-10T03:38:58.000Z | 2022-02-10T03:38:58.000Z | src/realsense_ingestor.cpp | open-edge-insights/video-ingestion | 189f50c73df6a2879de278f1232f14f291c8e6cf | [
"MIT"
] | 6 | 2021-09-19T17:48:37.000Z | 2022-03-22T04:22:48.000Z | // Copyright (c) 2021 Intel Corporation.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
/**
* @file
* @brief RealSense Ingestor implementation
*/
#include <string>
#include <vector>
#include <cerrno>
#include <unistd.h>
#include <eii/msgbus/msgbus.h>
#include <eii/utils/logger.h>
#include <eii/utils/json_config.h>
#include "eii/vi/realsense_ingestor.h"
using namespace eii::vi;
using namespace eii::utils;
using namespace eii::udf;
#define SERIAL "serial"
#define IMU "imu_on"
#define FRAMERATE "framerate"
#define UUID_LENGTH 5
RealSenseIngestor::RealSenseIngestor(config_t* config, FrameQueue* frame_queue, std::string service_name, std::condition_variable& snapshot_cv, EncodeType enc_type, int enc_lvl):
Ingestor(config, frame_queue, service_name, snapshot_cv, enc_type, enc_lvl) {
m_encoding = false;
m_initialized.store(true);
m_imu_on = false;
m_imu_support = false;
m_framerate = 0;
const auto dev_list = m_ctx.query_devices();
if(dev_list.size() == 0) {
const char* err = "No RealSense devices found";
LOG_ERROR("%s", err);
throw(err);
}
std::string first_serial = std::string(dev_list[0].get_info(RS2_CAMERA_INFO_SERIAL_NUMBER));
config_value_t* cvt_serial = config->get_config_value(config->cfg, SERIAL);
if(cvt_serial == NULL) {
LOG_DEBUG_0("\"serial\" key is not added, first connected device in the list will be enabled");
// Get the serial number of the first connected device in the list
m_serial = first_serial;
} else {
LOG_DEBUG_0("cvt_serial initialized");
if(cvt_serial->type != CVT_STRING) {
config_value_destroy(cvt_serial);
const char* err = "JSON value must be a string";
LOG_ERROR("%s for \'%s\'", err, SERIAL);
throw(err);
}
m_serial = std::string(cvt_serial->body.string);
config_value_destroy(cvt_serial);
// Verify serial number when single device is connected
if(dev_list.size() == 1 && m_serial != first_serial) {
const char* err = "Input serial not matching with RealSence Device Serial";
LOG_ERROR("%s", err);
throw(err);
}
// Verify serial number when multiple devices are connected
if(dev_list.size() > 1) {
bool serial_found = false;
for(int i = 0; i <= dev_list.size(); i++) {
if (m_serial == std::string(dev_list[i].get_info(RS2_CAMERA_INFO_SERIAL_NUMBER))) {
serial_found = true;
break;
}
}
if(!serial_found) {
const char* err = "Input serial not matching with RealSence Device Serial";
LOG_ERROR("%s", err);
throw(err);
}
}
}
LOG_INFO("Device Serial: %s", m_serial.c_str());
// Get framerate config value
config_value_t* cvt_framerate = config->get_config_value(config->cfg, FRAMERATE);
if(cvt_framerate != NULL) {
if(cvt_framerate->type != CVT_INTEGER) {
const char* err = "framerate must be an integer";
LOG_ERROR("%s", err);
config_value_destroy(cvt_framerate);
throw(err);
}
m_framerate = cvt_framerate->body.integer;
config_value_destroy(cvt_framerate);
} else if(cvt_framerate == NULL) {
m_framerate = 30;
}
LOG_INFO("Framerate: %d", m_framerate);
// Enable streaming configuration
m_cfg.enable_device(m_serial);
m_cfg.enable_stream(RS2_STREAM_COLOR, RS2_FORMAT_BGR8, m_framerate);
m_cfg.enable_stream(RS2_STREAM_DEPTH, RS2_FORMAT_Z16, m_framerate);
//TODO: Verify pose stream from tracking camera
config_value_t* cvt_imu = config->get_config_value(
config->cfg, IMU);
if(cvt_imu != NULL) {
if(cvt_imu->type != CVT_BOOLEAN) {
LOG_ERROR_0("IMU must be a boolean");
config_value_destroy(cvt_imu);
}
if(cvt_imu->body.boolean) {
m_imu_on = true;
}
config_value_destroy(cvt_imu);
}
if(m_imu_on) {
// Enable streams to get IMU data
if (!check_imu_is_supported()) {
LOG_DEBUG_0("Device supporting IMU not found");
} else {
LOG_DEBUG_0("Device supports IMU");
m_cfg.enable_stream(RS2_STREAM_ACCEL, RS2_FORMAT_MOTION_XYZ32F);
m_cfg.enable_stream(RS2_STREAM_GYRO, RS2_FORMAT_MOTION_XYZ32F);
m_imu_support = true;
}
}
// Start streaming with enabled configuration
m_pipe.start(m_cfg);
}
RealSenseIngestor::~RealSenseIngestor() {
LOG_DEBUG_0("RealSense ingestor destructor");
m_pipe.stop();
}
void free_rs2_frame(void* obj) {
// This may not be needed as the frame memory
// is internally handled.
}
void RealSenseIngestor::run(bool snapshot_mode) {
// indicate that the run() function corresponding to the m_th thread has started
m_running.store(true);
LOG_INFO_0("Ingestor thread running publishing on stream");
Frame* frame = NULL;
int64_t frame_count = 0;
msg_envelope_elem_body_t* elem = NULL;
try {
while (!m_stop.load()) {
this->read(frame);
msg_envelope_t* meta_data = frame->get_meta_data();
// Profiling start
DO_PROFILING(this->m_profile, meta_data, "ts_Ingestor_entry")
// Profiling end
msgbus_ret_t ret;
if(frame_count == INT64_MAX) {
LOG_WARN_0("frame count has reached INT64_MAX, so resetting \
it back to zero");
frame_count = 0;
}
frame_count++;
elem = msgbus_msg_envelope_new_integer(frame_count);
if (elem == NULL) {
delete frame;
const char* err = "Failed to create frame_number element";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_put(meta_data, "frame_number", elem);
if(ret != MSG_SUCCESS) {
delete frame;
const char* err = "Failed to put frame_number in meta-data";
LOG_ERROR("%s", err);
throw err;
}
elem = NULL;
LOG_DEBUG("Frame number: %ld", frame_count);
// Profiling start
DO_PROFILING(this->m_profile, meta_data, "ts_filterQ_entry")
// Profiling end
// Set encding type and level
try {
frame->set_encoding(m_enc_type, m_enc_lvl);
} catch(const char *err) {
LOG_ERROR("Exception: %s", err);
} catch(...) {
LOG_ERROR("Exception occurred in set_encoding()");
}
QueueRetCode ret_queue = m_udf_input_queue->push(frame);
if(ret_queue == QueueRetCode::QUEUE_FULL) {
if(m_udf_input_queue->push_wait(frame) != QueueRetCode::SUCCESS) {
LOG_ERROR_0("Failed to enqueue message, "
"message dropped");
}
// Add timestamp which acts as a marker if queue if blocked
DO_PROFILING(this->m_profile, meta_data, m_ingestor_block_key.c_str());
}
frame = NULL;
if(snapshot_mode) {
m_stop.store(true);
m_snapshot_cv.notify_all();
}
}
} catch(const char* e) {
LOG_ERROR("Exception: %s", e);
if (elem != NULL)
msgbus_msg_envelope_elem_destroy(elem);
if(frame != NULL)
delete frame;
throw e;
} catch (const rs2::error & e) {
LOG_ERROR("RealSense error calling %s( %s ): %s",
e.get_failed_function().c_str(),
e.get_failed_args().c_str(), e.what());
if (elem != NULL)
msgbus_msg_envelope_elem_destroy(elem);
if(frame != NULL)
delete frame;
throw e;
}
catch (const std::exception& e) {
LOG_ERROR("Exception: %s", e.what());
if (elem != NULL)
msgbus_msg_envelope_elem_destroy(elem);
if(frame != NULL)
delete frame;
throw e;
} catch(...) {
LOG_ERROR("Exception occured in opencv ingestor run()");
if (elem != NULL)
msgbus_msg_envelope_elem_destroy(elem);
if(frame != NULL)
delete frame;
throw;
}
if (elem != NULL)
msgbus_msg_envelope_elem_destroy(elem);
if(frame != NULL)
delete frame;
LOG_INFO_0("Ingestor thread stopped");
if(snapshot_mode)
m_running.store(false);
}
void RealSenseIngestor::read(Frame*& frame) {
LOG_DEBUG_0("Reading set of frames from RealSense camera");
// Wait for next set of frames from the camera
rs2::frameset data = m_pipe.wait_for_frames();
// Retrieve the first color frame
rs2::video_frame color = data.get_color_frame();
// Retrieve the first depth frame
rs2::depth_frame depth = data.get_depth_frame();
// Query frame width and height
const int color_width = color.get_width();
const int color_height = color.get_height();
const int depth_width = depth.get_width();
const int depth_height = depth.get_height();
frame = new Frame(
(void*) color.get(), free_rs2_frame, (void*) color.get_data(),
color_width , color_height, 3);
frame->add_frame((void*) depth.get(), free_rs2_frame, (void*) depth.get_data(),
depth_width, depth_height, 3, EncodeType::NONE, 0);
auto depth_profile = depth.get_profile().as<rs2::video_stream_profile>();
auto depth_intrinsics = depth_profile.get_intrinsics();
msgbus_ret_t ret;
msg_envelope_t* rs2_meta = frame->get_meta_data();
msg_envelope_elem_body_t* e_di_width = msgbus_msg_envelope_new_integer(depth_intrinsics.width);
if(e_di_width == NULL) {
delete frame;
const char* err = "Failed to initialize depth instrinsics width meta-data";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_put(rs2_meta, "rs2_depth_intrinsics_width", e_di_width);
if(ret != MSG_SUCCESS) {
delete frame;
msgbus_msg_envelope_elem_destroy(e_di_width);
const char* err = "Failed to put depth intrinsics width in meta-data";
LOG_ERROR("%s", err);
throw err;
}
msg_envelope_elem_body_t* e_di_height = msgbus_msg_envelope_new_integer(depth_intrinsics.height);
if(e_di_height == NULL) {
delete frame;
const char* err = "Failed to initialize depth instrinsics height meta-data";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_put(rs2_meta, "rs2_depth_intrinsics_height", e_di_height);
if(ret != MSG_SUCCESS) {
delete frame;
msgbus_msg_envelope_elem_destroy(e_di_height);
const char* err = "Failed to put depth intrinsics height in meta-data";
LOG_ERROR("%s", err);
throw err;
}
msg_envelope_elem_body_t* e_di_ppx = msgbus_msg_envelope_new_floating(depth_intrinsics.ppx);
if(e_di_ppx == NULL) {
delete frame;
const char* err = "Failed to initialize depth instrinsics x-principal-point meta-data";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_put(rs2_meta, "rs2_depth_intrinsics_ppx", e_di_ppx);
if(ret != MSG_SUCCESS) {
delete frame;
msgbus_msg_envelope_elem_destroy(e_di_ppx);
const char* err = "Failed to put depth intrinsics x-principal-point in meta-data";
LOG_ERROR("%s", err);
throw err;
}
msg_envelope_elem_body_t* e_di_ppy = msgbus_msg_envelope_new_floating(depth_intrinsics.ppy);
if(e_di_ppy == NULL) {
delete frame;
const char* err = "Failed to initialize depth instrinsics y-principal-point meta-data";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_put(rs2_meta, "rs2_depth_intrinsics_ppy", e_di_ppy);
if(ret != MSG_SUCCESS) {
delete frame;
msgbus_msg_envelope_elem_destroy(e_di_ppy);
const char* err = "Failed to put depth intrinsics y-principal-point in meta-data";
LOG_ERROR("%s", err);
throw err;
}
msg_envelope_elem_body_t* e_di_fx = msgbus_msg_envelope_new_floating(depth_intrinsics.fx);
if(e_di_fx == NULL) {
delete frame;
const char* err = "Failed to initialize depth instrinsics x-focal-point meta-data";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_put(rs2_meta, "rs2_depth_intrinsics_fx", e_di_fx);
if(ret != MSG_SUCCESS) {
delete frame;
msgbus_msg_envelope_elem_destroy(e_di_fx);
const char* err = "Failed to put depth intrinsics x-focal-point in meta-data";
LOG_ERROR("%s", err);
throw err;
}
msg_envelope_elem_body_t* e_di_fy = msgbus_msg_envelope_new_floating(depth_intrinsics.fy);
if(e_di_fy == NULL) {
delete frame;
const char* err = "Failed to initialize depth instrinsics y-focal-point meta-data";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_put(rs2_meta, "rs2_depth_intrinsics_fy", e_di_fy);
if(ret != MSG_SUCCESS) {
delete frame;
msgbus_msg_envelope_elem_destroy(e_di_fy);
const char* err = "Failed to put depth intrinsics y-focal-point in meta-data";
LOG_ERROR("%s", err);
throw err;
}
msg_envelope_elem_body_t* e_di_model = msgbus_msg_envelope_new_integer((int)depth_intrinsics.model);
if(e_di_model == NULL) {
delete frame;
const char* err = "Failed to initialize depth instrinsics model meta-data";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_put(rs2_meta, "rs2_depth_intrinsics_model", e_di_model);
if(ret != MSG_SUCCESS) {
delete frame;
msgbus_msg_envelope_elem_destroy(e_di_model);
const char* err = "Failed to put depth intrinsics model in meta-data";
LOG_ERROR("%s", err);
throw err;
}
auto color_profile = color.get_profile().as<rs2::video_stream_profile>();
auto color_intrinsics = color_profile.get_intrinsics();
msg_envelope_elem_body_t* e_ci_width = msgbus_msg_envelope_new_integer(color_intrinsics.width);
if(e_ci_width == NULL) {
delete frame;
const char* err = "Failed to initialize color instrinsics width meta-data";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_put(rs2_meta, "rs2_color_intrinsics_width", e_ci_width);
if(ret != MSG_SUCCESS) {
delete frame;
msgbus_msg_envelope_elem_destroy(e_ci_width);
const char* err = "Failed to put color intrinsics width in meta-data";
LOG_ERROR("%s", err);
throw err;
}
msg_envelope_elem_body_t* e_ci_height = msgbus_msg_envelope_new_integer(color_intrinsics.height);
if(e_ci_height == NULL) {
delete frame;
const char* err = "Failed to initialize color instrinsics height meta-data";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_put(rs2_meta, "rs2_color_intrinsics_height", e_ci_height);
if(ret != MSG_SUCCESS) {
delete frame;
msgbus_msg_envelope_elem_destroy(e_ci_height);
const char* err = "Failed to put color intrinsics height in meta-data";
LOG_ERROR("%s", err);
throw err;
}
msg_envelope_elem_body_t* e_ci_ppx = msgbus_msg_envelope_new_floating(color_intrinsics.ppx);
if(e_ci_ppx == NULL) {
delete frame;
const char* err = "Failed to initialize color instrinsics x-principal-point meta-data";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_put(rs2_meta, "rs2_color_intrinsics_ppx", e_ci_ppx);
if(ret != MSG_SUCCESS) {
delete frame;
msgbus_msg_envelope_elem_destroy(e_ci_ppx);
const char* err = "Failed to put color intrinsics x-principal-point in meta-data";
LOG_ERROR("%s", err);
throw err;
}
msg_envelope_elem_body_t* e_ci_ppy = msgbus_msg_envelope_new_floating(color_intrinsics.ppy);
if(e_ci_ppy == NULL) {
delete frame;
const char* err = "Failed to initialize color instrinsics y-principal-point meta-data";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_put(rs2_meta, "rs2_color_intrinsics_ppy", e_ci_ppy);
if(ret != MSG_SUCCESS) {
delete frame;
msgbus_msg_envelope_elem_destroy(e_ci_ppy);
const char* err = "Failed to put color intrinsics y-principal-point in meta-data";
LOG_ERROR("%s", err);
throw err;
}
msg_envelope_elem_body_t* e_ci_fx = msgbus_msg_envelope_new_floating(color_intrinsics.fx);
if(e_ci_fx == NULL) {
delete frame;
const char* err = "Failed to initialize color instrinsics x-focal-point meta-data";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_put(rs2_meta, "rs2_color_intrinsics_fx", e_ci_fx);
if(ret != MSG_SUCCESS) {
delete frame;
msgbus_msg_envelope_elem_destroy(e_ci_fx);
const char* err = "Failed to put color intrinsics x-focal-point in meta-data";
LOG_ERROR("%s", err);
throw err;
}
msg_envelope_elem_body_t* e_ci_fy = msgbus_msg_envelope_new_floating(color_intrinsics.fy);
if(e_ci_fy == NULL) {
delete frame;
const char* err = "Failed to initialize color instrinsics y-focal-point meta-data";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_put(rs2_meta, "rs2_color_intrinsics_fy", e_ci_fy);
if(ret != MSG_SUCCESS) {
delete frame;
msgbus_msg_envelope_elem_destroy(e_ci_fy);
const char* err = "Failed to put color intrinsics y-focal-point in meta-data";
LOG_ERROR("%s", err);
throw err;
}
msg_envelope_elem_body_t* e_ci_model = msgbus_msg_envelope_new_integer((int)color_intrinsics.model);
if(e_ci_model == NULL) {
delete frame;
const char* err = "Failed to initialize color instrinsics model meta-data";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_put(rs2_meta, "rs2_color_intrinsics_model", e_ci_model);
if(ret != MSG_SUCCESS) {
delete frame;
msgbus_msg_envelope_elem_destroy(e_ci_model);
const char* err = "Failed to put color intrinsics model in meta-data";
LOG_ERROR("%s", err);
throw err;
}
auto depth_to_color_extrinsics = depth_profile.get_extrinsics_to(color_profile);
// Add rs2 extrinsics rotation
msg_envelope_elem_body_t* e_rotation_arr = msgbus_msg_envelope_new_array();
if (e_rotation_arr == NULL) {
delete frame;
msgbus_msg_envelope_elem_destroy(e_rotation_arr);
const char* err = "Failed to allocate rotation array";
LOG_ERROR("%s", err);
throw err;
}
msg_envelope_elem_body_t* e_r0 = msgbus_msg_envelope_new_floating(depth_to_color_extrinsics.rotation[0]);
if(e_r0 == NULL) {
delete frame;
const char* err = "Failed to initialize rotation meta-data";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_elem_array_add(e_rotation_arr, e_r0);
if (ret != MSG_SUCCESS) {
delete frame;
const char* err = "Failed to add rotation meta-data";
LOG_ERROR("%s", err);
throw err;
}
msg_envelope_elem_body_t* e_r1 = msgbus_msg_envelope_new_floating(depth_to_color_extrinsics.rotation[1]);
if(e_r1 == NULL) {
delete frame;
const char* err = "Failed to initialize rotation meta-data";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_elem_array_add(e_rotation_arr, e_r1);
if (ret != MSG_SUCCESS) {
delete frame;
const char* err = "Failed to add rotation meta-data";
LOG_ERROR("%s", err);
throw err;
}
msg_envelope_elem_body_t* e_r2 = msgbus_msg_envelope_new_floating(depth_to_color_extrinsics.rotation[2]);
if(e_r2 == NULL) {
delete frame;
const char* err = "Failed to initialize rotation meta-data";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_elem_array_add(e_rotation_arr, e_r2);
if (ret != MSG_SUCCESS) {
delete frame;
const char* err = "Failed to add rotation meta-data";
LOG_ERROR("%s", err);
throw err;
}
msg_envelope_elem_body_t* e_r3 = msgbus_msg_envelope_new_floating(depth_to_color_extrinsics.rotation[3]);
if(e_r3 == NULL) {
delete frame;
const char* err = "Failed to initialize rotation meta-data";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_elem_array_add(e_rotation_arr, e_r3);
if (ret != MSG_SUCCESS) {
delete frame;
const char* err = "Failed to add rotation meta-data";
LOG_ERROR("%s", err);
throw err;
}
msg_envelope_elem_body_t* e_r4 = msgbus_msg_envelope_new_floating(depth_to_color_extrinsics.rotation[4]);
if(e_r4 == NULL) {
delete frame;
const char* err = "Failed to initialize rotation meta-data";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_elem_array_add(e_rotation_arr, e_r4);
if (ret != MSG_SUCCESS) {
delete frame;
const char* err = "Failed to add rotation meta-data";
LOG_ERROR("%s", err);
throw err;
}
msg_envelope_elem_body_t* e_r5 = msgbus_msg_envelope_new_floating(depth_to_color_extrinsics.rotation[5]);
if(e_r5 == NULL) {
delete frame;
const char* err = "Failed to initialize rotation meta-data";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_elem_array_add(e_rotation_arr, e_r5);
if (ret != MSG_SUCCESS) {
delete frame;
const char* err = "Failed to add rotation meta-data";
LOG_ERROR("%s", err);
throw err;
}
msg_envelope_elem_body_t* e_r6 = msgbus_msg_envelope_new_floating(depth_to_color_extrinsics.rotation[6]);
if(e_r6 == NULL) {
delete frame;
const char* err = "Failed to initialize rotation meta-data";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_elem_array_add(e_rotation_arr, e_r6);
if (ret != MSG_SUCCESS) {
delete frame;
const char* err = "Failed to add rotation meta-data";
LOG_ERROR("%s", err);
throw err;
}
msg_envelope_elem_body_t* e_r7 = msgbus_msg_envelope_new_floating(depth_to_color_extrinsics.rotation[7]);
if(e_r7 == NULL) {
delete frame;
const char* err = "Failed to initialize rotation meta-data";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_elem_array_add(e_rotation_arr, e_r7);
if (ret != MSG_SUCCESS) {
delete frame;
const char* err = "Failed to add rotation meta-data";
LOG_ERROR("%s", err);
throw err;
}
msg_envelope_elem_body_t* e_r8 = msgbus_msg_envelope_new_floating(depth_to_color_extrinsics.rotation[8]);
if(e_r8 == NULL) {
delete frame;
const char* err = "Failed to initialize rotation meta-data";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_elem_array_add(e_rotation_arr, e_r8);
if (ret != MSG_SUCCESS) {
delete frame;
const char* err = "Failed to add rotation meta-data";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_put(rs2_meta, "rotation_arr", e_rotation_arr);
if(ret != MSG_SUCCESS) {
delete frame;
msgbus_msg_envelope_elem_destroy(e_rotation_arr);
const char* err = "Failed to put rotation array in meta-data";
LOG_ERROR("%s", err);
throw err;
}
// Add rs2 extrinsics translation
msg_envelope_elem_body_t* e_translation_arr = msgbus_msg_envelope_new_array();
if (e_translation_arr == NULL) {
delete frame;
msgbus_msg_envelope_elem_destroy(e_translation_arr);
const char* err = "Failed to allocate translation array";
LOG_ERROR("%s", err);
throw err;
}
msg_envelope_elem_body_t* e_t0 = msgbus_msg_envelope_new_floating(depth_to_color_extrinsics.translation[0]);
if(e_t0 == NULL) {
delete frame;
const char* err = "Failed to initialize translation meta-data";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_elem_array_add(e_translation_arr, e_t0);
if (ret != MSG_SUCCESS) {
delete frame;
const char* err = "Failed to add translation meta-data";
LOG_ERROR("%s", err);
throw err;
}
msg_envelope_elem_body_t* e_t1 = msgbus_msg_envelope_new_floating(depth_to_color_extrinsics.translation[1]);
if(e_t1 == NULL) {
delete frame;
const char* err = "Failed to initialize translation meta-data";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_elem_array_add(e_translation_arr, e_t1);
if (ret != MSG_SUCCESS) {
delete frame;
const char* err = "Failed to add translation meta-data";
LOG_ERROR("%s", err);
throw err;
}
msg_envelope_elem_body_t* e_t2 = msgbus_msg_envelope_new_floating(depth_to_color_extrinsics.translation[2]);
if(e_t2 == NULL) {
delete frame;
const char* err = "Failed to initialize translation meta-data";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_elem_array_add(e_translation_arr, e_t2);
if (ret != MSG_SUCCESS) {
delete frame;
const char* err = "Failed to add translation meta-data";
LOG_ERROR("%s", err);
throw err;
}
ret = msgbus_msg_envelope_put(rs2_meta, "translation_arr", e_translation_arr);
if(ret != MSG_SUCCESS) {
delete frame;
msgbus_msg_envelope_elem_destroy(e_translation_arr);
const char* err = "Failed to put translation array in meta-data";
LOG_ERROR("%s", err);
throw err;
}
if (m_imu_support) {
// Add IMU data to frame metadata
msg_envelope_t* rs2_imu_meta_data = frame->get_meta_data();
msg_envelope_elem_body_t* rs2_meta_arr = msgbus_msg_envelope_new_array();
if(rs2_meta_arr == NULL) {
LOG_ERROR_0("Failed to initialize rs2 metadata");
delete frame;
}
// Find and retrieve IMU and/or tracking data
if (rs2::motion_frame accel_frame = data.first_or_default(RS2_STREAM_ACCEL))
{
rs2_vector accel_sample = accel_frame.get_motion_data();
LOG_DEBUG("Accel_Sample: x:%f, y:%f, z:%f", accel_sample.x, accel_sample.y, accel_sample.z);
msg_envelope_elem_body_t* accel_obj= msgbus_msg_envelope_new_object();
if(accel_obj == NULL) {
LOG_ERROR_0("Failed to initialize accel metadata");
delete frame;
}
msg_envelope_elem_body_t* accel_x = msgbus_msg_envelope_new_floating(accel_sample.x);
if(accel_x == NULL) {
LOG_ERROR_0("Failed to initialize accel sample x-coordinate metadata");
delete frame;
}
ret = msgbus_msg_envelope_elem_object_put(accel_obj, "accel_sample_x", accel_x);
if(ret != MSG_SUCCESS) {
msgbus_msg_envelope_elem_destroy(accel_x);
LOG_ERROR_0("Failed to put accel sample x-coordinate metadata");
delete frame;
}
msg_envelope_elem_body_t* accel_y = msgbus_msg_envelope_new_floating(accel_sample.y);
if(accel_y == NULL) {
LOG_ERROR_0("Failed to initialize accel sample y-coordinate metadata");
delete frame;
}
ret = msgbus_msg_envelope_elem_object_put(accel_obj, "accel_sample_y", accel_y);
if(ret != MSG_SUCCESS) {
msgbus_msg_envelope_elem_destroy(accel_x);
msgbus_msg_envelope_elem_destroy(accel_y);
LOG_ERROR_0("Failed to put accel sample y-coordinate metadata");
delete frame;
}
msg_envelope_elem_body_t* accel_z = msgbus_msg_envelope_new_floating(accel_sample.z);
if(accel_z == NULL) {
LOG_ERROR_0("Failed to initialize accel sample z-coordinate metadata");
delete frame;
}
ret = msgbus_msg_envelope_elem_object_put(accel_obj, "accel_sample_z", accel_z);
if(ret != MSG_SUCCESS) {
msgbus_msg_envelope_elem_destroy(accel_x);
msgbus_msg_envelope_elem_destroy(accel_y);
msgbus_msg_envelope_elem_destroy(accel_z);
LOG_ERROR_0("Failed to put accel sample z-coordinate metadata");
delete frame;
}
ret = msgbus_msg_envelope_elem_array_add(rs2_meta_arr, accel_obj);
if(ret != MSG_SUCCESS) {
LOG_ERROR_0("Failed to add accel object to rs2 metadata");
delete frame;
}
}
if (rs2::motion_frame gyro_frame = data.first_or_default(RS2_STREAM_GYRO))
{
rs2_vector gyro_sample = gyro_frame.get_motion_data();
LOG_DEBUG("Gyro Sample: x:%f, y:%f, z:%f", gyro_sample.x, gyro_sample.y, gyro_sample.z);
msg_envelope_elem_body_t* gyro_obj= msgbus_msg_envelope_new_object();
if(gyro_obj == NULL) {
LOG_ERROR_0("Failed to initialize gyro metadata");
delete frame;
}
msg_envelope_elem_body_t* gyro_x = msgbus_msg_envelope_new_floating(gyro_sample.x);
if(gyro_x == NULL) {
LOG_ERROR_0("Failed to initialize gyro sample x-coordinate metadata");
delete frame;
}
ret = msgbus_msg_envelope_elem_object_put(gyro_obj, "gyro_sample_x", gyro_x);
if(ret != MSG_SUCCESS) {
msgbus_msg_envelope_elem_destroy(gyro_x);
LOG_ERROR_0("Failed to put gyro sample x-coordinate metadata");
delete frame;
}
msg_envelope_elem_body_t* gyro_y = msgbus_msg_envelope_new_floating(gyro_sample.y);
if(gyro_y == NULL) {
LOG_ERROR_0("Failed to initialize gyro sample y-coordinate metadata");
delete frame;
}
ret = msgbus_msg_envelope_elem_object_put(gyro_obj, "gyro_sample_y", gyro_y);
if(ret != MSG_SUCCESS) {
msgbus_msg_envelope_elem_destroy(gyro_x);
msgbus_msg_envelope_elem_destroy(gyro_y);
LOG_ERROR_0("Failed to put gyro sample y-coordinate metadata");
delete frame;
}
msg_envelope_elem_body_t* gyro_z = msgbus_msg_envelope_new_floating(gyro_sample.z);
if(gyro_z == NULL) {
LOG_ERROR_0("Failed to initialize gyro sample z-coordinate metadata");
delete frame;
}
ret = msgbus_msg_envelope_elem_object_put(gyro_obj, "gyro_sample_z", gyro_z);
if(ret != MSG_SUCCESS) {
msgbus_msg_envelope_elem_destroy(gyro_x);
msgbus_msg_envelope_elem_destroy(gyro_y);
msgbus_msg_envelope_elem_destroy(gyro_z);
LOG_ERROR_0("Failed to put gyro sample z-coordinate metadata");
delete frame;
}
ret = msgbus_msg_envelope_elem_array_add(rs2_meta_arr, gyro_obj);
if(ret != MSG_SUCCESS) {
LOG_ERROR_0("Failed to add gyro object to rs2 metadata");
delete frame;
}
}
//TODO: Verify pose sample from tracking camera
ret = msgbus_msg_envelope_put(rs2_imu_meta_data, "rs2_imu_meta_data", rs2_meta_arr);
if(ret != MSG_SUCCESS) {
LOG_ERROR_0("Failed to put rs2 metadata");
delete frame;
}
}
if(m_poll_interval > 0) {
LOG_WARN("poll_interval not supported in realsense ingestor please use framerate config");
}
}
void RealSenseIngestor::stop() {
if(m_initialized.load()) {
if(!m_stop.load()) {
m_stop.store(true);
// wait for the ingestor thread run() to finish its execution.
if(m_th != NULL) {
m_th->join();
}
}
// After run() has been stopped m_stop flag is reset,
// so that the ingestor is ready for the next ingestion.
m_running.store(false);
m_stop.store(false);
}
}
bool RealSenseIngestor::check_imu_is_supported()
{
bool found_gyro = false;
bool found_accel = false;
for (auto dev : m_ctx.query_devices())
{
// The same device should support gyro and accel
found_gyro = false;
found_accel = false;
for (auto sensor : dev.query_sensors())
{
for (auto profile : sensor.get_stream_profiles())
{
if (profile.stream_type() == RS2_STREAM_GYRO)
found_gyro = true;
if (profile.stream_type() == RS2_STREAM_ACCEL)
found_accel = true;
}
}
if (found_gyro && found_accel)
break;
}
return found_gyro && found_accel;
}
| 35.773333 | 178 | 0.622237 | [
"object",
"vector",
"model"
] |
74737ac0a300529f8dd999eee91dc05c204cb01d | 3,394 | hpp | C++ | src/ttauri/skeleton/skeleton_block_node.hpp | RustWorks/ttauri | 4b093eb16465091d01d80159e23fd26e5d4e4c03 | [
"BSL-1.0"
] | 279 | 2021-02-17T09:53:40.000Z | 2022-03-22T04:08:40.000Z | src/ttauri/skeleton/skeleton_block_node.hpp | RustWorks/ttauri | 4b093eb16465091d01d80159e23fd26e5d4e4c03 | [
"BSL-1.0"
] | 269 | 2021-02-17T12:53:15.000Z | 2022-03-29T22:10:49.000Z | src/ttauri/skeleton/skeleton_block_node.hpp | RustWorks/ttauri | 4b093eb16465091d01d80159e23fd26e5d4e4c03 | [
"BSL-1.0"
] | 25 | 2021-02-17T17:14:10.000Z | 2022-03-16T04:13:00.000Z | // Copyright Take Vos 2020.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include "skeleton_node.hpp"
namespace tt::inline v1 {
struct skeleton_block_node final : skeleton_node {
std::string name;
statement_vector children;
formula_post_process_context::function_type function;
formula_post_process_context::function_type super_function;
skeleton_block_node(
parse_location location,
formula_post_process_context &context,
std::unique_ptr<formula_node> name_expression) noexcept :
skeleton_node(std::move(location)), name(name_expression->get_name())
{
name = name_expression->get_name();
super_function =
context.set_function(name, [&](formula_evaluation_context &context, datum::vector_type const &arguments) {
return this->evaluate_call(context, arguments);
});
}
/** Append a template-piece to the current template.
*/
bool append(std::unique_ptr<skeleton_node> x) noexcept override
{
append_child(children, std::move(x));
return true;
}
void post_process(formula_post_process_context &context) override
{
if (ssize(children) > 0) {
children.back()->left_align();
}
function = context.get_function(name);
tt_assert(function);
context.push_super(super_function);
for (ttlet &child : children) {
child->post_process(context);
}
context.pop_super();
}
datum evaluate(formula_evaluation_context &context) override
{
datum tmp;
try {
tmp = function(context, datum::vector_type{});
} catch (std::exception const &e) {
throw operation_error("{}: Could not evaluate block.\n{}", location, e.what());
}
if (tmp.is_break()) {
throw operation_error("{}: Found #break not inside a loop statement.", location);
} else if (tmp.is_continue()) {
throw operation_error("{}: Found #continue not inside a loop statement.", location);
} else if (tmp.is_undefined()) {
return {};
} else {
throw operation_error("{}: Can not use a #return statement inside a #block.", location);
}
}
datum evaluate_call(formula_evaluation_context &context, datum::vector_type const &arguments)
{
context.push();
auto tmp = evaluate_children(context, children);
context.pop();
if (tmp.is_break()) {
throw operation_error("{}: Found #break not inside a loop statement.", location);
} else if (tmp.is_continue()) {
throw operation_error("{}: Found #continue not inside a loop statement.", location);
} else if (tmp.is_undefined()) {
return {};
} else {
throw operation_error("{}: Can not use a #return statement inside a #block.", location);
}
}
std::string string() const noexcept override
{
std::string s = "<block ";
s += name;
s += join(transform<std::vector<std::string>>(children, [](auto &x) {
return to_string(*x);
}));
s += ">";
return s;
}
};
} // namespace tt::inline v1 | 30.303571 | 118 | 0.606364 | [
"vector",
"transform"
] |
7473b424078b1fb984983f4b4c6a0f86477a31b6 | 39,740 | cpp | C++ | Vessel/Common/radiosity.cpp | tostathaina/farsight | 7e9d6d15688735f34f7ca272e4e715acd11473ff | [
"Apache-2.0"
] | 8 | 2016-07-22T11:24:19.000Z | 2021-04-10T04:22:31.000Z | Vessel/Common/radiosity.cpp | YanXuHappygela/Farsight | 1711b2a1458c7e035edd21fe0019a1f7d23fcafa | [
"Apache-2.0"
] | null | null | null | Vessel/Common/radiosity.cpp | YanXuHappygela/Farsight | 1711b2a1458c7e035edd21fe0019a1f7d23fcafa | [
"Apache-2.0"
] | 7 | 2016-07-21T07:39:17.000Z | 2020-01-29T02:03:27.000Z | /*=========================================================================
Copyright 2009 Rensselaer Polytechnic Institute
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 "radiosity.h"
#include "mesh.h"
#include "face.h"
#include "glCanvas.h"
#include "draw_sphere.h"
#include "array.h"
#include <queue>
#include <algorithm>
#include <string.h>
#include "matrix.h"
using namespace std;
#define BUFSIZE 1000000
#ifndef M_PI
#define M_PI (2*acos(double(0)))
#endif
int GLCanvas::curr_type;
GLfloat GLCanvas::xtrans,GLCanvas::ytrans,GLCanvas::ztrans;
Face *faces_picked[3];
int num_picked[3];
char curr_annotation[512];
int picked_faces =0;
#define SKIP 2
// ================================================================
// CONSTRUCTOR & DESTRUCTOR
// ================================================================
void BFS_debug (Face *f, int depth, Array<Face*> *array)
{
//printf("I am in BFS_debug and I got Face %p depth %d array_faces %p\n",f,depth,array);
queue<Face*> q;
queue<int> qindex;
if(depth==0)
return;
Face *temp;
Face * t;
while(!q.empty())
q.pop();
while(!qindex.empty())
qindex.pop();
q.push(f);
qindex.push(depth);
while(!q.empty())
{
//if(q.size()<10)
//printf("queue %d\t",q.size());
temp = q.front();
int index = qindex.front();
q.pop();
qindex.pop();
if(index==0)
{
continue;
}
Edge *e = temp->getEdge();
if(e==NULL)
printf("e is null.. :((\n");
//Edge * temp1 = NULL;
for (int counter =0; counter < 3; counter ++)
{
Edge *e1 = e->getOpposite();
if(e1!= NULL)
{
t = e1->getFace();
if(!array->Member(t))
{
if(index>=1)
{
q.push(t);
qindex.push(index-1);
}
array->Add(t);
}
}
e=e->getNext();
if(e==NULL)
printf("e is null now!\n");
}
}
// printf("I'm at the end of debug_BFS\n");
}
void draw_transparent_sphere(GLfloat);
GLuint selectBuf[BUFSIZE];
Vec3f LAST_MOUSE;
Vec3f CENTER;
Face *PICKED = NULL;
Radiosity::Radiosity(Mesh *m, ArgParser *a) {
mesh = m;
args = a;
Initialize();
volume_rendering_setup_complete=false;
}
Radiosity::~Radiosity() {
Cleanup();
}
void Radiosity::Reset() {
printf ("Reset Radiosity Solution\n");
Cleanup();
Initialize();
}
void Radiosity::Initialize() {
// create and fill the data structures
n = mesh->numFaces();
patches = new Face*[n];
//formfactors = new float[n*n];
area = new float[n];
undistributed = new Vec3f[n];
absorbed = new Vec3f[n];
radiance = new Vec3f[n];
// number the patches, store them in an array (since the bag is unordered)
Iterator<Face*> *iter = mesh->getFaces()->StartIteration();
int i = 0;
while (Face *f = iter->GetNext()) {
patches[i] = f;
f->setRadiosityPatchIndex(i);
setArea(i,patches[i]->getArea());
i++;
}
mesh->getFaces()->EndIteration(iter);
printf("Just before computing form factors\n");
//scanf("%*c");
// compute the form factors and initialize the energies
for (i = 0; i < n; i++) {
computeFormFactors(i);
Vec3f emit = getPatch(i)->getEmit();
setUndistributed(i,emit);
setAbsorbed(i,Vec3f(0,0,0));
setRadiance(i,emit);
}
// find the patch with the most undistributed energy
findMaxUndistributed();
}
void Radiosity::Cleanup() {
delete [] patches;
delete [] formfactors;
delete [] area;
delete [] undistributed;
delete [] absorbed;
delete [] radiance;
}
// ================================================================
// ================================================================
void Radiosity::findMaxUndistributed() {
// find the patch with the most undistributed energy
// don't forget that the patches may have different sizes!
max_undistributed_patch = -1;
total_undistributed = 0;
total_area = 0;
float max = -1;
for (int i = 0; i < n; i++) {
float m = getUndistributed(i).Length() * getArea(i);
total_undistributed += m;
total_area += getArea(i);
if (max < m) {
max = m;
max_undistributed_patch = i;
}
}
assert (max_undistributed_patch >= 0 && max_undistributed_patch < n);
}
// =======================================================================
// =======================================================================
bool Radiosity::Iterate() {
printf ("Iterate\n");
// compute the radiosity solution!
// return true when the solution error is < epsilon
// so the animation loop can stop
return false;
}
void Radiosity::computeFormFactors(int i) {
// compute the form factors
// if your method for determining the form factors is only an
// estimate, you may need to normalize something so you don't
// gain/lose energy in the system
}
// =======================================================================
// PAINT
// =======================================================================
Vec3f ComputeNormal(const Vec3f &p1, const Vec3f &p2, const Vec3f &p3) {
Vec3f v12 = p2;
v12 -= p1;
Vec3f v23 = p3;
v23 -= p2;
Vec3f normal;
Vec3f::Cross3(normal,v12,v23);
normal.Normalize();
return normal;
}
Vec3f ComputeNormal(Face *f) {
return ComputeNormal((*f)[0]->get(),(*f)[1]->get(),(*f)[2]->get());
}
inline float tone_func(float x) {
assert (x >= 0);
// a tone mapping hack to map [0,oo) -> [0,1]
// there's nothing special or physically based about this function
float answer = -exp(-3*x)+1;
assert (answer >= 0 && answer <= 1);
return answer;
}
void Radiosity::insertColor(Vec3f v) {
if (args->tone_map) {
float r = tone_func(v.x());
float g = tone_func(v.y());
float b = tone_func(v.z());
glColor3f(r,g,b);
} else {
glColor3f(v.x(),v.y(),v.z());
}
}
void insertNormal(const Vec3f &p1, const Vec3f &p2, const Vec3f &p3) {
Vec3f normal = ComputeNormal(p1,p2,p3);
glNormal3f(normal.x(), normal.y(), normal.z());
}
Vec3f Radiosity::whichVisualization(enum RENDER_MODE mode, Face *f, int i)
{
assert (getPatch(i) == f);
assert (i >= 0 && i < n);
if (mode == RENDER_LIGHTS) {
return f->getEmit();
} else if (mode == RENDER_UNDISTRIBUTED) {
return getUndistributed(i);
} else if (mode == RENDER_ABSORBED) {
return getAbsorbed(i);
} else if (mode == RENDER_RADIANCE) {
return getRadiance(i);
} else if (mode == RENDER_FORM_FACTORS) {
float scale = 0.2 * total_area/getArea(i);
float factor = scale * getFormFactor(max_undistributed_patch,i);
return Vec3f(factor,factor,factor);
} else {
assert(0);
}
}
void CollectFacesWithVertex(Vertex *have, Face *f, Array<Face*> *array) {
if (array->Member(f)) return;
if (have != (*f)[0] && have != (*f)[1] && have != (*f)[2]) return;
array->Add(f);
for (int i = 0; i < 4; i++) {
Edge *ea = f->getEdge()->getOpposite();
Edge *eb = f->getEdge()->getNext()->getOpposite();
Edge *ec = f->getEdge()->getNext()->getNext()->getOpposite();
// Edge *ed = f->getEdge()->getNext()->getNext()->getNext()->getOpposite();
if (ea != NULL) CollectFacesWithVertex(have,ea->getFace(),array);
if (eb != NULL) CollectFacesWithVertex(have,eb->getFace(),array);
if (ec != NULL) CollectFacesWithVertex(have,ec->getFace(),array);
// if (ed != NULL) CollectFacesWithVertex(have,ed->getFace(),array);
}
}
void Radiosity::insertInterpolatedColor(int index, Face *f, Vertex *v) {
Array<Face*> faces = Array<Face*>(10);
CollectFacesWithVertex(v,f,&faces);
float total = 0;
Vec3f color = Vec3f(0,0,0);
Vec3f normal = ComputeNormal(f);
for (int i = 0; i < faces.Count(); i++) {
Vec3f normal2 = ComputeNormal(faces[i]);
if (normal.Dot3(normal2) < 0.9) continue;
total += faces[i]->getArea();
color += faces[i]->getArea() * whichVisualization(RENDER_RADIANCE,faces[i],faces[i]->getRadiosityPatchIndex());
}
if(total == 0)
for(;;);
assert (total > 0);
color /= total;
insertColor(color);
}
void Radiosity::PaintSelection(ArgParser *args)
{
Vec3f center; mesh->getBoundingBox()->getCenter(center);
float s = 1/mesh->getBoundingBox()->maxDim();
glScalef(s,s,s);
glTranslatef(GLCanvas::xtrans-center.x(),GLCanvas::ytrans-center.y(),GLCanvas::ztrans-center.z());
// glNewList(GLCanvas::display_list_selection,GL_COMPILE_AND_EXECUTE);
//glDisable(GL_LIGHTING);
printf("Came to render_selection mode\n");
glPushName(1);
GLuint pname =1;
for (int i = 0; i < n; i++) {
Face *f = patches[i];
//printf("%u",pname);
glLoadName(pname++);
// Vec3f color = f->getColor();
Vec3f a = (*f)[0]->get();
Vec3f b = (*f)[1]->get();
Vec3f c = (*f)[2]->get();
glBegin(GL_TRIANGLES);
// insertNormal(a,b,c);
glVertex3f(a.x(),a.y(),a.z());
glVertex3f(b.x(),b.y(),b.z());
glVertex3f(c.x(),c.y(),c.z());
glEnd();
//glPopName();
}
//glEndList();
}
void render_stroke_string(void* font, const char* string)
{
char* p;
//float width = 0;
// Center Our Text On The Screen
//glPushMatrix();
// Render The Text
p = (char*) string;
while (*p != '\0') glutStrokeCharacter(font, *p++);
//glPopMatrix();
}
void render_string(void* font, const char* string)
{
char* p = (char*) string;
while (*p != '\0') glutBitmapCharacter(font, *p++);
}
void Radiosity::Paint(ArgParser *args) {
// scale it so it fits in the window
Vec3f center; mesh->getBoundingBox()->getCenter(center);
float s = 1/mesh->getBoundingBox()->maxDim();
glScalef(s,s,s);
glTranslatef(GLCanvas::xtrans-center.x(),GLCanvas::ytrans-center.y(),GLCanvas::ztrans-center.z());
// this offset prevents "z-fighting" bewteen the edges and faces
// the edges will always win.
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(1.1,4.0);
//printf("\nrender mode %d\n",args->render_mode);
if (args->render_mode == RENDER_MATERIALS) {
// draw the faces with OpenGL lighting, just to understand the geometry
// (the GL light has nothing to do with the surfaces that emit light!)
// printf("I am here\n");
//scanf("%%d"); // CHANGED
// glDisable(GL_BLEND);
// glEnable(GL_LIGHT1);
// glEnable(GL_LIGHT0);
glBegin (GL_TRIANGLES);
for (int i = 0; i < n; i++) {
Face *f = patches[i];
Vec3f color = f->getColor();
//color = Vec3f(1,1,0);
insertColor(color);
Vec3f a = (*f)[0]->get();
Vec3f b = (*f)[1]->get();
Vec3f c = (*f)[2]->get();
//Vec3f d = (*f)[3]->get();
insertNormal(a,b,c);
glVertex3f(a.x(),a.y(),a.z());
glVertex3f(b.x(),b.y(),b.z());
glVertex3f(c.x(),c.y(),c.z());
//glVertex3f(d.x(),d.y(),d.z());
}
glEnd();
//glEnable(GL_BLEND);
} else if (args->render_mode == RENDER_SELECTION)
{
// glNewList(GLCanvas::display_list_selection,GL_COMPILE_AND_EXECUTE);
//glDisable(GL_LIGHTING);
printf("Came to render_selection mode\n");
glPushName(1);
GLuint pname =1;
for (int i = 0; i < n; i++) {
Face *f = patches[i];
//printf("%u",pname);
glLoadName(pname++);
// Vec3f color = f->getColor();
Vec3f a = (*f)[0]->get();
Vec3f b = (*f)[1]->get();
Vec3f c = (*f)[2]->get();
glBegin(GL_TRIANGLES);
// insertNormal(a,b,c);
glVertex3f(a.x(),a.y(),a.z());
glVertex3f(b.x(),b.y(),b.z());
glVertex3f(c.x(),c.y(),c.z());
glEnd();
//glPopName();
}
//glEndList();
//glEnable(GL_LIGHTING);
} else if (args->render_mode == RENDER_RADIANCE && args->interpolate == true) {
// interpolate the radiance values with neighboring faces having the same normal
glDisable(GL_LIGHTING);
glBegin (GL_TRIANGLES);
for (int i = 0; i < n; i++) {
Face *f = patches[i];
Vec3f a = (*f)[0]->get();
Vec3f b = (*f)[1]->get();
Vec3f c = (*f)[2]->get();
// Vec3f d = (*f)[3]->get();
insertInterpolatedColor(i,f,(*f)[0]);
glVertex3f(a.x(),a.y(),a.z());
insertInterpolatedColor(i,f,(*f)[1]);
glVertex3f(b.x(),b.y(),b.z());
insertInterpolatedColor(i,f,(*f)[2]);
glVertex3f(c.x(),c.y(),c.z());
// insertInterpolatedColor(i,f,(*f)[3]);
// glVertex3f(d.x(),d.y(),d.z());
}
glEnd();
glEnable(GL_LIGHTING);
} else {
// for all other visualizations, just render the patch in a uniform color
// glDisable(GL_LIGHTING);
// glBegin (GL_TRIANGLES);
//// printf("%d\n",n);
//// scanf("%*d");
// for (int i = 0; i < n; i++) {
// Face *f = patches[i];
// Vec3f color = whichVisualization(args->render_mode,f,i);
// insertColor(color);
// Vec3f a = (*f)[0]->get();
// Vec3f b = (*f)[1]->get();
// Vec3f c = (*f)[2]->get();
// // Vec3f d = (*f)[3]->get();
// if(f->getColor()==Vec3f(0,0,1))
// {
// glVertex3f(a.x(),a.y(),a.z());
// glVertex3f(b.x(),b.y(),b.z());
// glVertex3f(c.x(),c.y(),c.z());
// }
// // glVertex3f(d.x(),d.y(),d.z());
// }
// printf("End\n");
// glEnd();
// glEnable(GL_LIGHTING);
}
if (args->render_mode == RENDER_FORM_FACTORS) {
// render the form factors of the patch with the most undistributed light
glDisable(GL_LIGHTING);
glColor3f(1,0,0);
Face *t = getPatch(max_undistributed_patch);
glLineWidth(3);
glBegin(GL_LINES);
Vec3f a = (*t)[0]->get();
Vec3f b = (*t)[1]->get();
Vec3f c = (*t)[2]->get();
// Vec3f d = (*t)[3]->get();
glVertex3f(a.x(),a.y(),a.z());
glVertex3f(b.x(),b.y(),b.z());
glVertex3f(b.x(),b.y(),b.z());
glVertex3f(c.x(),c.y(),c.z());
glVertex3f(c.x(),c.y(),c.z());
// glVertex3f(d.x(),d.y(),d.z());
//glVertex3f(d.x(),d.y(),d.z());
glVertex3f(a.x(),a.y(),a.z());
glEnd();
glEnable(GL_LIGHTING);
}
glDisable(GL_POLYGON_OFFSET_FILL);
HandleGLError();
if(args->show_number)
{
GLboolean bb;
glGetBooleanv(GL_LIGHT0,&bb);
printf("light0 is %d\n",bb);
if(bb==false)
glEnable(GL_LIGHT0);
vector<trio> vect = getMesh()->undo_operations;
glColor3f(1,1,0);
GLfloat line_width;
glGetFloatv(GL_LINE_WIDTH,&line_width);
GLfloat params[2];
glGetFloatv(GL_LINE_WIDTH_RANGE,params);
glLineWidth(params[0]*0.6+params[1]*0.4);
GLdouble model[16],proj[16];
GLint view[4];
glGetIntegerv(GL_VIEWPORT,view);
glGetDoublev(GL_MODELVIEW_MATRIX,model);
glGetDoublev(GL_PROJECTION_MATRIX,proj);
HandleGLError();
// printf("projection matrix:\n");
/*
for(int counter=0; counter<4; counter++)
{
for(int counter1=0; counter1<4; counter1++)
{
printf("%lf ",proj[counter*4+counter1]);
}
printf("\n");
}
printf("\n");
printf("modelview matrix:\n");
for(int counter=0; counter<4; counter++)
{
for(int counter1=0; counter1<4; counter1++)
{
printf("%lf ",model[counter*4+counter1]);
}
printf("\n");
}*/
GLdouble winx,winy,winz;
// printf("__________________________________________________________\n");
while(!vect.empty())
{
trio temp = vect.back();
Vec3f one,two,three;
one = getFaceFromID(temp.a)->getCenter();
two = getFaceFromID(temp.b)->getCenter();
three = getFaceFromID(temp.c)->getCenter();
Vec3f av = (one+two+three)/3;
one = getFaceFromID(temp.a)->getNormal();
two = getFaceFromID(temp.b)->getNormal();
three = getFaceFromID(temp.c)->getNormal();
Vec3f av1 = (one+two+three)/3;
av1.Normalize();
Vec3f av2= av-av1*3;
char buff[10];
sprintf(buff,"n%d",temp.edit_number);
glPushMatrix();
// gluLookAt(av.x(),av.y(),av.z(),av2.x(),av2.y(),av2.z(),0,0,1);
bool test = gluProject(av.x(),av.y(),av.z(),model,proj,view,&winx,&winy,&winz);
if(test == false)
printf("gluproject failed\n");
//printf("winx winy winz %d %d %d\n",int(winx),int(winy),int(winz));
//glMatrixMode(GL_MODELVIEW);
//glLoadIdentity();
//glTranslatef(0,0,-1);
//glRasterPos2f(0.5,0.5);
// printf("av2 %f %f %f\n\n\n",av2.x(),av2.y(),av2.z());
//printf("final pos = %lf %lf %lf %lf\n",pos[0],pos[1],pos[2],pos[3]);
//printf("Av1 %f %f %f\n",av1.x(),av1.y(),av1.z());
Vec3f zvec = Vec3f(0,0,-1);
Vec3f zv = Vec3f(0,0,1);
Vec3f cross;
Vec3f::Cross3(cross,zvec,av1);
cross.Normalize();
Matrix m= Matrix::MakeAxisRotation(cross,-acos(zvec.Dot3(av1)));
/* for(int counter=0; counter<16; counter++)
{
printf("%lf ",m.Get(counter/4,counter%4));
if(counter%4==3)
printf("\n");
}*/
Vec3f new1 = Vec3f(m.Get(0,0),m.Get(1,0),m.Get(2,0));
/*if(av1.Dot3(zv)> 0)
new1=Vec3f(0,0,0)-new1;
*/
Vec3f new2;
/*
if(av1.Dot3(zv)<0)*/
Vec3f::Cross3(new2,Vec3f(1,0,0),av1);
/*
else
Vec3f::Cross3(new2,Vec3f(1,0,0),av1);
*/
/*
printf("Details :\n AV1");av1.Write();
printf("\nCross :");cross.Write();
printf("\nnew1 :");new1.Write();
printf("\n new2 : ");new2.Write();
printf("\n zv : ");zv.Write();
printf("angle of rotation matrix %lf\n",-180/M_PI*acos(zvec.Dot3(av1)));
glColor3f(1,0,0);
glBegin(GL_LINES);
glVertex3f(av.x(),av.y(),av.z());
glVertex3f(av.x()+10,av.y(),av.z());
glColor3f(0,1,1);
glVertex3f(av.x(),av.y(),av.z());
glVertex3f(av.x(),av.y(),av.z()+30);
glColor3f(1,1,0);
glVertex3f(av.x(),av.y(),av.z());
glVertex3f(av.x()-10*av1.x(),av.y()-10*av1.y(),av.z()-10*av1.z());
glColor3f(1,0,1);
glVertex3f(av.x(),av.y(),av.z());
glVertex3f(av.x()+10*new2.x(),av.y()+10*new2.y(),av.z()+10*new2.z());
glColor3f(1,1,1);
glVertex3f(av.x(),av.y(),av.z());
glVertex3f(av.x()+100*new1.x(),av.y()+100*new1.y(),av.z()+100*new1.z());
glEnd();*/
new2.Normalize();
glTranslatef(av2.x(),av2.y(),av2.z());
//if(cross.Length()>0.05)
{
glRotatef(180/M_PI*acos(zvec.Dot3(av1)),cross.x(),cross.y(),cross.z());
//printf("angle of rot needed = %lf\n\n\n\n",(double)(90-180/M_PI*acos(new2.Dot3(new1))));
}
glRotatef((90-180/M_PI*acos(new2.Dot3(new1))),0,0,1);
glScalef(0.03,0.03,0.03);
// glRotatef(180.0/M_PI*acos(av1.x()),1,0,0);
// glRotatef(180.0/M_PI*acos(av1.y()),0,1,0);
render_stroke_string(GLUT_STROKE_ROMAN,buff);
glPopMatrix();
vect.pop_back();
}
//printf("__________________________________________________________\n");
glLineWidth(line_width);
if(bb==false)
glDisable(GL_LIGHT0);
}
if (args->wireframe) {
mesh->PaintWireframe();
}
if(args->votes)
{
glDisable(GL_LIGHTING);
mesh->PaintVotes(args->vote_number);
glEnable(GL_LIGHTING);
}
// mesh->PaintCenterLines();
if(args->points)
{
mesh->PaintConfidence();
}
if(args->volume_rendering && args->render_mode !=RENDER_SELECTION)
{
if(!volume_rendering_setup_complete)
{
volume_rendering_setup_complete=true;
mesh->texture_list_init();
HandleGLError();
}
// glEnable(GL_TEXTURE_3D);
glDisable(GL_LIGHTING);
glDisable(GL_DEPTH_TEST);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glColor4f(1,1,1,0.5);
//CHANGED!!!!
//PFNGLBLENDEQUATIONPROC glBlendEquation = (PFNGLBLENDEQUATIONPROC) wglGetProcAddress("glBlendEquation");
//glBlendEquation(GL_MAX);
//glBlendFunc(GL_ONE,GL_ONE);
//glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
//printf("%s",glGetString(GL_EXTENSIONS));
HandleGLError();
// gluLookAt(0,0,30,0,0,10,0,1,0);
glColor3f(1,0,0);
//glTranslatef(60,0,-10);
//glTranslatef(1.5,1.5,0);
glTranslatef(0.5,0.5,0.5);
//printf("\nrdepth = %u\n",mesh->rdepth);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
for(int counter=mesh->rdepth-1; counter>=0; counter--)
{
//printf("%u ",mesh->texturexy[counter]);
//glColor3f(1.0,0.0,0.0);
glBindTexture(GL_TEXTURE_2D, mesh->texturexy[counter]);
glBegin(GL_QUADS);
glTexCoord2f(0,0);glVertex3f(0,mesh->rlength/SKIP,counter);
glTexCoord2f(1,0);glVertex3f(mesh->rwidth/SKIP,mesh->rlength/SKIP,counter);
glTexCoord2f(1,1);glVertex3f(mesh->rwidth/SKIP,0,counter);
glTexCoord2f(0,1);glVertex3f(0,0,counter);
glEnd();
}
/*
glColor4f(1,1,1,1);
glBegin(GL_TRIANGLES);
glVertex3f(-100,-100,0);
glVertex3f(-100,100,0);
glVertex3f(100,100,100);
glEnd();
*/
// glTranslatef(-1.5,-1.5,0);
glDisable(GL_BLEND);
glDisable(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
//glCallList(mesh->list);
mesh->getBoundingBox()->Print();
// glCallList(GLCanvas::list);
// printf("I was called man!\n");
HandleGLError();
}
//draw_transparent_sphere(10);
/*GLint glmaxnamestackdepth;
glGetIntegerv(GL_MAX_NAME_STACK_DEPTH,&glmaxnamestackdepth);
printf("GL_MAX_NAME_STACK_DEPTH %u\n", glmaxnamestackdepth);
if(glmaxnamestackdepth >=1)
printf("niceeeeee :D we have enough space in the name depth stack\n");
*/
}
void draw_transparent_sphere(GLfloat radius)
{
glDepthMask(GL_FALSE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
glColor4f(1.0, 0.0, 0.0, 0.3);
DrawSphere(radius,3); // file attached
glDisable(GL_BLEND);
glDepthMask(GL_TRUE);
}
Face * Radiosity::getFaceFromID(int id)
{
//assert(id>=1);
return patches[id-1];
}
int processHits (GLint hits, GLuint buffer[]);
Vec3f getCenter1(Face * f)
{
Edge *e = f->getEdge();
Vec3f center = Vec3f(0,0,0);
for(int co = 0; co <3; co++)
{
center = center + e->getVertex()->get();
e = e->getNext();
}
center = center/3.0;
return center;
}
void GLCanvas::show_editing(void)
{
Array<Face*> arr1(1000);
Array<Face*> arr2(1000);
//printf("Entering show_editing\n");
//int n = picked_faces;
if(picked_faces == 2)
{
/*printf("Picked_faces==2");
glBegin(GL_LINES);
Vec3f vec = (faces_picked[0]->getCenter())-Vec3f(0,0,0.1);
glVertex3f(vec.x(),vec.y(),vec.z());
vec =(faces_picked[1]->getCenter())-Vec3f(0,0,0.1);
glVertex3f(vec.x(),vec.y(),vec.z());
glEnd();*/
faces_picked[1]->setColor(Vec3f(1,0,0));
}
else if (picked_faces == 1)
{
/*printf("Picked_faces==1");
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
Vec3f v = (faces_picked[0]->getCenter());
glTranslatef(v.x(),v.y(),v.z());
DrawSphere(1,3);
glPopMatrix();*/
faces_picked[0]->setColor(Vec3f(1,0,0));
}
else if(picked_faces == 3)
{
faces_picked[0]->setColor(Vec3f(1,1,1));
faces_picked[1]->setColor(Vec3f(1,1,1));
trio tri;
tri.a = num_picked[0];
tri.b = num_picked[1];
tri.c = num_picked[2];
tri.type = curr_type;
tri.edit_number = radiosity->getMesh()->undo_operations.size();
strcpy(tri.annotation,curr_annotation);
radiosity->getMesh()->undo_operations.push_back(tri);
while(!radiosity->getMesh()->redo_operations.empty())
radiosity->getMesh()->redo_operations.pop_back();
for(int counter=0; counter<3; counter++)
{
if(faces_picked[counter]==NULL)
printf("faces_picked[%d] is NULL!\n",counter);
}
// printf("Picked_faces==3");
double h = (faces_picked[0]->getCenter()-faces_picked[1]->getCenter()).Length();
Vec3f nor = (faces_picked[0]->getCenter())-(faces_picked[1]->getCenter());
nor.Normalize();
Vec3f temppoint = ((faces_picked[2]->getCenter())-(faces_picked[1]->getCenter()));
double lambda = temppoint.Dot3(nor);
double radius = ((faces_picked[2]->getCenter())-((faces_picked[1]->getCenter())+lambda*nor)).Length();
// printf("About to do BFS\n");
arr1.Clear();
arr2.Clear();
BFS_debug(faces_picked[0],30,&arr1);
BFS_debug(faces_picked[1],30,&arr2);
// printf("Reached till the end of doing debug_BFS\n");
//return;
for(int counter=0; counter<arr1.Count(); counter++)
{
Vec3f center1 = (arr1[counter]->getCenter());
double lambda_temp = (center1- (faces_picked[1]->getCenter())).Dot3(nor);
if(lambda_temp >=0 && lambda_temp <= h)
{
// its probably inside the cylinder
double radius_temp = (center1-((faces_picked[1]->getCenter())+lambda_temp*nor)).Length();
if(radius_temp < radius)
{
// its inside
if(curr_type ==0)
arr1[counter]->setColor(Vec3f(0,1,0));
else
arr1[counter]->setColor(Vec3f(1,0,0));
}
}
}
// printf("Reached till the end of first loop\n");
for(int counter=0; counter<arr2.Count(); counter++)
{
Vec3f center1 = (arr2[counter]->getCenter());
double lambda_temp = (center1- (faces_picked[1]->getCenter())).Dot3(nor);
if(lambda_temp >0 && lambda_temp < h)
{
// its probably inside the cylinder
double radius_temp = (center1-((faces_picked[1]->getCenter())+lambda_temp*nor)).Length();
if(radius_temp < radius)
{
// its inside
if(curr_type ==0)
arr2[counter]->setColor(Vec3f(0,1,0));
else
arr2[counter]->setColor(Vec3f(1,0,0));
}
}
}
// printf("Reached till the end of second loop\n");
}
//printf("Exiting show_editing\n");
}
void GLCanvas::remove_editing()
{
Array<Face*> arr1(1000);
Array<Face*> arr2(1000);
if(radiosity->getMesh()->undo_operations.empty())
{
printf("Nothing to undo!\n");
return;
}
trio top = radiosity->getMesh()->undo_operations.back();
faces_picked[0]=radiosity->getFaceFromID(top.a);
faces_picked[1]=radiosity->getFaceFromID(top.b);
faces_picked[2]=radiosity->getFaceFromID(top.c);
radiosity->getMesh()->undo_operations.pop_back();
if(!radiosity->getMesh()->undo_operations.empty())
strcpy(curr_annotation,radiosity->getMesh()->undo_operations.back().annotation);
else
strcpy(curr_annotation,"");
radiosity->getMesh()->redo_operations.push_back(top);
double h = (faces_picked[0]->getCenter()-faces_picked[1]->getCenter()).Length();
Vec3f nor = (faces_picked[0]->getCenter())-(faces_picked[1]->getCenter());
nor.Normalize();
Vec3f temppoint = ((faces_picked[2]->getCenter())-(faces_picked[1]->getCenter()));
double lambda = temppoint.Dot3(nor);
double radius = ((faces_picked[2]->getCenter())-((faces_picked[1]->getCenter())+lambda*nor)).Length();
//printf("About to do BFS\n");
arr1.Clear();
arr2.Clear();
BFS_debug(faces_picked[0],30,&arr1);
BFS_debug(faces_picked[1],30,&arr2);
//printf("Reached till the end of doing debug_BFS\n");
//return;
for(int counter=0; counter<arr1.Count(); counter++)
{
Vec3f center1 = (arr1[counter]->getCenter());
double lambda_temp = (center1- (faces_picked[1]->getCenter())).Dot3(nor);
if(lambda_temp >=0 && lambda_temp <= h)
{
// its probably inside the cylinder
double radius_temp = (center1-((faces_picked[1]->getCenter())+lambda_temp*nor)).Length();
if(radius_temp < radius)
{
// its inside
arr1[counter]->setColor(Vec3f(1,1,1));
}
}
}
//printf("Reached till the end of first loop\n");
for(int counter=0; counter<arr2.Count(); counter++)
{
Vec3f center1 = (arr2[counter]->getCenter());
double lambda_temp = (center1- (faces_picked[1]->getCenter())).Dot3(nor);
if(lambda_temp >0 && lambda_temp < h)
{
// its probably inside the cylinder
double radius_temp = (center1-((faces_picked[1]->getCenter())+lambda_temp*nor)).Length();
if(radius_temp < radius)
{
// its inside
arr2[counter]->setColor(Vec3f(1,1,1));
}
}
}
}
void GLCanvas::redo_editing()
{
Array<Face*> arr1(1000);
Array<Face*> arr2(1000);
if(radiosity->getMesh()->redo_operations.empty())
{
printf("Nothing to redo!\n");
return;
}
trio top = radiosity->getMesh()->redo_operations.back();
faces_picked[0]=radiosity->getFaceFromID(top.a);
faces_picked[1]=radiosity->getFaceFromID(top.b);
faces_picked[2]=radiosity->getFaceFromID(top.c);
strcpy(curr_annotation,top.annotation);
radiosity->getMesh()->redo_operations.pop_back();
radiosity->getMesh()->undo_operations.push_back(top);
double h = (faces_picked[0]->getCenter()-faces_picked[1]->getCenter()).Length();
Vec3f nor = (faces_picked[0]->getCenter())-(faces_picked[1]->getCenter());
nor.Normalize();
Vec3f temppoint = ((faces_picked[2]->getCenter())-(faces_picked[1]->getCenter()));
double lambda = temppoint.Dot3(nor);
double radius = ((faces_picked[2]->getCenter())-((faces_picked[1]->getCenter())+lambda*nor)).Length();
// printf("About to do BFS\n");
arr1.Clear();
arr2.Clear();
BFS_debug(faces_picked[0],30,&arr1);
BFS_debug(faces_picked[1],30,&arr2);
// printf("Reached till the end of doing debug_BFS\n");
//return;
for(int counter=0; counter<arr1.Count(); counter++)
{
Vec3f center1 = (arr1[counter]->getCenter());
double lambda_temp = (center1- (faces_picked[1]->getCenter())).Dot3(nor);
if(lambda_temp >=0 && lambda_temp <= h)
{
// its probably inside the cylinder
double radius_temp = (center1-((faces_picked[1]->getCenter())+lambda_temp*nor)).Length();
if(radius_temp < radius)
{
// its inside
if(curr_type ==0)
arr1[counter]->setColor(Vec3f(0,1,0));
else
arr1[counter]->setColor(Vec3f(1,0,0));
}
}
}
// printf("Reached till the end of first loop\n");
for(int counter=0; counter<arr2.Count(); counter++)
{
Vec3f center1 = (arr2[counter]->getCenter());
double lambda_temp = (center1- (faces_picked[1]->getCenter())).Dot3(nor);
if(lambda_temp >0 && lambda_temp < h)
{
// its probably inside the cylinder
double radius_temp = (center1-((faces_picked[1]->getCenter())+lambda_temp*nor)).Length();
if(radius_temp < radius)
{
// its inside
if(curr_type ==0)
arr2[counter]->setColor(Vec3f(0,1,0));
else
arr2[counter]->setColor(Vec3f(1,0,0));
}
}
}
}
void GLCanvas::get_annotation(void)
{
printf("\nEnter the annotation for the current edit :");
if( fgets(curr_annotation, sizeof(curr_annotation), stdin) == NULL )
{
cerr << "fgets returned null..." << endl;
}
}
void GLCanvas::load_edits(void)
{
printf("\n Enter the filename to load the edits from: ");
char filename[512];
if( fgets(filename, sizeof(filename), stdin) == NULL )
{
cerr << "fgets returned null..." << endl;
}
//char ch;
//while((ch=getc(stdin))!=EOF);
FILE * fp = fopen(filename,"r");
if(fp==NULL)
{
printf("Couldn't open %s for reading\n",filename);
return;
}
int num;
trio t;
int pc = 0;
while(fscanf(fp,"Edit %d\n",&num)>0)
{
pc++;
if( fscanf(fp,"Type %d\n",&curr_type) == EOF )
{
cerr << "EOF encountered by fscanf" << endl;
}
t.type = curr_type;
t.edit_number = num;
if( fscanf(fp,"Triangles %d %d %d\n",&t.a,&t.b,&t.c) == EOF )
{
cerr << "EOF encountered by fscanf" << endl;
}
if( fgets(filename,512,fp) == NULL )
{
cerr << "fgets returned null..." << endl;
}
printf("f-%s\n",filename);
if( fgets(filename,512,fp) == NULL )
{
cerr << "fgets returned null..." << endl;
}
printf("f-%s\n",filename);
if( fgets(filename,512,fp) == NULL )
{
cerr << "fgets returned null..." << endl;
}
printf("f-%s\n",filename);
//finished throwing junk
int unused = fscanf(fp,"Annotation:'");
unused++;
if( fgets(t.annotation,512,fp) == NULL )
{
cerr << "fgets returned null..." << endl;
}
// printf("\nt.annotation size = %d\n t.annotation = |%s|\n",strlen(t.annotation),t.annotation);
t.annotation[strlen(t.annotation)-2]=0;
// printf("annot-%s-",t.annotation);
strcpy(curr_annotation,t.annotation);
Array<Face*> arr1(1000);
Array<Face*> arr2(1000);
faces_picked[0]=radiosity->getFaceFromID(t.a);
faces_picked[1]=radiosity->getFaceFromID(t.b);
faces_picked[2]=radiosity->getFaceFromID(t.c);
//radiosity->getMesh()->redo_operations.pop();
radiosity->getMesh()->undo_operations.push_back(t);
double h = (faces_picked[0]->getCenter()-faces_picked[1]->getCenter()).Length();
Vec3f nor = (faces_picked[0]->getCenter())-(faces_picked[1]->getCenter());
nor.Normalize();
Vec3f temppoint = ((faces_picked[2]->getCenter())-(faces_picked[1]->getCenter()));
double lambda = temppoint.Dot3(nor);
double radius = ((faces_picked[2]->getCenter())-((faces_picked[1]->getCenter())+lambda*nor)).Length();
// printf("About to do BFS\n");
arr1.Clear();
arr2.Clear();
BFS_debug(faces_picked[0],30,&arr1);
BFS_debug(faces_picked[1],30,&arr2);
// printf("Reached till the end of doing debug_BFS\n");
//return;
for(int counter=0; counter<arr1.Count(); counter++)
{
Vec3f center1 = (arr1[counter]->getCenter());
double lambda_temp = (center1- (faces_picked[1]->getCenter())).Dot3(nor);
if(lambda_temp >=0 && lambda_temp <= h)
{
// its probably inside the cylinder
double radius_temp = (center1-((faces_picked[1]->getCenter())+lambda_temp*nor)).Length();
if(radius_temp < radius)
{
// its inside
if(curr_type ==0)
arr1[counter]->setColor(Vec3f(0,1,0));
else
arr1[counter]->setColor(Vec3f(1,0,0));
}
}
}
// printf("Reached till the end of first loop\n");
for(int counter=0; counter<arr2.Count(); counter++)
{
Vec3f center1 = (arr2[counter]->getCenter());
double lambda_temp = (center1- (faces_picked[1]->getCenter())).Dot3(nor);
if(lambda_temp >0 && lambda_temp < h)
{
// its probably inside the cylinder
double radius_temp = (center1-((faces_picked[1]->getCenter())+lambda_temp*nor)).Length();
if(radius_temp < radius)
{
// its inside
if(curr_type ==0)
arr2[counter]->setColor(Vec3f(0,1,0));
else
arr2[counter]->setColor(Vec3f(1,0,0));
}
}
}
/* if(num==1)
for(;;);*/
}
// printf("final num %d\n",num);
printf("Loaded Edits\n");
fclose(fp);
}
void GLCanvas::save_edits(void)
{
//save the edits in a file
//ask for the filename
printf("\nEnter the filename to save the edits: ");
char filename[512];
if( fgets(filename, sizeof(filename), stdin) == NULL )
{
cerr << "fgets returned null..." << endl;
}
printf("Writing to file %s\n",filename);
FILE * fp = fopen(filename,"w");
vector<trio> stk = radiosity->getMesh()->undo_operations;
//int si = stk.size();
while(!stk.empty())
{
trio temp = stk.back();
Vec3f one,two,three;
one = radiosity->getFaceFromID(temp.a)->getCenter();
two = radiosity->getFaceFromID(temp.b)->getCenter();
three = radiosity->getFaceFromID(temp.c)->getCenter();
fprintf(fp,"Edit %d\nType %d\nTriangles %d %d %d\npos1 %lf %lf %lf\npos2 %lf %lf %lf\npos3 %lf %lf %lf\nAnnotation:'%s'\n",temp.edit_number,temp.type,temp.a,temp.b,temp.c,one.x(),one.y(),one.z(),two.x(),two.y(),two.z(),three.x(),three.y(),three.z(),temp.annotation);
stk.pop_back();
}
printf("Edits saved\n");
fclose(fp);
}
void GLCanvas::PickPaint(int x, int y) {
//assert_stackdump(HandleGLError());
//meshes->args->render_vis_mode = 1;
//glui->sync_live();
//Mesh *mesh = radiosity->getMesh();
// select triangle with mouse click!
GLint viewport[4];
glSelectBuffer(BUFSIZE,selectBuf);
(void) glRenderMode (GL_SELECT);
//assert_stackdump(HandleGLError());
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
//camera->glPlaceCamera();
glGetIntegerv(GL_VIEWPORT,viewport);
gluPickMatrix(x,viewport[3]-y-1,5,5,viewport);
//double ratio = 1;
int w = args->width;
int h = args->height;
// printf("w = %d h = %d\n",w,h);
double aspect = double(w)/double(h);
double asp_angle = camera->getAngle() * 180/M_PI;
if (aspect > 1) asp_angle /= aspect;
gluPerspective(asp_angle, aspect, 1, 100.0);
glMatrixMode(GL_MODELVIEW);
//camera->glPlaceCamera();
glInitNames();
//render for select here
//Render::renderForSelect(meshes);
bool vol_render = args->volume_rendering;
bool wire_render = args->wireframe;
args->volume_rendering=false;
args->wireframe = false;
//render here
enum RENDER_MODE curr_rm = args->render_mode;
args->render_mode = RENDER_SELECTION;
//printf("I'm about to call display\n");
// display
display_select(0,0);
// end display
//printf("I finished calling display!\n");
//radiosity->Paint(args);
args->render_mode = curr_rm;
args->volume_rendering = vol_render;
args->wireframe = wire_render;
//assert_stackdump(HandleGLError());
int hits;
HandleGLError();
// restoring the original projection matrix
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glFlush();
// returning to normal rendering mode
hits = glRenderMode(GL_RENDER);
// if there are hits process them
int id = -1;
if(hits!=0)
printf("I got a hit! hits = %d\n",hits);
else
printf("no hits :(\n");
if (hits != 0)
id = processHits(hits,selectBuf);
// assert_stackdump(HandleGLError());
PICKED = NULL;
LAST_MOUSE = Vec3f(0,0,0);
CENTER = Vec3f(0,0,0);
if (id >= 0) {
// printf("\nand I got an id too! %d\n",id);
Face *e = radiosity->getFaceFromID(id);
if(picked_faces <3)
{
faces_picked[picked_faces]=e;
num_picked[picked_faces]=id;
picked_faces ++;
show_editing();
if(picked_faces==3)
{
strcpy(curr_annotation,"");
picked_faces=0;
}
}
//assert_stackdump (e != NULL && e->isATriangle());
PICKED = (Face*)e;
Array<Face*> arr(50);
/*BFS_debug(e,5,&arr);
for(int counter=0; counter<arr.Count(); counter++)
arr[counter]->setColor(Vec3f(1,0,1));
if(e->getColor()==Vec3f(1,0,0))
{
printf("Already picked face :(\n");
}*/
//e->setColor(Vec3f(1,0,0));
// Vec3f vert = (*e)[0]->get();
// Vec3f normal=Vec3f(0,0,0)- PICKED->getNormal();
// // find the point on the image plane!
// // do the matrix stuff
// GLdouble modelview[16], projmatr[16];
// GLint viewport[4];
// glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
// glGetDoublev(GL_PROJECTION_MATRIX, projmatr);
// glGetIntegerv(GL_VIEWPORT, viewport);
// y = viewport[3]-y-1; // it's upside down
//
// GLdouble modelX, modelY, modelZ;
// gluUnProject(x, y, 0, modelview, projmatr, viewport, &modelX,
//&modelY, &modelZ);
//
// Vec3f center = Vec3f(modelX,modelY,modelZ);
//
// gluUnProject(x, y, 1, modelview, projmatr, viewport, &modelX,
//&modelY, &modelZ);
//
// Vec3f image_point = Vec3f(modelX,modelY,modelZ);
// Vec3f direction = image_point - center;
// direction.Normalize();
//
// CENTER = center;
//
// double d1 = vert.Dot3(normal);
// double d2 = center.Dot3(normal);
// double d3 = (center+direction).Dot3(normal);
//
// double depth = (d2-d1) / (d2-d3);
//
// LAST_MOUSE = center + depth*direction;
//double radius = meshes->args->painting_radius;
//meshes->getTriangleMesh()->Paint(PICKED,LAST_MOUSE, radius,(density-1)/8.0);
}
Render();
//display();
HandleGLError();
//rerender_sceneCB(0);
// assert_stackdump(HandleGLError());
}
int processHits (GLint hits, GLuint buffer[]) {
int i;
unsigned int j;
GLuint names, *ptr, minZ;
GLuint numberOfNames = 0;
GLuint *ptrNames = 0;
if (hits <= 0) return -1;
ptr = (GLuint *) buffer;
minZ = 0xffffffff;
for (i = 0; i < hits; i++) {
names = *ptr;
ptr++;
// printf("*ptr = %u minZ = %u\n",*ptr,minZ);
if (*ptr < minZ) {
numberOfNames = names;
minZ = *ptr;
ptrNames = ptr+2;
}
ptr += names+2;
}
// assert_stackdump (numberOfNames == 1);
//printf("number of names = %d", numberOfNames);
ptr = ptrNames;
for (j = 0; j < numberOfNames; j++,ptr++) {
return *ptr;
}
// printf("I came here\n");
return 0;
}
// =======================================================================
// =======================================================================
| 29.220588 | 268 | 0.610695 | [
"mesh",
"geometry",
"render",
"vector",
"model"
] |
748b83089fc0bded32a9bdc97590808dcdd7c7af | 5,396 | cpp | C++ | include/Music/Music.cpp | sonich2401/SM64_Save_File_Converter | bd6876d66cbc3177b634540c7a2241e0ae8c759c | [
"MIT-0"
] | 6 | 2020-07-27T19:07:37.000Z | 2021-08-29T19:16:07.000Z | include/Music/Music.cpp | sonich2401/SM64_Save_File_Converter | bd6876d66cbc3177b634540c7a2241e0ae8c759c | [
"MIT-0"
] | 2 | 2021-06-09T05:49:41.000Z | 2022-01-30T04:06:40.000Z | include/Music/Music.cpp | sonich2401/SM64_Save_File_Converter | bd6876d66cbc3177b634540c7a2241e0ae8c759c | [
"MIT-0"
] | null | null | null | /*RenDev#2616 SM64SFM
Copyright (C) 2021 RenDev
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted.
Permission is also granted to not credit the author in any way as long as you do not take credit
for this piece of software.
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.
Contact me at vgngamingnetwork@gmail.com if you need to contact me about this licence*/
#include "Music.h"
#define CHANNEL_COUNT 2
#define SAMPLE_FORMAT ma_format_f32
#define SAMPLE_RATE 48000
Music* mixer;
ma_uint32 read_and_mix_pcm_frames_f32(ma_decoder* pDecoder, float* pOutputF32, float gain, ma_uint32 frameCount)
{
/*
The way mixing works is that we just read into a temporary buffer, then take the contents of that buffer and mix it with the
contents of the output buffer by simply adding the samples together. You could also clip the samples to -1..+1, but I'm not
doing that in this example.
*/
#define TEMP_BUFF_SIZE__MIXER 4069
float temp[TEMP_BUFF_SIZE__MIXER];
ma_uint32 tempCapInFrames = TEMP_BUFF_SIZE__MIXER / CHANNEL_COUNT;
ma_uint32 totalFramesRead = 0;
while (totalFramesRead < frameCount) {
ma_uint32 iSample;
ma_uint32 framesReadThisIteration;
ma_uint32 totalFramesRemaining = frameCount - totalFramesRead;
ma_uint32 framesToReadThisIteration = tempCapInFrames;
if (framesToReadThisIteration > totalFramesRemaining) {
framesToReadThisIteration = totalFramesRemaining;
}
framesReadThisIteration = (ma_uint32)ma_decoder_read_pcm_frames(pDecoder, temp, framesToReadThisIteration);
if (framesReadThisIteration == 0) {
break;
}
/* Mix the frames together. */
for (iSample = 0; iSample < framesReadThisIteration*CHANNEL_COUNT; ++iSample) {
//pOutputF32[totalFramesRead*CHANNEL_COUNT + iSample] += temp[iSample];
pOutputF32[totalFramesRead*CHANNEL_COUNT + iSample] += temp[iSample] * gain;
}
totalFramesRead += framesReadThisIteration;
if (framesReadThisIteration < framesToReadThisIteration) {
break; /* Reached EOF. */
}
}
return totalFramesRead;
}
void data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount)
{
float* pOutputF32 = (float*)pOutput;
std::vector<int> to_delete;
for (int iDecoder = 0; iDecoder < mixer->decoders.size(); iDecoder++) {
ma_uint32 framesRead = read_and_mix_pcm_frames_f32(&mixer->decoders[iDecoder]->file, pOutputF32, mixer->decoders[iDecoder]->gain, frameCount);
if (framesRead < frameCount) {
if(!mixer->decoders[iDecoder]->loops){
mixer->decoders[iDecoder]->end = true;
to_delete.push_back(iDecoder);
}
else
mixer->decoders[iDecoder]->GoToStart();
}
}
for(auto& del : to_delete){
delete mixer->decoders[del];
mixer->decoders.erase(mixer->decoders.begin() + del);
}
(void)pInput;
}
Music::Music(){
mixer= this;
deviceConfig = ma_device_config_init(ma_device_type_playback);
deviceConfig.playback.format = SAMPLE_FORMAT;
deviceConfig.playback.channels = CHANNEL_COUNT;
deviceConfig.sampleRate = SAMPLE_RATE;
deviceConfig.dataCallback = data_callback;
deviceConfig.pUserData = NULL;
ma_device_init(NULL, &deviceConfig, &device);
ma_device_start(&device);
decoderConfig = ma_decoder_config_init(SAMPLE_FORMAT, CHANNEL_COUNT, SAMPLE_RATE);
}
void Music::AddFile(std::string file_path, unsigned char gain, bool loop){
for(auto& dec : decoders){
if(dec->fp == file_path){
dec->GoToStart();
return;
}
}
decoders.push_back(new MusicFile(file_path, gain, loop));
}
void Music::Clear(){
for(auto& dec : this->decoders){
delete dec;
}
decoders.clear();
}
Music::~Music(){
ma_device_uninit(&device);
for(auto& dec : this->decoders){
delete dec;
}
}
MusicFile::MusicFile(std::string fn, unsigned char _gain, bool loop){
ma_decoder_init_file(fn.c_str(), (const ma_decoder_config*)&mixer->decoderConfig, &file);
this->loops = loop;
this->end = false;
this->paused = false;
this->fp = fn;
this->gain = float(_gain)/255;
}
void MusicFile::TogglePause(){
this->paused = !this->paused;
}
void MusicFile::Pause(){
this->paused = true;
}
void MusicFile::Play(){
this->paused = false;
}
void MusicFile::GoToStart(){
ma_decoder_seek_to_pcm_frame(&file, 0);
}
void MusicFile::SeekTo(float time){
unsigned long long int frame = ((unsigned long long int)(SAMPLE_RATE * time));
ma_decoder_seek_to_pcm_frame(&file, frame);
}
MusicFile::~MusicFile(){
ma_decoder_uninit(&this->file);
} | 31.555556 | 170 | 0.680319 | [
"vector"
] |
748c5fd2211650f1a121f46432c56de623ccec59 | 11,683 | cpp | C++ | src/subcommand/explode_main.cpp | pjotrp/odgi | 4eb47f891d768bb5150dda763948f2c7441d67dc | [
"MIT"
] | null | null | null | src/subcommand/explode_main.cpp | pjotrp/odgi | 4eb47f891d768bb5150dda763948f2c7441d67dc | [
"MIT"
] | null | null | null | src/subcommand/explode_main.cpp | pjotrp/odgi | 4eb47f891d768bb5150dda763948f2c7441d67dc | [
"MIT"
] | null | null | null | #include "subcommand.hpp"
#include "args.hxx"
#include <queue>
#include <atomic_bitvector.hpp>
#include "src/algorithms/subgraph/extract.hpp"
namespace odgi {
using namespace odgi::subcommand;
int main_explode(int argc, char **argv) {
// trick argumentparser to do the right thing with the subcommand
for (uint64_t i = 1; i < argc - 1; ++i) {
argv[i] = argv[i + 1];
}
std::string prog_name = "odgi explode";
argv[0] = (char *) prog_name.c_str();
--argc;
args::ArgumentParser parser(
"Breaks a graph into connected components storing each component in its own file.");
args::Group mandatory_opts(parser, "[ MANDATORY OPTIONS ]");
args::ValueFlag<std::string> dg_in_file(mandatory_opts, "FILE", "Load the succinct variation graph in ODGI format from this *FILE*. The file name usually ends with *.og*. It also accepts GFAv1, but the on-the-fly conversion to the ODGI format requires additional time!", {'i', "idx"});
args::Group explode_opts(parser, "[ Explode Options ]");
args::ValueFlag<std::string> _prefix(explode_opts, "STRING",
"Write each connected component to a file with the given STRING prefix. "
"The file for the component `i` will be named `STRING.i.og` "
"(default: `component.i.og`).", {'p', "prefix"});
args::ValueFlag<uint64_t> _write_biggest_components(explode_opts, "N",
"Specify the number of the biggest connected components to write, sorted by decreasing size (default: disabled, for writing them all).",
{'b', "biggest"});
args::ValueFlag<char> _size_metric(explode_opts, "C",
"Specify how to sort the connected components by size:\np) Path mass (total number of path bases) (default).\nl) Graph length (number of node bases).\nn) Number of nodes.\nP) Longest path.",
{'s', "sorting-criteria"});
args::Flag _optimize(explode_opts, "optimize", "Compact the node ID space in each connected component.",
{'O', "optimize"});
args::Group threading_opts(parser, "[ Threading ]");
args::ValueFlag<uint64_t> nthreads(threading_opts, "N",
"Number of threads to use for parallel operations.",
{'t', "threads"});
args::Group processing_info_opts(parser, "[ Processing Information ]");
args::Flag _debug(processing_info_opts, "progress", "Print information about the components and the progress to stderr.",
{'P', "progress"});
args::Group program_info_opts(parser, "[ Program Information ]");
args::HelpFlag help(program_info_opts, "help", "Print a help message for odgi explode.", {'h', "help"});
try {
parser.ParseCLI(argc, argv);
} catch (args::Help) {
std::cout << parser;
return 0;
} catch (args::ParseError e) {
std::cerr << e.what() << std::endl;
std::cerr << parser;
return 1;
}
if (argc == 1) {
std::cout << parser;
return 1;
}
if (!dg_in_file) {
std::cerr
<< "[odgi::explode] error: please specify an input file from where to load the graph via -i=[FILE], --idx=[FILE]."
<< std::endl;
return 1;
}
const uint64_t num_threads = args::get(nthreads) ? args::get(nthreads) : 1;
graph_t graph;
assert(argc > 0);
if (!args::get(dg_in_file).empty()) {
std::string infile = args::get(dg_in_file);
if (infile == "-") {
graph.deserialize(std::cin);
} else {
utils::handle_gfa_odgi_input(infile, "explode", args::get(_debug), num_threads, graph);
}
}
const bool debug = args::get(_debug);
const bool optimize = args::get(_optimize);
std::string output_dir_plus_prefix = "./";
if (!args::get(_prefix).empty()) {
output_dir_plus_prefix += args::get(_prefix);
} else {
output_dir_plus_prefix += "component";
}
std::vector<ska::flat_hash_set<handlegraph::nid_t>> weak_components =
algorithms::weakly_connected_components(&graph);
atomicbitvector::atomic_bv_t ignore_component(weak_components.size());
if (_write_biggest_components && args::get(_write_biggest_components) > 0) {
char size_metric = _size_metric ? args::get(_size_metric) : 'p';
auto get_path_handles = [](const graph_t &graph, const ska::flat_hash_set<handlegraph::nid_t> &node_ids,
set<path_handle_t> &paths) {
for (auto node_id : node_ids) {
handle_t handle = graph.get_handle(node_id);
graph.for_each_step_on_handle(handle, [&](const step_handle_t &source_step) {
paths.insert(graph.get_path_handle_of_step(source_step));
});
}
};
auto get_path_length = [](const graph_t &graph, const path_handle_t &path_handle) {
uint64_t path_len = 0;
graph.for_each_step_in_path(path_handle, [&](const step_handle_t &s) {
path_len += graph.get_length(graph.get_handle_of_step(s));
});
return path_len;
};
std::vector<std::pair<uint64_t, uint64_t>> component_and_size;
component_and_size.resize(weak_components.size());
// Fill the vector with component sizes
#pragma omp parallel for schedule(dynamic, 1) num_threads(num_threads)
for (uint64_t component_index = 0; component_index < weak_components.size(); ++component_index) {
ignore_component.set(component_index);
component_and_size[component_index].first = component_index;
auto &weak_component = weak_components[component_index];
uint64_t size = 0;
switch (size_metric) {
case 'l': {
// graph length (number of node bases)
for (auto node_id : weak_component) {
size += graph.get_length(graph.get_handle(node_id));
}
break;
}
case 'n': {
// number of nodes
size = weak_component.size();
break;
}
case 'P': {
// longest path",
set<path_handle_t> paths;
get_path_handles(graph, weak_component, paths);
uint64_t current_path_len;
for (path_handle_t path_handle : paths) {
current_path_len = get_path_length(graph, path_handle);
if (current_path_len > size) {
size = current_path_len;
}
}
break;
}
default: {
// p: path mass (total number of path bases)
set<path_handle_t> paths;
get_path_handles(graph, weak_component, paths);
for (path_handle_t path_handle : paths) {
size += get_path_length(graph, path_handle);
}
break;
}
}
component_and_size[component_index].second = size;
}
// Sort by component size
std::sort(component_and_size.begin(), component_and_size.end(), [](auto &a, auto &b) {
return a.second > b.second;
});
// Not ignore the first `write_biggest_components` components
uint64_t write_biggest_components = args::get(_write_biggest_components);
for (auto &c_and_s : component_and_size) {
ignore_component.reset(c_and_s.first);
if (--write_biggest_components == 0) {
break;
}
}
// for(auto& c : component_and_size) {
// std::cerr << c.first << " (" << ignore_component.test(c.first) << ") - " << c.second << std::endl;
// }
}
std::unique_ptr<algorithms::progress_meter::ProgressMeter> component_progress;
if (debug) {
component_progress = std::make_unique<algorithms::progress_meter::ProgressMeter>(
weak_components.size(), "[odgi::explode] exploding component(s)");
std::cerr << "[odgi::explode] detected " << weak_components.size() << " connected component(s)"
<< std::endl;
if (_write_biggest_components && args::get(_write_biggest_components) > 0) {
uint64_t write_biggest_components = args::get(_write_biggest_components);
std::cerr << "[odgi::explode] explode the "
<< (write_biggest_components <= weak_components.size() ? write_biggest_components
: weak_components.size())
<< " biggest connected component(s)" << std::endl;
}
}
for (uint64_t component_index = 0; component_index < weak_components.size(); ++component_index) {
if (!ignore_component.test(component_index)) {
auto &weak_component = weak_components[component_index];
graph_t subgraph;
for (auto node_id : weak_component) {
subgraph.create_handle(graph.get_sequence(graph.get_handle(node_id)), node_id);
}
weak_component.clear();
algorithms::add_connecting_edges_to_subgraph(graph, subgraph);
algorithms::add_full_paths_to_component(graph, subgraph, num_threads);
if (optimize) {
subgraph.optimize();
}
const string filename = output_dir_plus_prefix + "." + to_string(component_index) + ".og";
// Save the component
ofstream f(filename);
subgraph.serialize(f);
f.close();
/*if (debug) {
#pragma omp critical (cout)
std::cerr << "Written component num. " << component_index
<< " - num. of nodes " << subgraph.get_node_count()
<< " - num. of paths: " << subgraph.get_path_count()
<< std::endl;
}*/
}
if (debug) {
component_progress->increment(1);
}
}
if (debug) {
component_progress->finish();
}
return 0;
}
static Subcommand odgi_explode("explode", "Breaks a graph into connected components storing each component in its own file.",
PIPELINE, 3, main_explode);
}
| 42.32971 | 293 | 0.514851 | [
"vector"
] |
749395bbeac54a86885ac961831d8bc60a24eb0e | 3,081 | hpp | C++ | stan/math/prim/mat/fun/mdivide_right_tri.hpp | PhilClemson/math | fffe604a7ead4525be2551eb81578c5f351e5c87 | [
"BSD-3-Clause"
] | null | null | null | stan/math/prim/mat/fun/mdivide_right_tri.hpp | PhilClemson/math | fffe604a7ead4525be2551eb81578c5f351e5c87 | [
"BSD-3-Clause"
] | null | null | null | stan/math/prim/mat/fun/mdivide_right_tri.hpp | PhilClemson/math | fffe604a7ead4525be2551eb81578c5f351e5c87 | [
"BSD-3-Clause"
] | null | null | null | #ifndef STAN_MATH_PRIM_MAT_FUN_MDIVIDE_RIGHT_TRI_HPP
#define STAN_MATH_PRIM_MAT_FUN_MDIVIDE_RIGHT_TRI_HPP
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/mat/fun/mdivide_left_tri.hpp>
#include <stan/math/prim/mat/fun/promote_common.hpp>
#include <stan/math/prim/mat/fun/transpose.hpp>
#include <stan/math/prim/mat/err/check_multiplicable.hpp>
#include <stan/math/prim/mat/err/check_square.hpp>
#include <stan/math/prim/scal/err/domain_error.hpp>
#include <boost/math/tools/promotion.hpp>
namespace stan {
namespace math {
/**
* Returns the solution of the system Ax=b when A is triangular
* @param A Triangular matrix. Specify upper or lower with TriView
* being Eigen::Upper or Eigen::Lower.
* @param b Right hand side matrix or vector.
* @return x = b A^-1, solution of the linear system.
* @throws std::domain_error if A is not square or the rows of b don't
* match the size of A.
*/
template <Eigen::UpLoType TriView, typename T1, typename T2, int R1, int C1,
int R2, int C2>
inline Eigen::Matrix<return_type_t<T1, T2>, R1, C2> mdivide_right_tri(
const Eigen::Matrix<T1, R1, C1> &b, const Eigen::Matrix<T2, R2, C2> &A) {
check_square("mdivide_right_tri", "A", A);
check_multiplicable("mdivide_right_tri", "b", b, "A", A);
if (TriView != Eigen::Lower && TriView != Eigen::Upper) {
domain_error("mdivide_left_tri",
"triangular view must be Eigen::Lower or Eigen::Upper", "",
"");
}
return promote_common<Eigen::Matrix<T1, R2, C2>, Eigen::Matrix<T2, R2, C2> >(
A)
.template triangularView<TriView>()
.transpose()
.solve(
promote_common<Eigen::Matrix<T1, R1, C1>, Eigen::Matrix<T2, R1, C1> >(
b)
.transpose())
.transpose();
}
/**
* Returns the solution of the system Ax=b when A is triangular
* and A and b are matrices of doubles.
* @param A Triangular matrix. Specify upper or lower with TriView
* being Eigen::Upper or Eigen::Lower.
* @param b Right hand side matrix or vector.
* @return x = b A^-1, solution of the linear system.
* @throws std::domain_error if A is not square or the rows of b don't
* match the size of A.
*/
template <Eigen::UpLoType TriView, int R1, int C1, int R2, int C2>
inline Eigen::Matrix<double, R1, C2> mdivide_right_tri(
const Eigen::Matrix<double, R1, C1> &b,
const Eigen::Matrix<double, R2, C2> &A) {
check_square("mdivide_right_tri", "A", A);
check_multiplicable("mdivide_right_tri", "b", b, "A", A);
#ifdef STAN_OPENCL
if (A.rows()
>= opencl_context.tuning_opts().tri_inverse_size_worth_transfer) {
matrix_cl<double> A_cl(A, from_eigen_uplo_type(TriView));
matrix_cl<double> b_cl(b);
matrix_cl<double> A_inv_cl = tri_inverse(A_cl);
matrix_cl<double> C_cl = b_cl * A_inv_cl;
return from_matrix_cl(C_cl);
} else {
#endif
return A.template triangularView<TriView>()
.transpose()
.solve(b.transpose())
.transpose();
#ifdef STAN_OPENCL
}
#endif
}
} // namespace math
} // namespace stan
#endif
| 36.247059 | 80 | 0.679 | [
"vector"
] |
74980e42fc7d053709b5ce1584b3fcc2dead7f2e | 2,904 | cpp | C++ | SparCraft/source/UnitScriptData.cpp | TongTongX/defbot | f590b70678043b93e0056ad1c917381fd49509ed | [
"MIT"
] | 15 | 2018-12-29T20:31:28.000Z | 2021-11-27T08:01:59.000Z | SparCraft/source/UnitScriptData.cpp | TongTongX/defbot | f590b70678043b93e0056ad1c917381fd49509ed | [
"MIT"
] | 1 | 2016-11-29T00:11:56.000Z | 2016-12-03T22:29:05.000Z | SparCraft/source/UnitScriptData.cpp | TongTongX/defbot | f590b70678043b93e0056ad1c917381fd49509ed | [
"MIT"
] | 3 | 2019-01-12T09:16:43.000Z | 2020-12-15T16:02:11.000Z | #include "UnitScriptData.h"
using namespace SparCraft;
UnitScriptData::UnitScriptData()
{
}
std::vector<Action> & UnitScriptData::getMoves(const IDType & player, const IDType & actualScript)
{
return _allScriptMoves[player][actualScript];
}
Action & UnitScriptData::getMove(const IDType & player, const IDType & unitIndex, const IDType & actualScript)
{
return _allScriptMoves[player][actualScript][unitIndex];
}
void UnitScriptData::calculateMoves(const IDType & player, MoveArray & moves, GameState & state, std::vector<Action> & moveVec)
{
// generate all script moves for this player at this state and store them in allScriptMoves
for (size_t scriptIndex(0); scriptIndex<_scriptVec[player].size(); ++scriptIndex)
{
// get the associated player pointer
const PlayerPtr & pp = getPlayerPtr(player, scriptIndex);
// get the actual script we are working with
const IDType actualScript = getScript(player, scriptIndex);
// generate the moves inside the appropriate vector
getMoves(player, actualScript).clear();
pp->getMoves(state, moves, getMoves(player, actualScript));
}
// for each unit the player has to move, populate the move vector with the appropriate script move
for (size_t unitIndex(0); unitIndex < moves.numUnits(); ++unitIndex)
{
// the unit from the state
const Unit & unit = state.getUnit(player, unitIndex);
// the move it would choose to do based on its associated script preference
Action unitMove = getMove(player, unitIndex, getUnitScript(unit));
// put the unit into the move vector
moveVec.push_back(unitMove);
}
}
const IDType & UnitScriptData::getUnitScript(const IDType & player, const int & id) const
{
return (*_unitScriptMap[player].find(id)).second;
}
const IDType & UnitScriptData::getUnitScript(const Unit & unit) const
{
return getUnitScript(unit.player(), unit.ID());
}
const IDType & UnitScriptData::getScript(const IDType & player, const size_t & index)
{
return _scriptVec[player][index];
}
const PlayerPtr & UnitScriptData::getPlayerPtr(const IDType & player, const size_t & index)
{
return _playerPtrVec[player][index];
}
const size_t UnitScriptData::getNumScripts(const IDType & player) const
{
return _scriptSet[player].size();
}
void UnitScriptData::setUnitScript(const IDType & player, const int & id, const IDType & script)
{
if (_scriptSet[player].find(script) == _scriptSet[player].end())
{
_scriptSet[player].insert(script);
_scriptVec[player].push_back(script);
_playerPtrVec[player].push_back(PlayerPtr(AllPlayers::getPlayerPtr(player, script)));
}
_unitScriptMap[player][id] = script;
}
void UnitScriptData::setUnitScript(const Unit & unit, const IDType & script)
{
setUnitScript(unit.player(), unit.ID(), script);
} | 32.629213 | 127 | 0.704201 | [
"vector"
] |
749a3f3df63594e149d74020373351ecfbb80488 | 5,632 | cpp | C++ | Libs/Nodes/src/PaletteNode.cpp | n8vm/OpenVisus | dab633f6ecf13ffcf9ac2ad47d51e48902d4aaef | [
"Unlicense"
] | 1 | 2019-04-30T12:11:24.000Z | 2019-04-30T12:11:24.000Z | Libs/Nodes/src/PaletteNode.cpp | tjhei/OpenVisus | f0c3bf21cb0c02f303025a8efb68b8c36701a9fd | [
"Unlicense"
] | null | null | null | Libs/Nodes/src/PaletteNode.cpp | tjhei/OpenVisus | f0c3bf21cb0c02f303025a8efb68b8c36701a9fd | [
"Unlicense"
] | null | null | null | /*-----------------------------------------------------------------------------
Copyright(c) 2010 - 2018 ViSUS L.L.C.,
Scientific Computing and Imaging Institute of the University of Utah
ViSUS L.L.C., 50 W.Broadway, Ste. 300, 84101 - 2044 Salt Lake City, UT
University of Utah, 72 S Central Campus Dr, Room 3750, 84112 Salt Lake City, UT
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met :
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder 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.
For additional information about this project contact : pascucci@acm.org
For support : support@visus.net
-----------------------------------------------------------------------------*/
#include <Visus/PaletteNode.h>
namespace Visus {
///////////////////////////////////////////////////////////////////////
class ComputeStatsJob : public NodeJob
{
public:
Node* node;
Array data;
ComputeRange compute_range;
//constructor
ComputeStatsJob(Node* node_,Array data_,ComputeRange compute_range_)
: node(node_), data(data_),compute_range(compute_range_){
}
//runJob
virtual void runJob() override
{
if (auto stats = Statistics::compute(data, compute_range, 256, aborted))
node->publish(std::map<String, SharedPtr<Object> >({{"statistics",std::make_shared<Statistics>(stats)}}));
}
};
///////////////////////////////////////////////////////////////////////
PaletteNode::PaletteNode(String name,String default_palette) : Node(name)
{
//in case you want to show statistics when you are editing the palette
//to enable statistics, connect it
addInputPort("data");
addOutputPort("palette");
setPalette(std::make_shared<Palette>(default_palette));
}
///////////////////////////////////////////////////////////////////////
PaletteNode::~PaletteNode() {
setPalette(nullptr);
}
///////////////////////////////////////////////////////////////////////
void PaletteNode::setPalette(SharedPtr<Palette> value)
{
if (this->palette)
{
this->palette->begin_update.disconnect(this->palette_begin_update_slot);
this->palette->changed.disconnect(this->palette_changed_slot);
}
this->palette=value;
if (this->palette)
{
// a change in the palette means a change in the node
this->palette->begin_update.connect(this->palette_begin_update_slot=[this](){
beginUpdate();
});
this->palette->changed.connect(this->palette_changed_slot=[this](){
endUpdate();
});
}
}
///////////////////////////////////////////////////////////////////////
bool PaletteNode::processInput()
{
abortProcessing();
//important to remove any input from the queue
auto data = readInput<Array>("data");
if (!data)
return false;
//not interested in statistics
if (!areStatisticsEnabled())
return false;
//avoid computing stuff if not shown
if (views.empty())
return false;
addNodeJob(std::make_shared<ComputeStatsJob>(this,*data,palette->input_range));
return true;
}
///////////////////////////////////////////////////////////////////////
void PaletteNode::enterInDataflow() {
Node::enterInDataflow();
doPublish();
}
///////////////////////////////////////////////////////////////////////
void PaletteNode::exitFromDataflow() {
Node::exitFromDataflow();
}
///////////////////////////////////////////////////////////////////////
void PaletteNode::writeToObjectStream(ObjectStream& ostream)
{
Node::writeToObjectStream(ostream);
ostream.pushContext("palette");
palette->writeToObjectStream(ostream);
ostream.popContext("palette");
}
///////////////////////////////////////////////////////////////////////
void PaletteNode::readFromObjectStream(ObjectStream& istream)
{
Node::readFromObjectStream(istream);
istream.pushContext("palette");
palette->readFromObjectStream(istream);
istream.popContext("palette");
}
///////////////////////////////////////////////////////////////////////
void PaletteNode::messageHasBeenPublished(const DataflowMessage& msg)
{
VisusAssert(VisusHasMessageLock());
auto statistics=std::dynamic_pointer_cast<Statistics>(msg.readContent("statistics"));
if (!statistics)
return;
for (auto it: this->views)
{
if (auto view=dynamic_cast<BasePaletteNodeView*>(it)) {
view->newStatsAvailable(*statistics);
}
}
}
} //namespace Visus
| 30.608696 | 112 | 0.628551 | [
"object"
] |
74a439a8449b16461fbae73fa518bf671374511e | 14,009 | cc | C++ | dwarfproc.cc | platinum95/pstack | 545a210ee753b300f63689b1c0d22a39349ba427 | [
"BSD-2-Clause"
] | null | null | null | dwarfproc.cc | platinum95/pstack | 545a210ee753b300f63689b1c0d22a39349ba427 | [
"BSD-2-Clause"
] | null | null | null | dwarfproc.cc | platinum95/pstack | 545a210ee753b300f63689b1c0d22a39349ba427 | [
"BSD-2-Clause"
] | null | null | null | #include "libpstack/dwarf.h"
#include "libpstack/elf.h"
#include "libpstack/proc.h"
#include <cassert>
#include <limits>
#include <stack>
namespace Dwarf {
void
StackFrame::setCoreRegs(const Elf::CoreRegisters &sys)
{
#define REGMAP(number, field) setReg(number, sys.field);
#include "libpstack/dwarf/archreg.h"
#undef REGMAP
}
void
StackFrame::getCoreRegs(Elf::CoreRegisters &core) const
{
#define REGMAP(number, field) core.field = getReg(number);
#include "libpstack/dwarf/archreg.h"
#undef REGMAP
}
void
StackFrame::getFrameBase(const Process &p, intmax_t offset, ExpressionStack *stack) const
{
const Attribute *attr;
if (function == nullptr || (attr = function->attrForName(DW_AT_frame_base)) == nullptr) {
stack->push(0);
return;
}
stack->push(stack->eval(p, attr, this, elfReloc) + offset);
}
Elf::Addr
ExpressionStack::eval(const Process &proc, const Attribute *attr, const StackFrame *frame, Elf::Addr reloc)
{
const Info *dwarf = attr->entry->unit->dwarf;
switch (attr->form()) {
case DW_FORM_sec_offset: {
auto &sec = dwarf->elf->getSection(".debug_loc", SHT_PROGBITS);
auto objIp = frame->ip - reloc;
// convert this object-relative addr to a unit-relative one
const Entry &unitEntry = *attr->entry->unit->entries.begin();
auto unitLow = unitEntry.attrForName(DW_AT_low_pc);
#ifndef NDEBUG
auto unitHigh = unitEntry.attrForName(DW_AT_high_pc);
Elf::Addr endAddr;
if (unitHigh) {
switch (unitHigh->form()) {
case DW_FORM_addr:
endAddr = uintmax_t(*unitHigh);
break;
case DW_FORM_data1: case DW_FORM_data2: case DW_FORM_data4: case DW_FORM_data8: case DW_FORM_udata:
endAddr = intmax_t(*unitHigh) + uintmax_t(*unitLow);
break;
default:
abort();
}
assert(objIp >= uintmax_t(*unitLow) && objIp < endAddr);
}
#endif
Elf::Addr unitIp = objIp - uintmax_t(*unitLow);
DWARFReader r(sec.io, uintmax_t(*attr));
for (;;) {
Elf::Addr start = r.getint(sizeof start);
Elf::Addr end = r.getint(sizeof end);
if (start == 0 && end == 0)
return 0;
auto len = r.getuint(2);
if (unitIp >= start && unitIp < end) {
DWARFReader exr(r.io, r.getOffset(), r.getOffset() + Elf::Word(len));
return eval(proc, exr, frame, frame->elfReloc);
}
r.skip(len);
}
abort();
}
case DW_FORM_block1:
case DW_FORM_block:
case DW_FORM_exprloc: {
auto &block = attr->block();
DWARFReader r(dwarf->io, block.offset, block.offset + block.length);
return eval(proc, r, frame, reloc);
}
default:
abort();
}
}
Elf::Addr
ExpressionStack::eval(const Process &proc, DWARFReader &r, const StackFrame *frame, Elf::Addr reloc)
{
isReg = false;
while (!r.empty()) {
auto op = ExpressionOp(r.getu8());
switch (op) {
case DW_OP_deref: {
intmax_t addr = poptop();
Elf::Addr value;
proc.io->readObj(addr, &value);
push(intptr_t(value));
break;
}
case DW_OP_consts: {
push(r.getsleb128());
break;
}
case DW_OP_constu: {
push(r.getuleb128());
break;
}
case DW_OP_const2s: {
push(int16_t(r.getu16()));
break;
}
case DW_OP_const4u: {
push(r.getu32());
break;
}
case DW_OP_const4s: {
push(int32_t(r.getu32()));
break;
}
case DW_OP_minus: {
Elf::Addr tos = poptop();
Elf::Addr second = poptop();
push(second - tos);
break;
}
case DW_OP_plus: {
Elf::Addr tos = poptop();
Elf::Addr second = poptop();
push(second + tos);
break;
}
case DW_OP_breg0: case DW_OP_breg1: case DW_OP_breg2: case DW_OP_breg3:
case DW_OP_breg4: case DW_OP_breg5: case DW_OP_breg6: case DW_OP_breg7:
case DW_OP_breg8: case DW_OP_breg9: case DW_OP_breg10: case DW_OP_breg11:
case DW_OP_breg12: case DW_OP_breg13: case DW_OP_breg14: case DW_OP_breg15:
case DW_OP_breg16: case DW_OP_breg17: case DW_OP_breg18: case DW_OP_breg19:
case DW_OP_breg20: case DW_OP_breg21: case DW_OP_breg22: case DW_OP_breg23:
case DW_OP_breg24: case DW_OP_breg25: case DW_OP_breg26: case DW_OP_breg27:
case DW_OP_breg28: case DW_OP_breg29: case DW_OP_breg30: case DW_OP_breg31: {
Elf::Off offset = r.getsleb128();
push(frame->getReg(op - DW_OP_breg0) + offset);
break;
}
case DW_OP_lit0: case DW_OP_lit1: case DW_OP_lit2: case DW_OP_lit3: case DW_OP_lit4:
case DW_OP_lit5: case DW_OP_lit6: case DW_OP_lit7: case DW_OP_lit8: case DW_OP_lit9:
case DW_OP_lit10: case DW_OP_lit11: case DW_OP_lit12: case DW_OP_lit13: case DW_OP_lit14:
case DW_OP_lit15: case DW_OP_lit16: case DW_OP_lit17: case DW_OP_lit18: case DW_OP_lit19:
case DW_OP_lit20: case DW_OP_lit21: case DW_OP_lit22: case DW_OP_lit23: case DW_OP_lit24:
case DW_OP_lit25: case DW_OP_lit26: case DW_OP_lit27: case DW_OP_lit28: case DW_OP_lit29:
case DW_OP_lit30: case DW_OP_lit31:
push(op - DW_OP_lit0);
break;
case DW_OP_and: {
Elf::Addr lhs = poptop();
Elf::Addr rhs = poptop();
push(lhs & rhs);
break;
}
case DW_OP_or: {
Elf::Addr lhs = poptop();
Elf::Addr rhs = poptop();
push(lhs | rhs);
break;
}
case DW_OP_le: {
Elf::Addr rhs = poptop();
Elf::Addr lhs = poptop();
push(value_type(lhs <= rhs));
break;
}
case DW_OP_ge: {
Elf::Addr rhs = poptop();
Elf::Addr lhs = poptop();
push(value_type(lhs >= rhs));
break;
}
case DW_OP_eq: {
Elf::Addr rhs = poptop();
Elf::Addr lhs = poptop();
push(value_type(lhs == rhs));
break;
}
case DW_OP_lt: {
Elf::Addr rhs = poptop();
Elf::Addr lhs = poptop();
push(value_type(lhs < rhs));
break;
}
case DW_OP_gt: {
Elf::Addr rhs = poptop();
Elf::Addr lhs = poptop();
push(value_type(lhs > rhs));
break;
}
case DW_OP_ne: {
Elf::Addr rhs = poptop();
Elf::Addr lhs = poptop();
push(value_type(lhs != rhs));
break;
}
case DW_OP_shl: {
Elf::Addr rhs = poptop();
Elf::Addr lhs = poptop();
push(lhs << rhs);
break;
}
case DW_OP_shr: {
Elf::Addr rhs = poptop();
Elf::Addr lhs = poptop();
push(lhs >> rhs);
break;
}
case DW_OP_addr: {
auto value = r.getuint(r.addrLen);
push(value + reloc);
break;
}
case DW_OP_call_frame_cfa:
push(frame->cfa);
break;
case DW_OP_fbreg:
// Yuk - find DW_AT_frame_base, and offset from that.
frame->getFrameBase(proc, r.getsleb128(), this);
break;
case DW_OP_reg0: case DW_OP_reg1: case DW_OP_reg2: case DW_OP_reg3:
case DW_OP_reg4: case DW_OP_reg5: case DW_OP_reg6: case DW_OP_reg7:
case DW_OP_reg8: case DW_OP_reg9: case DW_OP_reg10: case DW_OP_reg11:
case DW_OP_reg12: case DW_OP_reg13: case DW_OP_reg14: case DW_OP_reg15:
case DW_OP_reg16: case DW_OP_reg17: case DW_OP_reg18: case DW_OP_reg19:
case DW_OP_reg20: case DW_OP_reg21: case DW_OP_reg22: case DW_OP_reg23:
case DW_OP_reg24: case DW_OP_reg25: case DW_OP_reg26: case DW_OP_reg27:
case DW_OP_reg28: case DW_OP_reg29: case DW_OP_reg30: case DW_OP_reg31:
isReg = true;
inReg = op - DW_OP_reg0;
push(frame->getReg(op - DW_OP_reg0));
break;
case DW_OP_regx:
push(frame->getReg(r.getsleb128()));
break;
case DW_OP_entry_value:
case DW_OP_GNU_entry_value: {
auto len = r.getuleb128();
DWARFReader r2(r.io, r.getOffset(), r.getOffset() + len);
push(eval(proc, r2, frame, reloc));
break;
}
case DW_OP_stack_value:
break; // XXX: the returned value is not a location, but the underlying value itself.
default:
std::clog << "error evaluating DWARF OP " << op << " (" << int(op) << ")\n";
return -1;
}
}
return poptop();
}
Elf::Addr
StackFrame::getCFA(const Process &proc, const CallFrame &dcf) const
{
switch (dcf.cfaValue.type) {
case SAME:
return getReg(dcf.cfaReg);
case VAL_OFFSET:
case VAL_EXPRESSION:
case REG:
case UNDEF:
case ARCH:
abort();
break;
case OFFSET:
return getReg(dcf.cfaReg) + dcf.cfaValue.u.offset;
case EXPRESSION: {
ExpressionStack stack;
auto start = dcf.cfaValue.u.expression.offset;
auto end = start + dcf.cfaValue.u.expression.length;
DWARFReader r(frameInfo->io, start, end);
return stack.eval(proc, r, this, elfReloc);
}
}
return -1;
}
StackFrame *
StackFrame::unwind(Process &p)
{
elf = p.findObject(ip, &elfReloc);
if (!elf)
throw (Exception() << "no image for instruction address " << std::hex << ip);
Elf::Off objaddr = ip - elfReloc; // relocate process address to object address
// Try and find DWARF data with debug frame information, or an eh_frame section.
dwarf = p.getDwarf(elf);
if (dwarf) {
auto frames = { dwarf->debugFrame.get(), dwarf->ehFrame.get() };
for (auto f : frames) {
if (f != nullptr) {
fde = f->findFDE(objaddr);
if (fde != nullptr) {
frameInfo = f;
cie = &f->cies[fde->cieOff];
break;
}
}
}
}
if (fde == nullptr)
throw (Exception() << "no FDE for instruction address " << std::hex << ip << " in " << *elf->io);
DWARFReader r(frameInfo->io, fde->instructions, fde->end);
auto iter = dwarf->callFrameForAddr.find(objaddr);
if (iter == dwarf->callFrameForAddr.end())
dwarf->callFrameForAddr[objaddr] = cie->execInsns(r, fde->iloc, objaddr);
const CallFrame &dcf = dwarf->callFrameForAddr[objaddr];
// Given the registers available, and the state of the call unwind data, calculate the CFA at this point.
cfa = getCFA(p, dcf);
auto out = new StackFrame();
#ifdef CFA_RESTORE_REGNO
// "The CFA is defined to be the stack pointer in the calling frame."
out->setReg(CFA_RESTORE_REGNO, cfa);
#endif
for (auto &entry : dcf.registers) {
const auto &unwind = entry.second;
const int regno = entry.first;
switch (unwind.type) {
case UNDEF:
case SAME:
out->setReg(regno, getReg(regno));
break;
case OFFSET: {
Elf::Addr reg; // XXX: assume addrLen = sizeof Elf_Addr
p.io->readObj(cfa + unwind.u.offset, ®);
out->setReg(regno, reg);
break;
}
case REG:
out->setReg(regno, getReg(unwind.u.reg));
break;
case VAL_EXPRESSION:
case EXPRESSION: {
ExpressionStack stack;
stack.push(cfa);
DWARFReader reader(frameInfo->io, unwind.u.expression.offset, unwind.u.expression.offset + unwind.u.expression.length);
auto val = stack.eval(p, reader, this, elfReloc);
// EXPRESSIONs give an address, VAL_EXPRESSION gives a literal.
if (unwind.type == EXPRESSION)
p.io->readObj(val, &val);
out->setReg(regno, val);
break;
}
default:
case ARCH:
break;
}
}
// If the return address isn't defined, then we can't unwind.
auto rar = cie->rar;
auto rarInfo = dcf.registers.find(rar);
if (rarInfo == dcf.registers.end() || rarInfo->second.type == UNDEF) {
delete out;
return nullptr;
}
out->ip = out->getReg(rar);
return out;
}
void
StackFrame::setReg(unsigned regno, cpureg_t regval)
{
regs[regno] = regval;
}
cpureg_t
StackFrame::getReg(unsigned regno) const
{
auto i = regs.find(regno);
return i != regs.end() ? i->second : 0;
}
}
| 33.354762 | 135 | 0.518238 | [
"object"
] |
74b3185f7ad5a8cbc84f953071bcaff9617acf99 | 1,407 | cpp | C++ | c2.cpp | kunwar-vikrant/LeetCode-Problems | cf432b7723c53563dc7635617f53e43376493daa | [
"MIT"
] | 1 | 2020-05-13T15:21:24.000Z | 2020-05-13T15:21:24.000Z | c2.cpp | kunwar-vikrant/LeetCode-Problems | cf432b7723c53563dc7635617f53e43376493daa | [
"MIT"
] | null | null | null | c2.cpp | kunwar-vikrant/LeetCode-Problems | cf432b7723c53563dc7635617f53e43376493daa | [
"MIT"
] | null | null | null | #include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
vector<int> v(n);
for(int i = 0; i < n; i++){
cin>>v[i];
}
int count = 0, minIndex = 0, minElement = 0;
vector<int> t;
for(int i = 0; i < n; i++){
t.push_back(v[i]);
t[i] -= 1;
}
int sz = t.size();
while(sz >= 1){
// minIndex = min_element(t.begin(),t.end()) - t.begin();
minElement = *min_element(t.begin(), t.end());
for(int i = t.size()-1; i >= 0; i--){
if(t[i] == minElement){
minIndex = i;
break;
}
}
if(minElement == 0){
t.clear();
t.resize(minIndex);
for(int i = 0; i < minIndex; i++){
t[i] = v[i];
}
// copy(v.begin(), v.begin() + minIndex, t.begin());
sz = t.size();
}else if(sz == 1){
count += 1;
break;
}
else{
t.clear();
t.resize(minIndex+1);
for(int i = 0; i <= minIndex; i++){
t[i] = v[i];
}
// copy(v.begin(), v.begin() + (minIndex+1), t.begin());
count += (minIndex+1);
for(int i = 0; i < t.size(); i++){
t[i] -= 1;
}
sz = t.size();
}
}
count += n;
cout<<count<<endl;
}
} | 17.37037 | 63 | 0.39801 | [
"vector"
] |
74b42f2c55cb8da166a524cc7bf6d4eac55cef34 | 7,798 | hpp | C++ | include/CameraModels/OpenGLProjectionMatrix.hpp | lukier/camera_models | 90196141fa4749148b6a7b0adc7af19cb1971039 | [
"BSD-3-Clause"
] | 34 | 2016-11-13T22:17:50.000Z | 2021-01-20T19:59:25.000Z | include/CameraModels/OpenGLProjectionMatrix.hpp | lukier/camera_models | 90196141fa4749148b6a7b0adc7af19cb1971039 | [
"BSD-3-Clause"
] | null | null | null | include/CameraModels/OpenGLProjectionMatrix.hpp | lukier/camera_models | 90196141fa4749148b6a7b0adc7af19cb1971039 | [
"BSD-3-Clause"
] | 6 | 2016-11-14T00:45:56.000Z | 2019-04-02T11:56:50.000Z | /**
* ****************************************************************************
* Copyright (c) 2015, Robert Lukierski.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the copyright holder 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.
*
* ****************************************************************************
* Projection matrices to be used with OpenGL.
* ****************************************************************************
*/
#ifndef CAMERA_PROJECTION_MATRICES_HPP
#define CAMERA_PROJECTION_MATRICES_HPP
#include <Eigen/Core>
#include <Eigen/Dense>
#include <Eigen/Geometry>
// http://www.songho.ca/opengl/gl_projectionmatrix.html
namespace camera
{
template<typename T>
EIGEN_DEVICE_FUNC inline Eigen::Matrix<T,4,4> getOrtographicProjection(T l, T r, T b, T t, T n, T f)
{
Eigen::Matrix<T,4,4> m;
m << T(2.0)/(r-l) , T(0.0) , T(0.0) , -(r+l)/(r-l),
T(0.0) , T(2.0)/(t-b) , T(0.0) , -(t+b)/(t-b),
T(0.0) , T(0.0) , T(-2.0)/(f-n) , -(f+n)/(f-n),
T(0.0) , T(0.0) , T(0.0) , T(1.0);
return m;
}
// Camera Axis:
// X - Right, Y - Up, Z - Back
// Image Origin:
// Bottom Left
// Caution: Principal point defined with respect to image origin (0,0) at
// top left of top-left pixel (not center, and in different frame
// of reference to projection function image)
template<typename CameraModel>
EIGEN_DEVICE_FUNC inline Eigen::Matrix<typename CameraModel::Scalar,4,4> getPerspectiveProjectionRUBBottomLeft(const CameraModel& cam, typename CameraModel::Scalar N, typename CameraModel::Scalar F)
{
typedef typename CameraModel::Scalar Scalar;
const Scalar L = +(cam.u0()) * N / -cam.fx();
const Scalar T = +(cam.v0()) * N / cam.fy();
const Scalar R = -(cam.width() - cam.u0()) * N / -cam.fx();
const Scalar B = -(cam.height() - cam.v0()) * N / cam.fy();
Eigen::Matrix<typename CameraModel::Scalar,4,4> ret;
ret <<
Scalar(2.0)*N/(R-L) , Scalar(0.0) , (R+L)/(R-L) , Scalar(0.0),
Scalar(0.0) , Scalar(2.0)*N/(T-B) , (T+B)/(T-B) , Scalar(0.0),
Scalar(0.0) , Scalar(0.0) ,-(F+N)/(F-N) ,-(Scalar(2.0)*F*N)/(F-N),
Scalar(0.0) , Scalar(0.0) ,-Scalar(1.0) , Scalar(0.0);
return ret;
}
// Camera Axis:
// X - Right, Y - Down, Z - Forward
// Image Origin:
// Top Left
// Pricipal point specified with image origin (0,0) at top left of top-left pixel (not center)
template<typename CameraModel>
EIGEN_DEVICE_FUNC inline Eigen::Matrix<typename CameraModel::Scalar,4,4> getPerspectiveProjectionRDFTopLeft(const CameraModel& cam, typename CameraModel::Scalar N, typename CameraModel::Scalar F)
{
typedef typename CameraModel::Scalar Scalar;
const Scalar L = -(cam.u0()) * N / cam.fx();
const Scalar T = -(cam.v0()) * N / cam.fy();
const Scalar R = +(cam.width() - cam.u0()) * N / cam.fx();
const Scalar B = +(cam.height() - cam.v0()) * N / cam.fy();
Eigen::Matrix<typename CameraModel::Scalar,4,4> ret;
ret <<
Scalar(2.0)*N/(R-L) , Scalar(0.0) , (R+L)/(L-R) , Scalar(0.0),
Scalar(0.0) , Scalar(2.0)*N/(T-B) , (T+B)/(B-T) , Scalar(0.0),
Scalar(0.0) , Scalar(0.0) , (F+N)/(F-N) ,(Scalar(2.0)*F*N)/(N-F),
Scalar(0.0) , Scalar(0.0) , Scalar(1.0) , Scalar(0.0);
return ret;
}
// Camera Axis:
// X - Right, Y - Down, Z - Forward
// Image Origin:
// Bottom Left
// Pricipal point specified with image origin (0,0) at top left of top-left pixel (not center)
template<typename CameraModel>
EIGEN_DEVICE_FUNC inline Eigen::Matrix<typename CameraModel::Scalar,4,4> getPerspectiveProjectionRDFBottomLeft(const CameraModel& cam, typename CameraModel::Scalar N, typename CameraModel::Scalar F)
{
typedef typename CameraModel::Scalar Scalar;
const Scalar L = -(cam.u0()) * N / cam.fx();
const Scalar T = +(cam.height() - cam.v0()) * N / cam.fy();
const Scalar R = +(cam.width() - cam.u0()) * N / cam.fx();
const Scalar B = -(cam.v0()) * N / cam.fy();
Eigen::Matrix<typename CameraModel::Scalar,4,4> ret;
ret <<
Scalar(2.0)*N/(R-L) , Scalar(0.0) , (R+L)/(L-R) , Scalar(0.0),
Scalar(0.0) , Scalar(2.0)*N/(T-B) , (T+B)/(B-T) , Scalar(0.0),
Scalar(0.0) , Scalar(0.0) , (F+N)/(F-N) ,(Scalar(2.0)*F*N)/(N-F),
Scalar(0.0) , Scalar(0.0) , Scalar(1.0) , Scalar(0.0);
return ret;
}
template<typename CameraModel>
EIGEN_DEVICE_FUNC inline Eigen::Matrix<typename CameraModel::Scalar,4,4> getPerspectiveProjection(const CameraModel& cam, typename CameraModel::Scalar N, typename CameraModel::Scalar F)
{
return getPerspectiveProjectionRDFTopLeft(cam,N,F);
}
// NOTE element (2,3) may be wrong
template<typename T>
EIGEN_DEVICE_FUNC inline Eigen::Matrix<T,4,4> lookAtRUB(const Eigen::Matrix<T,3,1>& eye, const Eigen::Matrix<T,3,1>& center, const Eigen::Matrix<T,3,1>& up)
{
Eigen::Matrix<T,4,4> view_matrix = Eigen::Matrix<T,4,4>::Zero();
Eigen::Matrix<T,3,3> R;
R.col(2) = (eye-center).normalized();
R.col(0) = up.cross(R.col(2)).normalized();
R.col(1) = R.col(2).cross(R.col(0));
view_matrix.template topLeftCorner<3,3>() = R.transpose();
view_matrix.template topRightCorner<3,1>() = -R.transpose() * center;
view_matrix.row(3) << T(0.0), T(0.0), T(0.0), T(1.0);
return view_matrix;
}
template<typename T>
EIGEN_DEVICE_FUNC inline Eigen::Matrix<T,4,4> lookAtRDF(const Eigen::Matrix<T,3,1>& eye, const Eigen::Matrix<T,3,1>& center, const Eigen::Matrix<T,3,1>& up)
{
Eigen::Matrix<T,4,4> view_matrix = Eigen::Matrix<T,4,4>::Zero();
Eigen::Matrix<T,3,3> R;
R.col(2) = (center-eye).normalized();
R.col(0) = R.col(2).cross(up).normalized();
R.col(1) = R.col(2).cross(R.col(0));
view_matrix.template topLeftCorner<3,3>() = R.transpose();
view_matrix.template topRightCorner<3,1>() = -R.transpose() * center;
view_matrix.row(3) << T(0.0), T(0.0), T(0.0), T(1.0);
return view_matrix;
}
template<typename T>
EIGEN_DEVICE_FUNC inline Eigen::Matrix<T,4,4> lookAt(const Eigen::Matrix<T,3,1>& eye, const Eigen::Matrix<T,3,1>& center, const Eigen::Matrix<T,3,1>& up)
{
return lookAtRDF(eye, center, up);
}
}
#endif // CAMERA_PROJECTION_MATRICES_HPP | 42.151351 | 198 | 0.619261 | [
"geometry"
] |
74b56e25efa5cfae7b45485828123c741bb62bf2 | 1,182 | cpp | C++ | code/src/BinaryJson/BinaryJsonTypes.cpp | salmanahmedshaikh/streamOLAPOptimization | 0a352bbd6e364865013452d30d2654e33b627e69 | [
"Apache-2.0"
] | 1 | 2021-04-15T11:42:52.000Z | 2021-04-15T11:42:52.000Z | code/src/BinaryJson/BinaryJsonTypes.cpp | salmanahmedshaikh/streamOLAPOptimization | 0a352bbd6e364865013452d30d2654e33b627e69 | [
"Apache-2.0"
] | null | null | null | code/src/BinaryJson/BinaryJsonTypes.cpp | salmanahmedshaikh/streamOLAPOptimization | 0a352bbd6e364865013452d30d2654e33b627e69 | [
"Apache-2.0"
] | 1 | 2019-08-25T05:46:20.000Z | 2019-08-25T05:46:20.000Z | //////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2017 KDE Laboratory, University of Tsukuba, Tsukuba, Japan. //
// //
// The JsSpinnerSPE/StreamingCube and the accompanying materials are made available //
// under the terms of Eclipse Public License v1.0 which accompanies this distribution //
// and is available at <https://eclipse.org/org/documents/epl-v10.php> //
//////////////////////////////////////////////////////////////////////////////////////////
#include "../Common/stdafx.h"
#include "../BinaryJson/BinaryJsonTypes.h"
/* take a BSONType and return the name of that type as a char* */
const char* typeName (BinaryJsonType type) {
switch (type) {
case EOO: return "EOO";
case NumberDouble: return "NumberDouble";
case JSONString: return "String";
case Object: return "Object";
case JSONArray: return "Array";
case JSONBool: return "Bool";
case jstNULL: return "NULL";
case NumberInt: return "NumberInt32";
case NumberLong: return "NumberLong64";
default: return "Invalid";
}
}
| 42.214286 | 90 | 0.543147 | [
"object"
] |
74b5b7592f8c526c6e93f240f10fb9c89f637c78 | 665 | cpp | C++ | lib/2d/blanks/AuxFunc.cpp | dcseal/finess | 766e583ae9e84480640c7c3b3c157bf40ab87fe4 | [
"BSD-3-Clause"
] | null | null | null | lib/2d/blanks/AuxFunc.cpp | dcseal/finess | 766e583ae9e84480640c7c3b3c157bf40ab87fe4 | [
"BSD-3-Clause"
] | null | null | null | lib/2d/blanks/AuxFunc.cpp | dcseal/finess | 766e583ae9e84480640c7c3b3c157bf40ab87fe4 | [
"BSD-3-Clause"
] | null | null | null | #include "tensors.h"
// *REQUIRED*
//
// This is a user-required routine that defines the auxilary arrays when the
// parameter maux > 0.
//
// Each application is REQUIRED to define one of these.
//
//
// Input:
//
// xpts( 1:numpts, 1:2 ) - The x, and y-coordinates for a list of points
//
// Output:
//
// auxvals( 1:numpts, 1:maux ) - The vector containg auxilary values.
//
// See also: QinitFunc.
void AuxFunc(const dTensor1& xpts, dTensor2& auxvals)
{
const int numpts=xpts.getsize();
for (int i=1; i<=numpts; i++)
{
// Spatial location.
double x = xpts.get(i,1);
double y = xpts.get(i,2);
}
}
| 19.558824 | 87 | 0.596992 | [
"vector"
] |
74b6282d5c6b6b9281d1b6c7ef674d22dcb3b118 | 4,115 | cpp | C++ | src/applications/solvers/multiphase/vof/vofSolver/porousWaveSolver/porousWaveSolver.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/applications/solvers/multiphase/vof/vofSolver/porousWaveSolver/porousWaveSolver.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/applications/solvers/multiphase/vof/vofSolver/porousWaveSolver/porousWaveSolver.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
Copyright (C) 2011-2016 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of CAELUS.
CAELUS is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CAELUS is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with CAELUS. If not, see <http://www.gnu.org/licenses/>.
Application
porousWaveSolver
Description
Solver for 2 incompressible, isothermal immiscible fluids using a VOF
(volume of fluid) phase-fraction based interface capturing approach.
The momentum and other fluid properties are of the "mixture" and a single
momentum equation is solved.
Turbulence modelling is generic, i.e. laminar, RAS or LES may be selected.
---------------------------------------------------------------------------*/
#include "fvCFD.hpp"
#include "CMULES.hpp"
#include "EulerDdtScheme.hpp"
#include "localEulerDdtScheme.hpp"
#include "CrankNicolsonDdtScheme.hpp"
#include "subCycle.hpp"
#include "interfaceProperties.hpp"
#include "twoPhaseMixture.hpp"
#include "turbulenceModel.hpp"
#include "interpolationTable.hpp"
#include "pimpleControl.hpp"
#include "fvIOoptionList.hpp"
#include "fixedFluxPressureFvPatchScalarField.hpp"
#include "CorrectPhi_.hpp"
#include "fvcSmooth.hpp"
#include "relaxationZone.hpp"
#include "externalWaveForcing.hpp"
#include "wavesPorosityModel.hpp"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
int main(int argc, char *argv[])
{
#include "setRootCase.hpp"
#include "createTime.hpp"
#include "createMesh.hpp"
pimpleControl pimple(mesh);
#include "initContinuityErrs.hpp"
#include "createDyMControls.hpp"
#include "createPorosityFields.hpp"
#include "createFields.hpp"
#include "createMRF.hpp"
#include "createFvOptions.hpp"
#include "initCorrectPhi.hpp"
#include "createUfIfPresent.hpp"
if (!LTS)
{
#include "readTimeControls.hpp"
#include "CourantNo.hpp"
#include "setInitialDeltaT.hpp"
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
Info<< "\nStarting time loop\n" << endl;
while (runTime.run())
{
#include "readTimeControls.hpp"
if (LTS)
{
#include "setRDeltaTVoF.hpp"
}
else
{
#include "CourantNo.hpp"
#include "alphaCourantNo.hpp"
#include "setDeltaTVoF.hpp"
}
runTime++;
Info<< "Time = " << runTime.timeName() << nl << endl;
if (waves)
{
externalWave->step();
}
#include "calcPorosity.hpp"
// --- Pressure-velocity PIMPLE corrector loop
while (pimple.loop())
{
#include "alphaControls.hpp"
#include "alphaEqnSubCycle.hpp"
if (waves)
{
relaxing->correct();
}
mixture.correct();
#include "UEqn.hpp"
// --- Pressure corrector loop
while (pimple.correct())
{
#include "pEqn.hpp"
}
if (pimple.turbCorr())
{
turbulence->correct();
}
}
runTime.write();
#include "reportTimeStats.hpp"
}
if (waves)
{
// Close down the external wave forcing in a nice manner
externalWave->close();
}
Info<< "End\n" << endl;
return 0;
}
// ************************************************************************* //
| 26.720779 | 79 | 0.552369 | [
"mesh"
] |
74b64bd3e5437190fbcf3134658124f6dd8cf844 | 4,374 | cpp | C++ | src/problem/bp/filtering.cpp | ctjandra/ddopt-bounds | aaf7407da930503a17969cee71718ffcf0c1fe96 | [
"MIT"
] | null | null | null | src/problem/bp/filtering.cpp | ctjandra/ddopt-bounds | aaf7407da930503a17969cee71718ffcf0c1fe96 | [
"MIT"
] | null | null | null | src/problem/bp/filtering.cpp | ctjandra/ddopt-bounds | aaf7407da930503a17969cee71718ffcf0c1fe96 | [
"MIT"
] | null | null | null | #include "filtering.hpp"
void BPFiltering::filter(BPRow* row)
{
// Run top-down and bottom-up pass with left-hand side of row
BPOptimizePassFunc* filter_func;
if (row->sense == SENSE_LE) {
filter_func = new BPMinimizePassFunc(row, bpvar_to_ddvar);
} else { // row->sense == SENSE_GE
filter_func = new BPMaximizePassFunc(row, bpvar_to_ddvar);
}
bdd_pass(bdd, filter_func, filter_func);
// Calculate the feasibility of each arc with respect to row
int bdd_size = bdd->layers.size();
for (int layer = 0; layer < bdd_size; ++layer) {
int size = bdd->layers[layer].size();
for (int k = 0; k < size; ++k) {
Node* parent = bdd->layers[layer][k];
double parent_val = boost::any_cast<BDDPassValues*>(parent->temp_data)->top_down_val; // parent (source)
for (int val = 0; val <= 1; ++val) {
Node* child = (val == 0) ? parent->zero_arc : parent->one_arc;
if (child != NULL) {
double child_val = boost::any_cast<BDDPassValues*>(child->temp_data)->bottom_up_val;
double row_arc_val = val * filter_func->coeffs[bdd->layer_to_var[layer]];
// Long arcs are ok as long as they are of the form (*,0,...0)
double arc_pass_val = parent_val + child_val + row_arc_val;
// cout << "[" << layer << ", " << k << ", 0]" << " vals " << parent_val << ", " << row_arc_val << ", " << child_val;
// cout << " / Arc val: " << arc_pass_val << " / RHS: " << row->rhs << endl;
if ((row->sense == SENSE_LE && DBL_GE(arc_pass_val, row->rhs))
|| (row->sense == SENSE_GE && DBL_LE(arc_pass_val, row->rhs))) {
// Arc is infeasible with respect to row: filter
cout << "Filtered arc above: value " << arc_pass_val << " against rhs " << row->rhs << endl;
parent->detach_arc(val);
}
}
}
}
}
// Clean up values from pass
bdd_pass_clean_up(bdd);
delete filter_func;
}
void BPFiltering::filter(vector<BPRow*>& rows)
{
int nrows = rows.size();
for (int i = 0; i < nrows; ++i) {
cout << "Filtering row " << i << endl;
filter(rows[i]);
}
}
void BPFiltering::print_splittable_nodes(BPRow* row)
{
// Run top-down and bottom-up pass with left-hand side of row
BPOptimizePassFunc* filter_func;
if (row->sense == SENSE_LE) {
filter_func = new BPMaximizePassFunc(row, bpvar_to_ddvar);
} else { // row->sense == SENSE_GE
filter_func = new BPMinimizePassFunc(row, bpvar_to_ddvar);
}
bdd_pass(bdd, filter_func, filter_func);
cout << "RHS: " << row->rhs << endl;
int bdd_size = bdd->layers.size();
for (int layer = 0; layer < bdd_size; ++layer) {
int size = bdd->layers[layer].size();
cout << "Layer " << layer << ": ";
for (int k = 0; k < size; ++k) {
Node* node = bdd->layers[layer][k];
double top_down_val = boost::any_cast<BDDPassValues*>(node->temp_data)->top_down_val;
double bottom_up_val = boost::any_cast<BDDPassValues*>(node->temp_data)->bottom_up_val;
double node_val = top_down_val + bottom_up_val;
if ((row->sense == SENSE_LE && DBL_LE(node_val, row->rhs))
|| (row->sense == SENSE_GE && DBL_GE(node_val, row->rhs))) {
// Node is unrefinable; i.e. all paths through this node are feasible
cout << k << " ";
} else {
cout << "[" << k << "] ";
}
cout << node_val << " ";
}
cout << endl;
}
// Clean up values from pass
bdd_pass_clean_up(bdd);
delete filter_func;
if (row->sense == SENSE_LE) {
filter_func = new BPMinimizePassFunc(row, bpvar_to_ddvar);
} else { // row->sense == SENSE_GE
filter_func = new BPMaximizePassFunc(row, bpvar_to_ddvar);
}
bdd_pass(bdd, filter_func, filter_func);
cout << "RHS: " << row->rhs << endl;
for (int layer = 0; layer < bdd_size; ++layer) {
int size = bdd->layers[layer].size();
cout << "Layer " << layer << ": ";
for (int k = 0; k < size; ++k) {
Node* node = bdd->layers[layer][k];
double top_down_val = boost::any_cast<BDDPassValues*>(node->temp_data)->top_down_val;
double bottom_up_val = boost::any_cast<BDDPassValues*>(node->temp_data)->bottom_up_val;
double node_val = top_down_val + bottom_up_val;
cout << node_val << " ";
}
cout << endl;
}
// Clean up values from pass
bdd_pass_clean_up(bdd);
delete filter_func;
}
void BPFiltering::print_splittable_nodes(vector<BPRow*>& rows)
{
int nrows = rows.size();
for (int i = 0; i < nrows; ++i) {
cout << "Row " << i << endl;
print_splittable_nodes(rows[i]);
}
}
| 29.958904 | 122 | 0.630087 | [
"vector"
] |
74b79fe61989533a5d4b9919d64611bf0d6db544 | 3,646 | cpp | C++ | HelloWorldScene.cpp | Chenpix/MagicTowner | 26a43c684117372137439eac32283b72ef80167f | [
"Apache-2.0"
] | null | null | null | HelloWorldScene.cpp | Chenpix/MagicTowner | 26a43c684117372137439eac32283b72ef80167f | [
"Apache-2.0"
] | null | null | null | HelloWorldScene.cpp | Chenpix/MagicTowner | 26a43c684117372137439eac32283b72ef80167f | [
"Apache-2.0"
] | null | null | null | #include "HelloWorldScene.h"
#include "cocostudio/CocoStudio.h"
#include "ui/CocosGUI.h"
#include "GameMainScene.h"
USING_NS_CC;
Scene* HelloWorld::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create();
// 'layer' is an autorelease object
auto layer = HelloWorld::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
/** you can create scene with following comment code instead of using csb file.
// 1. super init first
if ( !Layer::init() )
{
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
/////////////////////////////
// 2. add a menu item with "X" image, which is clicked to quit the program
// you may modify it.
// add a "close" icon to exit the progress. it's an autorelease object
auto closeItem = MenuItemImage::create(
"CloseNormal.png",
"CloseSelected.png",
CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));
closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 ,
origin.y + closeItem->getContentSize().height/2));
// create menu, it's an autorelease object
auto menu = Menu::create(closeItem, NULL);
menu->setPosition(Vec2::ZERO);
this->addChild(menu, 1);
/////////////////////////////
// 3. add your codes below...
// add a label shows "Hello World"
// create and initialize a label
auto label = Label::createWithTTF("Hello World", "fonts/Marker Felt.ttf", 24);
// position the label on the center of the screen
label->setPosition(Vec2(origin.x + visibleSize.width/2,
origin.y + visibleSize.height - label->getContentSize().height));
// add the label as a child to this layer
this->addChild(label, 1);
// add "HelloWorld" splash screen"
auto sprite = Sprite::create("HelloWorld.png");
// position the sprite on the center of the screen
sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));
// add the sprite as a child to this layer
this->addChild(sprite, 0);
**/
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
}
Rect rect = Rect::ZERO;
rect.size = Director::getInstance()->getWinSize();
CCSprite* bg = CCSprite::create("game_bg.jpg", rect);
bg->setAnchorPoint(Vec2(0, 0));
addChild(bg);
CCSprite* startButton = CCSprite::create("playGame.png");
startButton->setPosition(Vec2(rect.size.width / 2, rect.size.height / 4));
addChild(startButton, 1, 1);
auto listener = EventListenerMouse::create();
listener->onMouseDown = CC_CALLBACK_1(HelloWorld::mouseDown, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
return true;
}
void HelloWorld::mouseDown(Event *event)
{
EventMouse *e = (EventMouse*)event;
printf("%f %f \n",e->getCursorX(), e->getCursorY());
if (getChildByTag(1)->boundingBox().containsPoint(Vec2(e->getCursorX(), e->getCursorY())) )
{
Director::getInstance()->replaceScene(TransitionCrossFade::create(1.0f, GameMainScene::createScene()));
}
} | 33.145455 | 106 | 0.599561 | [
"object"
] |
74c0e032a61964fc5e18dea9243bec00ffea3190 | 62,499 | hpp | C++ | vendor/krpc-cpp/include/krpc/services/drawing.hpp | TroyNeubauer/KRPC-Programming | 8cd1bd0bac38adf794c56273fd1767d75c7526f9 | [
"MIT"
] | null | null | null | vendor/krpc-cpp/include/krpc/services/drawing.hpp | TroyNeubauer/KRPC-Programming | 8cd1bd0bac38adf794c56273fd1767d75c7526f9 | [
"MIT"
] | null | null | null | vendor/krpc-cpp/include/krpc/services/drawing.hpp | TroyNeubauer/KRPC-Programming | 8cd1bd0bac38adf794c56273fd1767d75c7526f9 | [
"MIT"
] | null | null | null | #pragma once
#include <map>
#include <set>
#include <string>
#include <tuple>
#include <vector>
#include <krpc/decoder.hpp>
#include <krpc/encoder.hpp>
#include <krpc/error.hpp>
#include <krpc/event.hpp>
#include <krpc/object.hpp>
#include <krpc/service.hpp>
#include <krpc/stream.hpp>
namespace krpc {
namespace services {
class Drawing : public Service {
public:
explicit Drawing(Client* client);
// Class forward declarations
class Line;
class Polygon;
class Text;
/**
* Draw a direction vector in the scene, from the center of mass of the active vessel.
* @param direction Direction to draw the line in.
* @param referenceFrame Reference frame that the direction is in.
* @param length The length of the line.
* @param visible Whether the line is visible.
*/
Drawing::Line add_direction(std::tuple<double, double, double> direction, SpaceCenter::ReferenceFrame reference_frame, float length, bool visible);
/**
* Draw a line in the scene.
* @param start Position of the start of the line.
* @param end Position of the end of the line.
* @param referenceFrame Reference frame that the positions are in.
* @param visible Whether the line is visible.
*/
Drawing::Line add_line(std::tuple<double, double, double> start, std::tuple<double, double, double> end, SpaceCenter::ReferenceFrame reference_frame, bool visible);
/**
* Draw a polygon in the scene, defined by a list of vertices.
* @param vertices Vertices of the polygon.
* @param referenceFrame Reference frame that the vertices are in.
* @param visible Whether the polygon is visible.
*/
Drawing::Polygon add_polygon(std::vector<std::tuple<double, double, double> > vertices, SpaceCenter::ReferenceFrame reference_frame, bool visible);
/**
* Draw text in the scene.
* @param text The string to draw.
* @param referenceFrame Reference frame that the text position is in.
* @param position Position of the text.
* @param rotation Rotation of the text, as a quaternion.
* @param visible Whether the text is visible.
*/
Drawing::Text add_text(std::string text, SpaceCenter::ReferenceFrame reference_frame, std::tuple<double, double, double> position, std::tuple<double, double, double, double> rotation, bool visible);
/**
* Remove all objects being drawn.
* @param clientOnly If true, only remove objects created by the calling client.
*/
void clear(bool client_only);
::krpc::Stream<Drawing::Line> add_direction_stream(std::tuple<double, double, double> direction, SpaceCenter::ReferenceFrame reference_frame, float length, bool visible);
::krpc::Stream<Drawing::Line> add_line_stream(std::tuple<double, double, double> start, std::tuple<double, double, double> end, SpaceCenter::ReferenceFrame reference_frame, bool visible);
::krpc::Stream<Drawing::Polygon> add_polygon_stream(std::vector<std::tuple<double, double, double> > vertices, SpaceCenter::ReferenceFrame reference_frame, bool visible);
::krpc::Stream<Drawing::Text> add_text_stream(std::string text, SpaceCenter::ReferenceFrame reference_frame, std::tuple<double, double, double> position, std::tuple<double, double, double, double> rotation, bool visible);
::krpc::schema::ProcedureCall add_direction_call(std::tuple<double, double, double> direction, SpaceCenter::ReferenceFrame reference_frame, float length, bool visible);
::krpc::schema::ProcedureCall add_line_call(std::tuple<double, double, double> start, std::tuple<double, double, double> end, SpaceCenter::ReferenceFrame reference_frame, bool visible);
::krpc::schema::ProcedureCall add_polygon_call(std::vector<std::tuple<double, double, double> > vertices, SpaceCenter::ReferenceFrame reference_frame, bool visible);
::krpc::schema::ProcedureCall add_text_call(std::string text, SpaceCenter::ReferenceFrame reference_frame, std::tuple<double, double, double> position, std::tuple<double, double, double, double> rotation, bool visible);
::krpc::schema::ProcedureCall clear_call(bool client_only);
/**
* A line. Created using Drawing::add_line.
*/
class Line : public krpc::Object<Line> {
public:
explicit Line(Client* client = nullptr, uint64_t id = 0);
/**
* Remove the object.
*/
void remove();
/**
* Set the color
*/
std::tuple<double, double, double> color();
/**
* Set the color
*/
void set_color(std::tuple<double, double, double> value);
/**
* End position of the line.
*/
std::tuple<double, double, double> end();
/**
* End position of the line.
*/
void set_end(std::tuple<double, double, double> value);
/**
* Material used to render the object.
* Creates the material from a shader with the given name.
*/
std::string material();
/**
* Material used to render the object.
* Creates the material from a shader with the given name.
*/
void set_material(std::string value);
/**
* Reference frame for the positions of the object.
*/
SpaceCenter::ReferenceFrame reference_frame();
/**
* Reference frame for the positions of the object.
*/
void set_reference_frame(SpaceCenter::ReferenceFrame value);
/**
* Start position of the line.
*/
std::tuple<double, double, double> start();
/**
* Start position of the line.
*/
void set_start(std::tuple<double, double, double> value);
/**
* Set the thickness
*/
float thickness();
/**
* Set the thickness
*/
void set_thickness(float value);
/**
* Whether the object is visible.
*/
bool visible();
/**
* Whether the object is visible.
*/
void set_visible(bool value);
::krpc::Stream<std::tuple<double, double, double>> color_stream();
::krpc::Stream<std::tuple<double, double, double>> end_stream();
::krpc::Stream<std::string> material_stream();
::krpc::Stream<SpaceCenter::ReferenceFrame> reference_frame_stream();
::krpc::Stream<std::tuple<double, double, double>> start_stream();
::krpc::Stream<float> thickness_stream();
::krpc::Stream<bool> visible_stream();
::krpc::schema::ProcedureCall remove_call();
::krpc::schema::ProcedureCall color_call();
::krpc::schema::ProcedureCall set_color_call(std::tuple<double, double, double> value);
::krpc::schema::ProcedureCall end_call();
::krpc::schema::ProcedureCall set_end_call(std::tuple<double, double, double> value);
::krpc::schema::ProcedureCall material_call();
::krpc::schema::ProcedureCall set_material_call(std::string value);
::krpc::schema::ProcedureCall reference_frame_call();
::krpc::schema::ProcedureCall set_reference_frame_call(SpaceCenter::ReferenceFrame value);
::krpc::schema::ProcedureCall start_call();
::krpc::schema::ProcedureCall set_start_call(std::tuple<double, double, double> value);
::krpc::schema::ProcedureCall thickness_call();
::krpc::schema::ProcedureCall set_thickness_call(float value);
::krpc::schema::ProcedureCall visible_call();
::krpc::schema::ProcedureCall set_visible_call(bool value);
};
/**
* A polygon. Created using Drawing::add_polygon.
*/
class Polygon : public krpc::Object<Polygon> {
public:
explicit Polygon(Client* client = nullptr, uint64_t id = 0);
/**
* Remove the object.
*/
void remove();
/**
* Set the color
*/
std::tuple<double, double, double> color();
/**
* Set the color
*/
void set_color(std::tuple<double, double, double> value);
/**
* Material used to render the object.
* Creates the material from a shader with the given name.
*/
std::string material();
/**
* Material used to render the object.
* Creates the material from a shader with the given name.
*/
void set_material(std::string value);
/**
* Reference frame for the positions of the object.
*/
SpaceCenter::ReferenceFrame reference_frame();
/**
* Reference frame for the positions of the object.
*/
void set_reference_frame(SpaceCenter::ReferenceFrame value);
/**
* Set the thickness
*/
float thickness();
/**
* Set the thickness
*/
void set_thickness(float value);
/**
* Vertices for the polygon.
*/
std::vector<std::tuple<double, double, double> > vertices();
/**
* Vertices for the polygon.
*/
void set_vertices(std::vector<std::tuple<double, double, double> > value);
/**
* Whether the object is visible.
*/
bool visible();
/**
* Whether the object is visible.
*/
void set_visible(bool value);
::krpc::Stream<std::tuple<double, double, double>> color_stream();
::krpc::Stream<std::string> material_stream();
::krpc::Stream<SpaceCenter::ReferenceFrame> reference_frame_stream();
::krpc::Stream<float> thickness_stream();
::krpc::Stream<std::vector<std::tuple<double, double, double> >> vertices_stream();
::krpc::Stream<bool> visible_stream();
::krpc::schema::ProcedureCall remove_call();
::krpc::schema::ProcedureCall color_call();
::krpc::schema::ProcedureCall set_color_call(std::tuple<double, double, double> value);
::krpc::schema::ProcedureCall material_call();
::krpc::schema::ProcedureCall set_material_call(std::string value);
::krpc::schema::ProcedureCall reference_frame_call();
::krpc::schema::ProcedureCall set_reference_frame_call(SpaceCenter::ReferenceFrame value);
::krpc::schema::ProcedureCall thickness_call();
::krpc::schema::ProcedureCall set_thickness_call(float value);
::krpc::schema::ProcedureCall vertices_call();
::krpc::schema::ProcedureCall set_vertices_call(std::vector<std::tuple<double, double, double> > value);
::krpc::schema::ProcedureCall visible_call();
::krpc::schema::ProcedureCall set_visible_call(bool value);
};
/**
* Text. Created using Drawing::add_text.
*/
class Text : public krpc::Object<Text> {
public:
explicit Text(Client* client = nullptr, uint64_t id = 0);
/**
* Remove the object.
*/
void remove();
/**
* A list of all available fonts.
*/
static std::vector<std::string> available_fonts(Client& client);
/**
* Alignment.
*/
UI::TextAlignment alignment();
/**
* Alignment.
*/
void set_alignment(UI::TextAlignment value);
/**
* Anchor.
*/
UI::TextAnchor anchor();
/**
* Anchor.
*/
void set_anchor(UI::TextAnchor value);
/**
* Character size.
*/
float character_size();
/**
* Character size.
*/
void set_character_size(float value);
/**
* Set the color
*/
std::tuple<double, double, double> color();
/**
* Set the color
*/
void set_color(std::tuple<double, double, double> value);
/**
* The text string
*/
std::string content();
/**
* The text string
*/
void set_content(std::string value);
/**
* Name of the font
*/
std::string font();
/**
* Name of the font
*/
void set_font(std::string value);
/**
* Line spacing.
*/
float line_spacing();
/**
* Line spacing.
*/
void set_line_spacing(float value);
/**
* Material used to render the object.
* Creates the material from a shader with the given name.
*/
std::string material();
/**
* Material used to render the object.
* Creates the material from a shader with the given name.
*/
void set_material(std::string value);
/**
* Position of the text.
*/
std::tuple<double, double, double> position();
/**
* Position of the text.
*/
void set_position(std::tuple<double, double, double> value);
/**
* Reference frame for the positions of the object.
*/
SpaceCenter::ReferenceFrame reference_frame();
/**
* Reference frame for the positions of the object.
*/
void set_reference_frame(SpaceCenter::ReferenceFrame value);
/**
* Rotation of the text as a quaternion.
*/
std::tuple<double, double, double, double> rotation();
/**
* Rotation of the text as a quaternion.
*/
void set_rotation(std::tuple<double, double, double, double> value);
/**
* Font size.
*/
int32_t size();
/**
* Font size.
*/
void set_size(int32_t value);
/**
* Font style.
*/
UI::FontStyle style();
/**
* Font style.
*/
void set_style(UI::FontStyle value);
/**
* Whether the object is visible.
*/
bool visible();
/**
* Whether the object is visible.
*/
void set_visible(bool value);
static ::krpc::Stream<std::vector<std::string>> available_fonts_stream(Client& client);
::krpc::Stream<UI::TextAlignment> alignment_stream();
::krpc::Stream<UI::TextAnchor> anchor_stream();
::krpc::Stream<float> character_size_stream();
::krpc::Stream<std::tuple<double, double, double>> color_stream();
::krpc::Stream<std::string> content_stream();
::krpc::Stream<std::string> font_stream();
::krpc::Stream<float> line_spacing_stream();
::krpc::Stream<std::string> material_stream();
::krpc::Stream<std::tuple<double, double, double>> position_stream();
::krpc::Stream<SpaceCenter::ReferenceFrame> reference_frame_stream();
::krpc::Stream<std::tuple<double, double, double, double>> rotation_stream();
::krpc::Stream<int32_t> size_stream();
::krpc::Stream<UI::FontStyle> style_stream();
::krpc::Stream<bool> visible_stream();
::krpc::schema::ProcedureCall remove_call();
static ::krpc::schema::ProcedureCall available_fonts_call(Client& client);
::krpc::schema::ProcedureCall alignment_call();
::krpc::schema::ProcedureCall set_alignment_call(UI::TextAlignment value);
::krpc::schema::ProcedureCall anchor_call();
::krpc::schema::ProcedureCall set_anchor_call(UI::TextAnchor value);
::krpc::schema::ProcedureCall character_size_call();
::krpc::schema::ProcedureCall set_character_size_call(float value);
::krpc::schema::ProcedureCall color_call();
::krpc::schema::ProcedureCall set_color_call(std::tuple<double, double, double> value);
::krpc::schema::ProcedureCall content_call();
::krpc::schema::ProcedureCall set_content_call(std::string value);
::krpc::schema::ProcedureCall font_call();
::krpc::schema::ProcedureCall set_font_call(std::string value);
::krpc::schema::ProcedureCall line_spacing_call();
::krpc::schema::ProcedureCall set_line_spacing_call(float value);
::krpc::schema::ProcedureCall material_call();
::krpc::schema::ProcedureCall set_material_call(std::string value);
::krpc::schema::ProcedureCall position_call();
::krpc::schema::ProcedureCall set_position_call(std::tuple<double, double, double> value);
::krpc::schema::ProcedureCall reference_frame_call();
::krpc::schema::ProcedureCall set_reference_frame_call(SpaceCenter::ReferenceFrame value);
::krpc::schema::ProcedureCall rotation_call();
::krpc::schema::ProcedureCall set_rotation_call(std::tuple<double, double, double, double> value);
::krpc::schema::ProcedureCall size_call();
::krpc::schema::ProcedureCall set_size_call(int32_t value);
::krpc::schema::ProcedureCall style_call();
::krpc::schema::ProcedureCall set_style_call(UI::FontStyle value);
::krpc::schema::ProcedureCall visible_call();
::krpc::schema::ProcedureCall set_visible_call(bool value);
};
};
} // namespace services
namespace services {
inline Drawing::Drawing(Client* client):
Service(client) {
}
inline Drawing::Line Drawing::add_direction(std::tuple<double, double, double> direction, SpaceCenter::ReferenceFrame reference_frame, float length = 10.0, bool visible = true) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(direction));
_args.push_back(encoder::encode(reference_frame));
_args.push_back(encoder::encode(length));
_args.push_back(encoder::encode(visible));
std::string _data = this->_client->invoke("Drawing", "AddDirection", _args);
Drawing::Line _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline Drawing::Line Drawing::add_line(std::tuple<double, double, double> start, std::tuple<double, double, double> end, SpaceCenter::ReferenceFrame reference_frame, bool visible = true) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(start));
_args.push_back(encoder::encode(end));
_args.push_back(encoder::encode(reference_frame));
_args.push_back(encoder::encode(visible));
std::string _data = this->_client->invoke("Drawing", "AddLine", _args);
Drawing::Line _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline Drawing::Polygon Drawing::add_polygon(std::vector<std::tuple<double, double, double> > vertices, SpaceCenter::ReferenceFrame reference_frame, bool visible = true) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(vertices));
_args.push_back(encoder::encode(reference_frame));
_args.push_back(encoder::encode(visible));
std::string _data = this->_client->invoke("Drawing", "AddPolygon", _args);
Drawing::Polygon _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline Drawing::Text Drawing::add_text(std::string text, SpaceCenter::ReferenceFrame reference_frame, std::tuple<double, double, double> position, std::tuple<double, double, double, double> rotation, bool visible = true) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(text));
_args.push_back(encoder::encode(reference_frame));
_args.push_back(encoder::encode(position));
_args.push_back(encoder::encode(rotation));
_args.push_back(encoder::encode(visible));
std::string _data = this->_client->invoke("Drawing", "AddText", _args);
Drawing::Text _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline void Drawing::clear(bool client_only = false) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(client_only));
this->_client->invoke("Drawing", "Clear", _args);
}
inline ::krpc::Stream<Drawing::Line> Drawing::add_direction_stream(std::tuple<double, double, double> direction, SpaceCenter::ReferenceFrame reference_frame, float length = 10.0, bool visible = true) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(direction));
_args.push_back(encoder::encode(reference_frame));
_args.push_back(encoder::encode(length));
_args.push_back(encoder::encode(visible));
return ::krpc::Stream<Drawing::Line>(this->_client, this->_client->build_call("Drawing", "AddDirection", _args));
}
inline ::krpc::Stream<Drawing::Line> Drawing::add_line_stream(std::tuple<double, double, double> start, std::tuple<double, double, double> end, SpaceCenter::ReferenceFrame reference_frame, bool visible = true) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(start));
_args.push_back(encoder::encode(end));
_args.push_back(encoder::encode(reference_frame));
_args.push_back(encoder::encode(visible));
return ::krpc::Stream<Drawing::Line>(this->_client, this->_client->build_call("Drawing", "AddLine", _args));
}
inline ::krpc::Stream<Drawing::Polygon> Drawing::add_polygon_stream(std::vector<std::tuple<double, double, double> > vertices, SpaceCenter::ReferenceFrame reference_frame, bool visible = true) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(vertices));
_args.push_back(encoder::encode(reference_frame));
_args.push_back(encoder::encode(visible));
return ::krpc::Stream<Drawing::Polygon>(this->_client, this->_client->build_call("Drawing", "AddPolygon", _args));
}
inline ::krpc::Stream<Drawing::Text> Drawing::add_text_stream(std::string text, SpaceCenter::ReferenceFrame reference_frame, std::tuple<double, double, double> position, std::tuple<double, double, double, double> rotation, bool visible = true) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(text));
_args.push_back(encoder::encode(reference_frame));
_args.push_back(encoder::encode(position));
_args.push_back(encoder::encode(rotation));
_args.push_back(encoder::encode(visible));
return ::krpc::Stream<Drawing::Text>(this->_client, this->_client->build_call("Drawing", "AddText", _args));
}
inline ::krpc::schema::ProcedureCall Drawing::add_direction_call(std::tuple<double, double, double> direction, SpaceCenter::ReferenceFrame reference_frame, float length = 10.0, bool visible = true) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(direction));
_args.push_back(encoder::encode(reference_frame));
_args.push_back(encoder::encode(length));
_args.push_back(encoder::encode(visible));
return this->_client->build_call("Drawing", "AddDirection", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::add_line_call(std::tuple<double, double, double> start, std::tuple<double, double, double> end, SpaceCenter::ReferenceFrame reference_frame, bool visible = true) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(start));
_args.push_back(encoder::encode(end));
_args.push_back(encoder::encode(reference_frame));
_args.push_back(encoder::encode(visible));
return this->_client->build_call("Drawing", "AddLine", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::add_polygon_call(std::vector<std::tuple<double, double, double> > vertices, SpaceCenter::ReferenceFrame reference_frame, bool visible = true) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(vertices));
_args.push_back(encoder::encode(reference_frame));
_args.push_back(encoder::encode(visible));
return this->_client->build_call("Drawing", "AddPolygon", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::add_text_call(std::string text, SpaceCenter::ReferenceFrame reference_frame, std::tuple<double, double, double> position, std::tuple<double, double, double, double> rotation, bool visible = true) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(text));
_args.push_back(encoder::encode(reference_frame));
_args.push_back(encoder::encode(position));
_args.push_back(encoder::encode(rotation));
_args.push_back(encoder::encode(visible));
return this->_client->build_call("Drawing", "AddText", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::clear_call(bool client_only = false) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(client_only));
return this->_client->build_call("Drawing", "Clear", _args);
}
inline Drawing::Line::Line(Client* client, uint64_t id):
Object(client, "Drawing::Line", id) {}
inline void Drawing::Line::remove() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
this->_client->invoke("Drawing", "Line_Remove", _args);
}
inline std::tuple<double, double, double> Drawing::Line::color() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
std::string _data = this->_client->invoke("Drawing", "Line_get_Color", _args);
std::tuple<double, double, double> _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline void Drawing::Line::set_color(std::tuple<double, double, double> value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
this->_client->invoke("Drawing", "Line_set_Color", _args);
}
inline std::tuple<double, double, double> Drawing::Line::end() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
std::string _data = this->_client->invoke("Drawing", "Line_get_End", _args);
std::tuple<double, double, double> _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline void Drawing::Line::set_end(std::tuple<double, double, double> value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
this->_client->invoke("Drawing", "Line_set_End", _args);
}
inline std::string Drawing::Line::material() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
std::string _data = this->_client->invoke("Drawing", "Line_get_Material", _args);
std::string _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline void Drawing::Line::set_material(std::string value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
this->_client->invoke("Drawing", "Line_set_Material", _args);
}
inline SpaceCenter::ReferenceFrame Drawing::Line::reference_frame() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
std::string _data = this->_client->invoke("Drawing", "Line_get_ReferenceFrame", _args);
SpaceCenter::ReferenceFrame _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline void Drawing::Line::set_reference_frame(SpaceCenter::ReferenceFrame value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
this->_client->invoke("Drawing", "Line_set_ReferenceFrame", _args);
}
inline std::tuple<double, double, double> Drawing::Line::start() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
std::string _data = this->_client->invoke("Drawing", "Line_get_Start", _args);
std::tuple<double, double, double> _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline void Drawing::Line::set_start(std::tuple<double, double, double> value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
this->_client->invoke("Drawing", "Line_set_Start", _args);
}
inline float Drawing::Line::thickness() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
std::string _data = this->_client->invoke("Drawing", "Line_get_Thickness", _args);
float _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline void Drawing::Line::set_thickness(float value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
this->_client->invoke("Drawing", "Line_set_Thickness", _args);
}
inline bool Drawing::Line::visible() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
std::string _data = this->_client->invoke("Drawing", "Line_get_Visible", _args);
bool _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline void Drawing::Line::set_visible(bool value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
this->_client->invoke("Drawing", "Line_set_Visible", _args);
}
inline ::krpc::Stream<std::tuple<double, double, double>> Drawing::Line::color_stream() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return ::krpc::Stream<std::tuple<double, double, double>>(this->_client, this->_client->build_call("Drawing", "Line_get_Color", _args));
}
inline ::krpc::Stream<std::tuple<double, double, double>> Drawing::Line::end_stream() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return ::krpc::Stream<std::tuple<double, double, double>>(this->_client, this->_client->build_call("Drawing", "Line_get_End", _args));
}
inline ::krpc::Stream<std::string> Drawing::Line::material_stream() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return ::krpc::Stream<std::string>(this->_client, this->_client->build_call("Drawing", "Line_get_Material", _args));
}
inline ::krpc::Stream<SpaceCenter::ReferenceFrame> Drawing::Line::reference_frame_stream() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return ::krpc::Stream<SpaceCenter::ReferenceFrame>(this->_client, this->_client->build_call("Drawing", "Line_get_ReferenceFrame", _args));
}
inline ::krpc::Stream<std::tuple<double, double, double>> Drawing::Line::start_stream() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return ::krpc::Stream<std::tuple<double, double, double>>(this->_client, this->_client->build_call("Drawing", "Line_get_Start", _args));
}
inline ::krpc::Stream<float> Drawing::Line::thickness_stream() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return ::krpc::Stream<float>(this->_client, this->_client->build_call("Drawing", "Line_get_Thickness", _args));
}
inline ::krpc::Stream<bool> Drawing::Line::visible_stream() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return ::krpc::Stream<bool>(this->_client, this->_client->build_call("Drawing", "Line_get_Visible", _args));
}
inline ::krpc::schema::ProcedureCall Drawing::Line::remove_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Line_Remove", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Line::color_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Line_get_Color", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Line::set_color_call(std::tuple<double, double, double> value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
return this->_client->build_call("Drawing", "Line_set_Color", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Line::end_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Line_get_End", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Line::set_end_call(std::tuple<double, double, double> value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
return this->_client->build_call("Drawing", "Line_set_End", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Line::material_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Line_get_Material", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Line::set_material_call(std::string value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
return this->_client->build_call("Drawing", "Line_set_Material", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Line::reference_frame_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Line_get_ReferenceFrame", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Line::set_reference_frame_call(SpaceCenter::ReferenceFrame value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
return this->_client->build_call("Drawing", "Line_set_ReferenceFrame", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Line::start_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Line_get_Start", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Line::set_start_call(std::tuple<double, double, double> value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
return this->_client->build_call("Drawing", "Line_set_Start", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Line::thickness_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Line_get_Thickness", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Line::set_thickness_call(float value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
return this->_client->build_call("Drawing", "Line_set_Thickness", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Line::visible_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Line_get_Visible", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Line::set_visible_call(bool value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
return this->_client->build_call("Drawing", "Line_set_Visible", _args);
}
inline Drawing::Polygon::Polygon(Client* client, uint64_t id):
Object(client, "Drawing::Polygon", id) {}
inline void Drawing::Polygon::remove() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
this->_client->invoke("Drawing", "Polygon_Remove", _args);
}
inline std::tuple<double, double, double> Drawing::Polygon::color() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
std::string _data = this->_client->invoke("Drawing", "Polygon_get_Color", _args);
std::tuple<double, double, double> _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline void Drawing::Polygon::set_color(std::tuple<double, double, double> value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
this->_client->invoke("Drawing", "Polygon_set_Color", _args);
}
inline std::string Drawing::Polygon::material() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
std::string _data = this->_client->invoke("Drawing", "Polygon_get_Material", _args);
std::string _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline void Drawing::Polygon::set_material(std::string value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
this->_client->invoke("Drawing", "Polygon_set_Material", _args);
}
inline SpaceCenter::ReferenceFrame Drawing::Polygon::reference_frame() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
std::string _data = this->_client->invoke("Drawing", "Polygon_get_ReferenceFrame", _args);
SpaceCenter::ReferenceFrame _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline void Drawing::Polygon::set_reference_frame(SpaceCenter::ReferenceFrame value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
this->_client->invoke("Drawing", "Polygon_set_ReferenceFrame", _args);
}
inline float Drawing::Polygon::thickness() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
std::string _data = this->_client->invoke("Drawing", "Polygon_get_Thickness", _args);
float _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline void Drawing::Polygon::set_thickness(float value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
this->_client->invoke("Drawing", "Polygon_set_Thickness", _args);
}
inline std::vector<std::tuple<double, double, double> > Drawing::Polygon::vertices() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
std::string _data = this->_client->invoke("Drawing", "Polygon_get_Vertices", _args);
std::vector<std::tuple<double, double, double> > _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline void Drawing::Polygon::set_vertices(std::vector<std::tuple<double, double, double> > value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
this->_client->invoke("Drawing", "Polygon_set_Vertices", _args);
}
inline bool Drawing::Polygon::visible() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
std::string _data = this->_client->invoke("Drawing", "Polygon_get_Visible", _args);
bool _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline void Drawing::Polygon::set_visible(bool value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
this->_client->invoke("Drawing", "Polygon_set_Visible", _args);
}
inline ::krpc::Stream<std::tuple<double, double, double>> Drawing::Polygon::color_stream() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return ::krpc::Stream<std::tuple<double, double, double>>(this->_client, this->_client->build_call("Drawing", "Polygon_get_Color", _args));
}
inline ::krpc::Stream<std::string> Drawing::Polygon::material_stream() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return ::krpc::Stream<std::string>(this->_client, this->_client->build_call("Drawing", "Polygon_get_Material", _args));
}
inline ::krpc::Stream<SpaceCenter::ReferenceFrame> Drawing::Polygon::reference_frame_stream() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return ::krpc::Stream<SpaceCenter::ReferenceFrame>(this->_client, this->_client->build_call("Drawing", "Polygon_get_ReferenceFrame", _args));
}
inline ::krpc::Stream<float> Drawing::Polygon::thickness_stream() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return ::krpc::Stream<float>(this->_client, this->_client->build_call("Drawing", "Polygon_get_Thickness", _args));
}
inline ::krpc::Stream<std::vector<std::tuple<double, double, double> >> Drawing::Polygon::vertices_stream() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return ::krpc::Stream<std::vector<std::tuple<double, double, double> >>(this->_client, this->_client->build_call("Drawing", "Polygon_get_Vertices", _args));
}
inline ::krpc::Stream<bool> Drawing::Polygon::visible_stream() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return ::krpc::Stream<bool>(this->_client, this->_client->build_call("Drawing", "Polygon_get_Visible", _args));
}
inline ::krpc::schema::ProcedureCall Drawing::Polygon::remove_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Polygon_Remove", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Polygon::color_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Polygon_get_Color", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Polygon::set_color_call(std::tuple<double, double, double> value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
return this->_client->build_call("Drawing", "Polygon_set_Color", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Polygon::material_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Polygon_get_Material", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Polygon::set_material_call(std::string value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
return this->_client->build_call("Drawing", "Polygon_set_Material", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Polygon::reference_frame_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Polygon_get_ReferenceFrame", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Polygon::set_reference_frame_call(SpaceCenter::ReferenceFrame value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
return this->_client->build_call("Drawing", "Polygon_set_ReferenceFrame", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Polygon::thickness_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Polygon_get_Thickness", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Polygon::set_thickness_call(float value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
return this->_client->build_call("Drawing", "Polygon_set_Thickness", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Polygon::vertices_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Polygon_get_Vertices", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Polygon::set_vertices_call(std::vector<std::tuple<double, double, double> > value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
return this->_client->build_call("Drawing", "Polygon_set_Vertices", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Polygon::visible_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Polygon_get_Visible", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Polygon::set_visible_call(bool value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
return this->_client->build_call("Drawing", "Polygon_set_Visible", _args);
}
inline Drawing::Text::Text(Client* client, uint64_t id):
Object(client, "Drawing::Text", id) {}
inline void Drawing::Text::remove() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
this->_client->invoke("Drawing", "Text_Remove", _args);
}
inline UI::TextAlignment Drawing::Text::alignment() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
std::string _data = this->_client->invoke("Drawing", "Text_get_Alignment", _args);
UI::TextAlignment _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline void Drawing::Text::set_alignment(UI::TextAlignment value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
this->_client->invoke("Drawing", "Text_set_Alignment", _args);
}
inline UI::TextAnchor Drawing::Text::anchor() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
std::string _data = this->_client->invoke("Drawing", "Text_get_Anchor", _args);
UI::TextAnchor _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline void Drawing::Text::set_anchor(UI::TextAnchor value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
this->_client->invoke("Drawing", "Text_set_Anchor", _args);
}
inline float Drawing::Text::character_size() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
std::string _data = this->_client->invoke("Drawing", "Text_get_CharacterSize", _args);
float _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline void Drawing::Text::set_character_size(float value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
this->_client->invoke("Drawing", "Text_set_CharacterSize", _args);
}
inline std::tuple<double, double, double> Drawing::Text::color() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
std::string _data = this->_client->invoke("Drawing", "Text_get_Color", _args);
std::tuple<double, double, double> _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline void Drawing::Text::set_color(std::tuple<double, double, double> value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
this->_client->invoke("Drawing", "Text_set_Color", _args);
}
inline std::string Drawing::Text::content() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
std::string _data = this->_client->invoke("Drawing", "Text_get_Content", _args);
std::string _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline void Drawing::Text::set_content(std::string value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
this->_client->invoke("Drawing", "Text_set_Content", _args);
}
inline std::string Drawing::Text::font() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
std::string _data = this->_client->invoke("Drawing", "Text_get_Font", _args);
std::string _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline void Drawing::Text::set_font(std::string value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
this->_client->invoke("Drawing", "Text_set_Font", _args);
}
inline float Drawing::Text::line_spacing() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
std::string _data = this->_client->invoke("Drawing", "Text_get_LineSpacing", _args);
float _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline void Drawing::Text::set_line_spacing(float value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
this->_client->invoke("Drawing", "Text_set_LineSpacing", _args);
}
inline std::string Drawing::Text::material() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
std::string _data = this->_client->invoke("Drawing", "Text_get_Material", _args);
std::string _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline void Drawing::Text::set_material(std::string value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
this->_client->invoke("Drawing", "Text_set_Material", _args);
}
inline std::tuple<double, double, double> Drawing::Text::position() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
std::string _data = this->_client->invoke("Drawing", "Text_get_Position", _args);
std::tuple<double, double, double> _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline void Drawing::Text::set_position(std::tuple<double, double, double> value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
this->_client->invoke("Drawing", "Text_set_Position", _args);
}
inline SpaceCenter::ReferenceFrame Drawing::Text::reference_frame() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
std::string _data = this->_client->invoke("Drawing", "Text_get_ReferenceFrame", _args);
SpaceCenter::ReferenceFrame _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline void Drawing::Text::set_reference_frame(SpaceCenter::ReferenceFrame value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
this->_client->invoke("Drawing", "Text_set_ReferenceFrame", _args);
}
inline std::tuple<double, double, double, double> Drawing::Text::rotation() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
std::string _data = this->_client->invoke("Drawing", "Text_get_Rotation", _args);
std::tuple<double, double, double, double> _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline void Drawing::Text::set_rotation(std::tuple<double, double, double, double> value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
this->_client->invoke("Drawing", "Text_set_Rotation", _args);
}
inline int32_t Drawing::Text::size() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
std::string _data = this->_client->invoke("Drawing", "Text_get_Size", _args);
int32_t _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline void Drawing::Text::set_size(int32_t value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
this->_client->invoke("Drawing", "Text_set_Size", _args);
}
inline UI::FontStyle Drawing::Text::style() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
std::string _data = this->_client->invoke("Drawing", "Text_get_Style", _args);
UI::FontStyle _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline void Drawing::Text::set_style(UI::FontStyle value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
this->_client->invoke("Drawing", "Text_set_Style", _args);
}
inline bool Drawing::Text::visible() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
std::string _data = this->_client->invoke("Drawing", "Text_get_Visible", _args);
bool _result;
decoder::decode(_result, _data, this->_client);
return _result;
}
inline void Drawing::Text::set_visible(bool value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
this->_client->invoke("Drawing", "Text_set_Visible", _args);
}
inline std::vector<std::string> Drawing::Text::available_fonts(Client& _client) {
std::string _data = _client.invoke("Drawing", "Text_static_AvailableFonts");
std::vector<std::string> _result;
decoder::decode(_result, _data, &_client);
return _result;
}
inline ::krpc::Stream<UI::TextAlignment> Drawing::Text::alignment_stream() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return ::krpc::Stream<UI::TextAlignment>(this->_client, this->_client->build_call("Drawing", "Text_get_Alignment", _args));
}
inline ::krpc::Stream<UI::TextAnchor> Drawing::Text::anchor_stream() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return ::krpc::Stream<UI::TextAnchor>(this->_client, this->_client->build_call("Drawing", "Text_get_Anchor", _args));
}
inline ::krpc::Stream<float> Drawing::Text::character_size_stream() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return ::krpc::Stream<float>(this->_client, this->_client->build_call("Drawing", "Text_get_CharacterSize", _args));
}
inline ::krpc::Stream<std::tuple<double, double, double>> Drawing::Text::color_stream() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return ::krpc::Stream<std::tuple<double, double, double>>(this->_client, this->_client->build_call("Drawing", "Text_get_Color", _args));
}
inline ::krpc::Stream<std::string> Drawing::Text::content_stream() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return ::krpc::Stream<std::string>(this->_client, this->_client->build_call("Drawing", "Text_get_Content", _args));
}
inline ::krpc::Stream<std::string> Drawing::Text::font_stream() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return ::krpc::Stream<std::string>(this->_client, this->_client->build_call("Drawing", "Text_get_Font", _args));
}
inline ::krpc::Stream<float> Drawing::Text::line_spacing_stream() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return ::krpc::Stream<float>(this->_client, this->_client->build_call("Drawing", "Text_get_LineSpacing", _args));
}
inline ::krpc::Stream<std::string> Drawing::Text::material_stream() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return ::krpc::Stream<std::string>(this->_client, this->_client->build_call("Drawing", "Text_get_Material", _args));
}
inline ::krpc::Stream<std::tuple<double, double, double>> Drawing::Text::position_stream() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return ::krpc::Stream<std::tuple<double, double, double>>(this->_client, this->_client->build_call("Drawing", "Text_get_Position", _args));
}
inline ::krpc::Stream<SpaceCenter::ReferenceFrame> Drawing::Text::reference_frame_stream() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return ::krpc::Stream<SpaceCenter::ReferenceFrame>(this->_client, this->_client->build_call("Drawing", "Text_get_ReferenceFrame", _args));
}
inline ::krpc::Stream<std::tuple<double, double, double, double>> Drawing::Text::rotation_stream() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return ::krpc::Stream<std::tuple<double, double, double, double>>(this->_client, this->_client->build_call("Drawing", "Text_get_Rotation", _args));
}
inline ::krpc::Stream<int32_t> Drawing::Text::size_stream() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return ::krpc::Stream<int32_t>(this->_client, this->_client->build_call("Drawing", "Text_get_Size", _args));
}
inline ::krpc::Stream<UI::FontStyle> Drawing::Text::style_stream() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return ::krpc::Stream<UI::FontStyle>(this->_client, this->_client->build_call("Drawing", "Text_get_Style", _args));
}
inline ::krpc::Stream<bool> Drawing::Text::visible_stream() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return ::krpc::Stream<bool>(this->_client, this->_client->build_call("Drawing", "Text_get_Visible", _args));
}
inline ::krpc::Stream<std::vector<std::string>> Drawing::Text::available_fonts_stream(Client& _client) {
return ::krpc::Stream<std::vector<std::string>>(&_client, _client.build_call("Drawing", "Text_static_AvailableFonts"));
}
inline ::krpc::schema::ProcedureCall Drawing::Text::remove_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Text_Remove", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::alignment_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Text_get_Alignment", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::set_alignment_call(UI::TextAlignment value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
return this->_client->build_call("Drawing", "Text_set_Alignment", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::anchor_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Text_get_Anchor", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::set_anchor_call(UI::TextAnchor value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
return this->_client->build_call("Drawing", "Text_set_Anchor", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::character_size_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Text_get_CharacterSize", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::set_character_size_call(float value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
return this->_client->build_call("Drawing", "Text_set_CharacterSize", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::color_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Text_get_Color", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::set_color_call(std::tuple<double, double, double> value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
return this->_client->build_call("Drawing", "Text_set_Color", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::content_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Text_get_Content", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::set_content_call(std::string value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
return this->_client->build_call("Drawing", "Text_set_Content", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::font_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Text_get_Font", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::set_font_call(std::string value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
return this->_client->build_call("Drawing", "Text_set_Font", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::line_spacing_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Text_get_LineSpacing", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::set_line_spacing_call(float value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
return this->_client->build_call("Drawing", "Text_set_LineSpacing", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::material_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Text_get_Material", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::set_material_call(std::string value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
return this->_client->build_call("Drawing", "Text_set_Material", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::position_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Text_get_Position", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::set_position_call(std::tuple<double, double, double> value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
return this->_client->build_call("Drawing", "Text_set_Position", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::reference_frame_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Text_get_ReferenceFrame", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::set_reference_frame_call(SpaceCenter::ReferenceFrame value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
return this->_client->build_call("Drawing", "Text_set_ReferenceFrame", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::rotation_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Text_get_Rotation", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::set_rotation_call(std::tuple<double, double, double, double> value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
return this->_client->build_call("Drawing", "Text_set_Rotation", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::size_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Text_get_Size", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::set_size_call(int32_t value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
return this->_client->build_call("Drawing", "Text_set_Size", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::style_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Text_get_Style", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::set_style_call(UI::FontStyle value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
return this->_client->build_call("Drawing", "Text_set_Style", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::visible_call() {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
return this->_client->build_call("Drawing", "Text_get_Visible", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::set_visible_call(bool value) {
std::vector<std::string> _args;
_args.push_back(encoder::encode(*this));
_args.push_back(encoder::encode(value));
return this->_client->build_call("Drawing", "Text_set_Visible", _args);
}
inline ::krpc::schema::ProcedureCall Drawing::Text::available_fonts_call(Client& _client) {
return _client.build_call("Drawing", "Text_static_AvailableFonts");
}
} // namespace services
} // namespace krpc
| 36.147484 | 245 | 0.710011 | [
"render",
"object",
"vector"
] |
74c23b9de09730072af1082c9518a1f0cd030d3d | 2,209 | cxx | C++ | tomviz/pybind11/ctvlib/WrappingCtvlib.cxx | danielballan/tomviz | b49216dd1a39b7402be61931fe954ffa85df3f96 | [
"BSD-3-Clause"
] | 284 | 2015-01-05T08:53:20.000Z | 2022-03-31T07:35:16.000Z | tomviz/pybind11/ctvlib/WrappingCtvlib.cxx | danielballan/tomviz | b49216dd1a39b7402be61931fe954ffa85df3f96 | [
"BSD-3-Clause"
] | 1,579 | 2015-03-19T15:56:44.000Z | 2022-03-21T11:29:04.000Z | tomviz/pybind11/ctvlib/WrappingCtvlib.cxx | danielballan/tomviz | b49216dd1a39b7402be61931fe954ffa85df3f96 | [
"BSD-3-Clause"
] | 74 | 2015-01-29T16:24:32.000Z | 2022-03-07T21:52:29.000Z | /* This source file is part of the Tomviz project, https://tomviz.org/.
It is released under the 3-Clause BSD License, see "LICENSE". */
#include "ctvlib.h"
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include "eigenConversion.h"
namespace py = pybind11;
PYBIND11_PLUGIN(ctvlib)
{
py::module m("ctvlib", "C++ Tomography Reconstruction Scripts");
py::class_<ctvlib>(m, "ctvlib")
.def(pybind11::init<int, int, int>())
.def("Nslice", &ctvlib::get_Nslice, "Get Nslice")
.def("Nray", &ctvlib::get_Nray, "Get Nray")
.def("set_tilt_series", &ctvlib::set_tilt_series,
"Pass the Projections to C++ Object")
.def("initialize_recon_copy", &ctvlib::initialize_recon_copy,
"Initialize Recon Copy")
.def("initialize_tv_recon", &ctvlib::initialize_tv_recon,
"Initialize TV Recon")
.def("update_proj_angles", &ctvlib::update_proj_angles,
"Update Algorithm with New projections")
.def("get_recon", &ctvlib::get_recon, "Return the Reconstruction to Python")
.def("ART", &ctvlib::ART, "ART Reconstruction")
.def("randART", &ctvlib::randART, "Stochastic ART Reconstruction")
.def("SIRT", &ctvlib::SIRT, "SIRT Reconstruction")
.def("lipschits", &ctvlib::lipschits, "Calculate Lipschitz Constant")
.def("row_inner_product", &ctvlib::normalization,
"Calculate the Row Inner Product for Measurement Matrix")
.def("positivity", &ctvlib::positivity, "Remove Negative Elements")
.def("forward_projection", &ctvlib::forward_projection,
"Forward Projection")
.def("load_A", &ctvlib::loadA, "Load Measurement Matrix Created By Python")
.def("copy_recon", &ctvlib::copy_recon, "Copy the reconstruction")
.def("matrix_2norm", &ctvlib::matrix_2norm,
"Calculate L2-Norm of Reconstruction")
.def("data_distance", &ctvlib::data_distance,
"Calculate L2-Norm of Projection (aka Vectors)")
.def("tv_gd", &ctvlib::tv_gd_3D, "3D TV Gradient Descent")
.def("get_projections", &ctvlib::get_projections,
"Return the projection matrix to python")
.def("restart_recon", &ctvlib::restart_recon,
"Set all the Slices Equal to Zero");
return m.ptr();
}
| 42.480769 | 80 | 0.680851 | [
"object",
"3d"
] |
74c5dffd9acac4c469c7be2e9db7e2172d217be9 | 3,439 | hpp | C++ | liver/liver.hpp | ncrookston/liver_source | 9876ac4e9ea57d8e23767af9be061a9b10c6f1e5 | [
"BSL-1.0"
] | null | null | null | liver/liver.hpp | ncrookston/liver_source | 9876ac4e9ea57d8e23767af9be061a9b10c6f1e5 | [
"BSL-1.0"
] | null | null | null | liver/liver.hpp | ncrookston/liver_source | 9876ac4e9ea57d8e23767af9be061a9b10c6f1e5 | [
"BSL-1.0"
] | null | null | null | #ifndef JHMI_LIVER_HPP_NRC_20141124
#define JHMI_LIVER_HPP_NRC_20141124
#include "liver/fill_liver_volume.hpp"
#include "utility/cube.hpp"
#include "utility/grid.hpp"
#include <boost/tokenizer.hpp>
#include <range/v3/view/const.hpp>
#include <fstream>
namespace jhmi {
class liver {
using pt_list = std::vector<m3>;
liver() : pt_grid_{nullptr}, extents_{} {}
public:
template <typename Shape>
static liver create(Shape const& volume) {
liver lv;
std::size_t idx = 0;
lv.extents_ = extents(volume);
fill_liver_volume(lv.extents_,
[&](m3 const& pt) { return contains(volume, pt); },
[&, last_x=std::numeric_limits<std::size_t>::max()]
(m3 const& pt, int3 const& idxs) mutable
{
if (last_x != idxs.x)
{
lv.x_starts_.push_back(idx);
last_x = idxs.x;
}
idx += 2;
using namespace lobule;
lv.portal_tracts_.push_back(pt + m3{0_mm, -side_length, 0_mm});
lv.portal_tracts_.push_back(pt + m3{min_radius, -side_length / 2., 0_mm});
lv.centrilobular_veins_.push_back(pt);
});
lv.x_starts_.push_back(idx);
lv.pt_grid_.reset(new grid<pt_list>{lv.portal_tracts_,lobule::side_length});
return lv;
}
static liver load(std::string const& filename) {
liver lv;
std::ifstream fin{filename};
std::string line;
std::getline(fin, line);//Ignore first line
std::size_t idx = 0;
std::string last_x;
boost::optional<cube<m3>> oextents = boost::none;
while (fin) {
std::getline(fin, line);
if (line.empty())
continue;
line = line.substr(1, line.size() - 2);
boost::tokenizer<boost::char_separator<char>> tok{line, boost::char_separator<char>{","}};
auto it = tok.begin();
if (last_x != *it) {
lv.x_starts_.push_back(idx);
last_x = *it;
}
idx += 2;
m x = std::stod(*it++) * meters;
m y = std::stod(*it++) * meters;
m z = std::stod(*it++) * meters;
assert(it == tok.end());
m3 pt{x,y,z};
oextents = oextents ? expand(*oextents, pt) : cube<m3>{pt,pt};
using namespace lobule;
lv.portal_tracts_.push_back(pt + m3{0_mm, -side_length, 0_mm});
lv.portal_tracts_.push_back(pt + m3{min_radius, -side_length / 2., 0_mm});
lv.centrilobular_veins_.push_back(pt);
}
lv.pt_grid_.reset(new grid<pt_list>{lv.portal_tracts_,lobule::side_length});
lv.extents_ = *oextents;
return lv;
}
auto portal_tracts() const
{ return ranges::view::const_(portal_tracts_); }
auto centrilobular_veins() const
{ return ranges::view::const_(centrilobular_veins_); }
template <typename F>
void visit_portal_tracts(std::size_t x_step, std::size_t y_step, F f) const
{
for (std::size_t i = 0, i_end = x_starts_.size()-1; i < i_end; i += x_step)
{
for (std::size_t j = x_starts_[i], j_end = x_starts_[i+1]; j < j_end; j += y_step)
{
f(j);
}
}
}
template <typename F>
void for_lobules_in_radius(m3 const& pt, m radius, F f) const
{ pt_grid_->for_items_in_radius(pt, radius, f); }
private:
std::vector<m3> portal_tracts_;
std::vector<m3> centrilobular_veins_;
std::vector<std::size_t> x_starts_;
std::unique_ptr<grid<pt_list>> pt_grid_;
cube<m3> extents_;
};
liver get_liver_cube(m size) {
auto shape = cube<m3>{{0_mm,0_mm,0_mm},{size,size,size}};
return liver::create(shape);
}
}//jhmi
#endif
| 27.512 | 96 | 0.629834 | [
"shape",
"vector"
] |
74c86ae92e9c64ac7fe61dd674d3da31691db62e | 4,384 | cpp | C++ | tgmm-paper/src/UtilsCUDA/3DEllipticalHaarFeatures/AnnotationEllipsoid.cpp | msphan/tgmm-docker | bc417f4199801df9386817eba467026167320127 | [
"Apache-2.0"
] | null | null | null | tgmm-paper/src/UtilsCUDA/3DEllipticalHaarFeatures/AnnotationEllipsoid.cpp | msphan/tgmm-docker | bc417f4199801df9386817eba467026167320127 | [
"Apache-2.0"
] | null | null | null | tgmm-paper/src/UtilsCUDA/3DEllipticalHaarFeatures/AnnotationEllipsoid.cpp | msphan/tgmm-docker | bc417f4199801df9386817eba467026167320127 | [
"Apache-2.0"
] | null | null | null | /*
* Ellipsoid.cpp
*
* Created on: Feb 15, 2011
* Author: amatf
*/
#include "AnnotationEllipsoid.h"
#include <math.h>
#include "external/xmlParser/svlStrUtils.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
//TODO: find a better random numebr generator for windows
#ifdef _WIN32 || _WIN64
#define drand48() (rand()*(1.0/(double)RAND_MAX))
#endif
AnnotationEllipsoid::AnnotationEllipsoid()
{
imgFilename = string("");
classVal = -1;
TM = -1;
};
AnnotationEllipsoid::AnnotationEllipsoid(const double *mu_, const double *W_, string& imgFilename_)
{
imgFilename = imgFilename_;
memcpy(mu,mu_, sizeof(double) * dimsImage);
memcpy(W,W_, sizeof(double) * dimsImage * (dimsImage +1) /2);
classVal = -1;
TM = -1;
}
AnnotationEllipsoid::AnnotationEllipsoid(const AnnotationEllipsoid &p)
{
imgFilename = p.imgFilename;
memcpy(mu,p.mu, sizeof(double) * dimsImage);
memcpy(W,p.W, sizeof(double) * dimsImage * (dimsImage +1) /2);
className = p.className;
classVal = p.classVal;
svFilename = p.svFilename;
svIdx = p.svIdx;
TM = p.TM;
}
AnnotationEllipsoid& AnnotationEllipsoid::operator=(const AnnotationEllipsoid& p)
{
if (this != &p)
{
imgFilename = p.imgFilename;
memcpy(mu,p.mu, sizeof(double) * dimsImage);
memcpy(W,p.W, sizeof(double) * dimsImage * (dimsImage +1) /2);
className = p.className;
classVal = p.classVal;
svFilename = p.svFilename;
svIdx = p.svIdx;
TM = p.TM;
}
return *this;
}
bool operator< (const AnnotationEllipsoid& lhs, const AnnotationEllipsoid& rhs)
{
if( lhs.imgFilename.compare( rhs.imgFilename ) < 0 )
return true;
else
return false;
}
AnnotationEllipsoid::~AnnotationEllipsoid()
{
//nothing here yet
}
ostream& AnnotationEllipsoid::writeXML(ostream& os)
{
os<<"<Surface ";
os<<"name=\""<<"Ellipsoid"<<"\" id=\""<<1<<"\" numCoeffs=\""<<dimsImage * dimsImage<<"\" "<<endl;
os<<"coeffs=\"";
for(unsigned int ii=0;ii< dimsImage * (1+dimsImage) /2 ;ii++) os<<W[ii]<<" ";
for(unsigned int ii=0;ii< dimsImage ;ii++) os<<mu[ii]<<" ";
os<<"\""<<endl;
os<<"covarianceMatrixSize=\""<<dimsImage<<"\" ";
os<<" imFilename=\""<< imgFilename<<"\" class=\""<<className<<"\"";
if( svIdx.empty() == false )
{
os<<" svFilename=\""<< svFilename<<"\" svIdx=\"";
for(vector<int>::const_iterator iter = svIdx.begin(); iter != svIdx.end(); ++iter)
{
os<<(*iter)<<" ";
}
os<<"\"";
}
os<<"></Surface>"<<endl;
return os;
}
//HOW TO USE readXML
//XMLNode xMainNode=XMLNode::openFileHelper("filename.xml","document");
//int n=xMainNode.nChildNode("GaussianMixtureModel");
//for(int ii=0;ii<n;ii++) GaussianMixtureModel GM(xMainNode,ii);
AnnotationEllipsoid::AnnotationEllipsoid (XMLNode &xml,int position)
{
XMLNode node = xml.getChildNode("Surface",&position);
XMLCSTR aux=node.getAttribute("numCoeffs");
vector<unsigned long int> vv;
assert(aux != NULL);
parseString<unsigned long int>(string(aux), vv);
unsigned int numCoeffs_=vv[0];
vv.clear();
aux=node.getAttribute("coeffs");
vector<double> coeffs_;
assert(aux != NULL);
parseString<double>(string(aux), coeffs_);
int ii =0;
for(;ii<dimsImage * (1 + dimsImage) /2; ii++)
W[ii] = coeffs_[ii];
int jj =0;
for(;ii < (int) numCoeffs_; ii++, jj++)
mu[jj] = coeffs_[ii];
aux=node.getAttribute("imFilename");
assert(aux != NULL);
imgFilename = string(aux);
aux=node.getAttribute("class");
if( aux!= NULL)
className = string(aux);
else
className = "";
classVal = -1;
aux=node.getAttribute("svIdx");
vector<int> dd;
if(aux != NULL)
{
parseString<int>(string(aux), dd);
svIdx = dd;
dd.clear();
}
aux=node.getAttribute("svFilename");
if(aux != NULL)
svFilename = string(aux);
//double check that the rest of the properties are correct
aux=node.getAttribute("name");
assert(aux != NULL);
if(string(aux).compare("Ellipsoid")!=0)
{
cout<<"ERROR: at AnnotationEllipsoid::readXML : trying to read surface type "<<string(aux)<<" using "<<"Ellipsoid"<<" function"<<endl;
exit(10);
}
aux=node.getAttribute("covarianceMatrixSize");
assert(aux != NULL);
parseString<unsigned long int>(string(aux), vv);
if((int)vv[0]!=dimsImage)
{
cout<<"ERROR: at AnnotationEllipsoid::readXML : trying to read ellipsoid of dimensions "<<vv[0]<<" using "<<dimsImage<<" dimensions. Change covarianceMatrixSize and recompile"<<endl;
exit(10);
}
vv.clear();
}
| 22.833333 | 184 | 0.664918 | [
"vector"
] |
74c87013f1cfec778445d0e6f6ed05fb37c90449 | 10,132 | cpp | C++ | legacy/python/tinyrenderer/bindings/_legacy/src/camera_py.cpp | wpumacay/tiny_renderer | 9d59be49086822860654afddaf94ce1cec374ea8 | [
"MIT"
] | 1 | 2018-07-05T15:54:51.000Z | 2018-07-05T15:54:51.000Z | legacy/python/tinyrenderer/bindings/_legacy/src/camera_py.cpp | wpumacay/cat1 | 9d59be49086822860654afddaf94ce1cec374ea8 | [
"MIT"
] | null | null | null | legacy/python/tinyrenderer/bindings/_legacy/src/camera_py.cpp | wpumacay/cat1 | 9d59be49086822860654afddaf94ce1cec374ea8 | [
"MIT"
] | null | null | null |
#include <camera_py.h>
namespace py = pybind11;
namespace engine
{
void bindings_cameraBase( py::module& m )
{
/* Expose required enumerators */
py::enum_< engine::eCameraType >( m, "CameraType", py::arithmetic() )
.value( "FIXED", engine::eCameraType::FIXED )
.value( "FPS", engine::eCameraType::FPS )
.value( "ORBIT", engine::eCameraType::ORBIT );
py::enum_< engine::eCameraProjection >( m, "CameraProjection", py::arithmetic() )
.value( "PERSPECTIVE", engine::eCameraProjection::PERSPECTIVE )
.value( "ORTHOGRAPHIC", engine::eCameraProjection::ORTHOGRAPHIC );
/* Expose build|config struct for cameras */
py::class_< CCameraProjData >( m, "CameraProjData" )
.def( py::init<>() )
.def_readwrite( "projection", &CCameraProjData::projection )
.def_readwrite( "fov", &CCameraProjData::fov )
.def_readwrite( "aspect", &CCameraProjData::aspect )
.def_readwrite( "width", &CCameraProjData::width )
.def_readwrite( "height", &CCameraProjData::height )
.def_readwrite( "zNear", &CCameraProjData::zNear )
.def_readwrite( "zFar", &CCameraProjData::zFar )
.def_readwrite( "viewportWidth", &CCameraProjData::viewportWidth )
.def_readwrite( "viewportHeight", &CCameraProjData::viewportHeight );
/* Expose Base-Camera class */
py::class_< CICamera >( m, "ICamera" )
.def_property( "position",
[]( const CICamera* self ) -> py::array_t<float32>
{
return tinymath::vector_to_nparray<float32,3>( self->position() );
},
[]( CICamera* self, const py::array_t<float32>& pos )
{
self->SetPosition( tinymath::nparray_to_vector<float32,3>( pos ) );
} )
.def_property( "target_point",
[]( const CICamera* self ) -> py::array_t<float32>
{
return tinymath::vector_to_nparray<float32,3>( self->target_point() );
},
[]( CICamera* self, const py::array_t<float32>& tpoint )
{
self->SetTargetPoint( tinymath::nparray_to_vector<float32,3>( tpoint ) );
} )
.def_property( "active",
[]( const CICamera* self ) -> bool
{
return self->active();
},
[]( CICamera* self, bool active )
{
self->SetActiveMode( active );
} )
.def_property( "proj_data",
[]( const CICamera* self ) -> const CCameraProjData&
{
return self->proj_data();
},
[]( CICamera* self, const CCameraProjData& proj_data ) -> void
{
self->SetProjectionData( proj_data );
} )
.def( "update", &CICamera::Update )
.def( "resize", &CICamera::Resize )
.def_property_readonly( "name", &CICamera::name )
.def_property_readonly( "type", &CICamera::type )
.def_property_readonly( "up_axis", &CICamera::up_axis )
.def_property_readonly( "target_direction", []( const CICamera* self ) -> py::array_t<float32>
{
return tinymath::vector_to_nparray<float32,3>( self->target_direction() );
} )
.def_property_readonly( "front", []( const CICamera* self ) -> py::array_t<float32>
{
return tinymath::vector_to_nparray<float32,3>( self->front() );
} )
.def_property_readonly( "up", []( const CICamera* self ) -> py::array_t<float32>
{
return tinymath::vector_to_nparray<float32,3>( self->up() );
} )
.def_property_readonly( "right", []( const CICamera* self ) -> py::array_t<float32>
{
return tinymath::vector_to_nparray<float32,3>( self->right() );
} )
.def( "mat_view", []( const CICamera* self ) -> py::array_t<float32>
{
return tinymath::matrix_to_nparray<float32,4>( self->mat_view() );
} )
.def( "mat_proj", []( const CICamera* self ) -> py::array_t<float32>
{
return tinymath::matrix_to_nparray<float32,4>( self->mat_proj() );
} )
.def( "__repr__", []( const CICamera* self )
{
auto strrep = std::string( "Camera(\n" );
strrep += "cpp-address : " + tinyutils::PointerToHexAddress( self ) + "\n";
strrep += self->ToString();
strrep += ")";
return strrep;
} );
}
void bindings_cameraTypes( py::module& m )
{
/* Expose Fixed-camera */
py::class_< CFixedCamera, CICamera >( m, "FixedCamera" )
.def( py::init( []( const std::string& name,
const py::array_t<float32>& position,
const py::array_t<float32>& target_point,
const eAxis& up_axis,
const CCameraProjData& proj_data )
{
return std::make_unique<CFixedCamera>( name,
tinymath::nparray_to_vector<float32,3>( position ),
tinymath::nparray_to_vector<float32,3>( target_point ),
up_axis,
proj_data );
} ), py::arg( "name" ), py::arg( "position" ), py::arg( "target_point" ), py::arg( "up_axis" ), py::arg( "proj_data" ) )
.def( "SetCameraTransform", []( CFixedCamera* self, const py::array_t<float32,4>& transform )
{
self->SetCameraTransform( tinymath::nparray_to_matrix<float32,4>( transform ) );
} );
/* Expose Orbit-camera */
py::class_< COrbitCamera, CICamera >( m, "OrbitCamera" )
.def( py::init( []( const std::string& name,
const py::array_t<float32>& position,
const py::array_t<float32>& target_point,
const eAxis& up_axis,
const CCameraProjData& proj_data,
float move_sensitivity,
float zoom_sensitivity )
{
return std::make_unique<COrbitCamera>( name,
tinymath::nparray_to_vector<float32,3>( position ),
tinymath::nparray_to_vector<float32,3>( target_point ),
up_axis,
proj_data,
move_sensitivity,
zoom_sensitivity );
} ), py::arg( "name" ), py::arg( "position" ), py::arg( "target_point" ), py::arg( "up_axis" ),
py::arg( "proj_data" ), py::arg( "move_sensitivity" ) = 0.005f, py::arg( "zoom_sensitivity" ) = 1.000f )
.def_property( "move_sensitivity", &COrbitCamera::move_sensitivity, &COrbitCamera::SetMoveSensitivity )
.def_property( "zoom_sensitivity", &COrbitCamera::zoom_sensitivity, &COrbitCamera::SetZoomSensitivity );
/* Expose Fps-camera */
py::class_< CFpsCamera, CICamera >( m, "FpsCamera" )
.def( py::init( []( const std::string& name,
const py::array_t<float32>& position,
const py::array_t<float32>& target_point,
const eAxis& up_axis,
const CCameraProjData& proj_data,
float sensitivity,
float speed,
float max_delta )
{
return std::make_unique<CFpsCamera>( name,
tinymath::nparray_to_vector<float32,3>( position ),
tinymath::nparray_to_vector<float32,3>( target_point ),
up_axis,
proj_data,
sensitivity,
speed,
max_delta );
} ), py::arg( "name" ), py::arg( "position" ), py::arg( "target_point" ), py::arg( "up_axis" ),
py::arg( "proj_data" ), py::arg( "sensitivity" ) = 0.25f, py::arg( "speed" ) = 250.0f, py::arg( "max_delta" ) = 10.0f )
.def_property( "sensitivity", &CFpsCamera::sensitivity, &CFpsCamera::SetSensitivity )
.def_property( "speed", &CFpsCamera::speed, &CFpsCamera::SetSpeed )
.def_property( "max_delta", &CFpsCamera::max_delta, &CFpsCamera::SetMaxDelta )
.def_property_readonly( "current_front_speed", &CFpsCamera::current_front_speed )
.def_property_readonly( "current_right_speed", &CFpsCamera::current_right_speed )
.def_property_readonly( "roll", &CFpsCamera::roll )
.def_property_readonly( "pitch", &CFpsCamera::pitch )
.def_property_readonly( "yaw", &CFpsCamera::yaw );
}
}
| 55.065217 | 136 | 0.463482 | [
"transform"
] |
74ca0a527297ab0aba983bdedd42b847d3eae992 | 10,277 | cpp | C++ | automated-tests/src/dali/utc-Dali-ConstraintFunction.cpp | Coquinho/dali-core | 97a968a80ad681b1cbbc219fa6729f2344672476 | [
"Apache-2.0",
"BSD-3-Clause"
] | 21 | 2016-11-18T10:26:40.000Z | 2021-11-02T09:46:15.000Z | automated-tests/src/dali/utc-Dali-ConstraintFunction.cpp | Coquinho/dali-core | 97a968a80ad681b1cbbc219fa6729f2344672476 | [
"Apache-2.0",
"BSD-3-Clause"
] | 7 | 2016-10-18T17:39:12.000Z | 2020-12-01T11:45:36.000Z | automated-tests/src/dali/utc-Dali-ConstraintFunction.cpp | expertisesolutions/dali-core | 444ee3f60f12a23aca07059c5e1109f26613e44e | [
"Apache-2.0",
"BSD-3-Clause"
] | 16 | 2017-03-08T15:50:32.000Z | 2021-05-24T06:58:10.000Z | /*
* Copyright (c) 2014 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <dali-test-suite-utils.h>
#include <dali/public-api/dali-core.h>
#include <stdlib.h>
#include <iostream>
using namespace Dali;
///////////////////////////////////////////////////////////////////////////////
void utc_dali_constraint_function_startup(void)
{
test_return_value = TET_UNDEF;
}
void utc_dali_constraint_function_cleanup(void)
{
test_return_value = TET_PASS;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
namespace
{
bool gFunctionCalled = false;
template<typename T>
void TestCallbackFunction(T& /* current*/, const PropertyInputContainer& /* inputs */)
{
gFunctionCalled = true;
}
template<typename T>
struct TestCallbackFunctor
{
TestCallbackFunctor(bool& functorCalled)
: mFunctorCalled(functorCalled)
{
}
void operator()(T& /* current*/, const PropertyInputContainer& /* inputs */)
{
mFunctorCalled = true;
}
bool& mFunctorCalled;
};
template<typename T>
struct TestFunctorMethod
{
TestFunctorMethod(bool& functorCalled)
: mFunctorCalled(functorCalled)
{
}
void Method(T& /* current*/, const PropertyInputContainer& /* inputs */)
{
mFunctorCalled = true;
}
bool& mFunctorCalled;
};
} // unnamed namespace
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Constraint::Function::Function( void( *function )( P&, const PropertyInputContainer& ) )
///////////////////////////////////////////////////////////////////////////////
namespace
{
template<typename T>
void TestFunctionConstructor()
{
gFunctionCalled = false;
Constraint::Function<T> function(&TestCallbackFunction<T>);
T current;
PropertyInputContainer inputs;
DALI_TEST_EQUALS(gFunctionCalled, false, TEST_LOCATION);
CallbackBase::Execute<T&, const PropertyInputContainer&>(function, current, inputs);
DALI_TEST_EQUALS(gFunctionCalled, true, TEST_LOCATION);
}
} // unnamed namespace
int UtcDaliConstraintFunctionWithFunction(void)
{
TestFunctionConstructor<bool>();
TestFunctionConstructor<int>();
TestFunctionConstructor<unsigned int>();
TestFunctionConstructor<float>();
TestFunctionConstructor<Vector2>();
TestFunctionConstructor<Vector3>();
TestFunctionConstructor<Vector4>();
TestFunctionConstructor<Quaternion>();
TestFunctionConstructor<Matrix>();
TestFunctionConstructor<Matrix3>();
END_TEST;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Constraint::Function::Function( const T& object )
///////////////////////////////////////////////////////////////////////////////
namespace
{
template<typename T>
void TestFunctorConstructor()
{
bool called = false;
TestCallbackFunctor<T> functor(called);
Constraint::Function<T> callback(functor);
T current;
PropertyInputContainer inputs;
DALI_TEST_EQUALS(called, false, TEST_LOCATION);
CallbackBase::Execute<T&, const PropertyInputContainer&>(callback, current, inputs);
DALI_TEST_EQUALS(called, true, TEST_LOCATION);
}
} // unnamed namespace
int UtcDaliConstraintFunctionWithFunctor(void)
{
TestFunctorConstructor<bool>();
TestFunctorConstructor<int>();
TestFunctorConstructor<unsigned int>();
TestFunctorConstructor<float>();
TestFunctorConstructor<Vector2>();
TestFunctorConstructor<Vector3>();
TestFunctorConstructor<Vector4>();
TestFunctorConstructor<Quaternion>();
TestFunctorConstructor<Matrix>();
TestFunctorConstructor<Matrix3>();
END_TEST;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Constraint::Function::Function( const T& object, void ( T::*memberFunction ) ( P&, const PropertyInputContainer& ) )
///////////////////////////////////////////////////////////////////////////////
namespace
{
template<typename T>
void TestFunctorMethodConstructor()
{
bool called = false;
TestFunctorMethod<T> functor(called);
Constraint::Function<T> callback(functor, &TestFunctorMethod<T>::Method);
T current;
PropertyInputContainer inputs;
DALI_TEST_EQUALS(called, false, TEST_LOCATION);
CallbackBase::Execute<T&, const PropertyInputContainer&>(callback, current, inputs);
DALI_TEST_EQUALS(called, true, TEST_LOCATION);
}
} // unnamed namespace
int UtcDaliConstraintFunctionWithMethodFunctor(void)
{
TestFunctorMethodConstructor<bool>();
TestFunctorMethodConstructor<int>();
TestFunctorMethodConstructor<unsigned int>();
TestFunctorMethodConstructor<float>();
TestFunctorMethodConstructor<Vector2>();
TestFunctorMethodConstructor<Vector3>();
TestFunctorMethodConstructor<Vector4>();
TestFunctorMethodConstructor<Quaternion>();
TestFunctorMethodConstructor<Matrix>();
TestFunctorMethodConstructor<Matrix3>();
END_TEST;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Constraint::Function::Clone
///////////////////////////////////////////////////////////////////////////////
namespace
{
template<typename T>
void TestFunctionClone()
{
gFunctionCalled = false;
Constraint::Function<T> callback(&TestCallbackFunction<T>);
CallbackBase* clone = callback.Clone();
T current;
PropertyInputContainer inputs;
DALI_TEST_EQUALS(gFunctionCalled, false, TEST_LOCATION);
CallbackBase::Execute<T&, const PropertyInputContainer&>(*clone, current, inputs);
DALI_TEST_EQUALS(gFunctionCalled, true, TEST_LOCATION);
delete clone;
}
template<typename T>
void TestFunctorClone()
{
bool called = false;
TestCallbackFunctor<T> functor(called);
Constraint::Function<T> callback(functor);
CallbackBase* clone = callback.Clone();
T current;
PropertyInputContainer inputs;
DALI_TEST_EQUALS(called, false, TEST_LOCATION);
CallbackBase::Execute<T&, const PropertyInputContainer&>(*clone, current, inputs);
DALI_TEST_EQUALS(called, true, TEST_LOCATION);
delete clone;
}
template<typename T>
void TestMethodFunctorClone()
{
bool called = false;
TestFunctorMethod<T> functor(called);
Constraint::Function<T> callback(functor, &TestFunctorMethod<T>::Method);
CallbackBase* clone = callback.Clone();
T current;
PropertyInputContainer inputs;
DALI_TEST_EQUALS(called, false, TEST_LOCATION);
CallbackBase::Execute<T&, const PropertyInputContainer&>(*clone, current, inputs);
DALI_TEST_EQUALS(called, true, TEST_LOCATION);
delete clone;
}
} // unnamed namespace
int UtcDaliConstraintFunctionFunctionClone(void)
{
TestFunctionClone<bool>();
TestFunctionClone<int>();
TestFunctionClone<unsigned int>();
TestFunctionClone<float>();
TestFunctionClone<Vector2>();
TestFunctionClone<Vector3>();
TestFunctionClone<Vector4>();
TestFunctionClone<Quaternion>();
TestFunctionClone<Matrix>();
TestFunctionClone<Matrix3>();
END_TEST;
}
int UtcDaliConstraintFunctionFunctorClone(void)
{
TestFunctorClone<bool>();
TestFunctorClone<int>();
TestFunctorClone<unsigned int>();
TestFunctorClone<float>();
TestFunctorClone<Vector2>();
TestFunctorClone<Vector3>();
TestFunctorClone<Vector4>();
TestFunctorClone<Quaternion>();
TestFunctorClone<Matrix>();
TestFunctorClone<Matrix3>();
END_TEST;
}
int UtcDaliConstraintFunctionMethodFunctorClone(void)
{
TestMethodFunctorClone<bool>();
TestMethodFunctorClone<int>();
TestMethodFunctorClone<unsigned int>();
TestMethodFunctorClone<float>();
TestMethodFunctorClone<Vector2>();
TestMethodFunctorClone<Vector3>();
TestMethodFunctorClone<Vector4>();
TestMethodFunctorClone<Quaternion>();
TestMethodFunctorClone<Matrix>();
TestMethodFunctorClone<Matrix3>();
END_TEST;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
namespace
{
struct CountFunctor
{
CountFunctor(int& count)
: mCount(count)
{
++mCount;
}
CountFunctor(const CountFunctor& other)
: mCount(other.mCount)
{
++mCount;
}
CountFunctor& operator=(const CountFunctor& other)
{
this->mCount = other.mCount;
++mCount;
return *this;
}
~CountFunctor()
{
--mCount;
}
void operator()(bool& /* current*/, const PropertyInputContainer& /* inputs */)
{
}
int& mCount;
};
} // unnamed namespace
int UtcDaliConstraintFunctionEnsureMemoryCleanup(void)
{
// Functors are new'd in Constraint::Function, so check that all memory is released at the end
int count = 0;
{
CountFunctor functor(count);
Constraint::Function<bool> callback1(functor);
Constraint::Function<bool> callback2(functor);
Constraint::Function<bool> callback3(functor);
Constraint::Function<bool> callback4(functor);
Constraint::Function<bool> callback5(functor);
Constraint::Function<bool> callback6(functor);
Constraint::Function<bool> callback7(functor);
Constraint::Function<bool> callback8(functor);
Constraint::Function<bool> callback9(functor);
DALI_TEST_EQUALS(count, 10, TEST_LOCATION);
}
DALI_TEST_EQUALS(count, 0, TEST_LOCATION);
END_TEST;
}
///////////////////////////////////////////////////////////////////////////////
| 28.867978 | 119 | 0.625669 | [
"object"
] |
74cdfa60c4e56622b0eb190f63be1c6e2e65e17f | 4,937 | cc | C++ | components/service/ucloud/cloudapi/src/model/DescribeTrafficControlsResult.cc | wanguojian/AliOS-Things | 47fce29d4dd39d124f0bfead27998ad7beea8441 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | components/service/ucloud/cloudapi/src/model/DescribeTrafficControlsResult.cc | wanguojian/AliOS-Things | 47fce29d4dd39d124f0bfead27998ad7beea8441 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | components/service/ucloud/cloudapi/src/model/DescribeTrafficControlsResult.cc | wanguojian/AliOS-Things | 47fce29d4dd39d124f0bfead27998ad7beea8441 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/cloudapi/model/DescribeTrafficControlsResult.h>
#include <json/json.h>
using namespace AlibabaCloud::CloudAPI;
using namespace AlibabaCloud::CloudAPI::Model;
DescribeTrafficControlsResult::DescribeTrafficControlsResult() :
ServiceResult()
{}
DescribeTrafficControlsResult::DescribeTrafficControlsResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
DescribeTrafficControlsResult::~DescribeTrafficControlsResult()
{}
void DescribeTrafficControlsResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allTrafficControlsNode = value["TrafficControls"]["TrafficControl"];
for (auto valueTrafficControlsTrafficControl : allTrafficControlsNode)
{
TrafficControl trafficControlsObject;
if(!valueTrafficControlsTrafficControl["TrafficControlId"].isNull())
trafficControlsObject.trafficControlId = valueTrafficControlsTrafficControl["TrafficControlId"].asString();
if(!valueTrafficControlsTrafficControl["TrafficControlName"].isNull())
trafficControlsObject.trafficControlName = valueTrafficControlsTrafficControl["TrafficControlName"].asString();
if(!valueTrafficControlsTrafficControl["Description"].isNull())
trafficControlsObject.description = valueTrafficControlsTrafficControl["Description"].asString();
if(!valueTrafficControlsTrafficControl["TrafficControlUnit"].isNull())
trafficControlsObject.trafficControlUnit = valueTrafficControlsTrafficControl["TrafficControlUnit"].asString();
if(!valueTrafficControlsTrafficControl["ApiDefault"].isNull())
trafficControlsObject.apiDefault = std::stoi(valueTrafficControlsTrafficControl["ApiDefault"].asString());
if(!valueTrafficControlsTrafficControl["UserDefault"].isNull())
trafficControlsObject.userDefault = std::stoi(valueTrafficControlsTrafficControl["UserDefault"].asString());
if(!valueTrafficControlsTrafficControl["AppDefault"].isNull())
trafficControlsObject.appDefault = std::stoi(valueTrafficControlsTrafficControl["AppDefault"].asString());
if(!valueTrafficControlsTrafficControl["CreatedTime"].isNull())
trafficControlsObject.createdTime = valueTrafficControlsTrafficControl["CreatedTime"].asString();
if(!valueTrafficControlsTrafficControl["ModifiedTime"].isNull())
trafficControlsObject.modifiedTime = valueTrafficControlsTrafficControl["ModifiedTime"].asString();
auto allSpecialPoliciesNode = allTrafficControlsNode["SpecialPolicies"]["SpecialPolicy"];
for (auto allTrafficControlsNodeSpecialPoliciesSpecialPolicy : allSpecialPoliciesNode)
{
TrafficControl::SpecialPolicy specialPoliciesObject;
if(!allTrafficControlsNodeSpecialPoliciesSpecialPolicy["SpecialType"].isNull())
specialPoliciesObject.specialType = allTrafficControlsNodeSpecialPoliciesSpecialPolicy["SpecialType"].asString();
auto allSpecialsNode = allSpecialPoliciesNode["Specials"]["Special"];
for (auto allSpecialPoliciesNodeSpecialsSpecial : allSpecialsNode)
{
TrafficControl::SpecialPolicy::Special specialsObject;
if(!allSpecialPoliciesNodeSpecialsSpecial["SpecialKey"].isNull())
specialsObject.specialKey = allSpecialPoliciesNodeSpecialsSpecial["SpecialKey"].asString();
if(!allSpecialPoliciesNodeSpecialsSpecial["TrafficValue"].isNull())
specialsObject.trafficValue = std::stoi(allSpecialPoliciesNodeSpecialsSpecial["TrafficValue"].asString());
specialPoliciesObject.specials.push_back(specialsObject);
}
trafficControlsObject.specialPolicies.push_back(specialPoliciesObject);
}
trafficControls_.push_back(trafficControlsObject);
}
if(!value["TotalCount"].isNull())
totalCount_ = std::stoi(value["TotalCount"].asString());
if(!value["PageSize"].isNull())
pageSize_ = std::stoi(value["PageSize"].asString());
if(!value["PageNumber"].isNull())
pageNumber_ = std::stoi(value["PageNumber"].asString());
}
int DescribeTrafficControlsResult::getTotalCount()const
{
return totalCount_;
}
int DescribeTrafficControlsResult::getPageSize()const
{
return pageSize_;
}
int DescribeTrafficControlsResult::getPageNumber()const
{
return pageNumber_;
}
std::vector<DescribeTrafficControlsResult::TrafficControl> DescribeTrafficControlsResult::getTrafficControls()const
{
return trafficControls_;
}
| 43.690265 | 117 | 0.801499 | [
"vector",
"model"
] |
74cfff93a0433f69e35bdfa8b626dbbd6d732e06 | 1,378 | cpp | C++ | 01. Mathematics/15_QuadraticEquationRoots.cpp | Ujjawalgupta42/Hacktoberfest2021-DSA | eccd9352055085973e3d6a1feb10dd193905584b | [
"MIT"
] | 225 | 2021-10-01T03:09:01.000Z | 2022-03-11T11:32:49.000Z | 01. Mathematics/15_QuadraticEquationRoots.cpp | Ujjawalgupta42/Hacktoberfest2021-DSA | eccd9352055085973e3d6a1feb10dd193905584b | [
"MIT"
] | 252 | 2021-10-01T03:45:20.000Z | 2021-12-07T18:32:46.000Z | 01. Mathematics/15_QuadraticEquationRoots.cpp | Ujjawalgupta42/Hacktoberfest2021-DSA | eccd9352055085973e3d6a1feb10dd193905584b | [
"MIT"
] | 911 | 2021-10-01T02:55:19.000Z | 2022-02-06T09:08:37.000Z | // { Driver Code Starts
// Initial template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
class Solution
{
public:
vector<int> quadraticRoots(int a, int b, int c)
{
vector<int> ans;
if(a==0)
{
ans.push_back(-1);
return ans;
}
int d = b*b - 4*a*c;
double sqrt_val = sqrt(abs(d));
if(d>0)
{
double root1 = (double)(-b + sqrt_val)/(2*a);
double root2 = (double)(-b - sqrt_val)/(2*a);
ans.push_back(root1);
ans.push_back(root2);
}
else if(d==0)
{
double root = -(double)b/(2*a);
ans.push_back(root);
ans.push_back(root);
}
else
{
ans.push_back(-1);
}
return ans;
// code here
}
};
// { Driver Code Starts.
int main()
{
int T;
cin >> T;
while (T--)
{
int a, b, c;
cin >> a >> b >> c;
Solution ob;
vector<int> roots = ob.quadraticRoots(a, b, c);
if (roots.size() == 1 && roots[0] == -1)
cout << "Imaginary";
else
for (int i = 0; i < roots.size(); i++)
cout << roots[i] << " ";
cout << endl;
}
return 0;
} // } Driver Code Ends
| 20.878788 | 57 | 0.436865 | [
"vector"
] |
74d10de2e3130eb53c66e39d198e54fbf3bb0cf9 | 1,635 | cpp | C++ | 164/P164/P164/main.cpp | swy20190/Leetcode-Cracker | 3b80eacfa63983d5fcc50442f0813296d5c1af94 | [
"MIT"
] | null | null | null | 164/P164/P164/main.cpp | swy20190/Leetcode-Cracker | 3b80eacfa63983d5fcc50442f0813296d5c1af94 | [
"MIT"
] | null | null | null | 164/P164/P164/main.cpp | swy20190/Leetcode-Cracker | 3b80eacfa63983d5fcc50442f0813296d5c1af94 | [
"MIT"
] | null | null | null | #include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
int maximumGap(vector<int>& nums) {
int len = nums.size();
if (len < 2) {
return 0;
}
int min = INT_MAX;
int max = INT_MIN;
for (int num : nums) {
if (num > max) {
max = num;
}
if (num < min) {
min = num;
}
}
if (max == min) {
return 0;
}
double bucket_size = (max - min)*1.0 / len;
int* bucket_min = new int[len + 1];
int* bucket_max = new int[len + 1];
bool* bucket_empty = new bool[len + 1];
for (int i = 0; i <= len; i++) {
bucket_empty[i] = true;
}
for (int num : nums) {
//int index = 0;
int index = (int)((num - min) / bucket_size);
if (bucket_empty[index]) {
bucket_min[index] = num;
bucket_max[index] = num;
bucket_empty[index] = false;
}
else {
if (num > bucket_max[index]) {
bucket_max[index] = num;
}
if (num < bucket_min[index]) {
bucket_min[index] = num;
}
}
}
int answer = INT_MIN;
int pred = 0;
for (int i = 0; i <= len; i++) {
if (bucket_empty[i]) {
pred = i - 1;
break;
}
}
int curr = pred + 1;
while (curr <= len) {
if (bucket_empty[curr]) {
curr++;
}
else {
int diff = bucket_min[curr] - bucket_max[pred];
if (diff > answer) {
answer = diff;
}
pred = curr;
while (pred <= len) {
if (!bucket_empty[pred]) {
pred++;
}
else {
pred--;
break;
}
}
curr = pred + 1;
}
}
return answer;
}
};
int main() {
Solution solution;
vector<int> nums = { 1, 3, 100};
cout << solution.maximumGap(nums);
} | 17.771739 | 51 | 0.519878 | [
"vector"
] |
74d35234275b2d2841ae622a350003f16eb9877a | 7,260 | hpp | C++ | xpcc/src/xpcc/driver/connectivity/rpr/node.hpp | jrahlf/3D-Non-Contact-Laser-Profilometer | 912eb8890442f897c951594c79a8a594096bc119 | [
"MIT"
] | 5 | 2016-02-06T14:57:35.000Z | 2018-01-02T23:34:18.000Z | xpcc/src/xpcc/driver/connectivity/rpr/node.hpp | jrahlf/3D-Non-Contact-Laser-Profilometer | 912eb8890442f897c951594c79a8a594096bc119 | [
"MIT"
] | null | null | null | xpcc/src/xpcc/driver/connectivity/rpr/node.hpp | jrahlf/3D-Non-Contact-Laser-Profilometer | 912eb8890442f897c951594c79a8a594096bc119 | [
"MIT"
] | 1 | 2020-04-19T13:16:31.000Z | 2020-04-19T13:16:31.000Z | // coding: utf-8
// ----------------------------------------------------------------------------
/* Copyright (c) 2012, Roboterclub Aachen e.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Roboterclub Aachen e.V. 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 ROBOTERCLUB AACHEN E.V. ''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 ROBOTERCLUB AACHEN E.V. 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 XPCC_TOKEN_RING__NODE_HPP
#define XPCC_TOKEN_RING__NODE_HPP
#include <cstddef>
#include <xpcc/architecture/driver/accessor/flash.hpp>
#include <xpcc/workflow/timeout.hpp>
#include <stdint.h>
#include "interface.hpp"
namespace xpcc
{
namespace rpr
{
/**
* \internal
* \brief Interface used to transmit data through a slave object
*
* \ingroup rpr
*/
class Transmitter
{
public:
virtual void
unicastMessage(uint16_t destination,
uint8_t command,
const void *payload,
std::size_t payloadLength) = 0;
virtual void
multicastMessage(uint16_t destination,
uint8_t command,
const void *payload,
std::size_t payloadLength) = 0;
virtual void
broadcastMessage(uint8_t command,
const void *payload,
std::size_t payloadLength) = 0;
};
struct Callable
{
};
/**
* \brief Possible Listener
*
* \see RPR__LISTEN()
* \ingroup rpr
*/
struct Listener
{
typedef void (Callable::*Callback)(Transmitter& node, Message *message);
inline void
call(Transmitter& node, Message *message);
MessageType type;
uint16_t source;
uint8_t command;
Callable *object;
Callback function; //!< Method callActionback
};
/**
* \brief Possible Error
*
* \see RPR__ERROR()
* \ingroup rpr
*/
struct Error
{
typedef void (Callable::*Callback)(Transmitter& node, ErrorMessage *error);
inline void
call(Transmitter& node, ErrorMessage *error);
uint8_t command; //!< Command of message
Callable *object;
Callback function; //!< Method callActionback
};
/**
* \brief Token Ring Node
*
* \author Niklas Hauser
* \ingroup rpr
*/
template <typename Interface>
class Node : protected Transmitter
{
public:
/**
* \brief Initialize the node
*
* \param listenList List of all listener callbacks, need to be
* stored in flash-memory
* \param listenCount Number of entries in \a listenList
* \param errorHandlerList List of all error handler callbacks,
* need to be stored in flash-memory
* \param errorHandlerCount Number of entries in \a errorHandlerList
*
* \see RPR__LISTEN()
* \see RPR__ERROR()
*/
Node(xpcc::accessor::Flash<Listener> listenerCallbackList,
uint8_t listenerCallbackCount,
xpcc::accessor::Flash<Error> errorCallbackList,
uint8_t errorCallbackCount);
/**
* \brief Initialize the node without error handlers
*/
Node(xpcc::accessor::Flash<Listener> listenerCallbackList,
uint8_t listenerCallbackCount);
inline void
setAddress(uint16_t address, uint16_t groupAddress=0x7fff);
/**
* \brief Send a message to one node
*
* \param destination 14bit destination address
* \param command
* \param payload
* \param payloadLength
* \return \c true if no error occurred
*/
void
unicastMessage(uint16_t destination,
uint8_t command,
const void *payload,
std::size_t payloadLength);
void
multicastMessage(uint16_t destination,
uint8_t command,
const void *payload,
std::size_t payloadLength);
/**
* \brief Start a new broadcast with a payload
*
* \param command
* \param payload
* \param payloadLength
* \return \c true if no error occurred
*/
void
broadcastMessage(uint8_t command,
const void *payload,
std::size_t payloadLength);
/**
* \brief Receive and process messages
*
* This method will decode the incoming messages and call the
* corresponding callback methods from the listener list. It must
* be called periodically, best in every main loop cycle.
*/
void
update();
protected:
bool
checkErrorCallbacks(ErrorMessage *errorMessage);
bool
checkListenerCallbacks(Message *message);
xpcc::accessor::Flash<Listener> listenerCallbackList;
uint8_t listenerCallbackCount;
xpcc::accessor::Flash<Error> errorCallbackList;
uint8_t errorCallbackCount;
};
}
}
#ifdef __DOXYGEN__
/**
* \brief Define a Listener
*
* \param type Type of message (uni-, multi-, broadcast, funtional or any)
* \param source address of transmitter, use 0xffff for any
* \param command Command byte, use 0xff for any
* \param object object of class to be called
* \param function Member function of object
*
* \see xpcc::rpr::Listener
* \ingroup rpr
*/
#define RPR__LISTEN(type, source, command, object, function)
#else
#define RPR__LISTEN(type, source, command, object, function) \
{ type, \
source, \
command, \
static_cast<xpcc::rpr::Callable *>(&object), \
reinterpret_cast<xpcc::rpr::Listener::Callback>(&function) }
#endif // __DOXYGEN__
#ifdef __DOXYGEN__
/**
* \brief Define a ErrorHandler
*
* \param address Node address of message
* \param command Command of message
* \param object
* \param function Member function of object
*
* \see xpcc::rpr::ErrorHandler
* \ingroup rpr
*/
#define RPR__ERROR(address, command, object, function)
#else
#define RPR__ERROR(address, command, object, function) \
{ address, \
command, \
static_cast<xpcc::rpr::Callable *>(&object), \
reinterpret_cast<xpcc::rpr::ErrorHandler::Callback>(&function) }
#endif // __DOXYGEN__
#include "node_impl.hpp"
#endif // XPCC_TOKEN_RING__NODE_HPP
| 28.030888 | 79 | 0.664601 | [
"object"
] |
74d3c12e3d281a7511a36f96028d69a3178d25ef | 4,194 | cpp | C++ | aws-cpp-sdk-ds/source/model/DomainController.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-ds/source/model/DomainController.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-ds/source/model/DomainController.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/ds/model/DomainController.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace DirectoryService
{
namespace Model
{
DomainController::DomainController() :
m_directoryIdHasBeenSet(false),
m_domainControllerIdHasBeenSet(false),
m_dnsIpAddrHasBeenSet(false),
m_vpcIdHasBeenSet(false),
m_subnetIdHasBeenSet(false),
m_availabilityZoneHasBeenSet(false),
m_status(DomainControllerStatus::NOT_SET),
m_statusHasBeenSet(false),
m_statusReasonHasBeenSet(false),
m_launchTimeHasBeenSet(false),
m_statusLastUpdatedDateTimeHasBeenSet(false)
{
}
DomainController::DomainController(JsonView jsonValue) :
m_directoryIdHasBeenSet(false),
m_domainControllerIdHasBeenSet(false),
m_dnsIpAddrHasBeenSet(false),
m_vpcIdHasBeenSet(false),
m_subnetIdHasBeenSet(false),
m_availabilityZoneHasBeenSet(false),
m_status(DomainControllerStatus::NOT_SET),
m_statusHasBeenSet(false),
m_statusReasonHasBeenSet(false),
m_launchTimeHasBeenSet(false),
m_statusLastUpdatedDateTimeHasBeenSet(false)
{
*this = jsonValue;
}
DomainController& DomainController::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("DirectoryId"))
{
m_directoryId = jsonValue.GetString("DirectoryId");
m_directoryIdHasBeenSet = true;
}
if(jsonValue.ValueExists("DomainControllerId"))
{
m_domainControllerId = jsonValue.GetString("DomainControllerId");
m_domainControllerIdHasBeenSet = true;
}
if(jsonValue.ValueExists("DnsIpAddr"))
{
m_dnsIpAddr = jsonValue.GetString("DnsIpAddr");
m_dnsIpAddrHasBeenSet = true;
}
if(jsonValue.ValueExists("VpcId"))
{
m_vpcId = jsonValue.GetString("VpcId");
m_vpcIdHasBeenSet = true;
}
if(jsonValue.ValueExists("SubnetId"))
{
m_subnetId = jsonValue.GetString("SubnetId");
m_subnetIdHasBeenSet = true;
}
if(jsonValue.ValueExists("AvailabilityZone"))
{
m_availabilityZone = jsonValue.GetString("AvailabilityZone");
m_availabilityZoneHasBeenSet = true;
}
if(jsonValue.ValueExists("Status"))
{
m_status = DomainControllerStatusMapper::GetDomainControllerStatusForName(jsonValue.GetString("Status"));
m_statusHasBeenSet = true;
}
if(jsonValue.ValueExists("StatusReason"))
{
m_statusReason = jsonValue.GetString("StatusReason");
m_statusReasonHasBeenSet = true;
}
if(jsonValue.ValueExists("LaunchTime"))
{
m_launchTime = jsonValue.GetDouble("LaunchTime");
m_launchTimeHasBeenSet = true;
}
if(jsonValue.ValueExists("StatusLastUpdatedDateTime"))
{
m_statusLastUpdatedDateTime = jsonValue.GetDouble("StatusLastUpdatedDateTime");
m_statusLastUpdatedDateTimeHasBeenSet = true;
}
return *this;
}
JsonValue DomainController::Jsonize() const
{
JsonValue payload;
if(m_directoryIdHasBeenSet)
{
payload.WithString("DirectoryId", m_directoryId);
}
if(m_domainControllerIdHasBeenSet)
{
payload.WithString("DomainControllerId", m_domainControllerId);
}
if(m_dnsIpAddrHasBeenSet)
{
payload.WithString("DnsIpAddr", m_dnsIpAddr);
}
if(m_vpcIdHasBeenSet)
{
payload.WithString("VpcId", m_vpcId);
}
if(m_subnetIdHasBeenSet)
{
payload.WithString("SubnetId", m_subnetId);
}
if(m_availabilityZoneHasBeenSet)
{
payload.WithString("AvailabilityZone", m_availabilityZone);
}
if(m_statusHasBeenSet)
{
payload.WithString("Status", DomainControllerStatusMapper::GetNameForDomainControllerStatus(m_status));
}
if(m_statusReasonHasBeenSet)
{
payload.WithString("StatusReason", m_statusReason);
}
if(m_launchTimeHasBeenSet)
{
payload.WithDouble("LaunchTime", m_launchTime.SecondsWithMSPrecision());
}
if(m_statusLastUpdatedDateTimeHasBeenSet)
{
payload.WithDouble("StatusLastUpdatedDateTime", m_statusLastUpdatedDateTime.SecondsWithMSPrecision());
}
return payload;
}
} // namespace Model
} // namespace DirectoryService
} // namespace Aws
| 21.618557 | 109 | 0.742251 | [
"model"
] |
74da45d68f699a053333f9c466eb521ad053c409 | 39,637 | cpp | C++ | src/imaging/ossimTopographicCorrectionFilter.cpp | vladislav-horbatiuk/ossim | 82417ad868fac022672335e1684bdd91d662c18c | [
"MIT"
] | 251 | 2015-10-20T09:08:11.000Z | 2022-03-22T18:16:38.000Z | src/imaging/ossimTopographicCorrectionFilter.cpp | vladislav-horbatiuk/ossim | 82417ad868fac022672335e1684bdd91d662c18c | [
"MIT"
] | 73 | 2015-11-02T17:12:36.000Z | 2021-11-15T17:41:47.000Z | src/imaging/ossimTopographicCorrectionFilter.cpp | vladislav-horbatiuk/ossim | 82417ad868fac022672335e1684bdd91d662c18c | [
"MIT"
] | 146 | 2015-10-15T16:00:15.000Z | 2022-03-22T12:37:14.000Z | //*******************************************************************
// Copyright (C) 2000 ImageLinks Inc.
//
// License: LGPL
//
// See LICENSE.txt file in the top level directory for more details.
//
// Author: Garrett Potts
//
//*************************************************************************
// $Id: ossimTopographicCorrectionFilter.cpp 21184 2012-06-29 15:13:09Z dburken $
#include <algorithm>
#include <sstream>
#include <ossim/imaging/ossimTopographicCorrectionFilter.h>
#include <ossim/imaging/ossimImageToPlaneNormalFilter.h>
#include <ossim/imaging/ossimScalarRemapper.h>
#include <ossim/imaging/ossimScalarRemapper.h>
#include <ossim/imaging/ossimImageDataFactory.h>
#include <ossim/matrix/newmat.h>
#include <ossim/base/ossimMatrix3x3.h>
#include <ossim/base/ossimNotifyContext.h>
#include <ossim/base/ossimKeywordNames.h>
using namespace std;
static const char* CORRECTION_TYPE_KW = "correction_type";
static const char* C_COMPUTED_FLAG_KW = "c_computed_flag";
static const char* NDVI_RANGE_KW = "ndvi_range";
RTTI_DEF1(ossimTopographicCorrectionFilter, "ossimTopographicCorrectionFilter", ossimImageCombiner);
ossimTopographicCorrectionFilter::ossimTopographicCorrectionFilter()
:ossimImageCombiner(NULL, 2, 0, true, false),
theTile(NULL),
// theScalarRemapper(NULL),
theLightSourceElevationAngle(45.0),
theLightSourceAzimuthAngle(45.0),
theJulianDay(0),
theCComputedFlag(false),
theTopoCorrectionType(TOPO_CORRECTION_COSINE),
// theTopoCorrectionType(TOPO_CORRECTION_MINNAERT),
theNdviLowTest(-0.1),
theNdviHighTest(0.1)
{
// theScalarRemapper = new ossimScalarRemapper();
// theScalarRemapper->setOutputScalarType(OSSIM_NORMALIZED_DOUBLE);
// theScalarRemapper->initialize();
}
ossimTopographicCorrectionFilter::ossimTopographicCorrectionFilter(ossimImageSource* colorSource,
ossimImageSource* elevSource)
:ossimImageCombiner(NULL, 2, 0, true, false),
theTile(NULL),
theLightSourceElevationAngle(45.0),
theLightSourceAzimuthAngle(45.0),
theJulianDay(0),
theCComputedFlag(false),
theTopoCorrectionType(TOPO_CORRECTION_COSINE),
theNdviLowTest(-0.1),
theNdviHighTest(0.1)
{
connectMyInputTo(colorSource);
connectMyInputTo(elevSource);
}
ossimTopographicCorrectionFilter::~ossimTopographicCorrectionFilter()
{
}
ossimRefPtr<ossimImageData> ossimTopographicCorrectionFilter::getTile(
const ossimIrect& tileRect,
ossim_uint32 resLevel)
{
ossimImageSource* colorSource = PTR_CAST(ossimImageSource,
getInput(0));
ossimImageSource* normalSource = PTR_CAST(ossimImageSource,
getInput(1));
if(!isSourceEnabled()||!normalSource||!colorSource)
{
if(colorSource)
{
return colorSource->getTile(tileRect, resLevel);
}
}
if(!theTile.valid())
{
allocate();
}
if(!theTile)
{
return ossimRefPtr<ossimImageData>();
}
long w = tileRect.width();
long h = tileRect.height();
ossimIpt origin = tileRect.ul();
theTile->setOrigin(origin);
long tileW = theTile->getWidth();
long tileH = theTile->getHeight();
if((w != tileW)||
(h != tileH))
{
theTile->setWidth(w);
theTile->setHeight(h);
if((w*h)!=(tileW*tileH))
{
theTile->initialize();
}
else
{
theTile->makeBlank();
}
}
else
{
theTile->makeBlank();
}
// ossimImageData* inputTile = NULL;
ossimRefPtr<ossimImageData> normalData = normalSource->getTile(tileRect,
resLevel);
ossimRefPtr<ossimImageData> colorData = colorSource->getTile(tileRect,
resLevel);
if(!colorData.valid() || !normalData.valid())
{
return theTile;
}
if((normalData->getNumberOfBands() != 3)||
(normalData->getScalarType() != OSSIM_DOUBLE)||
!normalData->getBuf()||
!colorData->getBuf()||
(colorData->getDataObjectStatus() == OSSIM_EMPTY)||
(normalData->getDataObjectStatus()==OSSIM_EMPTY))
{
return colorData;
}
executeTopographicCorrection(theTile,
colorData,
normalData);
theTile->validate();
return theTile;
}
void ossimTopographicCorrectionFilter::initialize()
{
ossimImageCombiner::initialize();
// Force an "allocate()" on the first getTile.
theTile = NULL;
}
void ossimTopographicCorrectionFilter::allocate()
{
if(!getInput(0) || !getInput(1)) return;
theBandMapping.clear();
if(isSourceEnabled())
{
// ossimImageSource* colorSource = PTR_CAST(ossimImageSource, getInput(0));
theTile = ossimImageDataFactory::instance()->create(this, this);
theTile->initialize();
int arraySize = theTile->getNumberOfBands();
if(theGain.size() > 0)
{
arraySize = (int)theGain.size();
}
// we will do a non destructive resize onf the arrays
//
resizeArrays(arraySize);
ossimImageSource* input1 = PTR_CAST(ossimImageSource,
getInput(0));
if(input1)
{
input1->getOutputBandList(theBandMapping);
for(ossim_uint32 idx = 0; idx < theBandMapping.size(); ++idx)
{
if(theBias.size())
{
if(theBandMapping[idx] >= theBias.size())
{
theBandMapping[idx] = (unsigned int)theBias.size()-1;
}
}
else
{
theBandMapping[idx] = 0;
}
}
}
}
computeLightDirection();
}
void ossimTopographicCorrectionFilter::computeLightDirection()
{
NEWMAT::Matrix m = ossimMatrix3x3::createRotationMatrix(theLightSourceElevationAngle,
0.0,
theLightSourceAzimuthAngle);
NEWMAT::ColumnVector v(3);
v[0] = 0;
v[1] = 1;
v[2] = 0;
v = m*v;
// reflect Z. We need the Z pointing up from the surface and not into it.
//
ossimColumnVector3d d(v[0], v[1], -v[2]);
d = d.unit();
theLightDirection[0] = d[0];
theLightDirection[1] = d[1];
theLightDirection[2] = d[2];
}
void ossimTopographicCorrectionFilter::executeTopographicCorrection(
ossimRefPtr<ossimImageData>& outputData,
ossimRefPtr<ossimImageData>& colorData,
ossimRefPtr<ossimImageData>& normalData)
{
switch(colorData->getScalarType())
{
case OSSIM_UCHAR:
{
if(theTopoCorrectionType!=TOPO_CORRECTION_MINNAERT)
{
executeTopographicCorrectionTemplate((ossim_uint8)0,
outputData,
colorData,
normalData);
}
else
{
executeTopographicCorrectionMinnaertTemplate((ossim_uint8)0,
outputData,
colorData,
normalData);
}
break;
}
case OSSIM_USHORT11:
case OSSIM_USHORT12:
case OSSIM_USHORT13:
case OSSIM_USHORT14:
case OSSIM_USHORT15:
case OSSIM_USHORT16:
{
if(theTopoCorrectionType!=TOPO_CORRECTION_MINNAERT)
{
executeTopographicCorrectionTemplate((ossim_uint16)0,
outputData,
colorData,
normalData);
}
else
{
executeTopographicCorrectionMinnaertTemplate((ossim_uint16)0,
outputData,
colorData,
normalData);
}
break;
}
case OSSIM_SSHORT16:
{
if(theTopoCorrectionType!=TOPO_CORRECTION_MINNAERT)
{
executeTopographicCorrectionTemplate((ossim_sint16)0,
outputData,
colorData,
normalData);
}
else
{
executeTopographicCorrectionMinnaertTemplate((ossim_sint16)0,
outputData,
colorData,
normalData);
}
break;
}
case OSSIM_DOUBLE:
case OSSIM_NORMALIZED_DOUBLE:
{
if(theTopoCorrectionType!=TOPO_CORRECTION_MINNAERT)
{
executeTopographicCorrectionTemplate((ossim_float64)0,
outputData,
colorData,
normalData);
}
else
{
executeTopographicCorrectionMinnaertTemplate((ossim_float64)0,
outputData,
colorData,
normalData);
}
break;
}
case OSSIM_FLOAT:
case OSSIM_NORMALIZED_FLOAT:
{
if(theTopoCorrectionType!=TOPO_CORRECTION_MINNAERT)
{
executeTopographicCorrectionTemplate((ossim_float32)0,
outputData,
colorData,
normalData);
}
else
{
executeTopographicCorrectionMinnaertTemplate((ossim_float32)0,
outputData,
colorData,
normalData);
}
break;
}
default:
{
ossimNotify(ossimNotifyLevel_WARN)
<< "ossimTopographicCorrectionFilter::executeTopographicCorrection WARN: Not handling scalar type"
<< endl;
}
}
}
template <class T>
void ossimTopographicCorrectionFilter::executeTopographicCorrectionTemplate(
T /* dummy */,
ossimRefPtr<ossimImageData>& outputData,
ossimRefPtr<ossimImageData>& colorData,
ossimRefPtr<ossimImageData>& normalData)
{
ossim_int32 y = 0;
ossim_int32 x = 0;
ossim_int32 colorW = colorData->getWidth();
ossim_int32 colorH = colorData->getHeight();
T* colorDataBand = 0;
T* outputDataBand = 0;
ossim_float64 colorNp = 0;
ossim_float64 colorMin = 0;
ossim_float64 colorMax = 0;
// ossim_float64 outputDelta = 0;;
// ossim_float64 outputMin = 0;
// ossim_float64 outputMax = 0;
ossim_float64 outputNp;
double normalNp = normalData->getNullPix(0);
double LPrime = 0.0;
double LNew = 0.0;
double dn = 0.0;
double cosineZenith = ossim::cosd(90 - theLightSourceElevationAngle);
if(!colorData->getBuf()||
!normalData->getBuf()||
(colorData->getDataObjectStatus() == OSSIM_EMPTY))
{
return;
}
for(ossim_uint32 b = 0; b < outputData->getNumberOfBands();++b)
{
int mappedBand = theBandMapping[b];
double* normalX = (double*)normalData->getBuf(0);
double* normalY = (double*)normalData->getBuf(1);
double* normalZ = (double*)normalData->getBuf(2);
double numerator = cosineZenith + theC[mappedBand];
outputNp = (ossim_float64)outputData->getNullPix(b);
// outputMin = (ossim_float64)outputData->getMinPix(b);
// outputMax = (ossim_float64)outputData->getMaxPix(b);
// outputDelta = outputMax - outputMin;
colorDataBand = (T*)(colorData->getBuf(b));
colorNp = (ossim_float64)(colorData->getNullPix(b));
colorMin = (ossim_float64)(colorData->getMinPix(b));
colorMax = (ossim_float64)(colorData->getMaxPix(b));
outputDataBand = (T*)(outputData->getBuf(b));
bool theValuesAreGood = b < theC.size();
double c = theC[mappedBand];
if(theTopoCorrectionType != TOPO_CORRECTION_COSINE_C)
{
c = 0;
}
for(y = 0; y < colorH; ++y)
{
for(x = 0; x < colorW; ++x)
{
if((*colorDataBand) != colorNp)
{
if((*normalX != normalNp)&&
(*normalY != normalNp)&&
(*normalZ != normalNp)&&
theValuesAreGood)
{
double cosineNewI = ((*normalX)*theLightDirection[0] +
(*normalY)*theLightDirection[1] +
(*normalZ)*theLightDirection[2]);
double cosineRatioDenom = (cosineNewI + c);
if((fabs(cosineRatioDenom) > FLT_EPSILON)&&(cosineNewI >= 0.0))
{
double cosineRatio = numerator/cosineRatioDenom;
LPrime = theGain[mappedBand]*((ossim_float64)(*colorDataBand)) + theBias[mappedBand];
LNew = LPrime*cosineRatio;
dn = ((LNew-theBias[mappedBand])/theGain[mappedBand]);
if(dn < colorMin) dn = colorMin;
if(dn > colorMax) dn = colorMax;
*outputDataBand = (T)(dn);
}
else
{
*outputDataBand = (T)(*colorDataBand);
}
}
else
{
*outputDataBand = (T)(*colorDataBand);
}
}
else
{
*outputDataBand = (T)outputNp;
}
++outputDataBand;
++colorDataBand;
++normalX;
++normalY;
++normalZ;
}
}
}
}
template <class T>
void ossimTopographicCorrectionFilter::executeTopographicCorrectionMinnaertTemplate(
T /* dummy */,
ossimRefPtr<ossimImageData>& outputData,
ossimRefPtr<ossimImageData>& colorData,
ossimRefPtr<ossimImageData>& normalData)
{
ossim_int32 y = 0;
ossim_int32 x = 0;
ossim_int32 colorW = colorData->getWidth();
ossim_int32 colorH = colorData->getHeight();
T* colorDataBand = 0;
T* outputDataBand = 0;
ossim_float64 colorNp = 0;
ossim_float64 colorMin = 0;
ossim_float64 colorMax = 0;
// ossim_float64 outputDelta = 0;;
// ossim_float64 outputMin = 0;
// ossim_float64 outputMax = 0;
ossim_float64 outputNp;
double normalNp = normalData->getNullPix(0);
double LPrime = 0.0;
double LNew = 0.0;
double dn = 0.0;
if(!colorData->getBuf()||
!normalData->getBuf()||
(colorData->getDataObjectStatus() == OSSIM_EMPTY))
{
return;
}
int maxBands = ossim::min((int)theK.size(), (int)outputData->getNumberOfBands());
for(int b = 0; b < maxBands;++b)
{
int mappedBand = theBandMapping[b];
double* normalX = (double*)normalData->getBuf(0);
double* normalY = (double*)normalData->getBuf(1);
double* normalZ = (double*)normalData->getBuf(2);
outputNp = (ossim_float64)outputData->getNullPix(b);
// outputMin = (ossim_float64)outputData->getMinPix(b);
// outputMax = (ossim_float64)outputData->getMaxPix(b);
// outputDelta = outputMax - outputMin;
colorDataBand = (T*)(colorData->getBuf(b));
colorNp = (ossim_float64)(colorData->getNullPix(b));
colorMin = (ossim_float64)(colorData->getMinPix(b));
colorMax = (ossim_float64)(colorData->getMaxPix(b));
outputDataBand = (T*)(outputData->getBuf(b));
for(y = 0; y < colorH; ++y)
{
for(x = 0; x < colorW; ++x)
{
if((*colorDataBand) != colorNp)
{
if((*normalX != normalNp)&&
(*normalY != normalNp)&&
(*normalZ != normalNp))
{
// if(fabs(*normalZ) < FLT_EPSILON)
// {
// *normalZ = 0.0;
// }
double cosineNewI = (((*normalX)*theLightDirection[0] +
(*normalY)*theLightDirection[1] +
(*normalZ)*theLightDirection[2]));
double slopeAngle = acos(*normalZ);
double cosineSlope = cos(slopeAngle);
double k = theK[mappedBand];
double cosineSlopeKPower = pow(cosineSlope, k);
double denom = pow((double)cosineNewI, k)*cosineSlopeKPower;
double numerator = cosineSlope;
// double slopeAngle = asin(*normalZ);
// double tempK = theK[mappedBand]*cosineNewI;
// double denom = pow((double)cosineNewI*cosineSlope, theK[mappedBand]);
// double numerator = pow((double)cosineSlope, 1-tempK);
// if((fabs(denom) > .0001)&&(cosineNewI >= 0.0))
// if((cosineNewI >= 0.0) &&fabs(denom) > .000001)
if(fabs(denom) > .00000001)
{
// double cosineRatio = cosineSlope/denom;
double cosineRatio = numerator/denom;
LPrime = theGain[mappedBand]*((ossim_float64)(*colorDataBand)) + theBias[mappedBand];
LNew = LPrime*cosineRatio;
dn = ((LNew-theBias[mappedBand])/theGain[mappedBand]);
if(dn < colorMin) dn = colorMin;
if(dn > colorMax) dn = colorMax;
*outputDataBand = (T)(dn);
}
else
{
*outputDataBand = (T)(*colorDataBand);
}
}
else
{
*outputDataBand = (T)(*colorDataBand);
}
}
else
{
*outputDataBand = (T)outputNp;
}
++outputDataBand;
++colorDataBand;
++normalX;
++normalY;
++normalZ;
}
}
}
}
#if 0
void ossimTopographicCorrectionFilter::computeC()
{
theCComputedFlag = false;
int b = 0;
int tileCount = 0;
bool done = false;
if(theC.size()<1) return;
for(b = 0; b < (int) theC.size(); ++b)
{
theC[b] = 0.0;
}
theNdviLowTest = 0.1;
theNdviHighTest = 1;
ossimImageSource* colorSource = PTR_CAST(ossimImageSource, getInput(0));
ossimImageSource* normalSource = PTR_CAST(ossimImageSource, getInput(1));
if(!colorSource || !normalSource)
{
return;
}
std::vector<ossim2dLinearRegression> linearRegression(theC.size());
ossimIrect normalRect = normalSource->getBoundingRect();
ossimIrect colorRect = colorSource->getBoundingRect();
ossimIrect clipRect = normalRect.clipToRect(colorRect);
ossimIpt ul = clipRect.ul();
ossimIpt lr = clipRect.lr();
ossimIpt tileSize(128,128);
ossim_int32 tilesHoriz = clipRect.width()/tileSize.x;
ossim_int32 tilesVert = clipRect.height()/tileSize.y;
if(!normalRect.intersects(colorRect))
{
return;
}
ossim_int32 maxSize = tilesHoriz*tilesVert;//ossim::min(200, );
int idx = 0;
idx = 0;
std::vector<int> cosineIBucketCount(10);
std::fill(cosineIBucketCount.begin(), cosineIBucketCount.end(), 0);
const int maxBucketCount = 1000;
bool goodCoefficients = false;
long numberOfRuns = 0;
while((!goodCoefficients)&&(numberOfRuns < 2))
{
while((idx < maxSize)&&
(!done))
{
ossim_int32 ty = idx/tilesHoriz;
ossim_int32 tx = idx%tilesHoriz;
ossim_int32 x = (ul.x + tx*tileSize.x);
ossim_int32 y = (ul.y + ty*tileSize.y);
ossimIrect requestRect(x,
y,
x+tileSize.x-1,
y+tileSize.y-1);
ossimRefPtr<ossimImageData> colorData = colorSource->getTile(requestRect);
ossimRefPtr<ossimImageData> normalData = normalSource->getTile(requestRect);
switch(colorData->getScalarType())
{
case OSSIM_UCHAR:
{
addRegressionPointsTemplate((ossim_uint8)0,
linearRegression, cosineIBucketCount, maxBucketCount, colorData, normalData);
break;
}
case OSSIM_USHORT11:
case OSSIM_USHORT12:
case OSSIM_USHORT13:
case OSSIM_USHORT14:
case OSSIM_USHORT15:
case OSSIM_USHORT16:
{
addRegressionPointsTemplate((ossim_uint16)0,
linearRegression, cosineIBucketCount, maxBucketCount, colorData, normalData);
break;
}
case OSSIM_SSHORT16:
{
addRegressionPointsTemplate((ossim_sint16)0,
linearRegression, cosineIBucketCount, maxBucketCount, colorData, normalData);
break;
}
case OSSIM_FLOAT:
case OSSIM_NORMALIZED_FLOAT:
{
addRegressionPointsTemplate((ossim_float32)0,
linearRegression, cosineIBucketCount, maxBucketCount, colorData, normalData);
break;
}
case OSSIM_DOUBLE:
case OSSIM_NORMALIZED_DOUBLE:
{
addRegressionPointsTemplate((ossim_float64)0,
linearRegression, cosineIBucketCount, maxBucketCount, colorData, normalData);
break;
}
}
if(((double)linearRegression[0].getNumberOfPoints()/(double)(maxBucketCount*10.0))>=.7)
{
done = true;
}
++idx;
}
double intercept, m;
long numberOfPositiveSlopes=0;
for(b=0;b<theC.size();++b)
{
if(linearRegression[b].getNumberOfPoints()>2)
{
linearRegression[b].solve();
linearRegression[b].getEquation(m, intercept);
theC[b] = intercept/m;
ossimNotify(ossimNotifyLevel_INFO) << "equation for b = " << b <<" is y = " << m << "*x + " << intercept << endl
<< "with c = " << theC[b] << endl;
if(m >=0.0)
{
numberOfPositiveSlopes++;
}
}
}
for(idx = 0; idx < cosineIBucketCount.size(); ++idx)
{
ossimNotify(ossimNotifyLevel_INFO) << "bucket " << idx << " = " << cosineIBucketCount[idx] << endl;
}
if(numberOfPositiveSlopes > .5*theC.size())
{
goodCoefficients = true;
}
else
{
ossimNotify(ossimNotifyLevel_WARN) << "ossimTopographicCorrectionFilter::computeC() WARN: not enough positive slopes" << endl
<< "changing test to look for dirt areas" << endl;
theNdviLowTest = -1.0;
theNdviHighTest = .1;
for(b=0;b<theC.size();++b)
{
linearRegression[b].clear();
}
}
++numberOfRuns;
}
theCComputedFlag = true;
}
template<class T>
void ossimTopographicCorrectionFilter::addRegressionPointsTemplate(
T, //dummy
std::vector<ossim2dLinearRegression>& regressionPoints,
std::vector<int>& cosineIBucketCount,
ossim_int32 maxCountPerBucket,
ossimRefPtr<ossimImageData>& colorData,
ossimRefPtr<ossimImageData>& normalData)
{
if(!colorData||!normalData)
{
return;
}
if((colorData->getDataObjectStatus() == OSSIM_EMPTY)||
(!colorData->getBuf())||
(!normalData->getBuf())||
(normalData->getDataObjectStatus()==OSSIM_EMPTY))
{
return;
}
ossim_float64* normalBands[3];
ossim_float64 normalBandsNp[3];
ossim_uint32 count=0;
ossim_uint32 b = 0;
std::vector<T*> colorBands(colorData->getNumberOfBands());
std::vector<T> colorBandsNp(colorData->getNumberOfBands());
normalBands[0] = (ossim_float64*)normalData->getBuf(0);
normalBands[1] = (ossim_float64*)normalData->getBuf(1);
normalBands[2] = (ossim_float64*)normalData->getBuf(2);
normalBandsNp[0] = normalData->getNullPix(0);
normalBandsNp[1] = normalData->getNullPix(1);
normalBandsNp[2] = normalData->getNullPix(2);
for(b=0;b<colorData->getNumberOfBands();++b)
{
colorBands[b] = (T*)colorData->getBuf(b);
colorBandsNp[b] = (T)colorData->getNullPix(b);
}
ossim_uint32 maxOffset = colorData->getWidth()*colorData->getHeight();
ossim_uint32 offset=0;
ossim_float64 ndviTest=0.0;
ossim_uint32 numberOfTests = 0;
if(maxOffset)
{
maxOffset-=1;
}
ossim_int32 percent = (ossim_int32)(colorData->getWidth()*colorData->getHeight()*.2);
offset = 0;
ossim_uint32 countPixels = 0;
while(offset < maxOffset)
{
bool nullBandsExist = false;
for(b = 0; ((b < colorData->getNumberOfBands())&&(!nullBandsExist));++b)
{
if(*colorBands[b] == colorBandsNp[b])
{
nullBandsExist = true;
}
}
if((!nullBandsExist)&&
(*normalBands[0] != normalBandsNp[0])&&
(*normalBands[1] != normalBandsNp[1])&&
(*normalBands[2] != normalBandsNp[2]))
{
if(computeNdvi((T)0,
ndviTest,
offset,
colorBands))
{
if((ndviTest >= theNdviLowTest) && (ndviTest <= theNdviHighTest))
{
double cosineI = ((*(normalBands[0]+offset))*theLightDirection[0] +
(*(normalBands[1]+offset))*theLightDirection[1] +
(*(normalBands[2]+offset))*theLightDirection[2]);
if(cosineI >= 0.0)
{
long bucketIdx = (long)(cosineI*cosineIBucketCount.size());
// we will try to disperse the normals out and so we don't clump everything
// in one place
//
if(cosineIBucketCount[bucketIdx] < maxCountPerBucket)
{
for(b = 0; b < colorData->getNumberOfBands();++b)
{
regressionPoints[b].addPoint(ossimDpt(cosineI, *(colorBands[b]+offset)));
}
++cosineIBucketCount[bucketIdx];
++count;
}
}
}
}
}
++offset;
}
}
#endif
template <class T> bool ossimTopographicCorrectionFilter::computeNdvi(
T,
ossim_float64& result,
ossim_uint32 offset,
const std::vector<T*>& bands)const
{
if(bands.size() > 3)
{
result = (((double)*(bands[3]+offset) - (double)*(bands[2]+offset))/
((double)*(bands[3]+offset) + (double)*(bands[2]+offset)));
return true;
}
return false;
}
void ossimTopographicCorrectionFilter::resizeArrays(ossim_uint32 newSize)
{
if(!getInput(0) || !getInput(1)) return;
vector<double> tempC = theC;
vector<double> tempK = theK;
vector<double> tempBias = theBias;
vector<double> tempGain = theGain;
theC.resize(newSize);
theK.resize(newSize);
theBias.resize(newSize);
theGain.resize(newSize);
ossim_uint32 tempIdx = 0;
if(tempC.size() > 0 && (theC.size() > 0))
{
int numberOfElements = ossim::min((int)tempC.size(),(int)theC.size());
std::copy(tempC.begin(), tempC.begin()+numberOfElements,
theC.begin());
std::copy(tempK.begin(), tempK.begin()+numberOfElements,
theK.begin());
std::copy(tempBias.begin(), tempBias.begin()+numberOfElements,
theBias.begin());
std::copy(tempGain.begin(), tempGain.begin()+numberOfElements,
theGain.begin());
if(theC.size() > tempC.size())
{
std::fill(theC.begin()+numberOfElements, theC.end(), (double)0.0);
std::fill(theBias.begin()+numberOfElements, theBias.end(), (double)0.0);
std::fill(theGain.begin()+numberOfElements, theGain.end(), (double)1.0);
for(tempIdx = numberOfElements; tempIdx < theK.size(); ++tempIdx)
{
theK[tempIdx] = 0.3 + .4*(tempIdx/(double)(theK.size()));
}
}
}
else
{
std::fill(theC.begin(), theC.end(), (double)0.0);
std::fill(theBias.begin(), theBias.end(), (double)0.0);
std::fill(theGain.begin(), theGain.end(), (double)1.0);
for(tempIdx = 0; tempIdx < theK.size(); ++tempIdx)
{
theK[tempIdx] = 0.3 + .4*(tempIdx/(double)(theK.size()));
}
}
}
bool ossimTopographicCorrectionFilter::loadState(const ossimKeywordlist& kwl,
const char* prefix)
{
ossimString elevAngle = kwl.find(prefix, ossimKeywordNames::ELEVATION_ANGLE_KW);
ossimString azimuthAngle = kwl.find(prefix, ossimKeywordNames::AZIMUTH_ANGLE_KW);
ossimString bands = kwl.find(prefix, ossimKeywordNames::NUMBER_BANDS_KW);
ossimString correctionType = kwl.find(prefix, CORRECTION_TYPE_KW);
ossimString julianDay = kwl.find(prefix, ossimKeywordNames::JULIAN_DAY_KW);
ossimString cComputedFlag = kwl.find(prefix, C_COMPUTED_FLAG_KW);
ossimString ndviRange = kwl.find(prefix, NDVI_RANGE_KW);
theCComputedFlag = cComputedFlag.toBool();
correctionType = correctionType.downcase();
int numberOfBands = bands.toInt();
theLightSourceElevationAngle = elevAngle.toDouble();
theLightSourceAzimuthAngle = azimuthAngle.toDouble();
theJulianDay = julianDay.toDouble();
if(ndviRange != "")
{
std::istringstream input(ndviRange.c_str());
input >> theNdviLowTest >> theNdviHighTest;
}
if(numberOfBands>0)
{
theGain.resize(numberOfBands);
theBias.resize(numberOfBands);
theC.resize(numberOfBands);
theK.resize(numberOfBands);
for(int b = 0; b < numberOfBands; ++b)
{
ossimString k = "k"+ossimString::toString(b);
ossimString c = "c"+ossimString::toString(b);
ossimString bias = "bias"+ossimString::toString(b);
ossimString gain = "gain"+ossimString::toString(b);
const char* kValue = kwl.find(prefix, k);
const char* cValue = kwl.find(prefix, c);
const char* biasValue = kwl.find(prefix, bias);
const char* gainValue = kwl.find(prefix, gain);
if(kValue)
{
theK[b] = ossimString(kValue).toDouble();
}
else
{
theK[b] = 1.0;
}
if(cValue)
{
theC[b] = ossimString(cValue).toDouble();
}
else
{
theC[b] = 0.0;;
}
if(biasValue)
{
theBias[b] = ossimString(biasValue).toDouble();
}
else
{
theBias[b] = 0.0;
}
if(gainValue)
{
theGain[b] = ossimString(gainValue).toDouble();
}
else
{
theGain[b] = 1.0;
}
}
}
if(correctionType.contains("cosine_c"))
{
theTopoCorrectionType = TOPO_CORRECTION_COSINE_C;
}
else if(correctionType.contains("minnaert"))
{
theTopoCorrectionType = TOPO_CORRECTION_MINNAERT;
}
else
{
theTopoCorrectionType = TOPO_CORRECTION_COSINE;
}
bool result = ossimImageCombiner::loadState(kwl, prefix);
computeLightDirection();
return result;
}
bool ossimTopographicCorrectionFilter::saveState(ossimKeywordlist& kwl,
const char* prefix)const
{
// we can use any of the arrays theC, theBias, or theGain since
// they mirror the number of input bands
//
int numberOfBands = (int)theC.size();
kwl.add(prefix,
ossimKeywordNames::NUMBER_BANDS_KW,
numberOfBands,
true);
kwl.add(prefix,
ossimKeywordNames::ELEVATION_ANGLE_KW,
theLightSourceElevationAngle,
true);
kwl.add(prefix,
ossimKeywordNames::AZIMUTH_ANGLE_KW,
theLightSourceAzimuthAngle,
true);
kwl.add(prefix,
C_COMPUTED_FLAG_KW,
(ossim_uint32)theCComputedFlag,
true);
kwl.add(prefix,
NDVI_RANGE_KW,
ossimString::toString(theNdviLowTest) +
" " + ossimString::toString(theNdviHighTest),
true);
if(theTopoCorrectionType == TOPO_CORRECTION_COSINE_C)
{
kwl.add(prefix,
CORRECTION_TYPE_KW,
"cosine_c",
true);
}
else if(theTopoCorrectionType == TOPO_CORRECTION_MINNAERT)
{
kwl.add(prefix,
CORRECTION_TYPE_KW,
"minnaert",
true);
}
else
{
kwl.add(prefix,
CORRECTION_TYPE_KW,
"cosine",
true);
}
for(int b = 0; b < numberOfBands; ++b)
{
ossimString k = "k"+ossimString::toString(b);
ossimString c = "c"+ossimString::toString(b);
ossimString bias = "bias"+ossimString::toString(b);
ossimString gain = "gain"+ossimString::toString(b);
kwl.add(prefix,
k,
theK[b],
true);
kwl.add(prefix,
c,
theC[b],
true);
kwl.add(prefix,
bias,
theBias[b],
true);
kwl.add(prefix,
gain,
theGain[b],
true);
}
return ossimImageCombiner::saveState(kwl, prefix);
}
ossim_uint32 ossimTopographicCorrectionFilter::getNumberOfOutputBands() const
{
ossimImageSource* colorSource = PTR_CAST(ossimImageSource, getInput(0));
if(colorSource)
{
return colorSource->getNumberOfOutputBands();
}
return ossimImageCombiner::getNumberOfOutputBands();
}
ossimScalarType ossimTopographicCorrectionFilter::getOutputScalarType() const
{
ossimImageSource* colorSource = PTR_CAST(ossimImageSource, getInput(0));
if(colorSource)
{
return colorSource->getOutputScalarType();
}
return ossimImageCombiner::getOutputScalarType();
}
double ossimTopographicCorrectionFilter::getNullPixelValue(ossim_uint32 band)const
{
ossimImageSource* colorSource = PTR_CAST(ossimImageSource, getInput(0));
if(colorSource)
{
return colorSource->getNullPixelValue(band);
}
return ossimImageCombiner::getNullPixelValue(band);
}
double ossimTopographicCorrectionFilter::getMinPixelValue(ossim_uint32 band)const
{
ossimImageSource* colorSource = PTR_CAST(ossimImageSource, getInput(0));
if(colorSource)
{
return colorSource->getMinPixelValue(band);
}
return ossimImageCombiner::getMinPixelValue(band);
}
double ossimTopographicCorrectionFilter::getMaxPixelValue(ossim_uint32 band)const
{
ossimImageSource* colorSource = PTR_CAST(ossimImageSource, getInput(0));
if(colorSource)
{
return colorSource->getMaxPixelValue(band);
}
return ossimImageCombiner::getMaxPixelValue(band);
}
ossimIrect ossimTopographicCorrectionFilter::getBoundingRect(ossim_uint32 resLevel)const
{
ossimIrect result;
result.makeNan();
ossimImageSource* colorSource = PTR_CAST(ossimImageSource, getInput(0));
if(colorSource)
{
result = colorSource->getBoundingRect(resLevel);
}
return result;
}
void ossimTopographicCorrectionFilter::getDecimationFactor(ossim_uint32 resLevel,
ossimDpt& result) const
{
result.makeNan();
ossimImageSource* colorSource = PTR_CAST(ossimImageSource, getInput(0));
if(colorSource)
{
colorSource->getDecimationFactor(resLevel,
result);
}
}
void ossimTopographicCorrectionFilter::getDecimationFactors(vector<ossimDpt>& decimations) const
{
ossimImageSource* colorSource = PTR_CAST(ossimImageSource, getInput(0));
if(colorSource)
{
colorSource->getDecimationFactors(decimations);
}
}
ossim_uint32 ossimTopographicCorrectionFilter::getNumberOfDecimationLevels()const
{
ossimImageSource* colorSource = PTR_CAST(ossimImageSource, getInput(0));
if(colorSource)
{
return colorSource->getNumberOfDecimationLevels();
}
return 0;
}
double ossimTopographicCorrectionFilter::getAzimuthAngle()const
{
return theLightSourceAzimuthAngle;
}
double ossimTopographicCorrectionFilter::getElevationAngle()const
{
return theLightSourceElevationAngle;
}
void ossimTopographicCorrectionFilter::setAzimuthAngle(double angle)
{
theLightSourceAzimuthAngle = angle;
}
void ossimTopographicCorrectionFilter::setElevationAngle(double angle)
{
theLightSourceElevationAngle = angle;
}
bool ossimTopographicCorrectionFilter::canConnectMyInputTo(ossim_int32 inputIndex,
const ossimConnectableObject* object)const
{
return (object&&
( (inputIndex>=0) && inputIndex < 2)&&
PTR_CAST(ossimImageSource, object));
}
void ossimTopographicCorrectionFilter::connectInputEvent(ossimConnectionEvent& /* event */)
{
initialize();
}
void ossimTopographicCorrectionFilter::disconnectInputEvent(ossimConnectionEvent& /* event */)
{
initialize();
}
void ossimTopographicCorrectionFilter::propertyEvent(ossimPropertyEvent& /* event */)
{
initialize();
}
void ossimTopographicCorrectionFilter::refreshEvent(ossimRefreshEvent& /* event */)
{
initialize();
}
ossimTopographicCorrectionFilter::ossimTopoCorrectionType ossimTopographicCorrectionFilter::getTopoCorrectionType()const
{
return theTopoCorrectionType;
}
void ossimTopographicCorrectionFilter::setTopoCorrectionType(ossimTopoCorrectionType topoType)
{
theTopoCorrectionType = topoType;
}
const std::vector<double>& ossimTopographicCorrectionFilter::getGainValues()const
{
return theGain;
}
void ossimTopographicCorrectionFilter::setGainValues(const std::vector<double>& gainValues)
{
theGain = gainValues;
}
const vector<double>& ossimTopographicCorrectionFilter::getBiasValues()const
{
return theBias;
}
void ossimTopographicCorrectionFilter::setBiasValues(const std::vector<double>& biasValues)
{
theBias = biasValues;
}
const vector<double>& ossimTopographicCorrectionFilter::getKValues()const
{
return theK;
}
double ossimTopographicCorrectionFilter::getK(int idx)const
{
if(idx < (int)theK.size())
{
return theK[idx];
}
else
{
return 1.0;
}
}
void ossimTopographicCorrectionFilter::setK(int idx, double value)
{
if(idx < (int)theK.size())
{
theK[idx] = value;
}
}
void ossimTopographicCorrectionFilter::setKValues(const vector<double>& kValues)
{
theK = kValues;
}
double ossimTopographicCorrectionFilter::getC(int idx)const
{
if(idx < (int)theC.size())
{
return theC[idx];
}
else
{
return 0.0;
}
}
void ossimTopographicCorrectionFilter::setC(int idx, double value)
{
if(idx < (int)theC.size())
{
theC[idx] = value;
}
}
void ossimTopographicCorrectionFilter::setCValues(const vector<double>& cValues)
{
theC = cValues;
}
| 30.303517 | 134 | 0.570679 | [
"object",
"vector"
] |
74dd3bc6b99d00f4e86a2e530bfd8f5e3f776c37 | 1,036 | cpp | C++ | CS302_Operating-System/Report8/CLOOK.cpp | Eveneko/SUSTech-Courses | 0420873110e91e8d13e6e85a974f1856e01d28d6 | [
"MIT"
] | 4 | 2020-11-11T11:56:57.000Z | 2021-03-11T10:05:09.000Z | CS302_Operating-System/Report8/CLOOK.cpp | Eveneko/SUSTech-Courses | 0420873110e91e8d13e6e85a974f1856e01d28d6 | [
"MIT"
] | null | null | null | CS302_Operating-System/Report8/CLOOK.cpp | Eveneko/SUSTech-Courses | 0420873110e91e8d13e6e85a974f1856e01d28d6 | [
"MIT"
] | 3 | 2021-01-07T04:14:11.000Z | 2021-04-27T13:41:36.000Z | #include <bits/stdc++.h>
using namespace std;
int S; // the position of beginning track
int M; // the total number of tracks in disk
int N; // the number of scheduling requests
vector<int> tracks;
int main() {
scanf("%d %d %d", &S, &M, &N);
int num;
tracks.push_back(S);
for (int i = 0; i < N; ++i) {
scanf("%d", &num);
tracks.push_back(num);
}
sort(tracks.begin(), tracks.end());
// tracks.erase(unique(tracks.begin(), tracks.end()), tracks.end());
int ptr = -1;
for (int i = N; i >= 0; --i) {
if (tracks[i] == S) {
ptr = i;
break;
}
}
int l = ptr - 1;
int r = N;
ptr++;
int dis = 0;
int pre = S;
printf("%d", S);
while (l >= 0) {
dis += abs(tracks[l] - pre);
pre = tracks[l];
printf(" %d", tracks[l--]);
}
while (r >= ptr) {
dis += abs(tracks[r] - pre);
pre = tracks[r];
printf(" %d", tracks[r--]);
}
printf("\n%d\n", dis);
return 0;
} | 22.521739 | 72 | 0.465251 | [
"vector"
] |
74dd95b58aa8a44fa0e801e505482670cf58cdab | 1,370 | cpp | C++ | aws-cpp-sdk-pinpoint/source/model/GPSCoordinates.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-pinpoint/source/model/GPSCoordinates.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-pinpoint/source/model/GPSCoordinates.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/pinpoint/model/GPSCoordinates.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Pinpoint
{
namespace Model
{
GPSCoordinates::GPSCoordinates() :
m_latitude(0.0),
m_latitudeHasBeenSet(false),
m_longitude(0.0),
m_longitudeHasBeenSet(false)
{
}
GPSCoordinates::GPSCoordinates(JsonView jsonValue) :
m_latitude(0.0),
m_latitudeHasBeenSet(false),
m_longitude(0.0),
m_longitudeHasBeenSet(false)
{
*this = jsonValue;
}
GPSCoordinates& GPSCoordinates::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("Latitude"))
{
m_latitude = jsonValue.GetDouble("Latitude");
m_latitudeHasBeenSet = true;
}
if(jsonValue.ValueExists("Longitude"))
{
m_longitude = jsonValue.GetDouble("Longitude");
m_longitudeHasBeenSet = true;
}
return *this;
}
JsonValue GPSCoordinates::Jsonize() const
{
JsonValue payload;
if(m_latitudeHasBeenSet)
{
payload.WithDouble("Latitude", m_latitude);
}
if(m_longitudeHasBeenSet)
{
payload.WithDouble("Longitude", m_longitude);
}
return payload;
}
} // namespace Model
} // namespace Pinpoint
} // namespace Aws
| 17.341772 | 69 | 0.709489 | [
"model"
] |
74e28fceaa982c65ce1ac271ed2975ce52717a5d | 2,819 | cpp | C++ | test/cycle.cpp | NasalDaemon/iter | 598e959c43b95f38a8b37b19318df52edfbb9249 | [
"BSD-3-Clause"
] | 14 | 2021-04-26T06:21:39.000Z | 2022-02-11T21:46:23.000Z | test/cycle.cpp | NasalDaemon/iter | 598e959c43b95f38a8b37b19318df52edfbb9249 | [
"BSD-3-Clause"
] | 2 | 2021-04-27T19:10:55.000Z | 2021-04-28T19:50:31.000Z | test/cycle.cpp | NasalDaemon/iter | 598e959c43b95f38a8b37b19318df52edfbb9249 | [
"BSD-3-Clause"
] | 1 | 2021-04-27T19:02:17.000Z | 2021-04-27T19:02:17.000Z | #include "test.hpp"
#include <vector>
TEST(TestCycle, indices_take) {
constexpr auto c = indices |take| 5 | cycle();
using type = std::remove_cvref_t<decltype(c)>;
static_assert(concepts::random_access_iter<type>);
static_assert(impl::size(c) == std::numeric_limits<std::size_t>::max());
auto c1 = c;
ASSERT_EQ(c1 |nth| 0, 0);
ASSERT_EQ(c1 |nth| 1, 1);
ASSERT_EQ(c1 |nth| 2, 2);
ASSERT_EQ(c1 |nth| 3, 3);
ASSERT_EQ(c1 |nth| 4, 4);
ASSERT_EQ(c1 |nth| 5, 0);
ASSERT_EQ(c1 |nth| 6, 1);
ASSERT_EQ(c1 |nth| 7, 2);
ASSERT_EQ(c1 |nth| 8, 3);
ASSERT_EQ(c1 |nth| 9, 4);
ASSERT_EQ(c1 |nth| 10, 0);
for (int i = 0; i < 10; ++i) {
ASSERT_EQ(impl::next(c1), i % 5);
}
}
TEST(TestCycle, once) {
constexpr auto o = once{9} | cycle();
using type = std::remove_cvref_t<decltype(o)>;
static_assert(concepts::random_access_iter<type>);
static_assert(impl::size(o) == std::numeric_limits<std::size_t>::max());
auto o1 = o;
ASSERT_EQ(*nth(o1, 0), 9);
ASSERT_EQ(*nth(o1, 1), 9);
ASSERT_EQ(*nth(o1, 999), 9);
for (int i = 0; i < 10; ++i)
ASSERT_EQ(*impl::next(o1), 9);
}
TEST(TestCycle, once_ref) {
auto expected = 9;
auto o = once_ref(expected) | cycle();
using type = std::remove_cvref_t<decltype(o)>;
static_assert(concepts::random_access_iter<type>);
static_assert(impl::size(o) == std::numeric_limits<std::size_t>::max());
auto o1 = o;
ASSERT_EQ(*nth(o1, 0), expected);
ASSERT_EQ(*nth(o1, 1), expected);
ASSERT_EQ(*nth(o1, 999), expected);
for (int i = 0; i < 10; ++i)
ASSERT_EQ(*impl::next(o1), expected);
}
template<class T>
void test_container(T&& v) {
using type = std::remove_cvref_t<T>;
static_assert(concepts::random_access_iter<type>);
ASSERT_EQ(impl::size(v), std::numeric_limits<std::size_t>::max());
ASSERT_EQ(*nth(v, 0), 0);
ASSERT_EQ(*nth(v, 1), 3);
ASSERT_EQ(*nth(v, 2), 2);
ASSERT_EQ(*nth(v, 3), 6);
for (int i = 0; i < 16; ++i) {
auto n = *impl::next(v);
switch (i % 4) {
case 0: ASSERT_EQ(n, 0); break;
case 1: ASSERT_EQ(n, 3); break;
case 2: ASSERT_EQ(n, 2); break;
case 3: ASSERT_EQ(n, 6); break;
}
}
}
TEST(TestCycle, container) {
std::vector v{0, 3, 2, 6};
test_container(v | cycle());
test_container(v | to_iter() | cycle());
}
TEST(TestCycle, rvo) {
auto gen = generate {
[i = 0]() mutable {
return MAKE_OPTIONAL(ctor_count(i++));
}
};
auto s = gen
| take | 5
| cycle()
| take | 10
| inspect | [](auto& c) {
ASSERT_TRUE(c.value < 5);
ASSERT_EQ(c.total(), 0); }
| map | counter_unwrap
| sum();
ASSERT_EQ(s, 20);
}
| 28.474747 | 76 | 0.559773 | [
"vector"
] |
d55f1980b539766783571051ede44cd63a766dfa | 1,349 | hh | C++ | snmp/snmpoidtree.hh | kohler/click-packages | cec70da7cf460548ef08f1ddad6924db29d5c0c5 | [
"MIT"
] | 13 | 2015-02-26T23:12:09.000Z | 2021-04-18T04:37:12.000Z | snmp/snmpoidtree.hh | kohoumas/click-packages | 6bb5c4ba286e5dbc74efd1708921d530425691f6 | [
"MIT"
] | null | null | null | snmp/snmpoidtree.hh | kohoumas/click-packages | 6bb5c4ba286e5dbc74efd1708921d530425691f6 | [
"MIT"
] | 7 | 2015-08-25T09:29:41.000Z | 2021-04-18T04:37:13.000Z | #ifndef SNMPOIDTREE_HH
#define SNMPOIDTREE_HH
#include <click/vector.hh>
#include "snmpbasics.hh"
class SNMPOidTree { public:
struct Node;
SNMPOidTree();
~SNMPOidTree();
int find(const SNMPOid &) const;
int find_prefix(const SNMPOid &, int *prefix_length) const;
Node *insert(const SNMPOid &, int);
void extract_oid(Node *, SNMPOid *) const;
const Node *find_node(const SNMPOid &) const;
Node *force_node(const SNMPOid &);
static int node_data(const Node *n) { return n->data; }
static void set_node_data(Node *n, int d) { n->data = d; }
struct Node {
uint32_t suffix;
Node *parent;
Node *sibling;
Node *child;
int data;
};
private:
Node **_nodes;
int _nnodes;
int _nodes_cap;
enum { NODES_PER_GROUP = 256 };
SNMPOidTree(const SNMPOidTree &);
SNMPOidTree &operator=(const SNMPOidTree &);
Node *root_node() const;
Node *alloc_node(uint32_t, Node *, Node *);
};
inline SNMPOidTree::Node *
SNMPOidTree::root_node() const
{
assert(_nnodes > 0);
return &(_nodes[0][0]);
}
inline int
SNMPOidTree::find(const SNMPOid &oid) const
{
if (const Node *n = find_node(oid))
return n->data;
else
return -1;
}
inline SNMPOidTree::Node *
SNMPOidTree::insert(const SNMPOid &oid, int data)
{
Node *n = force_node(oid);
if (n)
n->data = data;
return n;
}
#endif
| 18.22973 | 61 | 0.664937 | [
"vector"
] |
d561a0b26de0d2ce49a8015dacacdab5b03ae462 | 9,873 | cpp | C++ | comprehensive_application/manager.cpp | teamwong111/Data-Structure-Course | 6aa84de6385d8428245f9950b6f926eb70b3ad3a | [
"MIT"
] | null | null | null | comprehensive_application/manager.cpp | teamwong111/Data-Structure-Course | 6aa84de6385d8428245f9950b6f926eb70b3ad3a | [
"MIT"
] | null | null | null | comprehensive_application/manager.cpp | teamwong111/Data-Structure-Course | 6aa84de6385d8428245f9950b6f926eb70b3ad3a | [
"MIT"
] | null | null | null | #include "manager.h"
//构造函数
Manager::Manager(){}
//从文件读取数据
bool Manager::readfile(QString filename)
{
QFile file(filename);
if(!file.open(QIODevice::ReadOnly))
{
return false;
}
QTextStream in(&file);
while(!in.atEnd())
{
bool ok;
int total, lineindex, stationindex1, stationindex2;
QString lineid, linename, linecolors, fromto, stationlist, linecolor, fromstation, tostation, longlat;
QStringList strList;
Line line;
Station station;
in>>lineid>>line.id;
in>>linename>>line.name;
in>>linecolors>>linecolor;
line.color.setRgba(linecolor.remove(0,1).toUInt(&ok, 16));
in>>fromto>>fromstation>>tostation;
in>>stationlist>>total;
line.fromto.push_back(fromstation);
line.fromto.push_back(tostation);
if (lineshash.count(line.name))
{
lineindex = lineshash[line.name];
lines[lineindex].fromto.push_back(fromstation);
lines[lineindex].fromto.push_back(tostation);
}
else
{
lineshash[line.name] = lines.size();
lineindex = lines.size();
lines.push_back(line);
}
for (int i=0; !in.atEnd()&&i<total; ++i)
{
in>>station.id>>station.name>>longlat;
strList=longlat.split(QChar(','));
station.longitude=strList.first().toDouble();
station.latitude=strList.last().toDouble();
if (stationshash.count(station.name))
{
stationindex2 = stationshash[station.name];
}
else
{
stationindex2 = stationshash[station.name] = stations.size();
stations.push_back(station);
}
stations[stationindex2].theline.insert(lineindex);
lines[lineindex].stationset.insert(stationindex2);
if (i)
{
lines[lineindex].edges.insert(Edge(stationindex1, stationindex2));
lines[lineindex].edges.insert(Edge(stationindex2, stationindex1));
insertedge(stationindex1, stationindex2);
}
stationindex1 = stationindex2;
}
bool flag = lineid=="lineid:" && linename=="linename:" && linecolors=="linecolors:" && fromto=="fromto:" && stationlist=="stationlist:" && ok && !in.atEnd();
if(flag==false)
{
file.close();
cleardata();
return false;
}
in.readLine();
}
file.close();
boundlongilatiupdate();
return true;
}
//清空数据
void Manager::cleardata()
{
stations.clear();
lines.clear();
stationshash.clear();
lineshash.clear();
edges.clear();
graph.clear();
}
//插入一条边
bool Manager::insertedge(int e1, int e2)
{
if (edges.contains(Edge(e1, e2)) || edges.contains(Edge(e2, e1)))
{
return false;
}
edges.insert(Edge(e1, e2));
return true;
}
//生成图结构
void Manager::tograph()
{
graph.clear();
graph=QVector<QVector<Node>>(stations.size(), QVector<Node>());
for (auto &a : edges)
{
double dist=distance(stations[a.first].latitude, stations[a.first].longitude, stations[a.second].latitude, stations[a.second].longitude);
graph[a.first].push_back(Node(a.second, dist));
graph[a.second].push_back(Node(a.first, dist));
}
}
//获取线路颜色
QColor Manager::getlinecolor(int i)
{
return lines[i].color;
}
//获取线路名
QString Manager::getlinename(int i)
{
return lines[i].name;
}
//获取线路名列表
QList<QString> Manager::getlinenamelist()
{
QList<QString> linenamelist;
for (auto a:lines)
{
linenamelist.push_back(a.name);
}
return linenamelist;
}
//获取线路hash值
int Manager::getlinehash(QString linename)
{
if(lineshash.contains(linename))
{
return lineshash[linename];
}
return -1;
}
//获取线路hash值列表
QList<int> Manager::getlinehashlist(QList<QString> linelist)
{
QList<int> hashlist;
for (auto &a:linelist)
{
hashlist.push_back(getlinehash(a));
}
return hashlist;
}
//获取线路所有站点
QList<QString> Manager::getstationlist(int i)
{
QList<QString> stationlist;
for (auto &a:lines[i].stationset)
{
stationlist.push_back(stations[a].name);
}
return stationlist;
}
//更新边界经纬度
void Manager::boundlongilatiupdate()
{
double minLongitude=200, minLatitude=200;
double maxLongitude=0, maxLatitude=0;
for (auto &s : stations)
{
minLongitude = qMin(minLongitude, s.longitude);
minLatitude = qMin(minLatitude, s.latitude);
maxLongitude = qMax(maxLongitude, s.longitude);
maxLatitude = qMax(maxLatitude, s.latitude);
}
theminLongitude = minLongitude;
theminLatitude = minLatitude;
themaxLongitude = maxLongitude;
themaxLatitude = maxLatitude;
}
//获取站点最小坐标
QPointF Manager::getmincoord()
{
return QPointF(theminLongitude, theminLatitude);
}
//获取站点最大坐标
QPointF Manager::getmaxcoord()
{
return QPointF(themaxLongitude, themaxLatitude);
}
//获取两个站点的公共所属线路
QList<int> Manager::getcommonlines(int s1, int s2)
{
QList<int> linelist;
for (auto &s : stations[s1].theline)
{
if(stations[s2].theline.contains(s))
linelist.push_back(s);
}
return linelist;
}
//获取站点名
QString Manager::getstationname(int i)
{
return stations[i].name;
}
//获取站点地理坐标
QPointF Manager::getstationcoord(int i)
{
return QPointF(stations[i].longitude, stations[i].latitude);
}
//获取站点所属线路
QList<int> Manager::getstationlines(int i)
{
return stations[i].theline.toList();
}
//获取站点hash值
int Manager::getstationhash(QString stationname)
{
if(stationshash.contains(stationname))
{
return stationshash[stationname];
}
return -1;
}
//获取站点hash值列表
QList<QString> Manager::getstationnamelist()
{
QList<QString> stationnamelist;
for (auto &a: stations)
{
stationnamelist.push_back(a.name);
}
return stationnamelist;
}
//获取站点间实地直线距离
int Manager::distance(double fLati1, double fLong1, double fLati2, double fLong2)
{
const double EARTH_RADIUS = 6378.137;
const double PI = 3.1415926535898;
double radLat1 = fLati1 * PI / 180.0;
double radLat2 = fLati2 * PI / 180.0;
double a = radLat1 - radLat2;
double b = fLong1 * PI / 180.0 - fLong2 * PI / 180.0;
double s = 2 * asin(sqrt(pow(sin(a/2),2) + cos(radLat1)*cos(radLat2)*pow(sin(b/2),2)));
s = s * EARTH_RADIUS;
s = (int)(s * 10000000) / 10000;
return s;
}
//添加新线路
void Manager::addline(QString linename, QColor color)
{
lineshash[linename]=lines.size();
lines.push_back(Line(linename,color));
}
//添加新站点
void Manager::addstation(Station s)
{
int hash=stations.size();
stationshash[s.name]=hash;
stations.push_back(s);
for (auto &a: s.theline)
{
lines[a].stationset.insert(hash);
}
boundlongilatiupdate();
}
//添加站点连接关系
void Manager::addconnect(int s1, int s2, int l)
{
insertedge(s1,s2);
lines[l].edges.insert(Edge(s1,s2));
lines[l].edges.insert(Edge(s2,s1));
}
//获取网络结构
void Manager::getgeneralroadmap(QList<int>&stationlist, QList<Edge>&edgelist)
{
stationlist.clear();
for (int i=0; i<stations.size(); ++i)
{
stationlist.push_back(i);
}
edgelist=edges.toList();
}
//获取最少时间的线路
bool Manager::getmintimetransfer(int s1, int s2, QList<int>&stationlist, QList<Edge>&edgelist)
{
const int INF = 999999999;
stationlist.clear();
edgelist.clear();
if(s1==s2)
{
stationlist.push_back(s2);
stationlist.push_back(s1);
return true;
}
tograph();
std::vector<int> path(stations.size(), -1);
std::vector<double> dist(stations.size(), INF);
dist[s1]=0;
std::priority_queue<Node, std::vector<Node>, std::greater<Node>> q;
q.push(Node(s1, 0));
while(!q.empty())
{
Node top=q.top();
q.pop();
if(top.station==s2)
{
break ;
}
for (int i=0; i<graph[top.station].size(); ++i)
{
Node &adjNode=graph[top.station][i];
if(top.distance+adjNode.distance<dist[adjNode.station])
{
path[adjNode.station]=top.station;
dist[adjNode.station]=top.distance+adjNode.distance;
q.push(Node(adjNode.station, dist[adjNode.station]));
}
}
}
if(path[s2]==-1)
{
return false;
}
int p=s2;
while(path[p]!=-1)
{
stationlist.push_front(p);
edgelist.push_front(Edge(path[p],p));
p=path[p];
}
stationlist.push_front(s1);
return true;
}
//获取最少换乘的线路
bool Manager::getmintransferline(int s1, int s2, QList<int>&stationlist, QList<Edge>&edgelist)
{
stationlist.clear();
edgelist.clear();
if(s1==s2)
{
stationlist.push_back(s2);
stationlist.push_back(s1);
return true;
}
std::vector<bool> linesVisted(lines.size(),false);
std::vector<int> path(stations.size(),-1);
path[s1]=-2;
std::queue<int> q;
q.push(s1);
while(!q.empty())
{
int top=q.front();
q.pop();
for (auto &l: stations[top].theline)
{
if(!linesVisted[l])
{
linesVisted[l]=true;
for (auto &s: lines[l].stationset)
{
if(path[s]==-1)
{
path[s]=top;
q.push(s);
}
}
}
}
}
if(path[s2]==-1)
{
return false;
}
int p=s2;
while(path[p]!=-2)
{
stationlist.push_front(p);
edgelist.push_front(Edge(path[p],p));
p=path[p];
}
stationlist.push_front(s1);
return true;
}
| 24.080488 | 165 | 0.586043 | [
"vector"
] |
d565c4ee2484d92368a0bec6b49f8d6cbac7ea33 | 9,828 | cpp | C++ | unit-tests/unit-tests-post-processing.cpp | arunabhcode/librealsense | 3cd61ee78b1793091243db888a36979cd9c74dbb | [
"BSD-2-Clause",
"Apache-2.0"
] | null | null | null | unit-tests/unit-tests-post-processing.cpp | arunabhcode/librealsense | 3cd61ee78b1793091243db888a36979cd9c74dbb | [
"BSD-2-Clause",
"Apache-2.0"
] | null | null | null | unit-tests/unit-tests-post-processing.cpp | arunabhcode/librealsense | 3cd61ee78b1793091243db888a36979cd9c74dbb | [
"BSD-2-Clause",
"Apache-2.0"
] | null | null | null | // License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2018 Intel Corporation. All Rights Reserved.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// This set of tests is valid for any number and combination of RealSense cameras, including R200 and F200 //
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "unit-tests-common.h"
#include "unit-tests-post-processing.h"
#include "../include/librealsense2/rs_advanced_mode.hpp"
#include <librealsense2/hpp/rs_frame.hpp>
#include <cmath>
#include <iostream>
#include <chrono>
#include <ctime>
#include <algorithm>
# define SECTION_FROM_TEST_NAME space_to_underscore(Catch::getCurrentContext().getResultCapture()->getCurrentTestName()).c_str()
class post_processing_filters
{
public:
post_processing_filters(void) : depth_to_disparity(true),disparity_to_depth(false) {};
~post_processing_filters() noexcept {};
void configure(const ppf_test_config& filters_cfg);
rs2::frame process(rs2::frame input_frame);
private:
post_processing_filters(const post_processing_filters& other);
post_processing_filters(post_processing_filters&& other);
// Declare filters
rs2::decimation_filter dec_filter; // Decimation - frame downsampling using median filter
rs2::spatial_filter spat_filter; // Spatial - edge-preserving spatial smoothing
rs2::temporal_filter temp_filter; // Temporal - reduces temporal noise
// Declare disparity transform from depth to disparity and vice versa
rs2::disparity_transform depth_to_disparity;
rs2::disparity_transform disparity_to_depth;
bool dec_pb = false;
bool spat_pb = false;
bool temp_pb = false;
};
void post_processing_filters::configure(const ppf_test_config& filters_cfg)
{
// Reconfigure the post-processing according to the test spec
dec_pb = (filters_cfg.downsample_scale != 1);
dec_filter.set_option(RS2_OPTION_FILTER_MAGNITUDE, (float)filters_cfg.downsample_scale);
if (spat_pb = filters_cfg.spatial_filter)
{
spat_filter.set_option(RS2_OPTION_FILTER_SMOOTH_ALPHA, filters_cfg.spatial_alpha);
spat_filter.set_option(RS2_OPTION_FILTER_SMOOTH_DELTA, filters_cfg.spatial_delta);
spat_filter.set_option(RS2_OPTION_FILTER_MAGNITUDE, (float)filters_cfg.spatial_iterations);
//spat_filter.set_option(RS2_OPTION_HOLES_FILL, filters_cfg.holes_filling_mode); // Currently disabled
}
if (temp_pb = filters_cfg.temporal_filter)
{
temp_filter.set_option(RS2_OPTION_FILTER_SMOOTH_ALPHA, filters_cfg.temporal_alpha);
temp_filter.set_option(RS2_OPTION_FILTER_SMOOTH_DELTA, filters_cfg.temporal_delta);
temp_filter.set_option(RS2_OPTION_HOLES_FILL, filters_cfg.temporal_persistence);
}
}
rs2::frame post_processing_filters::process(rs2::frame input)
{
auto processed = input;
// The filters are applied in the same order as recommended by the reference design
// Decimation -> Depth2Disparity -> Spatial ->Temporal -> Disparity2Depth
if (dec_pb)
processed = dec_filter.process(processed);
// Domain transform is mandatory according to the reference design
processed = depth_to_disparity.process(processed);
if (spat_pb)
processed = spat_filter.process(processed);
if (temp_pb)
processed = temp_filter.process(processed);
return disparity_to_depth.process(processed);
}
bool validate_ppf_results(rs2::frame origin_depth, rs2::frame result_depth, const ppf_test_config& reference_data, size_t frame_idx)
{
std::vector<uint16_t> diff2orig;
std::vector<uint16_t> diff2ref;
// Basic sanity scenario with no filters applied.
// validating domain transform in/out conversion. Requiring input=output
bool domain_transform_only = (reference_data.downsample_scale == 1) &&
(!reference_data.spatial_filter) && (!reference_data.temporal_filter);
auto result_profile = result_depth.get_profile().as<rs2::video_stream_profile>();
REQUIRE(result_profile);
CAPTURE(result_profile.width());
CAPTURE(result_profile.height());
REQUIRE(result_profile.width() == reference_data.output_res_x);
REQUIRE(result_profile.height() == reference_data.output_res_y);
auto pixels = result_profile.width()*result_profile.height();
diff2ref.resize(pixels);
if (domain_transform_only)
diff2orig.resize(pixels);
// Pixel-by-pixel comparison of the resulted filtered depth vs data ercorded with external tool
auto v1 = reinterpret_cast<const uint16_t*>(result_depth.get_data());
auto v2 = reinterpret_cast<const uint16_t*>(reference_data._output_frames[frame_idx].data());
for (auto i = 0; i < pixels; i++)
{
uint16_t diff = std::abs(*v1++ - *v2++);
diff2ref[i] = diff;
}
// Basic sanity scenario with no filters applied.
// validating domain transform in/out conversion.
if (domain_transform_only)
REQUIRE(profile_diffs("./DomainTransform.txt",diff2orig, 0, 0, frame_idx));
// The differences between the reference code and librealsense implementation are assessed below
// STD of 0.025 is "roughly" represents 50 pixels with offset of 1 in a 200k pixels frame
return profile_diffs("./Filterstransform.txt", diff2ref, 0.025f, 1, frame_idx);
}
// The test is intended to check the results of filters applied on a sequence of frames, specifically the temporal filter
// that preserves an internal state. The test utilizes rosbag recordings
TEST_CASE("Post-Processing Filters sequence validation", "[software-device][post-processing-filters]")
{
rs2::context ctx;
if (make_context(SECTION_FROM_TEST_NAME, &ctx))
{
// Test file name , Filters configuraiton
const std::vector< std::pair<std::string, std::string>> ppf_test_cases = {
{ "1523873668701", "D415_Downsample1" },
{ "1523873012723", "D415_Downsample2" },
{ "1523873362088", "D415_Downsample3" },
{ "1523874476600", "D415_Downsample2+Spat(A:0.85/D:32/I:3)" },
{ "1523874595767", "D415_Downsample2+Spat(A:0.3/D:8/I:3)" },
{ "1523889912588", "D415_Downsample2+Temp(A:0.4/D:20/P:0)" },
{ "1523890056362", "D415_Downsample2+Temp(A:0.3/D:10/P:4)" },
{ "1523887243933", "D415_DS:2_Spat(A:0.85/D:32/I:3)_Temp(A:0.25/D:15/P:0)" },
{ "1523889529572", "D415_DS:3_Spat(A:0.3/D:8/I:3)_Temp(A:0.5/D:6/P:4)" },
};
ppf_test_config test_cfg;
for (auto& ppf_test : ppf_test_cases)
{
CAPTURE(ppf_test.first);
CAPTURE(ppf_test.second);
WARN("PPF test " << ppf_test.first << "[" << ppf_test.second << "]");
// Load the data from configuration and raw frame files
if (!load_test_configuration(ppf_test.first, test_cfg))
continue;
post_processing_filters ppf;
// Apply the retrieved configuration onto a local post-processing chain of filters
REQUIRE_NOTHROW(ppf.configure(test_cfg));
rs2::software_device dev; // Create software-only device
auto depth_sensor = dev.add_sensor("Depth");
int width = test_cfg.input_res_x;
int height = test_cfg.input_res_y;
int depth_bpp = 2; //16bit unsigned
int frame_number = 1;
rs2_intrinsics depth_intrinsics = { width, height,
width / 2.f, height / 2.f, // Principal point (N/A in this test)
test_cfg.focal_length ,test_cfg.focal_length, // Focal Length
RS2_DISTORTION_BROWN_CONRADY ,{ 0,0,0,0,0 } };
auto depth_stream_profile = depth_sensor.add_video_stream({ RS2_STREAM_DEPTH, 0, 0, width, height, 30, depth_bpp, RS2_FORMAT_Z16, depth_intrinsics });
depth_sensor.add_read_only_option(RS2_OPTION_DEPTH_UNITS, test_cfg.depth_units);
depth_sensor.add_read_only_option(RS2_OPTION_STEREO_BASELINE, test_cfg.stereo_baseline);
// Establish the required chain of filters
dev.create_matcher(RS2_MATCHER_DLR_C);
rs2::syncer sync;
depth_sensor.open(depth_stream_profile);
depth_sensor.start(sync);
size_t frames = (test_cfg.frames_sequence_size > 1) ? test_cfg.frames_sequence_size : 1;
for (auto i = 0; i < frames; i++)
{
// Inject input frame
depth_sensor.on_video_frame({ test_cfg._input_frames[i].data(), // Frame pixels from capture API
[](void*) {}, // Custom deleter (if required)
(int)test_cfg.input_res_x *depth_bpp, // Stride
depth_bpp, // Bytes-per-pixels
(rs2_time_t)frame_number + i, // Timestamp
RS2_TIMESTAMP_DOMAIN_SYSTEM_TIME, // Clock Domain
frame_number, // Frame# for potential sync services
depth_stream_profile }); // Depth stream profile
rs2::frameset fset = sync.wait_for_frames();
REQUIRE(fset);
rs2::frame depth = fset.first_or_default(RS2_STREAM_DEPTH);
REQUIRE(depth);
// ... here the actual filters are being applied
auto filtered_depth = ppf.process(depth);
// Compare the resulted frame versus input
REQUIRE(validate_ppf_results(depth, filtered_depth, test_cfg, i));
}
}
}
}
| 43.486726 | 162 | 0.651201 | [
"vector",
"transform"
] |
d567150e672c89203ffdbd3079f427cb5867703b | 3,783 | cpp | C++ | soccerGame/src/Ball.cpp | amol-m/soccer | 112ebf543ebfa12264a1256f756368f4541b62f3 | [
"MIT"
] | null | null | null | soccerGame/src/Ball.cpp | amol-m/soccer | 112ebf543ebfa12264a1256f756368f4541b62f3 | [
"MIT"
] | null | null | null | soccerGame/src/Ball.cpp | amol-m/soccer | 112ebf543ebfa12264a1256f756368f4541b62f3 | [
"MIT"
] | null | null | null | //
// Ball.cpp
// soccerGame
//
// Created by Amol Mane on 9/19/15.
//
//
#include "Ball.h"
#include "cinder/Vector.h"
#include "Player.h"
#include "cinder/gl/gl.h"
#include "cinder/app/AppBasic.h"
using namespace ci;
Ball::Ball() {
// int x = app::getWindowWidth()/2;
// int y = app::getWindowWidth()/2;
// int x = 1024/2;
// int y = 768/2;
int x = 700;
int y = 700;
loc = Vec2i(x ,y);
speed = maxSpeed;
dir = Vec4i(0,0,0,0);
radius = 7;
}
void Ball::update(Player* (players)[], Player* &activePlayer) {
if(activePlayer->hasBall) {
loc = activePlayer->loc;
dir = activePlayer->dir;
//if player/ball come across the path of another player, lose the ball to that
//other player
}
else {
//move ball
double temp;
if (dir.y) {
temp = loc.y - speed;
if(temp < radius/2) {
dir.y = 0;
dir.w = 1;
loc.y += speed;
}
else {
loc.y -= speed;
}
}
else if (dir.w) {
temp = loc.y + speed;
if(temp > 768 - radius/2) {
dir.y = 1;
dir.w = 0;
loc.y -= speed;
}
else {
loc.y += speed;
}
}
if (dir.x) {
temp = loc.x + speed;
if(temp > 1024 - radius/2) {
dir.x = 0;
dir.z = 1;
loc.x -= speed;
}
else {
loc.x += speed;
}
}
else if (dir.z) {
temp = loc.x - speed;
if(temp < radius/2) {
dir.x = 1;
dir.z = 0;
loc.x += speed;
}
else {
loc.x -= speed;
}
}
if(speed < .1) {
speed = 0;
}
else {
speed *= decay;
}
//check if ball is in the radius of another player
int closestPlayerIndex = findClosestPlayer(players);
// cout<<closestPlayerIndex<<endl;
Player* closestPlayer = players[closestPlayerIndex];
// cout<<"just released ball: "<<closestPlayer->justReleasedBall<<endl;
cout<<speed<<endl;
cout<<"lhs: "<<pow((closestPlayer->loc.x - loc.x), 2) + pow((closestPlayer->loc.y - loc.y), 2)<<" r2:"<<pow(radius + 3, 2)<<endl;
cout<<"ball: ( "<<loc.x<<", "<<loc.y<<" ) player: ( "<<closestPlayer->loc.x<<", "<<closestPlayer->loc.y<<" )"<<endl;
if( pow((closestPlayer->loc.x - loc.x), 2) + pow((closestPlayer->loc.y - loc.y), 2) < pow(radius + 3, 2) ) {
cout<<"fucked it up"<<endl;
activePlayer->isActive = false;
activePlayer->hasBall = false;
activePlayer->dir.x = activePlayer->dir.y = activePlayer->dir.z = activePlayer->dir.w = 0;
activePlayer = players[closestPlayerIndex];
activePlayer->isActive = true;
activePlayer->hasBall = true;
loc = activePlayer->loc;
dir = activePlayer->dir;
}
}
}
int Ball::findClosestPlayer(Player* (players)[]) {
int closestPlayer;
double minDistance = 1024;
for(int i=0;i<5;i++) {
double distToBall = sqrt( pow((loc.x - players[i]->loc.x), 2) + pow((loc.y - players[i]->loc.y), 2) );
if( distToBall < minDistance) {
closestPlayer = i;
minDistance = distToBall;
}
}
// cout<<closestPlayer<<endl;
return closestPlayer;
}
void Ball::draw() {
gl::color(1, 0, 0);
gl::drawSolidCircle(loc, radius);
gl::color(1,1,1);
} | 26.829787 | 137 | 0.458895 | [
"vector"
] |
d57b15bee2cb8a9938602a6aea126870d9672c9e | 28,985 | cpp | C++ | move_gen.cpp | ia03/discord-chess-bot | 1befb7c413703304a5e51435b5de0f2d3c127443 | [
"MIT"
] | null | null | null | move_gen.cpp | ia03/discord-chess-bot | 1befb7c413703304a5e51435b5de0f2d3c127443 | [
"MIT"
] | 1 | 2019-01-18T14:14:49.000Z | 2019-01-24T14:36:41.000Z | move_gen.cpp | ia03/discord-chess-bot | 1befb7c413703304a5e51435b5de0f2d3c127443 | [
"MIT"
] | null | null | null | #include <vector>
#include <array>
#include <algorithm>
#include "game.h"
#include "utils.h"
#include "lib/magicmoves.h"
// Generates all pseudo-legal moves for White.
std::vector<Move> Game::pseudo_legal_w_moves() const
{
std::vector<Move> all_moves;
// Generate the pseudo-legal moves for each square.
for (auto square_index = 0; square_index < 64; square_index++)
{
std::vector<Move> piece_moves;
const auto square = static_cast<Square>(square_index);
switch (piece_on(square))
{
case Piece::w_pawn:
piece_moves = pseudo_legal_w_pawn_moves(square);
break;
case Piece::w_knight:
piece_moves = pseudo_legal_knight_moves(square);
break;
case Piece::w_bishop:
piece_moves = pseudo_legal_bishop_moves(square);
break;
case Piece::w_rook:
piece_moves = pseudo_legal_rook_moves(square);
break;
case Piece::w_queen:
piece_moves = pseudo_legal_queen_moves(square);
break;
case Piece::w_king:
piece_moves = pseudo_legal_king_moves(square);
break;
default:
continue;
}
all_moves.insert(
all_moves.end(),
piece_moves.begin(),
piece_moves.end());
}
return all_moves;
}
// Generates all pseudo-legal moves for Black.
std::vector<Move> Game::pseudo_legal_b_moves() const
{
std::vector<Move> all_moves;
// Generate the pseudo-legal moves for each square.
for (auto square_index = 0; square_index < 64; square_index++)
{
std::vector<Move> piece_moves;
const auto square = static_cast<Square>(square_index);
switch (piece_on(square))
{
case Piece::b_pawn:
piece_moves = pseudo_legal_b_pawn_moves(square);
break;
case Piece::b_knight:
piece_moves = pseudo_legal_knight_moves(square);
break;
case Piece::b_bishop:
piece_moves = pseudo_legal_bishop_moves(square);
break;
case Piece::b_rook:
piece_moves = pseudo_legal_rook_moves(square);
break;
case Piece::b_queen:
piece_moves = pseudo_legal_queen_moves(square);
break;
case Piece::b_king:
piece_moves = pseudo_legal_king_moves(square);
break;
default:
continue;
}
all_moves.insert(
all_moves.end(),
piece_moves.begin(),
piece_moves.end());
}
return all_moves;
}
// Generates all pseudo-legal moves for the current player.
std::vector<Move> Game::pseudo_legal_moves() const
{
if (turn == Color::white)
{
return pseudo_legal_w_moves();
}
else
{
return pseudo_legal_b_moves();
}
}
// If the destination square is invalid or is occupied by a friendly
// piece, this returns Move::none. Otherwise, it returns a normal move
// with the origin and destination squares set. Used with
// find_dest_square() to generate simple moves.
Move Game::pseudo_legal_normal_move(
const Square origin_sq,
const Square dest_sq
) const
{
// Return Move::none if the destination square is invalid or is occupied
// by a friendly piece.
if (dest_sq != Square::none && !is_occupied(dest_sq, turn))
{
return create_normal_move(origin_sq, dest_sq);
}
else
{
return Move::none;
}
}
// Generates a normal move from the origin square to wherever the
// directions lead to if that is a square within the boundaries of the
// board and is not occupied by any friendly pieces.
Move Game::pseudo_legal_normal_move(
const Square origin_sq,
const std::vector<Direction> &directions
) const
{
const auto dest_sq = find_dest_square(
origin_sq,
directions
);
// Generate a move to the specified square as long as it is within the
// boundaries of the board and is not occupied by any friendly pieces.
return pseudo_legal_normal_move(origin_sq, dest_sq);
}
// Removes squares from an attack bitboard that are occupied by pieces
// belonging to the player who is to move this turn.
Bitboard Game::discard_self_captures(const Bitboard attack_bitboard) const
{
// Discard self-captures.
if (turn == Color::white)
{
return attack_bitboard & ~white_bitboard;
}
else
{
return attack_bitboard & ~black_bitboard;
}
}
// Generates the pawn north-by-1 move using the origin square. Returns
// Move::none if the move would not be pseudo-legal.
Move Game::pawn_north_move(const Square origin_sq) const
{
const auto dest_sq = find_dest_square(origin_sq, {Direction::north});
// Generate the non-attack move of moving north by 1 square as long as
// that square is in the boundaries of the board and is not occupied.
if (dest_sq != Square::none && !is_occupied(dest_sq))
{
return create_normal_move(origin_sq, dest_sq);
}
else
{
return Move::none;
}
}
// Generates the pawn south-by-1 move using the origin square. Returns
// Move::none if the move would not be pseudo-legal.
Move Game::pawn_south_move(const Square origin_sq) const
{
const auto dest_sq = find_dest_square(origin_sq, {Direction::south});
// Generate the non-attack move of moving south by 1 square as long as
// that square is in the boundaries of the board and is not occupied.
if (dest_sq != Square::none && !is_occupied(dest_sq))
{
return create_normal_move(origin_sq, dest_sq);
}
else
{
return Move::none;
}
}
// Generates the pawn north-by-2 move using the origin square. Returns
// Move::none if the move would not be pseudo-legal.
Move Game::pawn_north_north_move(const Square origin_sq) const
{
const auto dest_sq = north_of(north_of(origin_sq));
// If the pawn is on the 2nd row (meaning it has not moved yet), generate
// the 2-squares-north move as long as both squares north of the pawn are
// not occupied.
if (on_bitboard(origin_sq, row_2) && !is_occupied(north_of(origin_sq)) &&
!is_occupied(dest_sq))
{
return create_normal_move(origin_sq, dest_sq);
}
else
{
return Move::none;
}
}
// Generates the pawn south-by-2 move using the origin square. Returns
// Move::none if the move would not be pseudo-legal.
Move Game::pawn_south_south_move(const Square origin_sq) const
{
const auto dest_sq = south_of(south_of(origin_sq));
// If the pawn is on the 7th row (meaning it has not moved yet), generate
// the 2-squares-south move as long as both squares south of the pawn are
// not occupied.
if (on_bitboard(origin_sq, row_7) && !is_occupied(south_of(origin_sq)) &&
!is_occupied(dest_sq))
{
return create_normal_move(origin_sq, dest_sq);
}
else
{
return Move::none;
}
}
// Generates the pawn north-east capture move using the origin square.
// Returns Move::none if the move would not be pseudo-legal.
Move Game::pawn_north_east_move(const Square origin_sq) const
{
const auto dest_sq = find_dest_square(
origin_sq,
{Direction::north, Direction::east}
);
// If the square north east of the pawn's square is within the boundaries
// of the board and is occupied by a black piece, generate an attack move
// to that square.
if (dest_sq != Square::none &&
is_occupied(dest_sq, Color::black))
{
return create_normal_move(origin_sq, dest_sq);
}
else
{
return Move::none;
}
}
// Generates the pawn south-east capture move using the origin square.
// Returns Move::none if the move would not be pseudo-legal.
Move Game::pawn_south_east_move(const Square origin_sq) const
{
const auto dest_sq = find_dest_square(
origin_sq,
{Direction::south, Direction::east}
);
// If the square south east of the pawn's square is within the boundaries
// of the board and is occupied by a white piece, generate an attack move
// to that square.
if (dest_sq != Square::none &&
is_occupied(dest_sq, Color::white))
{
return create_normal_move(origin_sq, dest_sq);
}
else
{
return Move::none;
}
}
// Generates the pawn north-west capture move using the origin square.
// Returns Move::none if the move would not be pseudo-legal.
Move Game::pawn_north_west_move(const Square origin_sq) const
{
const auto dest_sq = find_dest_square(
origin_sq,
{Direction::north, Direction::west}
);
// If the square north west of the pawn's square is within the boundaries
// of the board and is occupied by a black piece, generate an attack move
// to that square.
if (dest_sq != Square::none &&
is_occupied(dest_sq, Color::black))
{
return create_normal_move(origin_sq, dest_sq);
}
else
{
return Move::none;
}
}
// Generates the pawn south-west capture move using the origin square.
// Returns Move::none if the move would not be pseudo-legal.
Move Game::pawn_south_west_move(const Square origin_sq) const
{
const auto dest_sq = find_dest_square(
origin_sq,
{Direction::south, Direction::west}
);
// If the square south west of the pawn's square is within the boundaries
// of the board and is occupied by a white piece, generate an attack move
// to that square.
if (dest_sq != Square::none &&
is_occupied(dest_sq, Color::white))
{
return create_normal_move(origin_sq, dest_sq);
}
else
{
return Move::none;
}
}
// Generates the pawn north-east en passant move using the origin square.
// Returns Move::none if the move would not be pseudo-legal.
Move Game::pawn_ep_north_east_move(const Square origin_sq) const
{
const auto dest_sq = find_dest_square(
origin_sq,
{Direction::north, Direction::east}
);
// If the square north east of the pawn is within the boundaries of the
// board and is the en passant square, generate the en passant move.
if (dest_sq != Square::none && dest_sq == en_passant_square)
{
return create_en_passant_move(origin_sq, dest_sq);
}
else
{
return Move::none;
}
}
// Generates the pawn south-east en passant move using the origin square.
// Returns Move::none if the move would not be pseudo-legal.
Move Game::pawn_ep_south_east_move(const Square origin_sq) const
{
const auto dest_sq = find_dest_square(
origin_sq,
{Direction::south, Direction::east}
);
// If the square south east of the pawn is within the boundaries of the
// board and is the en passant square, generate the en passant move.
if (dest_sq != Square::none && dest_sq == en_passant_square)
{
return create_en_passant_move(origin_sq, dest_sq);
}
else
{
return Move::none;
}
}
// Generates the pawn north-west en passant move using the origin square.
// Returns Move::none if the move would not be pseudo-legal.
Move Game::pawn_ep_north_west_move(const Square origin_sq) const
{
const auto dest_sq = find_dest_square(
origin_sq,
{Direction::north, Direction::west}
);
// If the square north west of the pawn is within the boundaries of the
// board and is the en passant square, generate the en passant move.
if (dest_sq != Square::none && dest_sq == en_passant_square)
{
return create_en_passant_move(origin_sq, dest_sq);
}
else
{
return Move::none;
}
}
// Generates the pawn south-west en passant move using the origin square.
// Returns Move::none if the move would not be pseudo-legal.
Move Game::pawn_ep_south_west_move(const Square origin_sq) const
{
const auto dest_sq = find_dest_square(
origin_sq,
{Direction::south, Direction::west}
);
// If the square south west of the pawn is within the boundaries of the
// board and is the en passant square, generate the en passant move.
if (dest_sq != Square::none && dest_sq == en_passant_square)
{
return create_en_passant_move(origin_sq, dest_sq);
}
else
{
return Move::none;
}
}
// Generates the 4 north-by-1 promotion moves using the origin square.
// Returns Move::none if the moves would not be pseudo-legal.
std::array<Move, 4> Game::pawn_promo_north_moves(
const Square origin_sq
) const
{
const auto dest_sq = north_of(origin_sq);
// If the pawn is on the 7th row and the square in front of it is not
// occupied, generate all non-capture promotion moves.
if (on_bitboard(origin_sq, row_7) && !is_occupied(dest_sq))
{
return create_promo_moves(origin_sq, dest_sq);
}
else
{
return {Move::none, Move::none, Move::none, Move::none};
}
}
// Generates the 4 south-by-1 promotion moves using the origin square.
// Returns Move::none if the moves would not be pseudo-legal.
std::array<Move, 4> Game::pawn_promo_south_moves(
const Square origin_sq
) const
{
const auto dest_sq = south_of(origin_sq);
// If the pawn is on the 2nd row and the square in front of it is not
// occupied, generate all non-capture promotion moves.
if (on_bitboard(origin_sq, row_2) && !is_occupied(dest_sq))
{
return create_promo_moves(origin_sq, dest_sq);
}
else
{
return {Move::none, Move::none, Move::none, Move::none};
}
}
// Generates the 4 north-east promotion capture moves using the origin
// square. Returns Move::none if the moves would not be pseudo-legal.
std::array<Move, 4> Game::pawn_promo_north_east_moves(
const Square origin_sq
) const
{
const auto dest_sq = north_of(east_of(origin_sq));
// If the pawn is on the 7th row and is not on the H column and there
// is a black piece on the square north east of the pawn's square,
// generate all promotion attack moves to that square.
if (on_bitboard(origin_sq, row_7 & ~col_h) &&
is_occupied(dest_sq, Color::black))
{
return create_promo_moves(origin_sq, dest_sq);
}
else
{
return {Move::none, Move::none, Move::none, Move::none};
}
}
// Generates the 4 south-east promotion capture moves using the origin
// square. Returns Move::none if the moves would not be pseudo-legal.
std::array<Move, 4> Game::pawn_promo_south_east_moves(
const Square origin_sq
) const
{
const auto dest_sq = south_of(east_of(origin_sq));
// If the pawn is on the 2nd row and is not on the H column and there
// is a white piece on the square south east of the pawn's square,
// generate all promotion attack moves to that square.
if (on_bitboard(origin_sq, row_2 & ~col_h) &&
is_occupied(dest_sq, Color::white))
{
return create_promo_moves(origin_sq, dest_sq);
}
else
{
return {Move::none, Move::none, Move::none, Move::none};
}
}
// Generates the 4 north-west promotion capture moves using the origin
// square. Returns Move::none if the moves would not be pseudo-legal.
std::array<Move, 4> Game::pawn_promo_north_west_moves(
const Square origin_sq
) const
{
const auto dest_sq = north_of(west_of(origin_sq));
// If the pawn is on the 7th row and is not on the A column and there is a
// black piece on the square north west of the pawn's square, generate all
// promotion attack moves to that square.
if (on_bitboard(origin_sq, row_7 & ~col_a) &&
is_occupied(dest_sq, Color::black))
{
return create_promo_moves(origin_sq, dest_sq);
}
else
{
return {Move::none, Move::none, Move::none, Move::none};
}
}
// Generates the 4 south-west promotion capture moves using the origin
// square. Returns Move::none if the moves would not be pseudo-legal.
std::array<Move, 4> Game::pawn_promo_south_west_moves(
const Square origin_sq
) const
{
const auto dest_sq = south_of(west_of(origin_sq));
// If the pawn is on the 2nd row and is not on the A column and there is a
// white piece on the square south west of the pawn's square, generate all
// promotion attack moves to that square.
if (on_bitboard(origin_sq, row_2 & ~col_a) &&
is_occupied(dest_sq, Color::white))
{
return create_promo_moves(origin_sq, dest_sq);
}
else
{
return {Move::none, Move::none, Move::none, Move::none};
}
}
// Generates the white kingside castling move as long as it has not been
// invalidated and no pieces are blocking it.
Move Game::white_kingside_castle_move(const Square origin_sq) const
{
// Make sure castling has not been invalidated and no pieces are blocking
// it.
if (!w_kingside_castling_invalidated() && !is_occupied(Square::F1) &&
!is_occupied(Square::G1))
{
return create_castling_move(origin_sq, Square::G1);
}
else
{
return Move::none;
}
}
// Generates the white queenside castling move as long as it has not been
// invalidated and no pieces are blocking it.
Move Game::white_queenside_castle_move(const Square origin_sq) const
{
// Make sure castling has not been invalidated and no pieces are blocking
// it.
if (!w_queenside_castling_invalidated() && !is_occupied(Square::D1) &&
!is_occupied(Square::C1) && !is_occupied(Square::B1))
{
return create_castling_move(origin_sq, Square::C1);
}
else
{
return Move::none;
}
}
// Generates the black kingside castling move as long as it has not been
// invalidated and no pieces are blocking it.
Move Game::black_kingside_castle_move(const Square origin_sq) const
{
// Make sure castling has not been invalidated and no pieces are blocking
// it.
if (!b_kingside_castling_invalidated() && !is_occupied(Square::F8) &&
!is_occupied(Square::G8))
{
return create_castling_move(origin_sq, Square::G8);
}
else
{
return Move::none;
}
}
// Generates the black queenside castling move as long as it has not been
// invalidated and no pieces are blocking it.
Move Game::black_queenside_castle_move(const Square origin_sq) const
{
// Make sure castling has not been invalidated and no pieces are blocking
// it.
if (!b_queenside_castling_invalidated() && !is_occupied(Square::D8) &&
!is_occupied(Square::C8) && !is_occupied(Square::B8))
{
return create_castling_move(origin_sq, Square::C8);
}
else
{
return Move::none;
}
}
// Generates all pseudo-legal moves for a white pawn that belongs to the
// player to move this turn.
std::vector<Move> Game::pseudo_legal_w_pawn_moves(const Square square) const
{
std::vector<Move> possible_moves;
// Generate non-capture moves.
possible_moves.push_back(pawn_north_move(square));
possible_moves.push_back(pawn_north_north_move(square));
// Generate capture moves.
possible_moves.push_back(pawn_north_east_move(square));
possible_moves.push_back(pawn_north_west_move(square));
// Generate en passant moves.
possible_moves.push_back(pawn_ep_north_east_move(square));
possible_moves.push_back(pawn_ep_north_west_move(square));
// Generate non-capture promotion moves.
const auto promo_north = pawn_promo_north_moves(square);
possible_moves.insert(
possible_moves.end(),
promo_north.begin(),
promo_north.end()
);
// Generate capture promotion moves.
const auto promo_north_east = pawn_promo_north_east_moves(square);
possible_moves.insert(
possible_moves.end(),
promo_north_east.begin(),
promo_north_east.end()
);
const auto promo_north_west = pawn_promo_north_west_moves(square);
possible_moves.insert(
possible_moves.end(),
promo_north_west.begin(),
promo_north_west.end()
);
// Remove invalid moves.
possible_moves.erase(
std::remove(
possible_moves.begin(),
possible_moves.end(),
Move::none
),
possible_moves.end()
);
return possible_moves;
}
// Generates all pseudo-legal moves for a black pawn that belongs to the
// player to move this turn.
std::vector<Move> Game::pseudo_legal_b_pawn_moves(const Square square) const
{
std::vector<Move> possible_moves;
// Generate non-capture moves.
possible_moves.push_back(pawn_south_move(square));
possible_moves.push_back(pawn_south_south_move(square));
// Generate capture moves.
possible_moves.push_back(pawn_south_east_move(square));
possible_moves.push_back(pawn_south_west_move(square));
// Generate en passant moves.
possible_moves.push_back(pawn_ep_south_east_move(square));
possible_moves.push_back(pawn_ep_south_west_move(square));
// Generate non-capture promotion moves.
const auto promo_south = pawn_promo_south_moves(square);
possible_moves.insert(
possible_moves.end(),
promo_south.begin(),
promo_south.end()
);
// Generate capture promotion moves.
const auto promo_south_east = pawn_promo_south_east_moves(square);
possible_moves.insert(
possible_moves.end(),
promo_south_east.begin(),
promo_south_east.end()
);
const auto promo_south_west = pawn_promo_south_west_moves(square);
possible_moves.insert(
possible_moves.end(),
promo_south_west.begin(),
promo_south_west.end()
);
// Remove invalid moves.
possible_moves.erase(
std::remove(
possible_moves.begin(),
possible_moves.end(),
Move::none
),
possible_moves.end()
);
return possible_moves;
}
// Generates all pseudo-legal knight moves for a knight that belongs to the
// player to move this turn.
std::vector<Move> Game::pseudo_legal_knight_moves(const Square square) const
{
std::vector<Move> possible_moves;
// North North East
possible_moves.push_back(pseudo_legal_normal_move(
square,
{Direction::north, Direction::north, Direction::east}
));
// North North West
possible_moves.push_back(pseudo_legal_normal_move(
square,
{Direction::north, Direction::north, Direction::west}
));
// North East East
possible_moves.push_back(pseudo_legal_normal_move(
square,
{Direction::north, Direction::east, Direction::east}
));
// North West West
possible_moves.push_back(pseudo_legal_normal_move(
square,
{Direction::north, Direction::west, Direction::west}
));
// South South East
possible_moves.push_back(pseudo_legal_normal_move(
square,
{Direction::south, Direction::south, Direction::east}
));
// South South West
possible_moves.push_back(pseudo_legal_normal_move(
square,
{Direction::south, Direction::south, Direction::west}
));
// South East East
possible_moves.push_back(pseudo_legal_normal_move(
square,
{Direction::south, Direction::east, Direction::east}
));
// South West West
possible_moves.push_back(pseudo_legal_normal_move(
square,
{Direction::south, Direction::west, Direction::west}
));
// Remove invalid moves.
possible_moves.erase(
std::remove(
possible_moves.begin(),
possible_moves.end(),
Move::none
),
possible_moves.end()
);
return possible_moves;
}
// Generates all pseudo-legal bishop moves for a bishop that belongs to the
// player to move this turn.
std::vector<Move> Game::pseudo_legal_bishop_moves(const Square square) const
{
// Use magic bitboards to generate the attack bitboard.
Bitboard attack_bitboard = Bmagic(
static_cast<unsigned>(square),
all_bitboard
);
// Discard self-captures.
attack_bitboard = discard_self_captures(attack_bitboard);
return gen_moves_from_bitboard(square, attack_bitboard);
}
// Generates all pseudo-legal rook moves for a rook that belongs to the
// player to move this turn. Castling does not count as a rook move.
std::vector<Move> Game::pseudo_legal_rook_moves(const Square square) const
{
// Use magic bitboards to generate the attack bitboard.
Bitboard attack_bitboard = Rmagic(
static_cast<unsigned>(square),
all_bitboard
);
// Discard self-captures.
attack_bitboard = discard_self_captures(attack_bitboard);
return gen_moves_from_bitboard(square, attack_bitboard);
}
// Generates all pseudo-legal queen moves for a queen that belongs to the
// player to move this turn.
std::vector<Move> Game::pseudo_legal_queen_moves(const Square square) const
{
// Use magic bitboards to generate the attack bitboard.
Bitboard bishop_attack_bitboard = Bmagic(
static_cast<unsigned>(square),
all_bitboard
);
Bitboard rook_attack_bitboard = Rmagic(
static_cast<unsigned>(square),
all_bitboard
);
auto attack_bitboard = bishop_attack_bitboard | rook_attack_bitboard;
// Discard self-captures.
attack_bitboard = discard_self_captures(attack_bitboard);
return gen_moves_from_bitboard(square, attack_bitboard);
}
// Generates all pseudo-legal king moves for the king that belongs to the
// player to move this turn.
std::vector<Move> Game::pseudo_legal_king_moves(const Square square) const
{
std::vector<Move> possible_moves;
// Normal moves
// North
possible_moves.push_back(pseudo_legal_normal_move(
square,
{Direction::north}
));
// North East
possible_moves.push_back(pseudo_legal_normal_move(
square,
{Direction::north, Direction::east}
));
// East
possible_moves.push_back(pseudo_legal_normal_move(
square,
{Direction::east}
));
// South East
possible_moves.push_back(pseudo_legal_normal_move(
square,
{Direction::south, Direction::east}
));
// South
possible_moves.push_back(pseudo_legal_normal_move(
square,
{Direction::south}
));
// South West
possible_moves.push_back(pseudo_legal_normal_move(
square,
{Direction::south, Direction::west}
));
// West
possible_moves.push_back(pseudo_legal_normal_move(
square,
{Direction::west}
));
// North West
possible_moves.push_back(pseudo_legal_normal_move(
square,
{Direction::north, Direction::west}
));
// Castling moves
if (turn == Color::white)
{
possible_moves.push_back(white_kingside_castle_move(square));
possible_moves.push_back(white_queenside_castle_move(square));
}
else
{
possible_moves.push_back(black_kingside_castle_move(square));
possible_moves.push_back(black_queenside_castle_move(square));
}
// Remove invalid moves.
possible_moves.erase(
std::remove(
possible_moves.begin(),
possible_moves.end(),
Move::none
),
possible_moves.end()
);
return possible_moves;
}
| 30.09865 | 79 | 0.628083 | [
"vector"
] |
d580669b7ff154bd1e3c7ad402389ba687a077fb | 14,983 | hpp | C++ | Source/AllProjects/CQCWebSrv/Client/CQCWebSrvC_EchoHandler_.hpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 51 | 2020-12-26T18:17:16.000Z | 2022-03-15T04:29:35.000Z | Source/AllProjects/CQCWebSrv/Client/CQCWebSrvC_EchoHandler_.hpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | null | null | null | Source/AllProjects/CQCWebSrv/Client/CQCWebSrvC_EchoHandler_.hpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 4 | 2020-12-28T07:24:39.000Z | 2021-12-29T12:09:37.000Z | //
// FILE NAME: CQCWebSrvC_EchoHandler_.hpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 07/25/2015
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2020
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This is the header for the CQCWebSrv_EchoHandler.cpp file, which implements
// a specialized handler for the URL that is sent by the javascript that we provide
// for folks to install on the Amazon web server to handle Echo voice input. We
// watch for the special URL in the worker thread that is servicing incoming
// requests. If it sees that URL, it will pass it to this handler.
//
// We expect it to be a POST, with a JSON body. We parse out the JSON body to
// decide what needs to be done. That is determined by a configuration file we
// read in upon first access. We take the incoming info and use that to find the
// appropriating mapping in the file. That tells us what to do.
//
// The msg types we get are:
//
// The messages look like this:
//
// {
// MyKey : a unique key for security reasons,
// Type : RunAction | SetValue,
// Name : name of the action to run or value to set,
// Value : if applicable, the value to use
// }
//
// So we only have a couple of options, driven by the Type value. Currently we can
// run an action (global action or macro, depending on how the config file maps it)
// or set a value, which also runs a global action or macro, but passes in a value
// to it.
//
// The file is very simple, line oriented, and looks like this:
//
// EchoConfig=
// MyKey=xxxx [,xxx,...]
// EndEchoConfig
//
// RunMap
// Action=\User\Echo\Home Theater
// Home Theater, Theater
// EndAction
// EndRunMap
//
// SetMap
// Macro=\User\Echo\Set
// Volume
// Scene
// Channel
// EndMacro
// EndSetMap
//
// QueryMap
// Macro=\User\Echo\Query
// Current Channel, Channel
// Temperature, Current Temperature, Current Temp
// EndMacro
// EndQueryMap
//
// The reply format is also JSON and is currently just:
//
// {
// Reply : the reply text to speak
// }
//
// A 100 (Continue) status return means that more info is needed and so the reply
// text is a query to get more info from the user. For any other code the implication
// is that the session is ended.
//
// Note that there can be more than one key, because this handler may be invoked by more
// than one Echo, and this is used to allow the handler to distinguish which it is. For now
// they have to create multiple skills, each with a different key. Later, if the Echo provides
// a per-device id, that can be used.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
#pragma once
#pragma CIDLIB_PACK(CIDLIBPACK)
// ---------------------------------------------------------------------------
// CLASS: TWSEchoCfgBlock
// PREFIX: wsecb
// ---------------------------------------------------------------------------
class TWSEchoCfgBlock
{
public :
// --------------------------------------------------------------------
// Constructors and Destructor
// --------------------------------------------------------------------
TWSEchoCfgBlock();
TWSEchoCfgBlock
(
const TWSEchoCfgBlock& wsecbSrc
);
TWSEchoCfgBlock(TWSEchoCfgBlock&&) = delete;
~TWSEchoCfgBlock();
// --------------------------------------------------------------------
// Public operators
// --------------------------------------------------------------------
TWSEchoCfgBlock& operator=
(
const TWSEchoCfgBlock& wsecbSrc
);
TWSEchoCfgBlock& operator&(const TWSEchoCfgBlock&) = delete;
TWSEchoCfgBlock& operator&(TWSEchoCfgBlock&&) = delete;
// --------------------------------------------------------------------
// Public, non-virtual methods
// --------------------------------------------------------------------
tCIDLib::TVoid AddPhraseList
(
const tCIDLib::TStrList& colToAdd
);
tCIDLib::TBoolean bMatches
(
const TString& strCheck
, TString& strPhraseFound
) const;
tCIDLib::TBoolean bIsMacro() const;
const TString& strPath() const;
tCIDLib::TVoid Set
(
const tCIDLib::TBoolean bIsMacro
, const TString& strPath
);
private :
// --------------------------------------------------------------------
// Private data types
// --------------------------------------------------------------------
using TPhraseMap = TVector<tCIDLib::TStrList>;
// --------------------------------------------------------------------
// Private data members
//
// m_bIsMacro
// Indicates if this one is a macro or action based.
//
// m_colPhrases
// The phrases that can be matched for this block. It's a list of lists
// though often they have a single value. The first one in each list
// is the one passed to the user's handler.
//
// m_strPath
// The path to the global action or macro to run.
// --------------------------------------------------------------------
tCIDLib::TBoolean m_bIsMacro;
TPhraseMap m_colPhrases;
TString m_strPath;
};
// ---------------------------------------------------------------------------
// CLASS: TWSEchoCfg
// PREFIX: wsec
// ---------------------------------------------------------------------------
class TWSEchoCfg
{
public :
// --------------------------------------------------------------------
// Constructors and Destructor
// --------------------------------------------------------------------
TWSEchoCfg();
TWSEchoCfg(const TWSEchoCfg&) = delete;
TWSEchoCfg(TWSEchoCfg&&) = delete;
~TWSEchoCfg();
// --------------------------------------------------------------------
// Public operators
// --------------------------------------------------------------------
TWSEchoCfg& operator=(const TWSEchoCfg&) = delete;
TWSEchoCfg& operator=(TWSEchoCfg&&) = delete;
// --------------------------------------------------------------------
// Public, non-virtual methods
// --------------------------------------------------------------------
tCIDLib::TBoolean bCheckKey
(
const TString& strToCheck
) const;
tCIDLib::TBoolean bLoaded() const;
tCIDLib::TBoolean bLoadMaps
(
const tCIDLib::TBoolean bForce
);
tCIDLib::TBoolean bMapPhrase
(
const TString& strIntentType
, const TString& strPhraseWeGot
, TString& strPreferredPhrase
, TString& strPath
, tCIDLib::TBoolean& bIsMacro
) const;
private :
// --------------------------------------------------------------------
// Private data members
// --------------------------------------------------------------------
using TCfgMap = TVector<TWSEchoCfgBlock>;
// --------------------------------------------------------------------
// Private, non-virtual methods
// --------------------------------------------------------------------
tCIDLib::TBoolean bCheckLine
(
TTextInStream& strmSrc
, const TString& strToCheck
);
tCIDLib::TBoolean bReadLine
(
TTextInStream& strmSrc
, TString& strToFill
, const tCIDLib::TBoolean bEndOK
);
tCIDLib::TVoid CheckKey
(
TTextInStream& strmSrc
, const TString& strToCheck
, TString& strValue
, const tCIDLib::TBoolean bEmptyOk
);
tCIDLib::TVoid CheckKey2
(
TTextInStream& strmSrc
, const TString& strToCheck1
, const TString& strToCheck2
, TString& strKey
, TString& strValue
, const tCIDLib::TBoolean bEmptyOk
);
tCIDLib::TVoid CheckLine
(
TTextInStream& strmSrc
, const TString& strToCheck
);
tCIDLib::TVoid LoadMap
(
TTextInStream& strmSrc
, TCfgMap& colToFill
, tCIDLib::TStrList& colTmpList
, const TString& strMapName
);
tCIDLib::TVoid Reset();
// --------------------------------------------------------------------
// Private data members
//
// m_bMapLoaded
// We fault in our mapping file upon first need, so as to avoid
// doing work that will never be used.
//
// m_c4LineNum
// For use during parsing of the config file.
//
// m_colKeys
// The keys from the file, which we expect to see in incoming msgs from
// the Echo server.
//
// m_colQueryMap
// m_colRunMap
// m_colSetMap
// We have a map for each of the major types of requests from the Echo
// server.
//
// m_mtxSync
// We have to sync access this object.
//
// m_strPushback
// For use during parsing of the config file.
// --------------------------------------------------------------------
tCIDLib::TBoolean m_bMapLoaded;
tCIDLib::TCard4 m_c4LineNum;
tCIDLib::TStrList m_colKeys;
TCfgMap m_colQueryMap;
TCfgMap m_colRunMap;
TCfgMap m_colSetMap;
TMutex m_mtxSync;
TString m_strPushback;
};
// ---------------------------------------------------------------------------
// CLASS: TWSEchoHandler
// PREFIX: urlh
// ---------------------------------------------------------------------------
class TWSEchoHandler : public TWSURLHandler
{
public :
// --------------------------------------------------------------------
// Constructors and Destructor
// --------------------------------------------------------------------
TWSEchoHandler();
TWSEchoHandler(const TWSEchoHandler&) = delete;
TWSEchoHandler(TWSEchoHandler&&) = delete;
~TWSEchoHandler();
// --------------------------------------------------------------------
// Public operators
// --------------------------------------------------------------------
TWSEchoHandler& operator=(const TWSEchoHandler&) = delete;
TWSEchoHandler& operator=(TWSEchoHandler&&) = delete;
// --------------------------------------------------------------------
// Public, inherited methods
// --------------------------------------------------------------------
tCIDLib::TCard4 c4ProcessURL
(
const TURL& urlReq
, const TString& strType
, const tCIDLib::TKVPList& colInHdrLines
, tCIDLib::TKVPList& colOutHdrLines
, const tCIDLib::TKVPList& colPQVals
, const TString& strEncoding
, const TString& strBoundary
, THeapBuf& mbufToFill
, tCIDLib::TCard4& c4ContLen
, TString& strContType
, TString& strRepText
) final;
private :
// --------------------------------------------------------------------
// Private, non-virtual methods
// --------------------------------------------------------------------
tCIDLib::TBoolean bDoEchoOp
(
const TString& strIntentType
, const TString& strReportPhrase
, const TString& strPath
, const tCIDLib::TBoolean bIsMacro
, const TString& strEchoValue
, const TString& strEchoKey
, TString& strRepText
);
tCIDLib::TCard4 c4MakeReply
(
const TString& strText
, TMemBuf& mbufToFill
);
// --------------------------------------------------------------------
// Private data members
//
// m_ctarGlobalVars
// We need a global variables object to pass in when doing actions. There
// is no actual carryover, they are reset each time. And we don't need it
// to be thread safe.
//
// m_jprsData
// A JSON parser to parse out the incmoing data from the Amazon
// server.
// --------------------------------------------------------------------
TStdVarsTar m_ctarGlobalVars;
TJSONParser m_jprsComm;
// --------------------------------------------------------------------
// Private static methods
//
// s_wsecMaps
// This is the mapping configuration that we load from the config file. It's
// a static object because it must be shared among all echo handler instances.
// Each thread creates its own handlers, but we need to have a single shared
// loaded configuration.
// --------------------------------------------------------------------
static TWSEchoCfg s_wsecMaps;
// --------------------------------------------------------------------
// Magic macros
// --------------------------------------------------------------------
RTTIDefs(TWSEchoHandler,TWSURLHandler)
};
#pragma CIDLIB_POPPACK
| 34.763341 | 95 | 0.412067 | [
"object"
] |
d58740d5a74768041cfef27e632ff7deccc9e3dd | 13,584 | hpp | C++ | src/hotspot/cpu/ppc/interp_masm_ppc.hpp | siweilxy/openjdkstudy | 8597674ec1d6809faf55cbee1f45f4e9149d670d | [
"Apache-2.0"
] | null | null | null | src/hotspot/cpu/ppc/interp_masm_ppc.hpp | siweilxy/openjdkstudy | 8597674ec1d6809faf55cbee1f45f4e9149d670d | [
"Apache-2.0"
] | null | null | null | src/hotspot/cpu/ppc/interp_masm_ppc.hpp | siweilxy/openjdkstudy | 8597674ec1d6809faf55cbee1f45f4e9149d670d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, 2017 SAP SE. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef CPU_PPC_INTERP_MASM_PPC_HPP
#define CPU_PPC_INTERP_MASM_PPC_HPP
#include "asm/macroAssembler.hpp"
#include "interpreter/invocationCounter.hpp"
// This file specializes the assembler with interpreter-specific macros.
class InterpreterMacroAssembler: public MacroAssembler {
public:
InterpreterMacroAssembler(CodeBuffer* code) : MacroAssembler(code) {}
void null_check_throw(Register a, int offset, Register temp_reg);
void jump_to_entry(address entry, Register Rscratch);
// Handy address generation macros.
#define thread_(field_name) in_bytes(JavaThread::field_name ## _offset()), R16_thread
#define method_(field_name) in_bytes(Method::field_name ## _offset()), R19_method
virtual void check_and_handle_popframe(Register scratch_reg);
virtual void check_and_handle_earlyret(Register scratch_reg);
// Base routine for all dispatches.
void dispatch_base(TosState state, address* table);
void load_earlyret_value(TosState state, Register Rscratch1);
static const Address l_tmp;
static const Address d_tmp;
// dispatch routines
void dispatch_next(TosState state, int step = 0, bool generate_poll = false);
void dispatch_via (TosState state, address* table);
void load_dispatch_table(Register dst, address* table);
void dispatch_Lbyte_code(TosState state, Register bytecode, address* table, bool generate_poll = false);
// Called by shared interpreter generator.
void dispatch_prolog(TosState state, int step = 0);
void dispatch_epilog(TosState state, int step = 0);
// Super call_VM calls - correspond to MacroAssembler::call_VM(_leaf) calls.
void super_call_VM_leaf(Register thread_cache, address entry_point, Register arg_1);
void super_call_VM(Register thread_cache, Register oop_result, Register last_java_sp,
address entry_point, Register arg_1, Register arg_2, bool check_exception = true);
// Generate a subtype check: branch to ok_is_subtype if sub_klass is
// a subtype of super_klass. Blows registers tmp1, tmp2 and tmp3.
void gen_subtype_check(Register sub_klass, Register super_klass,
Register tmp1, Register tmp2, Register tmp3, Label &ok_is_subtype);
// Load object from cpool->resolved_references(index).
void load_resolved_reference_at_index(Register result, Register index, Label *L_handle_null = NULL);
// load cpool->resolved_klass_at(index)
void load_resolved_klass_at_offset(Register Rcpool, Register Roffset, Register Rklass);
void load_resolved_method_at_index(int byte_no, Register cache, Register method);
void load_receiver(Register Rparam_count, Register Rrecv_dst);
// helpers for expression stack
void pop_i( Register r = R17_tos);
void pop_ptr( Register r = R17_tos);
void pop_l( Register r = R17_tos);
void pop_f(FloatRegister f = F15_ftos);
void pop_d(FloatRegister f = F15_ftos );
void push_i( Register r = R17_tos);
void push_ptr( Register r = R17_tos);
void push_l( Register r = R17_tos);
void push_f(FloatRegister f = F15_ftos );
void push_d(FloatRegister f = F15_ftos);
void push_2ptrs(Register first, Register second);
void move_l_to_d(Register l = R17_tos, FloatRegister d = F15_ftos);
void move_d_to_l(FloatRegister d = F15_ftos, Register l = R17_tos);
void pop (TosState state); // transition vtos -> state
void push(TosState state); // transition state -> vtos
void empty_expression_stack(); // Resets both Lesp and SP.
public:
// Load values from bytecode stream:
enum signedOrNot { Signed, Unsigned };
enum setCCOrNot { set_CC, dont_set_CC };
void get_2_byte_integer_at_bcp(int bcp_offset,
Register Rdst,
signedOrNot is_signed);
void get_4_byte_integer_at_bcp(int bcp_offset,
Register Rdst,
signedOrNot is_signed = Unsigned);
void get_cache_index_at_bcp(Register Rdst, int bcp_offset, size_t index_size);
void get_cache_and_index_at_bcp(Register cache, int bcp_offset, size_t index_size = sizeof(u2));
void get_u4(Register Rdst, Register Rsrc, int offset, signedOrNot is_signed);
// common code
void field_offset_at(int n, Register tmp, Register dest, Register base);
int field_offset_at(Register object, address bcp, int offset);
void fast_iaaccess(int n, address bcp);
void fast_iaputfield(address bcp, bool do_store_check);
void index_check(Register array, Register index, int index_shift, Register tmp, Register res);
void index_check_without_pop(Register array, Register index, int index_shift, Register tmp, Register res);
void get_const(Register Rdst);
void get_constant_pool(Register Rdst);
void get_constant_pool_cache(Register Rdst);
void get_cpool_and_tags(Register Rcpool, Register Rtags);
void is_a(Label& L);
void narrow(Register result);
// Java Call Helpers
void call_from_interpreter(Register Rtarget_method, Register Rret_addr, Register Rscratch1, Register Rscratch2);
// --------------------------------------------------
void unlock_if_synchronized_method(TosState state, bool throw_monitor_exception = true,
bool install_monitor_exception = true);
// Removes the current activation (incl. unlocking of monitors).
// Additionally this code is used for earlyReturn in which case we
// want to skip throwing an exception and installing an exception.
void remove_activation(TosState state,
bool throw_monitor_exception = true,
bool install_monitor_exception = true);
void merge_frames(Register Rtop_frame_sp, Register return_pc, Register Rscratch1, Register Rscratch2); // merge top frames
void add_monitor_to_stack(bool stack_is_empty, Register Rtemp1, Register Rtemp2);
// Local variable access helpers
void load_local_int(Register Rdst_value, Register Rdst_address, Register Rindex);
void load_local_long(Register Rdst_value, Register Rdst_address, Register Rindex);
void load_local_ptr(Register Rdst_value, Register Rdst_address, Register Rindex);
void load_local_float(FloatRegister Rdst_value, Register Rdst_address, Register Rindex);
void load_local_double(FloatRegister Rdst_value, Register Rdst_address, Register Rindex);
void store_local_int(Register Rvalue, Register Rindex);
void store_local_long(Register Rvalue, Register Rindex);
void store_local_ptr(Register Rvalue, Register Rindex);
void store_local_float(FloatRegister Rvalue, Register Rindex);
void store_local_double(FloatRegister Rvalue, Register Rindex);
// Call VM for std frames
// Special call VM versions that check for exceptions and forward exception
// via short cut (not via expensive forward exception stub).
void check_and_forward_exception(Register Rscratch1, Register Rscratch2);
void call_VM(Register oop_result, address entry_point, bool check_exceptions = true);
void call_VM(Register oop_result, address entry_point, Register arg_1, bool check_exceptions = true);
void call_VM(Register oop_result, address entry_point, Register arg_1, Register arg_2, bool check_exceptions = true);
void call_VM(Register oop_result, address entry_point, Register arg_1, Register arg_2, Register arg_3, bool check_exceptions = true);
// Should not be used:
void call_VM(Register oop_result, Register last_java_sp, address entry_point, bool check_exceptions = true) {ShouldNotReachHere();}
void call_VM(Register oop_result, Register last_java_sp, address entry_point, Register arg_1, bool check_exceptions = true) {ShouldNotReachHere();}
void call_VM(Register oop_result, Register last_java_sp, address entry_point, Register arg_1, Register arg_2, bool check_exceptions = true) {ShouldNotReachHere();}
void call_VM(Register oop_result, Register last_java_sp, address entry_point, Register arg_1, Register arg_2, Register arg_3, bool check_exceptions = true) {ShouldNotReachHere();}
Address first_local_in_stack();
enum LoadOrStore { load, store };
void static_iload_or_store(int which_local, LoadOrStore direction, Register Rtmp);
void static_aload_or_store(int which_local, LoadOrStore direction, Register Rtmp);
void static_dload_or_store(int which_local, LoadOrStore direction);
void save_interpreter_state(Register scratch);
void restore_interpreter_state(Register scratch, bool bcp_and_mdx_only = false);
void increment_backedge_counter(const Register Rcounters, Register Rtmp, Register Rtmp2, Register Rscratch);
void test_backedge_count_for_osr(Register backedge_count, Register method_counters, Register target_bcp, Register disp, Register Rtmp);
void record_static_call_in_profile(Register Rentry, Register Rtmp);
void record_receiver_call_in_profile(Register Rklass, Register Rentry, Register Rtmp);
void get_method_counters(Register method, Register Rcounters, Label& skip);
void increment_invocation_counter(Register iv_be_count, Register Rtmp1, Register Rtmp2_r0);
// Object locking
void lock_object (Register lock_reg, Register obj_reg);
void unlock_object(Register lock_reg, bool check_for_exceptions = true);
// Interpreter profiling operations
void set_method_data_pointer_for_bcp();
void test_method_data_pointer(Label& zero_continue);
void verify_method_data_pointer();
void test_invocation_counter_for_mdp(Register invocation_count, Register method_counters, Register Rscratch, Label &profile_continue);
void set_mdp_data_at(int constant, Register value);
void increment_mdp_data_at(int constant, Register counter_addr, Register Rbumped_count, bool decrement = false);
void increment_mdp_data_at(Register counter_addr, Register Rbumped_count, bool decrement = false);
void increment_mdp_data_at(Register reg, int constant, Register scratch, Register Rbumped_count, bool decrement = false);
void set_mdp_flag_at(int flag_constant, Register scratch);
void test_mdp_data_at(int offset, Register value, Label& not_equal_continue, Register test_out);
void update_mdp_by_offset(int offset_of_disp, Register scratch);
void update_mdp_by_offset(Register reg, int offset_of_disp,
Register scratch);
void update_mdp_by_constant(int constant);
void update_mdp_for_ret(TosState state, Register return_bci);
void profile_taken_branch(Register scratch, Register bumped_count);
void profile_not_taken_branch(Register scratch1, Register scratch2);
void profile_call(Register scratch1, Register scratch2);
void profile_final_call(Register scratch1, Register scratch2);
void profile_virtual_call(Register Rreceiver, Register Rscratch1, Register Rscratch2, bool receiver_can_be_null);
void profile_typecheck(Register Rklass, Register Rscratch1, Register Rscratch2);
void profile_typecheck_failed(Register Rscratch1, Register Rscratch2);
void profile_ret(TosState state, Register return_bci, Register scratch1, Register scratch2);
void profile_switch_default(Register scratch1, Register scratch2);
void profile_switch_case(Register index, Register scratch1,Register scratch2, Register scratch3);
void profile_null_seen(Register Rscratch1, Register Rscratch2);
void record_klass_in_profile(Register receiver, Register scratch1, Register scratch2, bool is_virtual_call);
void record_klass_in_profile_helper(Register receiver, Register scratch1, Register scratch2, int start_row, Label& done, bool is_virtual_call);
// Argument and return type profiling.
void profile_obj_type(Register obj, Register mdo_addr_base, RegisterOrConstant mdo_addr_offs, Register tmp, Register tmp2);
void profile_arguments_type(Register callee, Register tmp1, Register tmp2, bool is_virtual);
void profile_return_type(Register ret, Register tmp1, Register tmp2);
void profile_parameters_type(Register tmp1, Register tmp2, Register tmp3, Register tmp4);
// Debugging
void verify_oop(Register reg, TosState state = atos); // only if +VerifyOops && state == atos
void verify_oop_or_return_address(Register reg, Register rtmp); // for astore
void verify_FPU(int stack_depth, TosState state = ftos);
typedef enum { NotifyJVMTI, SkipNotifyJVMTI } NotifyMethodExitMode;
// Support for jvmdi/jvmpi.
void notify_method_entry();
void notify_method_exit(bool is_native_method, TosState state,
NotifyMethodExitMode mode, bool check_exceptions);
};
#endif // CPU_PPC_INTERP_MASM_PPC_HPP
| 49.941176 | 181 | 0.769067 | [
"object"
] |
d58e40a0407b534aeea56825d0a0841308054404 | 13,763 | cp | C++ | Plug-ins/vCardAdbkIO/sources/CVCard.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 5 | 2015-03-23T13:45:09.000Z | 2021-11-06T08:37:42.000Z | Plug-ins/vCardAdbkIO/sources/CVCard.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | Plug-ins/vCardAdbkIO/sources/CVCard.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2021-03-27T09:10:59.000Z | 2022-01-19T12:12:48.000Z | /*
Copyright (c) 2007-2009 Cyrus Daboo. 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.
*/
// CVCard.cp
//
// Copyright 2006, Cyrus Daboo. All Rights Reserved.
//
// Created: 03-Aug-2002
// Author: Cyrus Daboo
// Platforms: Mac OS, Win32, Unix
//
// Description:
// This class implements a vCard object.
//
// History:
// 03-Aug-2002: Created initial header and implementation.
//
#include "CVCard.h"
#include "CStringUtils.h"
#include "quotedprintable.h"
#include <algorithm>
#include <strstream>
CVCardItem& CVCard::AddItem(const cdstring& name, const cdstring& value)
{
CVCardItems::iterator item = mItems.insert(CVCardItems::value_type(name, CVCardItem(value)));
return (*item).second;
}
void CVCard::AddItem(const cdstring& name, const CVCardItem& item)
{
mItems.insert(CVCardItems::value_type(name, item));
}
unsigned long CVCard::CountItems(const cdstring& name)
{
return mItems.count(name);
}
const cdstring& CVCard::GetValue(const cdstring& name)
{
CVCardItems::const_iterator found = mItems.find(name);
if (found != mItems.end())
return (*found).second.GetValue();
else
return cdstring::null_str;
}
unsigned long CVCard::CountItems(const cdstring& name, const cdstring& param_name, const cdstring& param_value)
{
unsigned long ctr = 0;
std::pair<CVCardItems::const_iterator, CVCardItems::const_iterator> iters1 = mItems.equal_range(name);
for(CVCardItems::const_iterator iter1 = iters1.first; iter1 != iters1.second; iter1++)
{
pair<cdstrmultimap::const_iterator, cdstrmultimap::const_iterator> iters2 = (*iter1).second.GetParams().equal_range(param_name);
for(cdstrmultimap::const_iterator iter2 = iters2.first; iter2 != iters2.second; iter2++)
{
if (!::strcmpnocase(param_value, (*iter2).second))
ctr++;
}
}
return ctr;
}
const cdstring& CVCard::GetValue(const cdstring& name, const cdstring& param_name, const cdstring& param_value)
{
std::pair<CVCardItems::const_iterator, CVCardItems::const_iterator> iters1 = mItems.equal_range(name);
for(CVCardItems::const_iterator iter1 = iters1.first; iter1 != iters1.second; iter1++)
{
pair<cdstrmultimap::const_iterator, cdstrmultimap::const_iterator> iters2 = (*iter1).second.GetParams().equal_range(param_name);
for(cdstrmultimap::const_iterator iter2 = iters2.first; iter2 != iters2.second; iter2++)
{
if (!::strcmpnocase(param_value, (*iter2).second))
return (*iter1).second.GetValue();
}
}
return cdstring::null_str;
}
unsigned long CVCard::CountItems(const cdstring& name, const cdstrmap& params)
{
unsigned long ctr = 0;
std::pair<CVCardItems::const_iterator, CVCardItems::const_iterator> iters1 = mItems.equal_range(name);
for(CVCardItems::const_iterator iter1 = iters1.first; iter1 != iters1.second; iter1++)
{
for(cdstrmap::const_iterator iter2 = params.begin(); iter2 != params.end(); iter2++)
{
pair<cdstrmultimap::const_iterator, cdstrmultimap::const_iterator> iters3 = (*iter1).second.GetParams().equal_range((*iter2).first);
for(cdstrmultimap::const_iterator iter3 = iters3.first; iter3 != iters3.second; iter3++)
{
if (!::strcmpnocase((*iter2).second, (*iter3).second))
ctr++;
}
}
}
return ctr;
}
const cdstring& CVCard::GetValue(const cdstring& name, const cdstrmap& params)
{
std::pair<CVCardItems::const_iterator, CVCardItems::const_iterator> iters1 = mItems.equal_range(name);
for(CVCardItems::const_iterator iter1 = iters1.first; iter1 != iters1.second; iter1++)
{
bool foundall = true;
for(cdstrmap::const_iterator iter2 = params.begin(); iter2 != params.end(); iter2++)
{
bool found_param = false;
pair<cdstrmultimap::const_iterator, cdstrmultimap::const_iterator> iters3 = (*iter1).second.GetParams().equal_range((*iter2).first);
for(cdstrmultimap::const_iterator iter3 = iters3.first; iter3 != iters3.second; iter3++)
{
if (!::strcmpnocase((*iter2).second, (*iter3).second))
{
found_param = true;
break;
}
}
if (!found_param)
{
foundall = false;
break;
}
}
if (foundall)
return (*iter1).second.GetValue();
}
return cdstring::null_str;
}
// Read a single vCard address from the input stream
bool CVCard::Read(istream& in)
{
// Read lines looking for starting line
cdstring line;
while(true)
{
// Get line and trim out whitespace
::getline(in, line, 0);
if (in.fail())
return false;
line.trimspace();
// Look for begin item
bool old_version = true;
if (!::strcmpnocase(line, "BEGIN:VCARD"))
{
// vCard allows for folding of long lines
// Use this to accumulate folded lines into one
cdstring unfoldedline;
// Loop until end
while(true)
{
// Get next line
::getline(in, line, 0);
if (in.fail())
return false;
// Look for fold
if (line.length() && isspace(line[(cdstring::size_type)0]))
{
// Add to existing line
unfoldedline += &line[(cdstring::size_type)1];
// Continue with loop
continue;
}
// Look for existing line that now needs to be processed
else if (unfoldedline.length())
{
ReadItem(unfoldedline, old_version);
}
// Just copy the new line into fold
unfoldedline = line;
// Look for end item and break out of loop
line.trimspace();
if (!::strcmpnocase(line, "END:VCARD"))
break;
if (!::strcmpnocase(line, "VERSION:3.0"))
old_version = false;
}
// Done with outer loop
break;
}
}
return true;
}
// Write a single vCard address to the output stream
void CVCard::Write(std::ostream& out)
{
out << os_endl;
out << "BEGIN:VCARD" << os_endl;
out << "VERSION:3.0" << os_endl;
// Output the FN item first - must exist
std::pair<CVCardItems::const_iterator, CVCardItems::const_iterator> iters = mItems.equal_range("FN");
for(CVCardItems::const_iterator iter = iters.first; iter != iters.second; iter++)
WriteItem(out, (*iter).first, (*iter).second);
// Output the N item first - must exist
iters = mItems.equal_range("N");
for(CVCardItems::const_iterator iter = iters.first; iter != iters.second; iter++)
WriteItem(out, (*iter).first, (*iter).second);
// Output remaining items in multimap order
for(CVCardItems::const_iterator iter = mItems.begin(); iter != mItems.end(); iter++)
{
if (((*iter).first != "FN") && ((*iter).first != "N"))
WriteItem(out, (*iter).first, (*iter).second);
}
out << "END:VCARD" << os_endl;
}
// Read a single vCard item into an address
void CVCard::ReadItem(cdstring& str, bool old_version)
{
const char* p = str.c_str();
const char* q = p;
// Look for name
while(*p && (*p != ';') && (*p != ':')) p++;
if (!*p)
return;
// Get the name
cdstring name(q, p - q);
name.trimspace();
// See if parameters follow
CVCardItem item;
if (*p == ';')
{
// Loop over each parameter
while(true)
{
// Read param in one blob
q = ++p;
// v2.1 allows TYPE= to be omitted
// v3.0 requires all parameters to be named
cdstring param_name;
if (old_version)
{
// Look for '=', ',', ';' or ':'
while(*p && (*p != '=') && (*p != ',') && (*p != ';') && (*p != ':')) p++;
if (!*p)
return;
// If '=' we have a parameter name
if (*p == '=')
// Grab the parameter name
param_name.assign(q, p - q);
else
{
// Implicit 'TYPE=' parameter
param_name = "TYPE";
// Move p back to q - 1 so that it will bump back to the param value
p = q - 1;
}
}
else
{
// Look for '='
while(*p && (*p != '=')) p++;
if (!*p)
return;
// Grab the parameter name
param_name.assign(q, p - q);
}
// Loop over values
while(true)
{
// Look for values
q = ++p;
if (*q == '"')
{
while(*p && (*p != '"')) p++;
if (!*p)
return;
}
else
{
while(*p && (*p != ',') && (*p != ';') && (*p != ':')) p++;
if (!*p)
return;
}
// Get the value
cdstring param_value(q, p - q);
if (*p == '"')
p++;
// Add to map
item.AddParam(param_name, param_value);
// Continue with loop only if another param-value
if (*p != ',')
break;
}
// Continue with loop only if another param
if (*p != ';')
break;
}
}
// Must be ':'
if (*p != ':')
return;
p++;
// Remainder is the value
cdstring value(p);
cdstring decoded;
if (!::strcmpnocase(name, "ADR"))
decoded = DecodeTextAddrValue(value);
else if (!::strcmpnocase(name, "N"))
decoded = DecodeTextNValue(value);
else
decoded = DecodeTextValue(value);
// For v2.1 might have q-p encoding
if (old_version && ::count(item.GetParams().begin(), item.GetParams().end(), cdstrmultimap::value_type("TYPE", "QUOTED-PRINTABLE")))
{
::qp_decode(decoded.c_str_mod());
::FilterEndls(decoded.c_str_mod());
}
item.SetValue(decoded);
// Add the item
AddItem(name, item);
}
const char* cParamSpecials = ";,:";
void CVCard::WriteItem(std::ostream& out, const cdstring& name, const CVCardItem& item)
{
// We need to fold lines so write into temp output stream first
std::ostrstream tout;
// Output the name
tout << name;
// Output each parameter accumulating multiple into comma list
cdstring last_param;
for(cdstrmultimap::const_iterator iter = item.GetParams().begin(); iter != item.GetParams().end(); iter++)
{
// Is it the same as the last one
if ((*iter).first == last_param)
{
// Comma separate list of param-values
tout << ',';
}
else
{
// New parameter
last_param = (*iter).first;
tout << ';' << last_param << '=';
}
// Look for param specials
if (::strpbrk((*iter).second, cParamSpecials))
{
// Quote it
tout << '"' << (*iter).second << '"';
}
else
tout << (*iter).second;
}
// Output encoded value
tout << ':';
if (!::strcmpnocase(name, "ADR"))
tout << EncodeTextAddrValue(item.GetValue());
else if (!::strcmpnocase(name, "N"))
tout << EncodeTextNValue(item.GetValue());
else
tout << EncodeTextValue(item.GetValue());
tout << os_endl << ends;
// Put into string
cdstring result;
result.steal(tout.str());
// Fold it
// Write to real output stream
out << result;
}
#pragma mark ____________________________text-value
// text-value - utf8/escaped
cdstring CVCard::DecodeTextValue(const cdstring& str)
{
// Escape it
std::ostrstream out;
const char* p = str.c_str();
while(*p)
{
switch(*p)
{
case '\\':
p++;
switch(*p)
{
case '\\':
case ';':
case ',':
out << *p++;
break;
case 'N':
case 'n':
// Always output \n
out << os_endl;
p++;
break;
default:
out << '\\';
break;
}
break;
default:
out << *p++;
break;
}
}
out << ends;
cdstring result;
result.steal(out.str());
return result;
}
cdstring CVCard::EncodeTextValue(const cdstring& str)
{
// Escape it
std::ostrstream out;
const char* p = str.c_str();
while(*p)
{
switch(*p)
{
case '\\':
case ';':
case ',':
out << '\\' << *p++;
break;
case '\n':
// Always output \n
out << "\\n";
p++;
break;
case '\r':
// Ignore if trailing \n, otherwise output \n
if (*(p+1) != '\n')
out << "\\n";
p++;
break;
default:
out << *p++;
break;
}
}
out << ends;
cdstring result;
result.steal(out.str());
return result;
}
#pragma mark ____________________________addr-value
cdstring CVCard::DecodeTextAddrValue(const cdstring& str)
{
// Escape it
cdstrvect items;
unsigned long items_with_content = 0;
const char* p = str.c_str();
const char* q = str.c_str();
while(*p)
{
switch(*p)
{
// Look for item separator
case ';':
if (p - q)
{
items.push_back(DecodeTextValue(cdstring(q, p - q)));
items_with_content++;
}
else
items.push_back(cdstring::null_str);
// Bump past blank line
q = ++p;
break;
// Look for quote
case '\\':
p++;
switch(*p)
{
case '\\':
case ';':
case ',':
case 'N':
case 'n':
// Valid quote - punt over both chars
p++;
break;
default:;
}
break;
// Punt over normal char
default:
p++;
break;
}
}
// Write out the remainder
items.push_back(DecodeTextValue(q));
// Now convert to multiline item
cdstring result;
for(cdstrvect::const_iterator iter = items.begin(); iter != items.end(); iter++)
{
if (result.length())
result += os_endl;
result += *iter;
}
return result;
}
cdstring CVCard::EncodeTextAddrValue(const cdstring& str)
{
// po-box;ext-addr;street;city;state;zip;country
cdstring result;
result += ";";
result += EncodeTextValue(str);
return result;
}
#pragma mark ____________________________n-value
cdstring CVCard::DecodeTextNValue(const cdstring& str)
{
// We ignore this and use FN for now
return DecodeTextValue(str);
}
cdstring CVCard::EncodeTextNValue(const cdstring& str)
{
// Family; Given; Middle; Prefix; Suffix
cdstring result;
if (::strchr(str, ' '))
{
cdstring copy(str);
const char* first = ::strtok(copy.c_str_mod(), " ");
const char* second = ::strtok(NULL, "");
result += EncodeTextValue(second);
result += ";";
result += EncodeTextValue(first);
}
else
result += EncodeTextValue(str);
return result;
}
| 22.451876 | 135 | 0.628715 | [
"object"
] |
d5916d408f07bea581f26290ddde4d1f2209647e | 10,424 | cpp | C++ | sources/ThirdParty/wxWidgets/src/msw/dlmsw.cpp | Sasha7b9Work/S8-57M | 24531cf6d285a400e8be20a939acb842a775a989 | [
"MIT"
] | null | null | null | sources/ThirdParty/wxWidgets/src/msw/dlmsw.cpp | Sasha7b9Work/S8-57M | 24531cf6d285a400e8be20a939acb842a775a989 | [
"MIT"
] | null | null | null | sources/ThirdParty/wxWidgets/src/msw/dlmsw.cpp | Sasha7b9Work/S8-57M | 24531cf6d285a400e8be20a939acb842a775a989 | [
"MIT"
] | 1 | 2020-03-08T18:55:21.000Z | 2020-03-08T18:55:21.000Z | /////////////////////////////////////////////////////////////////////////////
// Name: src/msw/dlmsw.cpp
// Purpose: Win32-specific part of wxDynamicLibrary and related classes
// Author: Vadim Zeitlin
// Modified by:
// Created: 2005-01-10 (partly extracted from common/dynlib.cpp)
// Copyright: (c) 1998-2005 Vadim Zeitlin <vadim@wxwidgets.org>
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#if wxUSE_DYNLIB_CLASS
#include "wx/dynlib.h"
#include "wx/msw/private.h"
#include "wx/msw/debughlp.h"
#include "wx/filename.h"
// For MSVC we can link in the required library explicitly, for the other
// compilers (e.g. MinGW) this needs to be done at makefiles level.
#ifdef __VISUALC__
#pragma comment(lib, "version")
#endif
// ----------------------------------------------------------------------------
// private classes
// ----------------------------------------------------------------------------
// class used to create wxDynamicLibraryDetails objects
class WXDLLIMPEXP_BASE wxDynamicLibraryDetailsCreator
{
public:
// type of parameters being passed to EnumModulesProc
struct EnumModulesProcParams
{
wxDynamicLibraryDetailsArray *dlls;
};
static BOOL CALLBACK
EnumModulesProc(const wxChar* name, DWORD64 base, ULONG size, PVOID data);
};
// ----------------------------------------------------------------------------
// DLL version operations
// ----------------------------------------------------------------------------
static wxString GetFileVersion(const wxString& filename)
{
wxString ver;
wxChar *pc = const_cast<wxChar *>((const wxChar*) filename.t_str());
DWORD dummy;
DWORD sizeVerInfo = ::GetFileVersionInfoSize(pc, &dummy);
if ( sizeVerInfo )
{
wxCharBuffer buf(sizeVerInfo);
if ( ::GetFileVersionInfo(pc, 0, sizeVerInfo, buf.data()) )
{
void *pVer;
UINT sizeInfo;
if ( ::VerQueryValue(buf.data(),
const_cast<wxChar *>(wxT("\\")),
&pVer,
&sizeInfo) )
{
VS_FIXEDFILEINFO *info = (VS_FIXEDFILEINFO *)pVer;
ver.Printf(wxT("%d.%d.%d.%d"),
HIWORD(info->dwFileVersionMS),
LOWORD(info->dwFileVersionMS),
HIWORD(info->dwFileVersionLS),
LOWORD(info->dwFileVersionLS));
}
}
}
return ver;
}
// ============================================================================
// wxDynamicLibraryDetailsCreator implementation
// ============================================================================
/* static */
BOOL CALLBACK
wxDynamicLibraryDetailsCreator::EnumModulesProc(const wxChar* name,
DWORD64 base,
ULONG size,
void *data)
{
EnumModulesProcParams *params = (EnumModulesProcParams *)data;
wxDynamicLibraryDetails *details = new wxDynamicLibraryDetails;
// fill in simple properties
details->m_name = name;
details->m_address = wxUIntToPtr(base);
details->m_length = size;
// to get the version, we first need the full path
const HMODULE hmod = wxDynamicLibrary::MSWGetModuleHandle
(
details->m_name,
details->m_address
);
if ( hmod )
{
wxString fullname = wxGetFullModuleName(hmod);
if ( !fullname.empty() )
{
details->m_path = fullname;
details->m_version = GetFileVersion(fullname);
}
}
params->dlls->Add(details);
// continue enumeration (returning FALSE would have stopped it)
return TRUE;
}
// ============================================================================
// wxDynamicLibrary implementation
// ============================================================================
// ----------------------------------------------------------------------------
// misc functions
// ----------------------------------------------------------------------------
wxDllType wxDynamicLibrary::GetProgramHandle()
{
return (wxDllType)::GetModuleHandle(NULL);
}
// ----------------------------------------------------------------------------
// error handling
// ----------------------------------------------------------------------------
/* static */
void wxDynamicLibrary::ReportError(const wxString& message, const wxString& name)
{
wxString msg(message);
if ( name.IsEmpty() && msg.Find("%s") == wxNOT_FOUND )
msg += "%s";
// msg needs a %s for the name
wxASSERT(msg.Find("%s") != wxNOT_FOUND);
const unsigned long code = wxSysErrorCode();
wxString errMsg = wxSysErrorMsgStr(code);
// The error message (specifically code==193) may contain a
// placeholder '%1' which stands for the filename.
errMsg.Replace("%1", name, false);
// Mimic the output of wxLogSysError(), but use our pre-processed
// errMsg.
wxLogError(msg + " " + _("(error %d: %s)"), name, code, errMsg);
}
// ----------------------------------------------------------------------------
// loading/unloading DLLs
// ----------------------------------------------------------------------------
#ifndef MAX_PATH
#define MAX_PATH 260 // from VC++ headers
#endif
/* static */
wxDllType
wxDynamicLibrary::RawLoad(const wxString& libname, int flags)
{
if (flags & wxDL_GET_LOADED)
return ::GetModuleHandle(libname.t_str());
return ::LoadLibrary(libname.t_str());
}
/* static */
void wxDynamicLibrary::Unload(wxDllType handle)
{
if ( !::FreeLibrary(handle) )
{
wxLogLastError(wxT("FreeLibrary"));
}
}
/* static */
void *wxDynamicLibrary::RawGetSymbol(wxDllType handle, const wxString& name)
{
return (void *)::GetProcAddress(handle,
name.ToAscii()
);
}
// ----------------------------------------------------------------------------
// enumerating loaded DLLs
// ----------------------------------------------------------------------------
/* static */
wxDynamicLibraryDetailsArray wxDynamicLibrary::ListLoaded()
{
wxDynamicLibraryDetailsArray dlls;
#if wxUSE_DBGHELP
if ( wxDbgHelpDLL::Init() )
{
wxDynamicLibraryDetailsCreator::EnumModulesProcParams params;
params.dlls = &dlls;
if ( !wxDbgHelpDLL::CallEnumerateLoadedModules
(
::GetCurrentProcess(),
wxDynamicLibraryDetailsCreator::EnumModulesProc,
¶ms
) )
{
wxLogLastError(wxT("EnumerateLoadedModules"));
}
}
#endif // wxUSE_DBGHELP
return dlls;
}
// ----------------------------------------------------------------------------
// Getting the module from an address inside it
// ----------------------------------------------------------------------------
namespace
{
// Tries to dynamically load GetModuleHandleEx() from kernel32.dll and call it
// to get the module handle from the given address. Returns NULL if it fails to
// either resolve the function (which can only happen on pre-Vista systems
// normally) or if the function itself failed.
HMODULE CallGetModuleHandleEx(const void* addr)
{
typedef BOOL (WINAPI *GetModuleHandleEx_t)(DWORD, LPCTSTR, HMODULE *);
static const GetModuleHandleEx_t INVALID_FUNC_PTR = (GetModuleHandleEx_t)-1;
static GetModuleHandleEx_t s_pfnGetModuleHandleEx = INVALID_FUNC_PTR;
if ( s_pfnGetModuleHandleEx == INVALID_FUNC_PTR )
{
wxDynamicLibrary dll(wxT("kernel32.dll"), wxDL_VERBATIM);
wxDL_INIT_FUNC_AW(s_pfn, GetModuleHandleEx, dll);
// dll object can be destroyed, kernel32.dll won't be unloaded anyhow
}
if ( !s_pfnGetModuleHandleEx )
return NULL;
// flags are GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
// GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
HMODULE hmod;
if ( !s_pfnGetModuleHandleEx(6, (LPCTSTR)addr, &hmod) )
return NULL;
return hmod;
}
} // anonymous namespace
/* static */
void* wxDynamicLibrary::GetModuleFromAddress(const void* addr, wxString* path)
{
HMODULE hmod = CallGetModuleHandleEx(addr);
if ( !hmod )
{
wxLogLastError(wxT("GetModuleHandleEx"));
return NULL;
}
if ( path )
{
TCHAR libname[MAX_PATH];
if ( !::GetModuleFileName(hmod, libname, MAX_PATH) )
{
// GetModuleFileName could also return extended-length paths (paths
// prepended with "//?/", maximum length is 32767 charachters) so,
// in principle, MAX_PATH could be unsufficient and we should try
// increasing the buffer size here.
wxLogLastError(wxT("GetModuleFromAddress"));
return NULL;
}
libname[MAX_PATH-1] = wxT('\0');
*path = libname;
}
// In Windows HMODULE is actually the base address of the module so we
// can just cast it to the address.
return reinterpret_cast<void *>(hmod);
}
/* static */
WXHMODULE wxDynamicLibrary::MSWGetModuleHandle(const wxString& name, void *addr)
{
// we want to use GetModuleHandleEx() instead of usual GetModuleHandle()
// because the former works correctly for comctl32.dll while the latter
// returns NULL when comctl32.dll version 6 is used under XP (note that
// GetModuleHandleEx() is only available under XP and later, coincidence?)
HMODULE hmod = CallGetModuleHandleEx(addr);
return hmod ? hmod : ::GetModuleHandle(name.t_str());
}
#endif // wxUSE_DYNLIB_CLASS
| 32.073846 | 81 | 0.504701 | [
"object"
] |
d591b5863368a4d5424263f60b90a7c0ed20c4ca | 46,440 | cc | C++ | src/developer/debug/debug_agent/arch_arm64_helpers_unittest.cc | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | null | null | null | src/developer/debug/debug_agent/arch_arm64_helpers_unittest.cc | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | null | null | null | src/developer/debug/debug_agent/arch_arm64_helpers_unittest.cc | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 The Fuchsia 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 "src/developer/debug/debug_agent/arch_arm64_helpers.h"
#include <optional>
#include <gtest/gtest.h>
#include "src/developer/debug/debug_agent/arch_arm64_helpers_unittest.h"
#include "src/developer/debug/debug_agent/test_utils.h"
#include "src/developer/debug/ipc/register_test_support.h"
#include "src/developer/debug/shared/logging/file_line_function.h"
#include "src/developer/debug/shared/zx_status.h"
#include "src/lib/fxl/arraysize.h"
namespace debug_agent {
namespace arch {
namespace {
constexpr uint64_t kDbgbvrE = 1u;
zx_thread_state_debug_regs_t GetDefaultRegs() {
zx_thread_state_debug_regs_t debug_regs = {};
debug_regs.hw_bps_count = 4;
return debug_regs;
}
void SetupHWBreakpointTest(debug_ipc::FileLineFunction file_line,
zx_thread_state_debug_regs_t* debug_regs, uint64_t address,
zx_status_t expected_result) {
zx_status_t result = SetupHWBreakpoint(address, debug_regs);
ASSERT_EQ(result, expected_result)
<< "[" << file_line.ToString() << "] "
<< "Got: " << debug_ipc::ZxStatusToString(result)
<< ", expected: " << debug_ipc::ZxStatusToString(expected_result);
}
void RemoveHWBreakpointTest(debug_ipc::FileLineFunction file_line,
zx_thread_state_debug_regs_t* debug_regs, uint64_t address,
zx_status_t expected_result) {
zx_status_t result = RemoveHWBreakpoint(address, debug_regs);
ASSERT_EQ(result, expected_result)
<< "[" << file_line.ToString() << "] "
<< "Got: " << debug_ipc::ZxStatusToString(result)
<< ", expected: " << debug_ipc::ZxStatusToString(expected_result);
}
// Always aligned address.
constexpr uint64_t kAddress1 = 0x10000;
constexpr uint64_t kAddress2 = 0x20000;
constexpr uint64_t kAddress3 = 0x30000;
constexpr uint64_t kAddress4 = 0x40000;
constexpr uint64_t kAddress5 = 0x50000;
TEST(arm64Helpers, SettingBreakpoints) {
auto debug_regs = GetDefaultRegs();
SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress1, ZX_OK);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, kAddress1);
for (size_t i = 1; i < arraysize(debug_regs.hw_bps); i++) {
EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u);
EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u);
}
// Adding the same breakpoint should detect that the same already exists.
SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress1, ZX_OK);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, kAddress1);
for (size_t i = 1; i < arraysize(debug_regs.hw_bps); i++) {
EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u);
EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u);
}
// Continuing adding should append.
SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress2, ZX_OK);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, kAddress1);
EXPECT_EQ(debug_regs.hw_bps[1].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[1].dbgbvr, kAddress2);
for (size_t i = 2; i < arraysize(debug_regs.hw_bps); i++) {
EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u);
EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u);
}
SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress3, ZX_OK);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, kAddress1);
EXPECT_EQ(debug_regs.hw_bps[1].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[1].dbgbvr, kAddress2);
EXPECT_EQ(debug_regs.hw_bps[2].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[2].dbgbvr, kAddress3);
for (size_t i = 3; i < arraysize(debug_regs.hw_bps); i++) {
EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u);
EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u);
}
SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress4, ZX_OK);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, kAddress1);
EXPECT_EQ(debug_regs.hw_bps[1].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[1].dbgbvr, kAddress2);
EXPECT_EQ(debug_regs.hw_bps[2].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[2].dbgbvr, kAddress3);
EXPECT_EQ(debug_regs.hw_bps[3].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[3].dbgbvr, kAddress4);
for (size_t i = 4; i < arraysize(debug_regs.hw_bps); i++) {
EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u);
EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u);
}
// No more registers left should not change anything.
SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress5, ZX_ERR_NO_RESOURCES);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, kAddress1);
EXPECT_EQ(debug_regs.hw_bps[1].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[1].dbgbvr, kAddress2);
EXPECT_EQ(debug_regs.hw_bps[2].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[2].dbgbvr, kAddress3);
EXPECT_EQ(debug_regs.hw_bps[3].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[3].dbgbvr, kAddress4);
for (size_t i = 4; i < arraysize(debug_regs.hw_bps); i++) {
EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u);
EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u);
}
}
TEST(arm64Helpers, Removing) {
auto debug_regs = GetDefaultRegs();
// Previous state verifies the state of this calls.
SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress1, ZX_OK);
SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress2, ZX_OK);
SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress3, ZX_OK);
SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress4, ZX_OK);
SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress5, ZX_ERR_NO_RESOURCES);
RemoveHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress3, ZX_OK);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, kAddress1);
EXPECT_EQ(debug_regs.hw_bps[1].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[1].dbgbvr, kAddress2);
EXPECT_EQ(debug_regs.hw_bps[2].dbgbcr & kDbgbvrE, 0u);
EXPECT_EQ(debug_regs.hw_bps[2].dbgbvr, 0u);
EXPECT_EQ(debug_regs.hw_bps[3].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[3].dbgbvr, kAddress4);
for (size_t i = 4; i < arraysize(debug_regs.hw_bps); i++) {
EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u);
EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u);
}
// Removing same breakpoint should not work.
RemoveHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress3, ZX_ERR_OUT_OF_RANGE);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, kAddress1);
EXPECT_EQ(debug_regs.hw_bps[1].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[1].dbgbvr, kAddress2);
EXPECT_EQ(debug_regs.hw_bps[2].dbgbcr & kDbgbvrE, 0u);
EXPECT_EQ(debug_regs.hw_bps[2].dbgbvr, 0u);
EXPECT_EQ(debug_regs.hw_bps[3].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[3].dbgbvr, kAddress4);
for (size_t i = 4; i < arraysize(debug_regs.hw_bps); i++) {
EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u);
EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u);
}
// Removing an unknown address should warn and change nothing.
RemoveHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, 0xaaaaaaa, ZX_ERR_OUT_OF_RANGE);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, kAddress1);
EXPECT_EQ(debug_regs.hw_bps[1].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[1].dbgbvr, kAddress2);
EXPECT_EQ(debug_regs.hw_bps[2].dbgbcr & kDbgbvrE, 0u);
EXPECT_EQ(debug_regs.hw_bps[2].dbgbvr, 0u);
EXPECT_EQ(debug_regs.hw_bps[3].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[3].dbgbvr, kAddress4);
for (size_t i = 4; i < arraysize(debug_regs.hw_bps); i++) {
EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u);
EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u);
}
RemoveHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress1, ZX_OK);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 0u);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, 0u);
EXPECT_EQ(debug_regs.hw_bps[1].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[1].dbgbvr, kAddress2);
EXPECT_EQ(debug_regs.hw_bps[2].dbgbcr & kDbgbvrE, 0u);
EXPECT_EQ(debug_regs.hw_bps[2].dbgbvr, 0u);
EXPECT_EQ(debug_regs.hw_bps[3].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[3].dbgbvr, kAddress4);
for (size_t i = 4; i < arraysize(debug_regs.hw_bps); i++) {
EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u);
EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u);
}
// Adding again should work.
SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress5, ZX_OK);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, kAddress5);
EXPECT_EQ(debug_regs.hw_bps[1].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[1].dbgbvr, kAddress2);
EXPECT_EQ(debug_regs.hw_bps[2].dbgbcr & kDbgbvrE, 0u);
EXPECT_EQ(debug_regs.hw_bps[2].dbgbvr, 0u);
EXPECT_EQ(debug_regs.hw_bps[3].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[3].dbgbvr, kAddress4);
for (size_t i = 4; i < arraysize(debug_regs.hw_bps); i++) {
EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u);
EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u);
}
SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress1, ZX_OK);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, kAddress5);
EXPECT_EQ(debug_regs.hw_bps[1].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[1].dbgbvr, kAddress2);
EXPECT_EQ(debug_regs.hw_bps[2].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[2].dbgbvr, kAddress1);
EXPECT_EQ(debug_regs.hw_bps[3].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[3].dbgbvr, kAddress4);
for (size_t i = 4; i < arraysize(debug_regs.hw_bps); i++) {
EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u);
EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u);
}
// Already exists should not change anything.
SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress5, ZX_OK);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, kAddress5);
EXPECT_EQ(debug_regs.hw_bps[1].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[1].dbgbvr, kAddress2);
EXPECT_EQ(debug_regs.hw_bps[2].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[2].dbgbvr, kAddress1);
EXPECT_EQ(debug_regs.hw_bps[3].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[3].dbgbvr, kAddress4);
for (size_t i = 4; i < arraysize(debug_regs.hw_bps); i++) {
EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u);
EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u);
}
SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress3, ZX_ERR_NO_RESOURCES);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, kAddress5);
EXPECT_EQ(debug_regs.hw_bps[1].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[1].dbgbvr, kAddress2);
EXPECT_EQ(debug_regs.hw_bps[2].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[2].dbgbvr, kAddress1);
EXPECT_EQ(debug_regs.hw_bps[3].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[3].dbgbvr, kAddress4);
for (size_t i = 4; i < arraysize(debug_regs.hw_bps); i++) {
EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u);
EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u);
}
// No more registers.
SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress3, ZX_ERR_NO_RESOURCES);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, kAddress5);
EXPECT_EQ(debug_regs.hw_bps[1].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[1].dbgbvr, kAddress2);
EXPECT_EQ(debug_regs.hw_bps[2].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[2].dbgbvr, kAddress1);
EXPECT_EQ(debug_regs.hw_bps[3].dbgbcr & kDbgbvrE, 1u);
EXPECT_EQ(debug_regs.hw_bps[3].dbgbvr, kAddress4);
for (size_t i = 4; i < arraysize(debug_regs.hw_bps); i++) {
EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u);
EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u);
}
}
TEST(ArmHelpers, WriteGeneralRegs) {
std::vector<debug_ipc::Register> regs;
regs.push_back(CreateRegisterWithData(debug_ipc::RegisterID::kARMv8_x0, 8));
regs.push_back(CreateRegisterWithData(debug_ipc::RegisterID::kARMv8_x3, 8));
regs.push_back(CreateRegisterWithData(debug_ipc::RegisterID::kARMv8_lr, 8));
regs.push_back(CreateRegisterWithData(debug_ipc::RegisterID::kARMv8_pc, 8));
zx_thread_state_general_regs_t out = {};
zx_status_t res = WriteGeneralRegisters(regs, &out);
ASSERT_EQ(res, ZX_OK) << "Expected ZX_OK, got " << debug_ipc::ZxStatusToString(res);
EXPECT_EQ(out.r[0], 0x0102030405060708u);
EXPECT_EQ(out.r[1], 0u);
EXPECT_EQ(out.r[2], 0u);
EXPECT_EQ(out.r[3], 0x0102030405060708u);
EXPECT_EQ(out.r[4], 0u);
EXPECT_EQ(out.r[29], 0u);
EXPECT_EQ(out.lr, 0x0102030405060708u);
EXPECT_EQ(out.pc, 0x0102030405060708u);
regs.clear();
regs.push_back(CreateUint64Register(debug_ipc::RegisterID::kARMv8_x0, 0xaabb));
regs.push_back(CreateUint64Register(debug_ipc::RegisterID::kARMv8_x15, 0xdead));
regs.push_back(CreateUint64Register(debug_ipc::RegisterID::kARMv8_pc, 0xbeef));
res = WriteGeneralRegisters(regs, &out);
ASSERT_EQ(res, ZX_OK) << "Expected ZX_OK, got " << debug_ipc::ZxStatusToString(res);
EXPECT_EQ(out.r[0], 0xaabbu);
EXPECT_EQ(out.r[1], 0u);
EXPECT_EQ(out.r[15], 0xdeadu);
EXPECT_EQ(out.r[29], 0u);
EXPECT_EQ(out.lr, 0x0102030405060708u);
EXPECT_EQ(out.pc, 0xbeefu);
}
TEST(ArmHelpers, InvalidWriteGeneralRegs) {
zx_thread_state_general_regs_t out;
std::vector<debug_ipc::Register> regs;
// Invalid length.
regs.push_back(CreateRegisterWithData(debug_ipc::RegisterID::kARMv8_v0, 4));
EXPECT_EQ(WriteGeneralRegisters(regs, &out), ZX_ERR_INVALID_ARGS);
// Invalid (non-canonical) register.
regs.push_back(CreateRegisterWithData(debug_ipc::RegisterID::kARMv8_w3, 8));
EXPECT_EQ(WriteGeneralRegisters(regs, &out), ZX_ERR_INVALID_ARGS);
}
TEST(ArmHelpers, WriteVectorRegs) {
std::vector<debug_ipc::Register> regs;
std::vector<uint8_t> v0_value;
v0_value.resize(16);
v0_value.front() = 0x42;
v0_value.back() = 0x12;
regs.emplace_back(debug_ipc::RegisterID::kARMv8_v0, v0_value);
std::vector<uint8_t> v31_value = v0_value;
v31_value.front()++;
v31_value.back()++;
regs.emplace_back(debug_ipc::RegisterID::kARMv8_v31, v31_value);
regs.emplace_back(debug_ipc::RegisterID::kARMv8_fpcr, std::vector<uint8_t>{5, 6, 7, 8});
regs.emplace_back(debug_ipc::RegisterID::kARMv8_fpsr, std::vector<uint8_t>{9, 0, 1, 2});
zx_thread_state_vector_regs_t out = {};
zx_status_t res = WriteVectorRegisters(regs, &out);
ASSERT_EQ(res, ZX_OK) << "Expected ZX_OK, got " << debug_ipc::ZxStatusToString(res);
EXPECT_EQ(out.v[0].low, 0x0000000000000042u);
EXPECT_EQ(out.v[0].high, 0x1200000000000000u);
EXPECT_EQ(out.v[31].low, 0x0000000000000043u);
EXPECT_EQ(out.v[31].high, 0x1300000000000000u);
EXPECT_EQ(out.fpcr, 0x08070605u);
EXPECT_EQ(out.fpsr, 0x02010009u);
}
TEST(ArmHelpers, WriteDebugRegs) {
std::vector<debug_ipc::Register> regs;
regs.emplace_back(debug_ipc::RegisterID::kARMv8_dbgbcr0_el1, std::vector<uint8_t>{1, 2, 3, 4});
regs.emplace_back(debug_ipc::RegisterID::kARMv8_dbgbcr1_el1, std::vector<uint8_t>{2, 3, 4, 5});
regs.emplace_back(debug_ipc::RegisterID::kARMv8_dbgbcr15_el1, std::vector<uint8_t>{3, 4, 5, 6});
regs.emplace_back(debug_ipc::RegisterID::kARMv8_dbgbvr0_el1,
std::vector<uint8_t>{4, 5, 6, 7, 8, 9, 0, 1});
regs.emplace_back(debug_ipc::RegisterID::kARMv8_dbgbvr1_el1,
std::vector<uint8_t>{5, 6, 7, 8, 9, 0, 1, 2});
regs.emplace_back(debug_ipc::RegisterID::kARMv8_dbgbvr15_el1,
std::vector<uint8_t>{6, 7, 8, 9, 0, 1, 2, 3});
// TODO(bug 40992) Add ARM64 hardware watchpoint registers here.
zx_thread_state_debug_regs_t out = {};
zx_status_t res = WriteDebugRegisters(regs, &out);
ASSERT_EQ(res, ZX_OK) << "Expected ZX_OK, got " << debug_ipc::ZxStatusToString(res);
EXPECT_EQ(out.hw_bps[0].dbgbcr, 0x04030201u);
EXPECT_EQ(out.hw_bps[1].dbgbcr, 0x05040302u);
EXPECT_EQ(out.hw_bps[15].dbgbcr, 0x06050403u);
EXPECT_EQ(out.hw_bps[0].dbgbvr, 0x0100090807060504u);
EXPECT_EQ(out.hw_bps[1].dbgbvr, 0x0201000908070605u);
EXPECT_EQ(out.hw_bps[15].dbgbvr, 0x0302010009080706u);
}
// Watchpoint Tests --------------------------------------------------------------------------------
// Tests -------------------------------------------------------------------------------------------
TEST(ArmHelpers_SetupWatchpoint, SetupMany) {
zx_thread_state_debug_regs regs = {};
ASSERT_TRUE(Check(®s, kAddress1, 1, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {kAddress1, kAddress1 + 1}, 0), 0x1));
EXPECT_TRUE(CheckAddresses(regs, {kAddress1, 0, 0, 0}));
EXPECT_TRUE(CheckEnabled(regs, {1, 0, 0, 0}));
EXPECT_TRUE(CheckLengths(regs, {1, 0, 0, 0}));
EXPECT_TRUE(CheckTypes(regs, {kWrite, 0, 0, 0}));
ASSERT_TRUE(Check(®s, kAddress1, 1, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_ALREADY_BOUND)));
EXPECT_TRUE(CheckAddresses(regs, {kAddress1, 0, 0, 0}));
EXPECT_TRUE(CheckEnabled(regs, {1, 0, 0, 0}));
EXPECT_TRUE(CheckLengths(regs, {1, 0, 0, 0}));
EXPECT_TRUE(CheckTypes(regs, {kWrite, 0, 0, 0}));
ASSERT_TRUE(Check(®s, kAddress2, 2, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {kAddress2, kAddress2 + 2}, 1), 0x3));
EXPECT_TRUE(CheckAddresses(regs, {kAddress1, kAddress2, 0, 0}));
EXPECT_TRUE(CheckEnabled(regs, {1, 1, 0, 0}));
EXPECT_TRUE(CheckLengths(regs, {1, 2, 0, 0}));
EXPECT_TRUE(CheckTypes(regs, {kWrite, kWrite, 0, 0}));
ASSERT_TRUE(Check(®s, kAddress3, 4, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {kAddress3, kAddress3 + 4}, 2), 0xf));
EXPECT_TRUE(CheckAddresses(regs, {kAddress1, kAddress2, kAddress3, 0}));
EXPECT_TRUE(CheckEnabled(regs, {1, 1, 1, 0}));
EXPECT_TRUE(CheckLengths(regs, {1, 2, 4, 0}));
EXPECT_TRUE(CheckTypes(regs, {kWrite, kWrite, kWrite, 0}));
ASSERT_TRUE(Check(®s, kAddress4, 8, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {kAddress4, kAddress4 + 8}, 3), 0xff));
EXPECT_TRUE(CheckAddresses(regs, {kAddress1, kAddress2, kAddress3, kAddress4}));
EXPECT_TRUE(CheckEnabled(regs, {1, 1, 1, 1}));
EXPECT_TRUE(CheckLengths(regs, {1, 2, 4, 8}));
EXPECT_TRUE(CheckTypes(regs, {kWrite, kWrite, kWrite, kWrite}));
ASSERT_TRUE(Check(®s, kAddress5, 8, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_NO_RESOURCES)));
EXPECT_TRUE(CheckAddresses(regs, {kAddress1, kAddress2, kAddress3, kAddress4}));
EXPECT_TRUE(CheckEnabled(regs, {1, 1, 1, 1}));
EXPECT_TRUE(CheckLengths(regs, {1, 2, 4, 8}));
EXPECT_TRUE(CheckTypes(regs, {kWrite, kWrite, kWrite, kWrite}));
ASSERT_ZX_EQ(RemoveWatchpoint(®s, {kAddress3, kAddress3 + 4}, kWatchpointCount), ZX_OK);
EXPECT_TRUE(CheckAddresses(regs, {kAddress1, kAddress2, 0, kAddress4}));
EXPECT_TRUE(CheckEnabled(regs, {1, 1, 0, 1}));
EXPECT_TRUE(CheckLengths(regs, {1, 2, 0, 8}));
EXPECT_TRUE(CheckTypes(regs, {kWrite, kWrite, 0, kWrite}));
ASSERT_TRUE(Check(®s, kAddress5, 8, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {kAddress5, kAddress5 + 8}, 2), 0xff));
EXPECT_TRUE(CheckAddresses(regs, {kAddress1, kAddress2, kAddress5, kAddress4}));
EXPECT_TRUE(CheckEnabled(regs, {1, 1, 1, 1}));
EXPECT_TRUE(CheckLengths(regs, {1, 2, 8, 8}));
EXPECT_TRUE(CheckTypes(regs, {kWrite, kWrite, kWrite, kWrite}));
ASSERT_ZX_EQ(RemoveWatchpoint(®s, {kAddress3, kAddress3 + 4}, kWatchpointCount),
ZX_ERR_NOT_FOUND);
EXPECT_TRUE(CheckAddresses(regs, {kAddress1, kAddress2, kAddress5, kAddress4}));
EXPECT_TRUE(CheckEnabled(regs, {1, 1, 1, 1}));
EXPECT_TRUE(CheckLengths(regs, {1, 2, 8, 8}));
EXPECT_TRUE(CheckTypes(regs, {kWrite, kWrite, kWrite, kWrite}));
}
TEST(ArmHelpers_SetupWatchpoint, Ranges) {
zx_thread_state_debug_regs_t regs = {};
// 1-byte alignment.
ASSERT_TRUE(ResetCheck(®s, 0x1000, 1, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x1000, 0x1001}, 0), 0b00000001));
ASSERT_TRUE(ResetCheck(®s, 0x1001, 1, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x1001, 0x1002}, 0), 0b00000010));
ASSERT_TRUE(ResetCheck(®s, 0x1002, 1, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x1002, 0x1003}, 0), 0b00000100));
ASSERT_TRUE(ResetCheck(®s, 0x1003, 1, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x1003, 0x1004}, 0), 0b00001000));
ASSERT_TRUE(ResetCheck(®s, 0x1004, 1, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x1004, 0x1005}, 0), 0b00000001));
ASSERT_TRUE(ResetCheck(®s, 0x1005, 1, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x1005, 0x1006}, 0), 0b00000010));
ASSERT_TRUE(ResetCheck(®s, 0x1006, 1, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x1006, 0x1007}, 0), 0b00000100));
ASSERT_TRUE(ResetCheck(®s, 0x1007, 1, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x1007, 0x1008}, 0), 0b00001000));
ASSERT_TRUE(ResetCheck(®s, 0x1008, 1, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x1008, 0x1009}, 0), 0b00000001));
ASSERT_TRUE(ResetCheck(®s, 0x1009, 1, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x1009, 0x100a}, 0), 0b00000010));
ASSERT_TRUE(ResetCheck(®s, 0x100a, 1, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x100a, 0x100b}, 0), 0b00000100));
ASSERT_TRUE(ResetCheck(®s, 0x100b, 1, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x100b, 0x100c}, 0), 0b00001000));
ASSERT_TRUE(ResetCheck(®s, 0x100c, 1, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x100c, 0x100d}, 0), 0b00000001));
ASSERT_TRUE(ResetCheck(®s, 0x100d, 1, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x100d, 0x100e}, 0), 0b00000010));
ASSERT_TRUE(ResetCheck(®s, 0x100e, 1, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x100e, 0x100f}, 0), 0b00000100));
ASSERT_TRUE(ResetCheck(®s, 0x100f, 1, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x100f, 0x1010}, 0), 0b00001000));
ASSERT_TRUE(ResetCheck(®s, 0x1010, 1, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x1010, 0x1011}, 0), 0b00000001));
// 2-byte alignment.
ASSERT_TRUE(ResetCheck(®s, 0x1000, 2, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x1000, 0x1002}, 0), 0b00000011));
ASSERT_TRUE(ResetCheck(®s, 0x1001, 2, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1002, 2, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x1002, 0x1004}, 0), 0b00001100));
ASSERT_TRUE(ResetCheck(®s, 0x1003, 2, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1004, 2, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x1004, 0x1006}, 0), 0b00000011));
ASSERT_TRUE(ResetCheck(®s, 0x1005, 2, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1006, 2, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x1006, 0x1008}, 0), 0b00001100));
ASSERT_TRUE(ResetCheck(®s, 0x1007, 2, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1008, 2, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x1008, 0x100a}, 0), 0b00000011));
ASSERT_TRUE(ResetCheck(®s, 0x1009, 2, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100a, 2, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x100a, 0x100c}, 0), 0b00001100));
ASSERT_TRUE(ResetCheck(®s, 0x100b, 2, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100c, 2, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x100c, 0x100e}, 0), 0b00000011));
ASSERT_TRUE(ResetCheck(®s, 0x100d, 2, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100e, 2, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x100e, 0x1010}, 0), 0b00001100));
ASSERT_TRUE(ResetCheck(®s, 0x100f, 2, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1010, 2, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x1010, 0x1012}, 0), 0b00000011));
// 3-byte alignment.
ASSERT_TRUE(ResetCheck(®s, 0x1000, 3, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1001, 3, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1002, 3, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1003, 3, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1004, 3, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1005, 3, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1006, 3, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1007, 3, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1008, 3, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1009, 3, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100a, 3, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100b, 3, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
// 4 byte range.
ASSERT_TRUE(ResetCheck(®s, 0x1000, 4, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x1000, 0x1004}, 0), 0x0f));
ASSERT_TRUE(ResetCheck(®s, 0x1001, 4, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1002, 4, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1003, 4, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1004, 4, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x1004, 0x1008}, 0), 0x0f));
ASSERT_TRUE(ResetCheck(®s, 0x1005, 4, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1006, 4, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1007, 4, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1008, 4, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x1008, 0x100c}, 0), 0x0f));
ASSERT_TRUE(ResetCheck(®s, 0x1009, 4, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100a, 4, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100b, 4, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100c, 4, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x100c, 0x1010}, 0), 0x0f));
// 5 byte range.
ASSERT_TRUE(ResetCheck(®s, 0x1000, 5, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1001, 5, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1002, 5, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1003, 5, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1004, 5, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1005, 5, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1006, 5, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1007, 5, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1008, 5, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1009, 5, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100a, 5, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100b, 5, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100c, 5, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100d, 5, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100e, 5, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100f, 5, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
// 6 byte range.
ASSERT_TRUE(ResetCheck(®s, 0x1000, 6, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1001, 6, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1002, 6, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1003, 6, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1004, 6, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1005, 6, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1006, 6, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1007, 6, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1008, 6, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1009, 6, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100a, 6, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100b, 6, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100c, 6, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100d, 6, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100e, 6, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100f, 6, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
// 7 byte range.
ASSERT_TRUE(ResetCheck(®s, 0x1000, 7, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1001, 7, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1002, 7, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1003, 7, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1004, 7, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1005, 7, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1006, 7, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1007, 7, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1008, 7, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1009, 7, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100a, 7, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100b, 7, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100c, 7, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100d, 7, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100e, 7, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100f, 7, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
// 8 byte range.
ASSERT_TRUE(ResetCheck(®s, 0x1000, 8, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x1000, 0x1008}, 0), 0xff));
ASSERT_TRUE(ResetCheck(®s, 0x1001, 8, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1002, 8, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1003, 8, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1004, 8, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1005, 8, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1006, 8, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1007, 8, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x1008, 8, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x1008, 0x1010}, 0), 0xff));
ASSERT_TRUE(ResetCheck(®s, 0x1009, 8, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100a, 8, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100b, 8, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100c, 8, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100d, 8, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100e, 8, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
ASSERT_TRUE(ResetCheck(®s, 0x100f, 8, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_OUT_OF_RANGE)));
}
TEST(ArmHelpers_SettingWatchpoints, RangeIsDifferentWatchpoint) {
zx_thread_state_debug_regs_t regs = {};
ASSERT_TRUE(Check(®s, 0x100, 1, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x100, 0x100 + 1}, 0), 0b00000001));
ASSERT_TRUE(CheckAddresses(regs, {0x100, 0, 0, 0}));
EXPECT_TRUE(CheckEnabled(regs, {1, 0, 0, 0}));
ASSERT_TRUE(CheckLengths(regs, {1, 0, 0, 0}));
EXPECT_TRUE(CheckTypes(regs, {kWrite, 0, 0, 0}));
ASSERT_TRUE(Check(®s, 0x100, 1, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_ALREADY_BOUND)));
ASSERT_TRUE(CheckAddresses(regs, {0x100, 0, 0, 0}));
EXPECT_TRUE(CheckEnabled(regs, {1, 0, 0, 0}));
ASSERT_TRUE(CheckLengths(regs, {1, 0, 0, 0}));
EXPECT_TRUE(CheckTypes(regs, {kWrite, 0, 0, 0}));
ASSERT_TRUE(Check(®s, 0x100, 2, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x100, 0x100 + 2}, 1), 0b00000011));
ASSERT_TRUE(CheckAddresses(regs, {0x100, 0x100, 0, 0}));
EXPECT_TRUE(CheckEnabled(regs, {1, 1, 0, 0}));
ASSERT_TRUE(CheckLengths(regs, {1, 2, 0, 0}));
EXPECT_TRUE(CheckTypes(regs, {kWrite, kWrite, 0, 0}));
ASSERT_TRUE(Check(®s, 0x100, 2, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_ALREADY_BOUND)));
ASSERT_TRUE(CheckAddresses(regs, {0x100, 0x100, 0, 0}));
EXPECT_TRUE(CheckEnabled(regs, {1, 1, 0, 0}));
ASSERT_TRUE(CheckLengths(regs, {1, 2, 0, 0}));
EXPECT_TRUE(CheckTypes(regs, {kWrite, kWrite, 0, 0}));
ASSERT_TRUE(Check(®s, 0x100, 4, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x100, 0x100 + 4}, 2), 0b00001111));
ASSERT_TRUE(CheckAddresses(regs, {0x100, 0x100, 0x100, 0}));
EXPECT_TRUE(CheckEnabled(regs, {1, 1, 1, 0}));
ASSERT_TRUE(CheckLengths(regs, {1, 2, 4, 0}));
EXPECT_TRUE(CheckTypes(regs, {kWrite, kWrite, kWrite, 0}));
ASSERT_TRUE(Check(®s, 0x100, 4, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_ALREADY_BOUND)));
ASSERT_TRUE(CheckAddresses(regs, {0x100, 0x100, 0x100, 0}));
EXPECT_TRUE(CheckEnabled(regs, {1, 1, 1, 0}));
ASSERT_TRUE(CheckLengths(regs, {1, 2, 4, 0}));
EXPECT_TRUE(CheckTypes(regs, {kWrite, kWrite, kWrite, 0}));
ASSERT_TRUE(Check(®s, 0x100, 8, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {0x100, 0x100 + 8}, 3), 0b11111111));
ASSERT_TRUE(CheckAddresses(regs, {0x100, 0x100, 0x100, 0x100}));
EXPECT_TRUE(CheckEnabled(regs, {1, 1, 1, 1}));
ASSERT_TRUE(CheckLengths(regs, {1, 2, 4, 8}));
EXPECT_TRUE(CheckTypes(regs, {kWrite, kWrite, kWrite, kWrite}));
// Deleting is by range too.
ASSERT_ZX_EQ(RemoveWatchpoint(®s, {0x100, 0x100 + 2}, kWatchpointCount), ZX_OK);
EXPECT_TRUE(CheckAddresses(regs, {0x100, 0, 0x100, 0x100}));
EXPECT_TRUE(CheckEnabled(regs, {1, 0, 1, 1}));
ASSERT_TRUE(CheckLengths(regs, {1, 0, 4, 8}));
EXPECT_TRUE(CheckTypes(regs, {kWrite, 0, kWrite, kWrite}));
ASSERT_ZX_EQ(RemoveWatchpoint(®s, {0x100, 0x100 + 2}, kWatchpointCount), ZX_ERR_NOT_FOUND);
EXPECT_TRUE(CheckAddresses(regs, {0x100, 0, 0x100, 0x100}));
EXPECT_TRUE(CheckEnabled(regs, {1, 0, 1, 1}));
ASSERT_TRUE(CheckLengths(regs, {1, 0, 4, 8}));
EXPECT_TRUE(CheckTypes(regs, {kWrite, 0, kWrite, kWrite}));
ASSERT_ZX_EQ(RemoveWatchpoint(®s, {0x100, 0x100 + 1}, kWatchpointCount), ZX_OK);
EXPECT_TRUE(CheckAddresses(regs, {0, 0, 0x100, 0x100}));
EXPECT_TRUE(CheckEnabled(regs, {0, 0, 1, 1}));
ASSERT_TRUE(CheckLengths(regs, {0, 0, 4, 8}));
EXPECT_TRUE(CheckTypes(regs, {0, 0, kWrite, kWrite}));
ASSERT_ZX_EQ(RemoveWatchpoint(®s, {0x100, 0x100 + 1}, kWatchpointCount), ZX_ERR_NOT_FOUND);
EXPECT_TRUE(CheckAddresses(regs, {0, 0, 0x100, 0x100}));
EXPECT_TRUE(CheckEnabled(regs, {0, 0, 1, 1}));
ASSERT_TRUE(CheckLengths(regs, {0, 0, 4, 8}));
EXPECT_TRUE(CheckTypes(regs, {0, 0, kWrite, kWrite}));
ASSERT_ZX_EQ(RemoveWatchpoint(®s, {0x100, 0x100 + 8}, kWatchpointCount), ZX_OK);
EXPECT_TRUE(CheckAddresses(regs, {0, 0, 0x100, 0}));
EXPECT_TRUE(CheckEnabled(regs, {0, 0, 1, 0}));
ASSERT_TRUE(CheckLengths(regs, {0, 0, 4, 0}));
EXPECT_TRUE(CheckTypes(regs, {0, 0, kWrite, 0}));
ASSERT_ZX_EQ(RemoveWatchpoint(®s, {0x100, 0x100 + 8}, kWatchpointCount), ZX_ERR_NOT_FOUND);
EXPECT_TRUE(CheckAddresses(regs, {0, 0, 0x100, 0}));
EXPECT_TRUE(CheckEnabled(regs, {0, 0, 1, 0}));
ASSERT_TRUE(CheckLengths(regs, {0, 0, 4, 0}));
EXPECT_TRUE(CheckTypes(regs, {0, 0, kWrite, 0}));
ASSERT_ZX_EQ(RemoveWatchpoint(®s, {0x100, 0x100 + 4}, kWatchpointCount), ZX_OK);
EXPECT_TRUE(CheckAddresses(regs, {0, 0, 0, 0}));
EXPECT_TRUE(CheckEnabled(regs, {0, 0, 0, 0}));
ASSERT_TRUE(CheckLengths(regs, {0, 0, 0, 0}));
EXPECT_TRUE(CheckTypes(regs, {0, 0, 0, 0}));
}
TEST(ArmHelpers_SettingWatchpoints, DifferentTypes) {
zx_thread_state_debug_regs_t regs = {};
ASSERT_TRUE(Check(®s, kAddress1, 1, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {kAddress1, kAddress1 + 1}, 0), 0x1));
EXPECT_TRUE(CheckAddresses(regs, {kAddress1, 0, 0, 0}));
EXPECT_TRUE(CheckEnabled(regs, {1, 0, 0, 0}));
EXPECT_TRUE(CheckLengths(regs, {1, 0, 0, 0}));
EXPECT_TRUE(CheckTypes(regs, {kWrite, 0, 0, 0}));
ASSERT_TRUE(Check(®s, kAddress2, 2, debug_ipc::BreakpointType::kRead,
CreateResult(ZX_OK, {kAddress2, kAddress2 + 2}, 1), 0x3));
EXPECT_TRUE(CheckAddresses(regs, {kAddress1, kAddress2, 0, 0}));
EXPECT_TRUE(CheckEnabled(regs, {1, 1, 0, 0}));
EXPECT_TRUE(CheckLengths(regs, {1, 2, 0, 0}));
EXPECT_TRUE(CheckTypes(regs, {kWrite, kRead, 0, 0}));
ASSERT_TRUE(Check(®s, kAddress3, 4, debug_ipc::BreakpointType::kReadWrite,
CreateResult(ZX_OK, {kAddress3, kAddress3 + 4}, 2), 0xf));
EXPECT_TRUE(CheckAddresses(regs, {kAddress1, kAddress2, kAddress3, 0}));
EXPECT_TRUE(CheckEnabled(regs, {1, 1, 1, 0}));
EXPECT_TRUE(CheckLengths(regs, {1, 2, 4, 0}));
EXPECT_TRUE(CheckTypes(regs, {kWrite, kRead, kReadWrite, 0}));
ASSERT_TRUE(Check(®s, kAddress4, 8, debug_ipc::BreakpointType::kRead,
CreateResult(ZX_OK, {kAddress4, kAddress4 + 8}, 3), 0xff));
EXPECT_TRUE(CheckAddresses(regs, {kAddress1, kAddress2, kAddress3, kAddress4}));
EXPECT_TRUE(CheckEnabled(regs, {1, 1, 1, 1}));
EXPECT_TRUE(CheckLengths(regs, {1, 2, 4, 8}));
EXPECT_TRUE(CheckTypes(regs, {kWrite, kRead, kReadWrite, kRead}));
ASSERT_TRUE(Check(®s, kAddress5, 8, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_ERR_NO_RESOURCES)));
EXPECT_TRUE(CheckAddresses(regs, {kAddress1, kAddress2, kAddress3, kAddress4}));
EXPECT_TRUE(CheckEnabled(regs, {1, 1, 1, 1}));
EXPECT_TRUE(CheckLengths(regs, {1, 2, 4, 8}));
EXPECT_TRUE(CheckTypes(regs, {kWrite, kRead, kReadWrite, kRead}));
ASSERT_ZX_EQ(RemoveWatchpoint(®s, {kAddress3, kAddress3 + 4}, kWatchpointCount), ZX_OK);
EXPECT_TRUE(CheckAddresses(regs, {kAddress1, kAddress2, 0, kAddress4}));
EXPECT_TRUE(CheckEnabled(regs, {1, 1, 0, 1}));
EXPECT_TRUE(CheckLengths(regs, {1, 2, 0, 8}));
EXPECT_TRUE(CheckTypes(regs, {kWrite, kRead, 0, kRead}));
ASSERT_TRUE(Check(®s, kAddress5, 8, debug_ipc::BreakpointType::kWrite,
CreateResult(ZX_OK, {kAddress5, kAddress5 + 8}, 2), 0xff));
EXPECT_TRUE(CheckAddresses(regs, {kAddress1, kAddress2, kAddress5, kAddress4}));
EXPECT_TRUE(CheckEnabled(regs, {1, 1, 1, 1}));
EXPECT_TRUE(CheckLengths(regs, {1, 2, 8, 8}));
EXPECT_TRUE(CheckTypes(regs, {kWrite, kRead, kWrite, kRead}));
ASSERT_ZX_EQ(RemoveWatchpoint(®s, {kAddress3, kAddress3 + 4}, kWatchpointCount),
ZX_ERR_NOT_FOUND);
EXPECT_TRUE(CheckAddresses(regs, {kAddress1, kAddress2, kAddress5, kAddress4}));
EXPECT_TRUE(CheckEnabled(regs, {1, 1, 1, 1}));
EXPECT_TRUE(CheckLengths(regs, {1, 2, 8, 8}));
EXPECT_TRUE(CheckTypes(regs, {kWrite, kRead, kWrite, kRead}));
}
} // namespace
} // namespace arch
} // namespace debug_agent
| 52.41535 | 100 | 0.685551 | [
"vector"
] |
d5938c7323cb1398808a990ac2e660ac05e74de2 | 1,988 | cpp | C++ | CIM_Framework/CIMFramework/CPPClasses/Src/CIM_ManagedCredential.cpp | rgl/lms | cda6a25e0f39b2a18f10415560ee6a2cfc5fbbcb | [
"Apache-2.0"
] | 18 | 2019-04-17T10:43:35.000Z | 2022-03-22T22:30:39.000Z | CIM_Framework/CIMFramework/CPPClasses/Src/CIM_ManagedCredential.cpp | rgl/lms | cda6a25e0f39b2a18f10415560ee6a2cfc5fbbcb | [
"Apache-2.0"
] | 9 | 2019-10-03T15:29:51.000Z | 2021-12-27T14:03:33.000Z | CIM_Framework/CIMFramework/CPPClasses/Src/CIM_ManagedCredential.cpp | isabella232/lms | 50d16f81b49aba6007388c001e8137352c5eb42e | [
"Apache-2.0"
] | 8 | 2019-06-13T23:30:50.000Z | 2021-06-25T15:51:59.000Z | //----------------------------------------------------------------------------
//
// Copyright (c) Intel Corporation, 2003 - 2012 All Rights Reserved.
//
// File: CIM_ManagedCredential.cpp
//
// Contents: This relationship associates a CredentialManagementService with the Credential it manages.
//
// This file was automatically generated from CIM_ManagedCredential.mof, version: 2.16.0
//
//----------------------------------------------------------------------------
#include "CIM_ManagedCredential.h"
namespace Intel
{
namespace Manageability
{
namespace Cim
{
namespace Typed
{
const CimFieldAttribute CIM_ManagedCredential::_metadata[] = {
{"Antecedent", true, false, true },
{"Dependent", true, false, true },
};
// class fields
CimBase *CIM_ManagedCredential::CreateFromCimObject(const CimObject &object)
{
CIM_ManagedCredential *ret = NULL;
if(object.ObjectType() != CLASS_NAME)
{
ret = new CimExtended<CIM_ManagedCredential>(object);
}
else
{
ret = new CIM_ManagedCredential(object);
}
return ret;
}
vector<shared_ptr<CIM_ManagedCredential> > CIM_ManagedCredential::Enumerate(ICimWsmanClient *client, const CimKeys &keys)
{
return CimBase::Enumerate<CIM_ManagedCredential>(client, keys);
}
void CIM_ManagedCredential::Delete(ICimWsmanClient *client, const CimKeys &keys)
{
CimBase::Delete(client, CLASS_URI, keys);
}
const vector<CimFieldAttribute> &CIM_ManagedCredential::GetMetaData() const
{
return _classMetaData;
}
const string CIM_ManagedCredential::CLASS_NAME = "CIM_ManagedCredential";
const string CIM_ManagedCredential::CLASS_URI = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ManagedCredential";
const string CIM_ManagedCredential::CLASS_NS = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ManagedCredential";
const string CIM_ManagedCredential::CLASS_NS_PREFIX = "AMa978";
CIMFRAMEWORK_API vector <CimFieldAttribute> CIM_ManagedCredential::_classMetaData;
}
}
}
}
| 31.555556 | 123 | 0.695171 | [
"object",
"vector"
] |
d5a0dc8be2a3e13b17d44633279f3b9b6f73660b | 29,040 | cpp | C++ | CreatureEditorAndPlugin/CreaturePlugin/Source/CreaturePlugin/Private/mpLib.cpp | kestrelm/Creature_UE4 | 62740b56722948cdacbd5977b00d81537ab051f1 | [
"Apache-2.0"
] | 208 | 2015-06-15T05:28:16.000Z | 2022-03-28T06:32:26.000Z | CreatureEditorAndPlugin/CreaturePlugin/Source/CreaturePlugin/Private/mpLib.cpp | kestrelm/Creature_UE4 | 62740b56722948cdacbd5977b00d81537ab051f1 | [
"Apache-2.0"
] | 4 | 2015-12-07T22:19:13.000Z | 2020-01-13T09:15:24.000Z | CreatureEditorAndPlugin/CreaturePlugin/Source/CreaturePlugin/Private/mpLib.cpp | kestrelm/Creature_UE4 | 62740b56722948cdacbd5977b00d81537ab051f1 | [
"Apache-2.0"
] | 70 | 2015-06-21T14:06:53.000Z | 2022-02-19T04:19:09.000Z | #include "mpLib.h"
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
namespace mpMiniLib {
enum {
MSG_MINI_TYPE_POSITIVE_FIXNUM, /* 0 */
MSG_MINI_TYPE_FIXMAP, /* 1 */
MSG_MINI_TYPE_FIXARRAY, /* 2 */
MSG_MINI_TYPE_FIXSTR, /* 3 */
MSG_MINI_TYPE_NIL, /* 4 */
MSG_MINI_TYPE_BOOLEAN, /* 5 */
MSG_MINI_TYPE_BIN8, /* 6 */
MSG_MINI_TYPE_BIN16, /* 7 */
MSG_MINI_TYPE_BIN32, /* 8 */
MSG_MINI_TYPE_EXT8, /* 9 */
MSG_MINI_TYPE_EXT16, /* 10 */
MSG_MINI_TYPE_EXT32, /* 11 */
MSG_MINI_TYPE_FLOAT, /* 12 */
MSG_MINI_TYPE_DOUBLE, /* 13 */
MSG_MINI_TYPE_UINT8, /* 14 */
MSG_MINI_TYPE_UINT16, /* 15 */
MSG_MINI_TYPE_UINT32, /* 16 */
MSG_MINI_TYPE_UINT64, /* 17 */
MSG_MINI_TYPE_SINT8, /* 18 */
MSG_MINI_TYPE_SINT16, /* 19 */
MSG_MINI_TYPE_SINT32, /* 20 */
MSG_MINI_TYPE_SINT64, /* 21 */
MSG_MINI_TYPE_FIXEXT1, /* 22 */
MSG_MINI_TYPE_FIXEXT2, /* 23 */
MSG_MINI_TYPE_FIXEXT4, /* 24 */
MSG_MINI_TYPE_FIXEXT8, /* 25 */
MSG_MINI_TYPE_FIXEXT16, /* 26 */
MSG_MINI_TYPE_STR8, /* 27 */
MSG_MINI_TYPE_STR16, /* 28 */
MSG_MINI_TYPE_STR32, /* 29 */
MSG_MINI_TYPE_ARRAY16, /* 30 */
MSG_MINI_TYPE_ARRAY32, /* 31 */
MSG_MINI_TYPE_MAP16, /* 32 */
MSG_MINI_TYPE_MAP32, /* 33 */
MSG_MINI_TYPE_NEGATIVE_FIXNUM /* 34 */
};
enum {
POSITIVE_FIXNUM_MARKER = 0x00,
FIXMAP_MARKER = 0x80,
FIXARRAY_MARKER = 0x90,
FIXSTR_MARKER = 0xA0,
NIL_MARKER = 0xC0,
FALSE_MARKER = 0xC2,
TRUE_MARKER = 0xC3,
BIN8_MARKER = 0xC4,
BIN16_MARKER = 0xC5,
BIN32_MARKER = 0xC6,
EXT8_MARKER = 0xC7,
EXT16_MARKER = 0xC8,
EXT32_MARKER = 0xC9,
FLOAT_MARKER = 0xCA,
DOUBLE_MARKER = 0xCB,
U8_MARKER = 0xCC,
U16_MARKER = 0xCD,
U32_MARKER = 0xCE,
U64_MARKER = 0xCF,
S8_MARKER = 0xD0,
S16_MARKER = 0xD1,
S32_MARKER = 0xD2,
S64_MARKER = 0xD3,
FIXEXT1_MARKER = 0xD4,
FIXEXT2_MARKER = 0xD5,
FIXEXT4_MARKER = 0xD6,
FIXEXT8_MARKER = 0xD7,
FIXEXT16_MARKER = 0xD8,
STR8_MARKER = 0xD9,
STR16_MARKER = 0xDA,
STR32_MARKER = 0xDB,
ARRAY16_MARKER = 0xDC,
ARRAY32_MARKER = 0xDD,
MAP16_MARKER = 0xDE,
MAP32_MARKER = 0xDF,
NEGATIVE_FIXNUM_MARKER = 0xE0
};
enum {
FIXARRAY_SIZE = 0xF,
FIXMAP_SIZE = 0xF,
FIXSTR_SIZE = 0x1F
};
enum {
ERROR_NONE,
STR_DATA_LENGTH_TOO_LONG_ERROR,
BIN_DATA_LENGTH_TOO_LONG_ERROR,
ARRAY_LENGTH_TOO_LONG_ERROR,
MAP_LENGTH_TOO_LONG_ERROR,
INPUT_VALUE_TOO_LARGE_ERROR,
FIXED_VALUE_WRITING_ERROR,
TYPE_MARKER_READING_ERROR,
TYPE_MARKER_WRITING_ERROR,
DATA_READING_ERROR,
DATA_WRITING_ERROR,
EXT_TYPE_READING_ERROR,
EXT_TYPE_WRITING_ERROR,
INVALID_TYPE_ERROR,
LENGTH_READING_ERROR,
LENGTH_WRITING_ERROR,
ERROR_MAX
};
const char *mp_error_strings[ERROR_MAX + 1] = {
"No Error",
"Specified string data length is too long (> 0xFFFFFFFF)",
"Specified binary data length is too long (> 0xFFFFFFFF)",
"Specified array length is too long (> 0xFFFFFFFF)",
"Specified map length is too long (> 0xFFFFFFFF)",
"Input value is too large",
"Error writing fixed value",
"Error reading type marker",
"Error writing type marker",
"Error reading packed data",
"Error writing packed data",
"Error reading ext type",
"Error writing ext type",
"Invalid type",
"Error reading size",
"Error writing size",
"Max Error"
};
static const int32_t _i = 1;
#define is_bigendian() ((*(char *)&_i) == 0)
static uint16_t be16(uint16_t x) {
char *b = (char *)&x;
if (!is_bigendian()) {
char swap = 0;
swap = b[0];
b[0] = b[1];
b[1] = swap;
}
return x;
}
static uint32_t be32(uint32_t x) {
char *b = (char *)&x;
if (!is_bigendian()) {
char swap = 0;
swap = b[0];
b[0] = b[3];
b[3] = swap;
swap = b[1];
b[1] = b[2];
b[2] = swap;
}
return x;
}
static uint64_t be64(uint64_t x) {
char *b = (char *)&x;
if (!is_bigendian()) {
char swap = 0;
swap = b[0];
b[0] = b[7];
b[7] = swap;
swap = b[1];
b[1] = b[6];
b[6] = swap;
swap = b[2];
b[2] = b[5];
b[5] = swap;
swap = b[3];
b[3] = b[4];
b[4] = swap;
}
return x;
}
static float befloat(float x) {
char *b = (char *)&x;
if (!is_bigendian()) {
char swap = 0;
swap = b[0];
b[0] = b[3];
b[3] = swap;
swap = b[1];
b[1] = b[2];
b[2] = swap;
}
return x;
}
static double bedouble(double x) {
char *b = (char *)&x;
if (!is_bigendian()) {
char swap = 0;
swap = b[0];
b[0] = b[7];
b[7] = swap;
swap = b[1];
b[1] = b[6];
b[6] = swap;
swap = b[2];
b[2] = b[5];
b[5] = swap;
swap = b[3];
b[3] = b[4];
b[4] = swap;
}
return x;
}
bool
msg_mini::read_one_byte(uint8_t *x) {
return read(x, sizeof(uint8_t));
}
bool
msg_mini::read_marker_type(uint8_t *marker) {
if (read_one_byte(marker))
return true;
error = TYPE_MARKER_READING_ERROR;
return false;
}
const char*
msg_mini::get_strerror() const
{
if (error > ERROR_NONE && error < ERROR_MAX)
return mp_error_strings[error];
return "";
}
bool
msg_mini::msg_mini_build_generic_objects()
{
// Assumes you must have packed everything into a main array
generic_data.clear();
uint32_t main_obj_num = 0;
bool can_read = msg_mini_read_array(&main_obj_num);
if (!can_read)
{
error = INVALID_TYPE_ERROR;
return false;
}
for (size_t main_idx = 0; main_idx < (size_t)main_obj_num; main_idx++)
{
// Determine object type
store_read_pos();
msg_mini_object read_msg_obj;
msg_mini_read_object(&read_msg_obj);
restore_read_pos();
// Parse through valid object types
if (msg_mini_object_is_array(&read_msg_obj))
{
msg_mini_object test_msg_obj;
uint32_t array_size;
msg_mini_read_array(&array_size);
// determine array type
store_read_pos();
msg_mini_read_object(&test_msg_obj);
restore_read_pos();
msg_mini_generic_data new_generic_data(0);
if (msg_mini_object_is_uint(&test_msg_obj))
{
new_generic_data.type = MSG_MINI_GENERIC_ARRAY_INT_TYPE;
new_generic_data.int_array_val.resize(array_size);
for (size_t j = 0; j < (size_t)array_size; j++)
{
msg_mini_read_int(&new_generic_data.int_array_val[j]);
}
}
else if (msg_mini_object_is_float(&test_msg_obj))
{
new_generic_data.type = MSG_MINI_GENERIC_ARRAY_FLOAT_TYPE;
new_generic_data.float_array_val.resize(array_size);
for (size_t j = 0; j < (size_t)array_size; j++)
{
msg_mini_read_real(&new_generic_data.float_array_val[j]);
}
}
else if (msg_mini_object_is_str(&test_msg_obj))
{
new_generic_data.type = MSG_MINI_GENERIC_ARRAY_STRING_TYPE;
new_generic_data.str_array_val.resize(array_size);
for (size_t j = 0; j < (size_t)array_size; j++)
{
msg_mini_read_str(new_generic_data.str_array_val[j]);
}
}
generic_data.push_back(new_generic_data);
}
else if (msg_mini_object_is_bin(&read_msg_obj))
{
uint32_t array_size;
msg_mini_read_bin(&array_size);
msg_mini_generic_data new_generic_data(0);
new_generic_data.type = MSG_MINI_GENERIC_ARRAY_BYTE_TYPE;
new_generic_data.byte_array_val.resize(array_size);
readBytesChunk(array_size,
[&new_generic_data](int idx, uint8_t data)
{
new_generic_data.byte_array_val[idx] = data;
});
generic_data.push_back(new_generic_data);
}
else if (msg_mini_object_is_float(&read_msg_obj))
{
msg_mini_generic_data new_generic_data(MSG_MINI_GENERIC_FLOAT_TYPE);
msg_mini_read_real(&new_generic_data.float_val);
generic_data.push_back(new_generic_data);
}
else if (msg_mini_object_is_int(&read_msg_obj))
{
msg_mini_generic_data new_generic_data(MSG_MINI_GENERIC_INT_TYPE);
msg_mini_read_int(&new_generic_data.int_val);
generic_data.push_back(new_generic_data);
}
else if (msg_mini_object_is_str(&read_msg_obj))
{
msg_mini_generic_data new_generic_data(MSG_MINI_GENERIC_STRING_TYPE);
msg_mini_read_str(new_generic_data.string_val);
generic_data.push_back(new_generic_data);
}
else {
// not supported type so just stop
error = INVALID_TYPE_ERROR;
return false;
}
}
return true;
}
const std::vector<msg_mini_generic_data>& msg_mini::msg_mini_get_generic_objects() const
{
return generic_data;
}
bool
msg_mini::msg_mini_read_pfix(uint8_t *c)
{
msg_mini_object obj;
if (!msg_mini_read_object(&obj))
return false;
if (obj.type != MSG_MINI_TYPE_POSITIVE_FIXNUM) {
error = INVALID_TYPE_ERROR;
return false;
}
*c = obj.as.u8;
return true;
}
bool
msg_mini::msg_mini_read_nfix(int8_t *c)
{
msg_mini_object obj;
if (!msg_mini_read_object(&obj))
return false;
if (obj.type != MSG_MINI_TYPE_NEGATIVE_FIXNUM) {
error = INVALID_TYPE_ERROR;
return false;
}
*c = obj.as.s8;
return true;
}
bool
msg_mini::msg_mini_read_sfix(int8_t *c)
{
msg_mini_object obj;
if (!msg_mini_read_object(&obj))
return false;
switch (obj.type) {
case MSG_MINI_TYPE_POSITIVE_FIXNUM:
case MSG_MINI_TYPE_NEGATIVE_FIXNUM:
*c = obj.as.s8;
return true;
default:
error = INVALID_TYPE_ERROR;
return false;
}
}
bool
msg_mini::msg_mini_read_s8(int8_t *c)
{
msg_mini_object obj;
if (!msg_mini_read_object(&obj))
return false;
if (obj.type != MSG_MINI_TYPE_SINT8) {
error = INVALID_TYPE_ERROR;
return false;
}
*c = obj.as.s8;
return true;
}
bool
msg_mini::msg_mini_read_s16(int16_t *s)
{
msg_mini_object obj;
if (!msg_mini_read_object(&obj))
return false;
if (obj.type != MSG_MINI_TYPE_SINT16) {
error = INVALID_TYPE_ERROR;
return false;
}
*s = obj.as.s16;
return true;
}
bool
msg_mini::msg_mini_read_s32(int32_t *i)
{
msg_mini_object obj;
if (!msg_mini_read_object(&obj))
return false;
if (obj.type != MSG_MINI_TYPE_SINT32) {
error = INVALID_TYPE_ERROR;
return false;
}
*i = obj.as.s32;
return true;
}
bool
msg_mini::msg_mini_read_s64(int64_t *l)
{
msg_mini_object obj;
if (!msg_mini_read_object(&obj))
return false;
if (obj.type != MSG_MINI_TYPE_SINT64) {
error = INVALID_TYPE_ERROR;
return false;
}
*l = obj.as.s64;
return true;
}
bool
msg_mini::msg_mini_read_int(int32_t *i)
{
msg_mini_object obj;
if (!msg_mini_read_object(&obj))
return false;
switch (obj.type) {
case MSG_MINI_TYPE_POSITIVE_FIXNUM:
case MSG_MINI_TYPE_NEGATIVE_FIXNUM:
case MSG_MINI_TYPE_SINT8:
*i = obj.as.s8;
return true;
case MSG_MINI_TYPE_UINT8:
*i = obj.as.u8;
return true;
case MSG_MINI_TYPE_SINT16:
*i = obj.as.s16;
return true;
case MSG_MINI_TYPE_UINT16:
*i = obj.as.u16;
return true;
case MSG_MINI_TYPE_SINT32:
*i = obj.as.s32;
return true;
case MSG_MINI_TYPE_UINT32:
if (obj.as.u32 <= 2147483647) {
*i = obj.as.u32;
return true;
}
default:
error = INVALID_TYPE_ERROR;
return false;
}
}
bool
msg_mini::msg_mini_read_ufix(uint8_t *c)
{
return msg_mini_read_pfix(c);
}
bool
msg_mini::msg_mini_read_u8(uint8_t *c)
{
msg_mini_object obj;
if (!msg_mini_read_object(&obj))
return false;
if (obj.type != MSG_MINI_TYPE_UINT8) {
error = INVALID_TYPE_ERROR;
return false;
}
*c = obj.as.u8;
return true;
}
bool
msg_mini::msg_mini_read_u16(uint16_t *s)
{
msg_mini_object obj;
if (!msg_mini_read_object(&obj))
return false;
if (obj.type != MSG_MINI_TYPE_UINT16) {
error = INVALID_TYPE_ERROR;
return false;
}
*s = obj.as.u16;
return true;
}
bool
msg_mini::msg_mini_read_u32(uint32_t *i)
{
msg_mini_object obj;
if (!msg_mini_read_object(&obj))
return false;
if (obj.type != MSG_MINI_TYPE_UINT32) {
error = INVALID_TYPE_ERROR;
return false;
}
*i = obj.as.u32;
return true;
}
bool
msg_mini::msg_mini_read_u64(uint64_t *l)
{
msg_mini_object obj;
if (!msg_mini_read_object(&obj))
return false;
if (obj.type != MSG_MINI_TYPE_UINT64) {
error = INVALID_TYPE_ERROR;
return false;
}
*l = obj.as.u64;
return true;
}
bool
msg_mini::msg_mini_read_float(float *f)
{
msg_mini_object obj;
if (!msg_mini_read_object(&obj))
return false;
if (obj.type != MSG_MINI_TYPE_FLOAT) {
error = INVALID_TYPE_ERROR;
return false;
}
*f = obj.as.flt;
return true;
}
bool
msg_mini::msg_mini_read_double(double *d)
{
msg_mini_object obj;
if (!msg_mini_read_object(&obj))
return false;
if (obj.type != MSG_MINI_TYPE_DOUBLE) {
error = INVALID_TYPE_ERROR;
return false;
}
*d = obj.as.dbl;
return true;
}
bool
msg_mini::msg_mini_read_real(float *d)
{
msg_mini_object obj;
if (!msg_mini_read_object(&obj))
return false;
switch (obj.type) {
case MSG_MINI_TYPE_FLOAT:
*d = (float)obj.as.flt;
return true;
case MSG_MINI_TYPE_DOUBLE:
*d = (float)obj.as.dbl;
return true;
default:
error = INVALID_TYPE_ERROR;
return false;
}
}
bool
msg_mini::msg_mini_read_nil()
{
msg_mini_object obj;
if (!msg_mini_read_object(&obj))
return false;
if (obj.type == MSG_MINI_TYPE_NIL)
return true;
error = INVALID_TYPE_ERROR;
return false;
}
bool
msg_mini::msg_mini_read_bool(bool *b)
{
msg_mini_object obj;
if (!msg_mini_read_object(&obj))
return false;
if (obj.type != MSG_MINI_TYPE_BOOLEAN) {
error = INVALID_TYPE_ERROR;
return false;
}
if (obj.as.boolean)
*b = true;
else
*b = false;
return true;
}
bool
msg_mini::msg_mini_read_str_size(uint32_t *size)
{
msg_mini_object obj;
if (!msg_mini_read_object(&obj))
return false;
switch (obj.type) {
case MSG_MINI_TYPE_FIXSTR:
case MSG_MINI_TYPE_STR8:
case MSG_MINI_TYPE_STR16:
case MSG_MINI_TYPE_STR32:
*size = obj.as.str_size;
return true;
default:
error = INVALID_TYPE_ERROR;
return false;
}
}
bool
msg_mini::msg_mini_read_str(std::string& data)
{
uint32_t str_size = 0;
if (!msg_mini_read_str_size(&str_size))
return false;
std::shared_ptr<char> raw_data = std::shared_ptr<char>(new char[str_size + 1], std::default_delete<char[]>());
if (!read(raw_data.get(), str_size)) {
error = DATA_READING_ERROR;
return false;
}
raw_data.get()[str_size] = 0;
data = std::string(raw_data.get());
return true;
}
bool
msg_mini::msg_mini_read_bin(uint32_t *size)
{
msg_mini_object obj;
if (!msg_mini_read_object(&obj))
return false;
switch (obj.type) {
case MSG_MINI_TYPE_BIN8:
case MSG_MINI_TYPE_BIN16:
case MSG_MINI_TYPE_BIN32:
*size = obj.as.array_size;
return true;
default:
error = INVALID_TYPE_ERROR;
return false;
}
}
bool
msg_mini::msg_mini_read_array(uint32_t *size)
{
msg_mini_object obj;
if (!msg_mini_read_object(&obj))
return false;
switch (obj.type) {
case MSG_MINI_TYPE_FIXARRAY:
case MSG_MINI_TYPE_ARRAY16:
case MSG_MINI_TYPE_ARRAY32:
*size = obj.as.array_size;
return true;
default:
error = INVALID_TYPE_ERROR;
return false;
}
}
bool
msg_mini::msg_mini_read_object(msg_mini_object *obj)
{
uint8_t type_marker = 0;
if (!read_marker_type(&type_marker))
return false;
if (type_marker <= 0x7F) {
obj->type = MSG_MINI_TYPE_POSITIVE_FIXNUM;
obj->as.u8 = type_marker;
}
else if (type_marker <= 0x8F) {
obj->type = MSG_MINI_TYPE_FIXMAP;
obj->as.map_size = type_marker & FIXMAP_SIZE;
}
else if (type_marker <= 0x9F) {
obj->type = MSG_MINI_TYPE_FIXARRAY;
obj->as.array_size = type_marker & FIXARRAY_SIZE;
}
else if (type_marker <= 0xBF) {
obj->type = MSG_MINI_TYPE_FIXSTR;
obj->as.str_size = type_marker & FIXSTR_SIZE;
}
else if (type_marker == NIL_MARKER) {
obj->type = MSG_MINI_TYPE_NIL;
obj->as.u8 = 0;
}
else if (type_marker == FALSE_MARKER) {
obj->type = MSG_MINI_TYPE_BOOLEAN;
obj->as.boolean = false;
}
else if (type_marker == TRUE_MARKER) {
obj->type = MSG_MINI_TYPE_BOOLEAN;
obj->as.boolean = true;
}
else if (type_marker == FLOAT_MARKER) {
obj->type = MSG_MINI_TYPE_FLOAT;
if (!read(&obj->as.flt, sizeof(float))) {
error = DATA_READING_ERROR;
return false;
}
obj->as.flt = befloat(obj->as.flt);
}
else if (type_marker == DOUBLE_MARKER) {
obj->type = MSG_MINI_TYPE_DOUBLE;
if (!read(&obj->as.dbl, sizeof(double))) {
error = DATA_READING_ERROR;
return false;
}
obj->as.dbl = bedouble(obj->as.dbl);
}
else if (type_marker == U8_MARKER) {
obj->type = MSG_MINI_TYPE_UINT8;
if (!read(&obj->as.u8, sizeof(uint8_t))) {
error = DATA_READING_ERROR;
return false;
}
}
else if (type_marker == U16_MARKER) {
obj->type = MSG_MINI_TYPE_UINT16;
if (!read(&obj->as.u16, sizeof(uint16_t))) {
error = DATA_READING_ERROR;
return false;
}
obj->as.u16 = be16(obj->as.u16);
}
else if (type_marker == U32_MARKER) {
obj->type = MSG_MINI_TYPE_UINT32;
if (!read(&obj->as.u32, sizeof(uint32_t))) {
error = DATA_READING_ERROR;
return false;
}
obj->as.u32 = be32(obj->as.u32);
}
else if (type_marker == U64_MARKER) {
obj->type = MSG_MINI_TYPE_UINT64;
if (!read(&obj->as.u64, sizeof(uint64_t))) {
error = DATA_READING_ERROR;
return false;
}
obj->as.u64 = be64(obj->as.u64);
}
else if (type_marker == S8_MARKER) {
obj->type = MSG_MINI_TYPE_SINT8;
if (!read(&obj->as.s8, sizeof(int8_t))) {
error = DATA_READING_ERROR;
return false;
}
}
else if (type_marker == S16_MARKER) {
obj->type = MSG_MINI_TYPE_SINT16;
if (!read(&obj->as.s16, sizeof(int16_t))) {
error = DATA_READING_ERROR;
return false;
}
obj->as.s16 = be16(obj->as.s16);
}
else if (type_marker == S32_MARKER) {
obj->type = MSG_MINI_TYPE_SINT32;
if (!read(&obj->as.s32, sizeof(int32_t))) {
error = DATA_READING_ERROR;
return false;
}
obj->as.s32 = be32(obj->as.s32);
}
else if (type_marker == S64_MARKER) {
obj->type = MSG_MINI_TYPE_SINT64;
if (!read(&obj->as.s64, sizeof(int64_t))) {
error = DATA_READING_ERROR;
return false;
}
obj->as.s64 = be64(obj->as.s64);
}
else if (type_marker == STR8_MARKER) {
obj->type = MSG_MINI_TYPE_STR8;
if (!read(&obj->as.u8, sizeof(uint8_t))) {
error = DATA_READING_ERROR;
return false;
}
obj->as.str_size = obj->as.u8;
}
else if (type_marker == STR16_MARKER) {
obj->type = MSG_MINI_TYPE_STR16;
if (!read(&obj->as.u16, sizeof(uint16_t))) {
error = DATA_READING_ERROR;
return false;
}
obj->as.str_size = be16(obj->as.u16);
}
else if (type_marker == STR32_MARKER) {
obj->type = MSG_MINI_TYPE_STR32;
if (!read(&obj->as.u32, sizeof(uint32_t))) {
error = DATA_READING_ERROR;
return false;
}
obj->as.str_size = be32(obj->as.u32);
}
else if (type_marker == ARRAY16_MARKER) {
obj->type = MSG_MINI_TYPE_ARRAY16;
if (!read(&obj->as.u16, sizeof(uint16_t))) {
error = DATA_READING_ERROR;
return false;
}
obj->as.array_size = be16(obj->as.u16);
}
else if (type_marker == ARRAY32_MARKER) {
obj->type = MSG_MINI_TYPE_ARRAY32;
if (!read(&obj->as.u32, sizeof(uint32_t))) {
error = DATA_READING_ERROR;
return false;
}
obj->as.array_size = be32(obj->as.u32);
}
else if (type_marker == BIN16_MARKER) {
obj->type = MSG_MINI_TYPE_BIN16;
if (!read(&obj->as.u16, sizeof(uint16_t))) {
error = DATA_READING_ERROR;
return false;
}
obj->as.array_size = be16(obj->as.u16);
}
else if (type_marker == BIN32_MARKER) {
obj->type = MSG_MINI_TYPE_BIN32;
if (!read(&obj->as.u32, sizeof(uint32_t))) {
error = DATA_READING_ERROR;
return false;
}
obj->as.array_size = be32(obj->as.u32);
}
else if (type_marker == MAP16_MARKER) {
obj->type = MSG_MINI_TYPE_MAP16;
if (!read(&obj->as.u16, sizeof(uint16_t))) {
error = DATA_READING_ERROR;
return false;
}
obj->as.map_size = be16(obj->as.u16);
}
else if (type_marker == MAP32_MARKER) {
obj->type = MSG_MINI_TYPE_MAP32;
if (!read(&obj->as.u32, sizeof(uint32_t))) {
error = DATA_READING_ERROR;
return false;
}
obj->as.map_size = be32(obj->as.u32);
}
else if (type_marker >= NEGATIVE_FIXNUM_MARKER) {
obj->type = MSG_MINI_TYPE_NEGATIVE_FIXNUM;
obj->as.s8 = type_marker;
}
else {
error = INVALID_TYPE_ERROR;
return false;
}
return true;
}
bool
msg_mini::msg_mini_object_is_char(msg_mini_object *obj)
{
switch (obj->type) {
case MSG_MINI_TYPE_NEGATIVE_FIXNUM:
case MSG_MINI_TYPE_SINT8:
return true;
default:
return false;
}
}
bool
msg_mini::msg_mini_object_is_short(msg_mini_object *obj)
{
switch (obj->type) {
case MSG_MINI_TYPE_NEGATIVE_FIXNUM:
case MSG_MINI_TYPE_SINT8:
case MSG_MINI_TYPE_SINT16:
return true;
default:
return false;
}
}
bool
msg_mini::msg_mini_object_is_int(msg_mini_object *obj)
{
switch (obj->type) {
case MSG_MINI_TYPE_POSITIVE_FIXNUM:
case MSG_MINI_TYPE_NEGATIVE_FIXNUM:
case MSG_MINI_TYPE_UINT8:
case MSG_MINI_TYPE_UINT16:
case MSG_MINI_TYPE_UINT32:
case MSG_MINI_TYPE_SINT8:
case MSG_MINI_TYPE_SINT16:
case MSG_MINI_TYPE_SINT32:
return true;
default:
return false;
}
}
bool
msg_mini::msg_mini_object_is_long(msg_mini_object *obj)
{
switch (obj->type) {
case MSG_MINI_TYPE_NEGATIVE_FIXNUM:
case MSG_MINI_TYPE_SINT8:
case MSG_MINI_TYPE_SINT16:
case MSG_MINI_TYPE_SINT32:
case MSG_MINI_TYPE_SINT64:
return true;
default:
return false;
}
}
bool
msg_mini::msg_mini_object_is_sinteger(msg_mini_object *obj)
{
return msg_mini_object_is_long(obj);
}
bool
msg_mini::msg_mini_object_is_uchar(msg_mini_object *obj)
{
switch (obj->type) {
case MSG_MINI_TYPE_POSITIVE_FIXNUM:
case MSG_MINI_TYPE_UINT8:
return true;
default:
return false;
}
}
bool
msg_mini::msg_mini_object_is_ushort(msg_mini_object *obj)
{
switch (obj->type) {
case MSG_MINI_TYPE_POSITIVE_FIXNUM:
case MSG_MINI_TYPE_UINT8:
return true;
case MSG_MINI_TYPE_UINT16:
return true;
default:
return false;
}
}
bool
msg_mini::msg_mini_object_is_uint(msg_mini_object *obj)
{
switch (obj->type) {
case MSG_MINI_TYPE_POSITIVE_FIXNUM:
case MSG_MINI_TYPE_UINT8:
case MSG_MINI_TYPE_UINT16:
case MSG_MINI_TYPE_UINT32:
return true;
default:
return false;
}
}
bool
msg_mini::msg_mini_object_is_ulong(msg_mini_object *obj)
{
switch (obj->type) {
case MSG_MINI_TYPE_POSITIVE_FIXNUM:
case MSG_MINI_TYPE_UINT8:
case MSG_MINI_TYPE_UINT16:
case MSG_MINI_TYPE_UINT32:
case MSG_MINI_TYPE_UINT64:
return true;
default:
return false;
}
}
bool
msg_mini::msg_mini_object_is_uinteger(msg_mini_object *obj)
{
return msg_mini_object_is_ulong(obj);
}
bool
msg_mini::msg_mini_object_is_float(msg_mini_object *obj)
{
if (obj->type == MSG_MINI_TYPE_FLOAT)
return true;
return false;
}
bool
msg_mini::msg_mini_object_is_double(msg_mini_object *obj)
{
if (obj->type == MSG_MINI_TYPE_DOUBLE)
return true;
return false;
}
bool
msg_mini::msg_mini_object_is_nil(msg_mini_object *obj)
{
if (obj->type == MSG_MINI_TYPE_NIL)
return true;
return false;
}
bool
msg_mini::msg_mini_object_is_bool(msg_mini_object *obj)
{
if (obj->type == MSG_MINI_TYPE_BOOLEAN)
return true;
return false;
}
bool
msg_mini::msg_mini_object_is_str(msg_mini_object *obj)
{
switch (obj->type) {
case MSG_MINI_TYPE_FIXSTR:
case MSG_MINI_TYPE_STR8:
case MSG_MINI_TYPE_STR16:
case MSG_MINI_TYPE_STR32:
return true;
default:
return false;
}
}
bool
msg_mini::msg_mini_object_is_bin(msg_mini_object *obj)
{
switch (obj->type) {
case MSG_MINI_TYPE_BIN8:
case MSG_MINI_TYPE_BIN16:
case MSG_MINI_TYPE_BIN32:
return true;
default:
return false;
}
}
bool
msg_mini::msg_mini_object_is_array(msg_mini_object *obj)
{
switch (obj->type) {
case MSG_MINI_TYPE_FIXARRAY:
case MSG_MINI_TYPE_ARRAY16:
case MSG_MINI_TYPE_ARRAY32:
return true;
default:
return false;
}
}
bool
msg_mini::msg_mini_object_is_map(msg_mini_object *obj)
{
switch (obj->type) {
case MSG_MINI_TYPE_FIXMAP:
case MSG_MINI_TYPE_MAP16:
case MSG_MINI_TYPE_MAP32:
return true;
default:
return false;
}
}
bool
msg_mini::msg_mini_object_as_char(msg_mini_object *obj, int8_t *c)
{
switch (obj->type) {
case MSG_MINI_TYPE_POSITIVE_FIXNUM:
case MSG_MINI_TYPE_NEGATIVE_FIXNUM:
case MSG_MINI_TYPE_SINT8:
*c = obj->as.s8;
return true;
case MSG_MINI_TYPE_UINT8:
if (obj->as.u8 <= 127) {
*c = obj->as.s8;
return true;
}
default:
return false;
}
}
bool
msg_mini::msg_mini_object_as_short(msg_mini_object *obj, int16_t *s)
{
switch (obj->type) {
case MSG_MINI_TYPE_POSITIVE_FIXNUM:
case MSG_MINI_TYPE_NEGATIVE_FIXNUM:
case MSG_MINI_TYPE_SINT8:
*s = obj->as.s8;
return true;
case MSG_MINI_TYPE_UINT8:
*s = obj->as.u8;
return true;
case MSG_MINI_TYPE_SINT16:
*s = obj->as.s16;
return true;
case MSG_MINI_TYPE_UINT16:
if (obj->as.u16 <= 32767) {
*s = obj->as.u16;
return true;
}
default:
return false;
}
}
bool
msg_mini::msg_mini_object_as_int(msg_mini_object *obj, int32_t *i)
{
switch (obj->type) {
case MSG_MINI_TYPE_POSITIVE_FIXNUM:
case MSG_MINI_TYPE_NEGATIVE_FIXNUM:
case MSG_MINI_TYPE_SINT8:
*i = obj->as.s8;
return true;
case MSG_MINI_TYPE_UINT8:
*i = obj->as.u8;
return true;
case MSG_MINI_TYPE_SINT16:
*i = obj->as.s16;
return true;
case MSG_MINI_TYPE_UINT16:
*i = obj->as.u16;
return true;
case MSG_MINI_TYPE_SINT32:
*i = obj->as.s32;
return true;
case MSG_MINI_TYPE_UINT32:
if (obj->as.u32 <= 2147483647) {
*i = obj->as.u32;
return true;
}
default:
return false;
}
}
bool
msg_mini::msg_mini_object_as_long(msg_mini_object *obj, int64_t *d)
{
switch (obj->type) {
case MSG_MINI_TYPE_POSITIVE_FIXNUM:
case MSG_MINI_TYPE_NEGATIVE_FIXNUM:
case MSG_MINI_TYPE_SINT8:
*d = obj->as.s8;
return true;
case MSG_MINI_TYPE_UINT8:
*d = obj->as.u8;
return true;
case MSG_MINI_TYPE_SINT16:
*d = obj->as.s16;
return true;
case MSG_MINI_TYPE_UINT16:
*d = obj->as.u16;
return true;
case MSG_MINI_TYPE_SINT32:
*d = obj->as.s32;
return true;
case MSG_MINI_TYPE_UINT32:
*d = obj->as.u32;
return true;
case MSG_MINI_TYPE_SINT64:
*d = obj->as.s64;
return true;
case MSG_MINI_TYPE_UINT64:
if (obj->as.u64 <= 9223372036854775807) {
*d = obj->as.u64;
return true;
}
default:
return false;
}
}
bool
msg_mini::msg_mini_object_as_sinteger(msg_mini_object *obj, int64_t *d)
{
return msg_mini_object_as_long(obj, d);
}
bool
msg_mini::msg_mini_object_as_float(msg_mini_object *obj, float *f)
{
if (obj->type == MSG_MINI_TYPE_FLOAT) {
*f = obj->as.flt;
return true;
}
return false;
}
bool
msg_mini::msg_mini_object_as_double(msg_mini_object *obj, double *d)
{
if (obj->type == MSG_MINI_TYPE_DOUBLE) {
*d = obj->as.dbl;
return true;
}
return false;
}
bool
msg_mini::msg_mini_object_as_bool(msg_mini_object *obj, bool *b)
{
if (obj->type == MSG_MINI_TYPE_BOOLEAN) {
if (obj->as.boolean)
*b = true;
else
*b = false;
return true;
}
return false;
}
bool
msg_mini::msg_mini_object_as_str(msg_mini_object *obj, uint32_t *size)
{
switch (obj->type) {
case MSG_MINI_TYPE_FIXSTR:
case MSG_MINI_TYPE_STR8:
case MSG_MINI_TYPE_STR16:
case MSG_MINI_TYPE_STR32:
*size = obj->as.str_size;
return true;
default:
return false;
}
}
bool
msg_mini::msg_mini_object_as_array(msg_mini_object *obj, uint32_t *size)
{
switch (obj->type) {
case MSG_MINI_TYPE_FIXARRAY:
case MSG_MINI_TYPE_ARRAY16:
case MSG_MINI_TYPE_ARRAY32:
*size = obj->as.array_size;
return true;
default:
return false;
}
}
bool
msg_mini::msg_mini_object_as_map(msg_mini_object *obj, uint32_t *size)
{
switch (obj->type) {
case MSG_MINI_TYPE_FIXMAP:
case MSG_MINI_TYPE_MAP16:
case MSG_MINI_TYPE_MAP32:
*size = obj->as.map_size;
return true;
default:
return false;
}
}
bool
msg_mini::msg_mini_object_to_str(msg_mini_object *obj, char *data, uint32_t buf_size)
{
uint32_t str_size = 0;
switch (obj->type) {
case MSG_MINI_TYPE_FIXSTR:
case MSG_MINI_TYPE_STR8:
case MSG_MINI_TYPE_STR16:
case MSG_MINI_TYPE_STR32:
str_size = obj->as.str_size;
if ((str_size + 1) > buf_size) {
error = STR_DATA_LENGTH_TOO_LONG_ERROR;
return false;
}
if (!read(data, str_size)) {
error = DATA_READING_ERROR;
return false;
}
data[str_size] = 0;
return true;
default:
return false;
}
}
} | 20.450704 | 112 | 0.665255 | [
"object",
"vector"
] |
d5a29fdb9b780de188c7ae57d86d3298161434a3 | 424 | cpp | C++ | blind_climbing_gazebo/src/obstacle_avoid.cpp | S201761102/Topomap | e15e7015f71b68c05a8c6412d7f6aecec7d00c46 | [
"Unlicense"
] | 1 | 2020-07-15T04:32:21.000Z | 2020-07-15T04:32:21.000Z | blind_climbing_gazebo/src/obstacle_avoid.cpp | S201761102/Topomap | e15e7015f71b68c05a8c6412d7f6aecec7d00c46 | [
"Unlicense"
] | null | null | null | blind_climbing_gazebo/src/obstacle_avoid.cpp | S201761102/Topomap | e15e7015f71b68c05a8c6412d7f6aecec7d00c46 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include "obstacle_avoid.h"
#include <vector>
#include <map>
const float OBSTACLE_DISTANCE = 0.6;
bool Obstacle_Avoidance::exist_obstacle(std::map<float, float> &angle_dis)
{
for(std::map<float, float>::iterator i = angle_dis.begin(); i != angle_dis.end(); ++i)
{
//std::cout << i->second << std::endl;
if( i->second < OBSTACLE_DISTANCE) return false;
}
return true;
}
| 26.5 | 90 | 0.646226 | [
"vector"
] |
d5a4bbd6cc544e301022b02f145e144f3b833c2d | 5,190 | cpp | C++ | Server/server.cpp | MrSeile/MinesweeperOnline | 2356fb34ded7450a704432aa83f2509cb240e550 | [
"MIT"
] | null | null | null | Server/server.cpp | MrSeile/MinesweeperOnline | 2356fb34ded7450a704432aa83f2509cb240e550 | [
"MIT"
] | null | null | null | Server/server.cpp | MrSeile/MinesweeperOnline | 2356fb34ded7450a704432aa83f2509cb240e550 | [
"MIT"
] | null | null | null | #include <iostream>
#include <SFML/Network.hpp>
#include "..\Minesweeper\Minesweeper.h"
#include <random>
#include <vector>
#include <iomanip>
#include <sstream>
#include <chrono>
#include <thread>
#define port 2002
using namespace std::chrono_literals;
#define WaitFor(x) std::this_thread::sleep_for(x)
// Struct to store client data
struct Client
{
Client()
: state(Minesweeper::Playing)
{
}
std::string name;
sf::TcpSocket socket;
Minesweeper::State state;
bool connected = true;
bool finished = false;
};
std::string TimeToStr(const float& time)
{
int seconds = (int)time % 60;
int minuts = (int)(time / 60.f);
int fract = (int)(time * 100.f) % 100;
std::stringstream ss;
ss << std::setfill('0') << std::setw(2) << minuts << ":" << std::setw(2) << seconds << "." << std::setw(2) << fract;
return ss.str();
}
std::ostream& operator<<(std::ostream& os, const Minesweeper::State& state)
{
switch (state)
{
case Minesweeper::Start:
os << "Start";
break;
case Minesweeper::Playing:
os << "Playing";
break;
case Minesweeper::Win:
os << "Win";
break;
case Minesweeper::Lost:
os << "Lost";
break;
case Minesweeper::Disconnect:
os << "Disconnect";
break;
default:
os << "Unknown";
break;
}
return os;
}
int main()
{
// Number of players that will play
std::cout << "Enter number players: ";
int maxPlayers;
std::cin >> maxPlayers;
std::cout << "Enter board x: ";
int xSize;
std::cin >> xSize;
std::cout << "Enter board y: ";
int ySize;
std::cin >> ySize;
std::cout << "Enter bomb density: ";
float bombDensity;
std::cin >> bombDensity;
sf::TcpListener listener;
if (listener.listen(port) != sf::Socket::Done)
{
std::cout << "An error occurred listening to port " << port << std::endl;
std::cin.ignore(10000, '\n');
return 0;
}
std::cout << "Connected to port " << port << std::endl << std::endl;
// Initialize board
const sf::Vector2i size = { xSize, ySize };
const int nBombs = (int)((size.x * size.y) * bombDensity);
Minesweeper ms(size, nBombs);
ms.Discover(size / 2);
// Get all bombs indexes
int* bombs = new int[nBombs];
int index = 0;
for (int i = 0; i < ms.board.size(); i++)
{
if (ms.board[i].bomb)
{
bombs[index] = i;
index++;
}
}
// Create board data packet to send
sf::Packet bloardData;
bloardData.append(&maxPlayers, sizeof(maxPlayers));
bloardData.append(&size, sizeof(size));
bloardData.append(&nBombs, sizeof(nBombs));
bloardData.append(bombs, sizeof(int) * nBombs);
// Wait for all the players to join
std::vector<Client*> clients;
while (maxPlayers != 0 ? clients.size() < maxPlayers : true)
{
// Accept a new client
Client* client = new Client;
if (listener.accept(client->socket) != sf::Socket::Done)
{
std::cout << "An error occurred accepting the client" << std::endl;
std::cin.ignore(10000, '\n');
return 0;
}
std::cout << "Client connected: " << client->socket.getRemoteAddress() << ":" << client->socket.getRemotePort() << std::endl;
// Send board data packet
client->socket.send(bloardData);
// Get the name
char name[128];
size_t size;
client->socket.receive(name, sizeof(name), size);
client->name = name;
// Add client to the list of clients
clients.push_back(client);
std::cout << "Data sent to " << client->name << std::endl << std::endl;
}
// Send to all clients the list of players
sf::Clock clock;
for (Client* client : clients)
{
for (Client* c : clients)
{
client->socket.send(c->name.c_str(), c->name.size() + 1);
// Wait for the message to be recieved (50ms)
WaitFor(50ms);
}
}
// Wait 5 secconds
std::cout << "Starting game!!" << std::endl;
clock.restart();
while (clock.getElapsedTime().asSeconds() < 5);
// Send ready signal to all clients
for (Client* client : clients)
{
const char msg[] = "Ready!";
client->socket.send(msg, sizeof(msg));
client->socket.setBlocking(false);
}
clock.restart();
// Create the selector
sf::SocketSelector selector;
// Wait for a winner (or looser)
int playersLeft = maxPlayers;
while (true)
{
selector.clear();
for (Client* client : clients)
if (client->connected && !client->finished)
selector.add(client->socket);
selector.wait();
float time = clock.getElapsedTime().asSeconds();
std::cout << "Input recieved: " << std::endl;
for (Client* client : clients)
{
if (client->connected && !client->finished && selector.isReady(client->socket))
{
sf::Packet playerUpdate;
client->socket.receive(playerUpdate);
for (Client* c : clients)
if (c->connected)
c->socket.send(playerUpdate);
std::string inName;
float inTime;
int inState;
playerUpdate >> inName >> inTime >> inState;
client->state = (Minesweeper::State)inState;
std::cout << client->name << ": " << client->state << std::endl;
if (client->state != Minesweeper::Playing)
{
if (client->state == Minesweeper::Disconnect)
client->connected = false;
client->finished = true;
playersLeft--;
}
}
}
std::cout << std::endl;
if (playersLeft <= 0)
std::cin.ignore(10000, '\n');
}
std::cin.ignore(10000, '\n');
} | 21.53527 | 127 | 0.632755 | [
"vector"
] |
d5a8c95688e8318d06100c9dbefdc29c02f8f87f | 8,737 | hpp | C++ | freeswitch/src/mod/endpoints/mod_khomp/commons/base/configurator/section.hpp | gidmoth/freeswitch-image-builder | f0169671d6a4683dd4ac7226a6b38ad94640e592 | [
"BSD-2-Clause"
] | null | null | null | freeswitch/src/mod/endpoints/mod_khomp/commons/base/configurator/section.hpp | gidmoth/freeswitch-image-builder | f0169671d6a4683dd4ac7226a6b38ad94640e592 | [
"BSD-2-Clause"
] | null | null | null | freeswitch/src/mod/endpoints/mod_khomp/commons/base/configurator/section.hpp | gidmoth/freeswitch-image-builder | f0169671d6a4683dd4ac7226a6b38ad94640e592 | [
"BSD-2-Clause"
] | null | null | null | /*
KHOMP generic endpoint/channel library.
Copyright (C) 2007-2009 Khomp Ind. & Com.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
the specific language governing rights and limitations under the License.
Alternatively, the contents of this file may be used under the terms of the
"GNU Lesser General Public License 2.1" license (the “LGPL" License), in which
case the provisions of "LGPL License" are applicable instead of those above.
If you wish to allow use of your version of this file only under the terms of
the LGPL License and not to allow others to use your version of this file under
the MPL, indicate your decision by deleting the provisions above and replace them
with the notice and other provisions required by the LGPL License. If you do not
delete the provisions above, a recipient may use your version of this file under
either the MPL or the LGPL License.
The LGPL header follows below:
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CONFIG_SECTION_HPP_
#define _CONFIG_SECTION_HPP_
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <iostream>
#include <format.hpp>
#include <configurator/option.hpp>
struct Section
{
typedef std::map < std::string, Option > OptionMap;
typedef std::vector< Option * > OptionVector;
typedef std::map < std::string, Section * > SectionMap;
typedef std::vector < Section * > SectionVector;
struct NotFound: public std::runtime_error
{
NotFound(const std::string & type, const std::string & name, const std::string & me)
: std::runtime_error(STG(FMT("%s '%s' not found on section '%s'") % type % name % me)) {};
};
struct OptionNotFound: public NotFound
{
OptionNotFound(const std::string & name, const std::string & me)
: NotFound("option", name, me) {};
};
struct SectionNotFound: public NotFound
{
SectionNotFound(const std::string & name, const std::string & me)
: NotFound("section", name, me) {};
};
typedef NotFound not_found; /* backward compatibility */
// protected:
Section(const std::string & name, const std::string & desc, bool recursive = true)
: _name(name), _description(desc), _recursive(recursive) {};
void add(const Option & o)
{
_options.insert(std::pair<std::string,Option>(o.name(), o));
};
void del(const std::string & name)
{
_options.erase(name);
};
void add(Section * s)
{
_sections.insert(std::pair< std::string, Section * >(s->name(), s));
};
public:
const std::string & name() const { return _name; };
const std::string & description() const { return _description; };
const bool recursive() const { return _recursive; };
OptionMap::const_iterator option_begin() const { return _options.begin(); };
OptionMap::const_iterator option_end() const { return _options.end(); };
SectionMap::const_iterator section_begin() const { return _sections.begin(); };
SectionMap::const_iterator section_end() const { return _sections.end(); };
/**/
// Option * option_find(const char *, bool recurse = false) const;
// Section * section_find(const char *, bool recurse = false) const;
Option * option_find(const std::string &, bool recurse = false) const;
Section * section_find(const std::string &, bool recurse = false) const;
/**/
void options(OptionVector &) const;
void sections(SectionVector &) const;
/**/
template < typename T, typename F >
bool search_and_apply(const std::string & key, T & value, F f)
{
OptionMap::iterator i = _options.find(key);
if (i != _options.end())
return f(i->second);
if (!_recursive)
return false;
return (find_if(_sections.begin(), _sections.end(), f) != _sections.end());
}
private:
struct ConstKeyValue
{
ConstKeyValue(const std::string & k, const std::string &v)
: _k(k), _v(v) {};
const std::string & _k;
const std::string & _v;
};
struct KeyValue
{
KeyValue(const std::string & k, std::string &v)
: _k(k), _v(v) {};
const std::string & _k;
std::string & _v;
};
struct load_section: protected ConstKeyValue
{
load_section(const std::string & k, const std::string & v): ConstKeyValue(k,v) {};
bool operator()(Option & o) { return o.load(_v); };
bool operator()(SectionMap::value_type & v) { return v.second->load(_k,_v); };
};
struct change_section: protected ConstKeyValue
{
change_section(const std::string & k, const std::string & v): ConstKeyValue(k,v) {};
bool operator()(Option & o) { return o.change(_v); };
bool operator()(SectionMap::value_type & v) { return v.second->change(_k,_v); };
};
struct store_section: protected KeyValue
{
store_section(const std::string & k, std::string & v): KeyValue(k,v) {};
bool operator()(Option & o) { return o.store(_v); };
bool operator()(SectionMap::value_type & v) { return v.second->store(_k,_v); };
};
struct set_section: protected ConstKeyValue
{
set_section(const std::string & k, const std::string & v): ConstKeyValue(k,v) {};
bool operator()(Option & o) { return (o.set(_v))[Option::F_ADJUSTED]; };
bool operator()(SectionMap::value_type & v) { return v.second->set(_k,_v); };
};
struct get_section: protected KeyValue
{
get_section(const std::string & k, std::string & v): KeyValue(k,v) {};
bool operator()(Option & o) { return o.get(_v); };
bool operator()(SectionMap::value_type & v) { return v.second->get(_k,_v); };
};
struct modified_section
{
bool operator()(const OptionMap::value_type & v) { return v.second.modified(); };
bool operator()(const SectionMap::value_type & v) { return v.second->modified(); };
};
public:
/*
bool load(const char * key, const std::string value)
{
std::string skey(key);
return search_and_apply(skey, value, load_section(skey, value));
}
*/
bool load(const std::string & key, const std::string & value)
{
return search_and_apply(key, value, load_section(key, value));
}
bool change(const std::string & key, const std::string & value)
{
return search_and_apply(key, value, change_section(key, value));
}
bool store(const std::string & key, std::string & value)
{
return search_and_apply(key, value, store_section(key, value));
}
bool set(const std::string & key, const std::string & value)
{
return search_and_apply(key, value, set_section(key, value));
}
bool get(const std::string & key, std::string & value)
{
return search_and_apply(key, value, get_section(key, value));
}
bool modified() const
{
return ((find_if(_options.begin(), _options.end(), modified_section()) != _options.end()) ||
(find_if(_sections.begin(), _sections.end(), modified_section()) != _sections.end()));
}
private:
Section(): _name(""), _description(""), _recursive(false) {};
protected:
const std::string _name;
const std::string _description;
OptionMap _options;
SectionMap _sections;
const bool _recursive;
};
#endif /* _CONFIG_SECTION_HPP_ */
| 33.475096 | 102 | 0.629507 | [
"vector"
] |
d5af500a1c244f26491f37894360f1cc223e7990 | 3,887 | cpp | C++ | src/bits_of_matcha/Shape.cpp | matcha-ai/matcha | c1375fc2bfc9fadcbd643fc1540e3ac470dd9408 | [
"MIT"
] | null | null | null | src/bits_of_matcha/Shape.cpp | matcha-ai/matcha | c1375fc2bfc9fadcbd643fc1540e3ac470dd9408 | [
"MIT"
] | null | null | null | src/bits_of_matcha/Shape.cpp | matcha-ai/matcha | c1375fc2bfc9fadcbd643fc1540e3ac470dd9408 | [
"MIT"
] | 1 | 2022-03-17T12:14:27.000Z | 2022-03-17T12:14:27.000Z | #include "bits_of_matcha/Shape.h"
#include "bits_of_matcha/error/IncompatibleShapesError.h"
#include <stdexcept>
#include <numeric>
namespace matcha {
Shape::Shape(std::initializer_list<unsigned> dims)
: dims_{dims}
{}
Shape::Shape(const std::vector<unsigned>& dims)
: dims_{dims}
{}
size_t Shape::rank() const {
return dims_.size();
}
size_t Shape::size() const {
return std::accumulate(
std::begin(dims_), std::end(dims_),
1,
std::multiplies()
);
}
unsigned Shape::operator[](int index) const {
if (index < 0) index += rank();
if (index < 0 || index >= rank()) throw std::out_of_range("axis index is out of range");
return dims_[index];
}
const unsigned* Shape::begin() const {
return &dims_[0];
}
const unsigned* Shape::end() const {
return begin() + rank();
}
bool Shape::operator==(const Shape& other) const {
if (rank() != other.rank()) return false;
return std::equal(begin(), end(), other.begin());
}
bool Shape::operator!=(const Shape& other) const {
return !operator==(other);
}
std::ostream& operator<<(std::ostream& os, const Shape& shape) {
os << "[";
for (int i = 0; i < shape.rank(); i++) {
if (i != 0) os << ", ";
os << shape[i];
}
os << "]";
return os;
}
Shape::Reshape::Reshape(const Shape& target)
: target_(target.begin(), target.end())
{
check();
}
Shape::Reshape::Reshape(const std::vector<int>& target)
: target_{target}
{
check();
}
Shape::Reshape::Reshape(std::initializer_list<int> target)
: target_{target}
{
check();
}
void Shape::Reshape::check() {
bool minusOne = false;
for (int dim: target_) {
if (dim == -1) {
if (minusOne) {
throw std::invalid_argument("Reshape can deduce at most one dimension (at most -1)");
}
minusOne = true;
continue;
}
if (dim == 0) {
throw std::invalid_argument("Shape dims must be positive");
}
if (dim < -1) {
throw std::invalid_argument("Shape can't contain negative dim/s");
}
}
}
Shape Shape::Reshape::operator()(const Shape& shape) const {
size_t size = 1;
unsigned deduced = 0;
for (auto i: target_) {
if (i == -1) {
deduced = 1;
} else {
size *= i;
}
}
if (shape.size() != size && (shape.size() % size != 0 || !deduced)) {
throw std::invalid_argument("reshaping failed; shapes are incompatible");
}
deduced = shape.size() / size;
std::vector<unsigned> dims;
dims.reserve(target_.size());
for (auto i: target_) {
if (i == -1) {
dims.push_back(deduced);
} else {
dims.push_back(i);
}
}
return dims;
}
Shape::Range::Range(bool all)
: begin{0}
, end{-1}
{
if (!all) throw std::invalid_argument("Range: expected true");
}
Shape::Range::Range(int idx)
: begin{idx}
, end{idx + 1}
{}
Shape::Range::Range(int begin, int end)
: begin{begin}
, end{end}
{}
Shape::Slice::Slice(std::initializer_list<Range> ranges)
: slice_{ranges}
{}
Shape::Slice::Slice(Slice leading, Range range)
: slice_{std::move(leading.slice_)}
{
slice_.push_back(range);
}
std::tuple<Shape::Indices, Shape> Shape::Slice::operator()(const Shape& shape) const {
if (shape.rank() < slice_.size()) {
throw std::invalid_argument("slice exceeds tensor rank");
}
Indices idxs;
idxs.reserve(shape.rank());
std::vector<unsigned> dims;
dims.reserve(shape.rank());
for (int i = 0; i < slice_.size(); i++) {
auto [begin, end] = slice_[i];
if (begin < 0) begin += (int) shape[i];
if (begin < 0 || begin >= shape[i]) throw std::out_of_range("slice is out of range");
if (end < 0) end += (int) shape[i];
if (end < 0 || end >= shape[i]) throw std::out_of_range("slice is out of range");
if (begin >= end) throw std::invalid_argument("ranges must have positive span");
idxs.push_back(begin);
dims.push_back(end - begin);
}
return {idxs, dims};
}
}
| 20.566138 | 93 | 0.609467 | [
"shape",
"vector"
] |
d5af6dfa1b6b6631ba6eb3481f06ff603514bdaf | 21,615 | cpp | C++ | src/editor.cpp | grend3d/grend | 379d8e7eac9953b6257f6b7de7b36fbced82e774 | [
"MIT"
] | 5 | 2021-03-11T08:34:56.000Z | 2021-11-14T15:41:21.000Z | src/editor.cpp | mushrom/grend | 379d8e7eac9953b6257f6b7de7b36fbced82e774 | [
"MIT"
] | 1 | 2021-08-14T08:48:15.000Z | 2021-08-14T10:25:42.000Z | src/editor.cpp | mushrom/grend | 379d8e7eac9953b6257f6b7de7b36fbced82e774 | [
"MIT"
] | null | null | null | #include <grend-config.h>
#include <grend/gameEditor.hpp>
#include <grend/gameState.hpp>
#include <grend/engine.hpp>
#include <grend/glManager.hpp>
#include <grend/geometryGeneration.hpp>
#include <imgui/imgui.h>
#include <imgui/backends/imgui_impl_sdl.h>
#include <imgui/backends/imgui_impl_opengl3.h>
using namespace grendx;
static gameModel::ptr physmodel;
gameEditor::gameEditor(gameMain *game) : gameView() {
objects = gameObject::ptr(new gameObject());
cam->setFar(1000.0);
/*
testpost = makePostprocessor<rOutput>(game->rend->shaders["tonemap"],
SCREEN_SIZE_X, SCREEN_SIZE_Y);
*/
// don't apply post-processing filters if this is an embedded profile
// (so no tonemapping/HDR)
#ifdef NO_FLOATING_FB
post = renderPostChain::ptr(new renderPostChain(
{loadPostShader(GR_PREFIX "shaders/baked/texpresent.frag",
game->rend->globalShaderOptions)},
SCREEN_SIZE_X, SCREEN_SIZE_Y));
#else
post = renderPostChain::ptr(new renderPostChain(
//{loadPostShader(GR_PREFIX "shaders/baked/texpresent.frag",
// game->rend->globalShaderOptions)},
//{game->rend->postShaders["tonemap"], game->rend->postShaders["psaa"]},
{game->rend->postShaders["psaa"]},
SCREEN_SIZE_X, SCREEN_SIZE_Y));
#endif
loading_thing = makePostprocessor<rOutput>(
loadProgram(GR_PREFIX "shaders/baked/postprocess.vert",
GR_PREFIX "shaders/baked/texpresent.frag",
game->rend->globalShaderOptions),
SCREEN_SIZE_X,
SCREEN_SIZE_Y
);
// XXX: constructing a full shared pointer for this is a bit wasteful...
loading_img = genTexture();
loading_img->buffer(std::make_shared<materialTexture>(GR_PREFIX "assets/tex/loading-splash.png"));
clear(game);
initImgui(game);
loadUIModels();
auto moda = std::make_shared<gameObject>();
auto modb = std::make_shared<gameObject>();
physmodel = load_object(GR_PREFIX "assets/obj/smoothsphere.obj");
compileModel("testphys", physmodel);
/*
setNode("lmao", moda, physmodel);
setNode("lmao", modb, physmodel);
setNode("fooa", game->state->physObjects, moda);
setNode("foob", game->state->physObjects, modb);
game->phys->addSphere(nullptr, glm::vec3(0, 10, 0), 1.0, 1.0);
game->phys->addSphere(nullptr, glm::vec3(-10, 10, 0), 1.0, 1.0);
*/
bindCookedMeshes();
loadInputBindings(game);
setMode(mode::View);
// XXX
showObjectEditorWindow = true;
};
class clicker : public gameObject {
public:
clicker(gameEditor *ptr, enum gameEditor::mode click)
: gameObject(), editor(ptr), clickmode(click) {};
virtual void onLeftClick() {
std::cerr << "have mode: " << clickmode << std::endl;
editor->setMode(clickmode);
if (auto p = parent.lock()) {
p->onLeftClick();
}
}
gameEditor *editor;
enum gameEditor::mode clickmode;
};
void gameEditor::loadUIModels(void) {
// TODO: Need to swap Z/Y pointer and spinner models
// blender coordinate system isn't the same as opengl's (duh)
std::string dir = GR_PREFIX "assets/obj/UI/";
UIModels["X-Axis-Pointer"] = load_object(dir + "X-Axis-Pointer.obj");
UIModels["Y-Axis-Pointer"] = load_object(dir + "Y-Axis-Pointer.obj");
UIModels["Z-Axis-Pointer"] = load_object(dir + "Z-Axis-Pointer.obj");
UIModels["X-Axis-Rotation-Spinner"]
= load_object(dir + "X-Axis-Rotation-Spinner.obj");
UIModels["Y-Axis-Rotation-Spinner"]
= load_object(dir + "Y-Axis-Rotation-Spinner.obj");
UIModels["Z-Axis-Rotation-Spinner"]
= load_object(dir + "Z-Axis-Rotation-Spinner.obj");
UIModels["Cursor-Placement"]
= load_object(dir + "Cursor-Placement.obj");
UIModels["Bounding-Box"] = generate_cuboid(1.f, 1.f, 1.f);
UIObjects = gameObject::ptr(new gameObject());
gameObject::ptr xptr = gameObject::ptr(new clicker(this, mode::MoveX));
gameObject::ptr yptr = gameObject::ptr(new clicker(this, mode::MoveY));
gameObject::ptr zptr = gameObject::ptr(new clicker(this, mode::MoveZ));
gameObject::ptr xrot = gameObject::ptr(new clicker(this, mode::RotateX));
gameObject::ptr yrot = gameObject::ptr(new clicker(this, mode::RotateY));
gameObject::ptr zrot = gameObject::ptr(new clicker(this, mode::RotateZ));
gameObject::ptr orientation = gameObject::ptr(new gameObject());
gameObject::ptr cursor = gameObject::ptr(new gameObject());
gameObject::ptr bbox = gameObject::ptr(new gameObject());
setNode("X-Axis", xptr, UIModels["X-Axis-Pointer"]);
setNode("X-Rotation", xrot, UIModels["X-Axis-Rotation-Spinner"]);
setNode("Y-Axis", yptr, UIModels["Y-Axis-Pointer"]);
setNode("Y-Rotation", yrot, UIModels["Y-Axis-Rotation-Spinner"]);
setNode("Z-Axis", zptr, UIModels["Z-Axis-Pointer"]);
setNode("Z-Rotation", zrot, UIModels["Z-Axis-Rotation-Spinner"]);
setNode("Cursor-Placement", cursor, UIModels["Cursor-Placement"]);
setNode("Bounding-Box", bbox, UIModels["Bounding-Box"]);
setNode("X-Axis", orientation, xptr);
setNode("Y-Axis", orientation, yptr);
setNode("Z-Axis", orientation, zptr);
setNode("X-Rotation", orientation, xrot);
setNode("Y-Rotation", orientation, yrot);
setNode("Z-Rotation", orientation, zrot);
setNode("Orientation-Indicator", UIObjects, orientation);
setNode("Cursor-Placement", UIObjects, cursor);
setNode("Bounding-Box", UIObjects, bbox);
bbox->visible = false;
orientation->visible = false;
cursor->visible = false;
compileModels(UIModels);
bindCookedMeshes();
}
void gameEditor::render(gameMain *game) {
renderQueue que(cam);
auto flags = game->rend->getLightingFlags();
renderWorld(game, cam, flags);
renderWorldObjects(game);
// TODO: this results in cursor not being clickable if the render
// object buffer has more than the stencil buffer can hold...
// also current stencil buffer access results in syncronizing the pipeline,
// need an overall better solution for clickable things
que.add(UIObjects);
renderFlags unshadedFlags = game->rend->getLightingFlags("unshaded");
renderFlags constantFlags = game->rend->getLightingFlags("constant-color");
unshadedFlags.depthTest = constantFlags.depthTest = true;
unshadedFlags.depthMask = constantFlags.depthMask = false;
renderQueue por = que;
for (auto& prog : {constantFlags.mainShader,
constantFlags.skinnedShader,
constantFlags.instancedShader})
{
prog->bind();
prog->set("outputColor", glm::vec4(0.2, 0.05, 0.0, 0.5));
}
// TODO: depth mode in render flags
glDepthFunc(GL_GEQUAL);
por.flush(game->rend->framebuffer, game->rend, constantFlags);
por = que;
glDepthFunc(GL_LESS);
por.flush(game->rend->framebuffer, game->rend, unshadedFlags);
// TODO: function to do this
int winsize_x, winsize_y;
SDL_GetWindowSize(game->ctx.window, &winsize_x, &winsize_y);
// TODO: move this to input (on resize event)
//post->setSize(winsize_x, winsize_y);
post->setUniform("exposure", game->rend->exposure);
// TODO: need to do this in player views too
post->setUniform("time_ms", SDL_GetTicks() * 1.f);
post->draw(game->rend->framebuffer);
// XXX: FIXME: imgui on es2 results in a blank screen, for whatever reason
// the postprocessing shader doesn't see anything from the
// render framebuffer, although the depth/stencil buffer seems
// to be there...
//
// also, now that I'm trying things on android, seems
// the phone I'm testing on has a driver bug triggered
// by one of the imgui draw calls, but only on es3... boy oh boy
#if !defined(__ANDROID__) && GLSL_VERSION > 100
renderEditor(game);
renderImgui(game);
#endif
}
void gameEditor::renderWorldObjects(gameMain *game) {
DO_ERROR_CHECK();
// XXX: wasteful, a bit wrong
static gameObject::ptr probeObj = std::make_shared<gameObject>();
setNode("model", probeObj, physmodel);
renderQueue tempque(cam);
renderQueue que(cam);
tempque.add(game->state->rootnode);
if (showProbes) {
renderFlags probeFlags;
auto& refShader = game->rend->internalShaders["refprobe_debug"];
auto& irradShader = game->rend->internalShaders["irradprobe_debug"];
probeFlags.mainShader = probeFlags.skinnedShader =
probeFlags.instancedShader = probeFlags.billboardShader = refShader;
refShader->bind();
for (auto& [_, center, __, probe] : tempque.probes) {
probeObj->setTransform((TRS) {
.position = center,
.scale = glm::vec3(0.5),
});
for (unsigned i = 0; i < 6; i++) {
std::string loc = "cubeface["+std::to_string(i)+"]";
glm::vec3 facevec =
game->rend->atlases.reflections->tex_vector(probe->faces[0][i]);
refShader->set(loc, facevec);
DO_ERROR_CHECK();
}
que.add(probeObj);
DO_ERROR_CHECK();
que.flush(game->rend->framebuffer, game->rend, probeFlags);
}
probeFlags.mainShader = probeFlags.skinnedShader =
probeFlags.instancedShader = irradShader;
irradShader->bind();
for (auto& [_, center, __, probe] : tempque.irradProbes) {
probeObj->setTransform((TRS) {
.position = center,
.scale = glm::vec3(0.5),
});
for (unsigned i = 0; i < 6; i++) {
std::string loc = "cubeface["+std::to_string(i)+"]";
glm::vec3 facevec =
game->rend->atlases.irradiance->tex_vector(probe->faces[i]);
irradShader->set(loc, facevec);
}
que.add(probeObj);
que.flush(game->rend->framebuffer, game->rend, probeFlags);
}
}
if (showLights) {
renderFlags unshadedFlags = game->rend->getLightingFlags("unshaded");
for (auto& [_, center, __, light] : tempque.lights) {
glm::vec3 pos = center;
if (cam->sphereInFrustum(pos, 0.5)) {
probeObj->setTransform((TRS) {
.position = center,
.scale = glm::vec3(0.5),
});
que.add(probeObj);
que.flush(game->rend->framebuffer, game->rend, unshadedFlags);
}
}
}
}
void gameEditor::initImgui(gameMain *game) {
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
//io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable;
ImGui::StyleColorsDark();
//ImGui::StyleColorsClassic();
//ImGui::StyleColorsLight();
ImGui_ImplSDL2_InitForOpenGL(game->ctx.window, game->ctx.glcontext);
// TODO: make the glsl version here depend on GL version/the string in
// shaders/version.glsl
//ImGui_ImplOpenGL3_Init("#version 100");
//ImGui_ImplOpenGL3_Init("#version 300 es");
ImGui_ImplOpenGL3_Init("#version " GLSL_STRING);
}
std::pair<gameObject::ptr, modelMap> grendx::loadModel(std::string path) {
std::string ext = filename_extension(path);
if (ext == ".obj") {
//model m(path);
gameModel::ptr m = load_object(path);
//compileModel(path, m);
// add the model at 0,0
auto obj = gameObject::ptr(new gameObject());
// make up a name for .obj models
auto fname = basenameStr(path) + ":model";
setNode(fname, obj, m);
//return obj;
modelMap models = {{ fname, m }};
return {obj, models};
}
else if (ext == ".gltf" || ext == ".glb") {
modelMap mods = load_gltf_models(path);
auto obj = std::make_shared<gameObject>();
//compileModels(mods);
for (auto& [name, model] : mods) {
// add the models at 0,0
setNode(name, obj, model);
}
return {obj, mods};
}
return {nullptr, {}};
}
std::pair<gameImport::ptr, modelMap> grendx::loadSceneData(std::string path) {
std::string ext = filename_extension(path);
if (ext == ".gltf" || ext == ".glb") {
std::cerr << "load_scene(): loading scene" << std::endl;
// TODO: this is kind of redundant now, unless I want this to also
// be able to load .map files from here... could be useful
return load_gltf_scene(path);
}
return {nullptr, {}};
}
gameImport::ptr grendx::loadSceneCompiled(std::string path) {
auto [obj, models] = loadSceneData(path);
if (obj) {
compileModels(models);
}
return obj;
}
#if 0
// old implementation of loadSceneAsyncCompiled, left here just in case (TODO: remove)
gameImport::ptr grendx::loadSceneAsyncCompiled(gameMain *game, std::string path) {
auto ret = std::make_shared<gameImport>(path);
auto fut = game->jobs->addAsync([=] () {
auto [obj, models] = loadSceneData(path);
// apparently you can't (officially) capture destructured bindings, only variables...
// ffs
gameImport::ptr objptr = obj;
modelMap modelptr = models;
if (obj) {
game->jobs->addDeferred([=] () {
compileModels(modelptr);
setNode("asyncLoaded", ret, objptr);
return true;
});
}
return obj != nullptr;
});
return ret;
}
#endif
std::pair<gameImport::ptr, std::future<bool>>
grendx::loadSceneAsyncCompiled(gameMain *game, std::string path) {
auto ret = std::make_shared<gameImport>(path);
auto fut = game->jobs->addAsync([=] () {
auto [obj, models] = loadSceneData(path);
// apparently you can't (officially) capture destructured bindings, only variables...
// ffs
gameImport::ptr objptr = obj;
modelMap modelptr = models;
if (obj) {
setNode("asyncData", ret, objptr);
// TODO: hmm, seems there's no way to wait on compilation in the system I've
// set up here... compileModels() neeeds to be run on the main thread,
// if this function waits on it, then something from the main thread
// waits for this function to complete, that would result in a deadlock
//
// this means it would be possible to get to the rendering step with a valid
// model that just hasn't been compiled yet... hmmmmmmmmmmmmmmm
game->jobs->addDeferred([=] () {
compileModels(modelptr);
//setNode("asyncLoaded", ret, std::make_shared<gameObject>());
return true;
});
}
return obj != nullptr;
});
//return std::pair<gameImport::ptr, std::future<bool>>(ret, std::move(fut));
return {ret, std::move(fut)};
}
void gameEditor::reloadShaders(gameMain *game) {
// push everything into one vector for simplicity, this will be
// run only from the editor so it doesn't need to be really efficient
std::vector<std::pair<std::string, Program::ptr>> shaders;
for (auto& [name, flags] : game->rend->lightingShaders) {
shaders.push_back({name, flags.mainShader});
shaders.push_back({name, flags.skinnedShader});
shaders.push_back({name, flags.instancedShader});
}
for (auto& [name, flags] : game->rend->probeShaders) {
shaders.push_back({name, flags.mainShader});
shaders.push_back({name, flags.skinnedShader});
shaders.push_back({name, flags.instancedShader});
}
for (auto& [name, prog] : game->rend->postShaders) {
shaders.push_back({name, prog});
}
/*
for (auto& [name, prog] : game->rend->internalShaders) {
shaders.push_back({name, prog});
}
*/
for (auto& [name, prog] : shaders) {
if (!prog->reload()) {
std::cerr << ">> couldn't reload shader: " << name << std::endl;
}
}
}
void gameEditor::setMode(enum mode newmode) {
mode = newmode;
inputBinds.setMode(mode);
}
void gameEditor::handleCursorUpdate(gameMain *game) {
// TODO: reuse this for cursor code
auto align = [&] (float x) { return floor(x * fidelity)/fidelity; };
cursorBuf.position = glm::vec3(
align(cam->direction().x*editDistance + cam->position().x),
align(cam->direction().y*editDistance + cam->position().y),
align(cam->direction().z*editDistance + cam->position().z));
}
void gameEditor::logic(gameMain *game, float delta) {
cam->updatePosition(delta);
auto orientation = UIObjects->getNode("Orientation-Indicator");
auto cursor = UIObjects->getNode("Cursor-Placement");
assert(orientation && cursor);
orientation->visible =
selectedNode != nullptr
&& !selectedNode->parent.expired()
&& selectedNode != game->state->rootnode;
cursor->visible =
mode == mode::AddObject
|| mode == mode::AddPointLight
|| mode == mode::AddSpotLight
|| mode == mode::AddDirectionalLight
|| mode == mode::AddReflectionProbe
|| mode == mode::AddIrradianceProbe
|| showAddEntityWindow;
if (selectedNode) {
for (auto& str : {"X-Axis", "Y-Axis", "Z-Axis",
"X-Rotation", "Y-Rotation", "Z-Rotation"})
{
auto ptr = orientation->getNode(str);
TRS newtrans = selectedNode->getTransformTRS();
newtrans.scale = glm::vec3(glm::distance(newtrans.position, cam->position()) * 0.22);
ptr->setTransform(newtrans);
}
if (selectedNode->type == gameObject::objType::ReflectionProbe) {
auto bbox = UIObjects->getNode("Bounding-Box");
auto probe = std::dynamic_pointer_cast<gameReflectionProbe>(selectedNode);
TRS transform = probe->getTransformTRS();
glm::vec3 bmin = transform.position + probe->boundingBox.min;
glm::vec3 bmax = transform.position + probe->boundingBox.max;
glm::vec3 center = 0.5f*(bmax + bmin);
glm::vec3 extent = (bmax - bmin);
assert(bbox != nullptr);
bbox->visible = true;
bbox->setTransform((TRS) {
.position = center,
.scale = extent,
});
} else {
auto bbox = UIObjects->getNode("Bounding-Box");
assert(bbox != nullptr);
bbox->visible = false;
}
handleMoveRotate(game);
}
{
auto ptr = UIObjects->getNode("Cursor-Placement");
if (ptr) {
handleCursorUpdate(game);
ptr->setTransform((TRS) { .position = cursorBuf.position, });
}
}
/*
switch (mode) {
case mode::AddObject:
case mode::AddPointLight:
case mode::AddSpotLight:
case mode::AddDirectionalLight:
case mode::AddReflectionProbe:
case mode::AddIrradianceProbe:
{
auto ptr = UIObjects->getNode("Cursor-Placement");
assert(ptr != nullptr);
handleCursorUpdate(game);
ptr->transform.position = entbuf.position;
break;
}
default: break;
}
*/
}
void gameEditor::showLoadingScreen(gameMain *game) {
// TODO: maybe not this
loading_thing->draw(loading_img, nullptr);
SDL_GL_SwapWindow(game->ctx.window);
}
bool gameEditor::isUIObject(gameObject::ptr obj) {
for (gameObject::ptr temp = obj; temp; temp = temp->parent.lock()) {
if (temp == UIObjects) {
return true;
}
}
return false;
}
gameObject::ptr gameEditor::getNonModel(gameObject::ptr obj) {
for (gameObject::ptr temp = obj; temp; temp = temp->parent.lock()) {
if (temp->type != gameObject::objType::Mesh
&& temp->type != gameObject::objType::Model)
{
return temp;
}
}
return nullptr;
}
void gameEditor::clear(gameMain *game) {
showLoadingScreen(game);
cam->setPosition({0, 0, 0});
models.clear();
// TODO: clear() for state
selectedNode = game->state->rootnode = gameObject::ptr(new gameObject());
}
// TODO: rename 'renderer' to 'rend' or something
void gameEditor::renderImgui(gameMain *game) {
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
ImGuiIO& io = ImGui::GetIO();
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) {
SDL_Window *w = SDL_GL_GetCurrentWindow();
SDL_GLContext g = SDL_GL_GetCurrentContext();
ImGui::UpdatePlatformWindows();
ImGui::RenderPlatformWindowsDefault();
SDL_GL_MakeCurrent(w, g);
}
}
#if 0
// messing around with an IDE-style layout, will set this up properly eventually
#include <imgui/imgui_internal.h>
static void initDocking(void) {
ImGuiIO& io = ImGui::GetIO();
ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_PassthruCentralNode;
ImGuiWindowFlags window_flags
= ImGuiWindowFlags_NoTitleBar
| ImGuiWindowFlags_NoCollapse
| ImGuiWindowFlags_NoResize
| ImGuiWindowFlags_NoMove
| ImGuiWindowFlags_NoBringToFrontOnFocus
| ImGuiWindowFlags_NoNavFocus
| ImGuiWindowFlags_NoBackground
;
if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable) {
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
ImGui::Begin("dockspace", nullptr, window_flags);
ImGui::PopStyleVar();
ImGuiID dockspace_id = ImGui::GetID("dockspace");
ImGui::DockSpace(dockspace_id, ImVec2(1280, 720), dockspace_flags);
static bool initialized = false;
if (!initialized) {
initialized = true;
ImGui::DockBuilderRemoveNode(dockspace_id);
ImGui::DockBuilderAddNode(dockspace_id, dockspace_flags | ImGuiDockNodeFlags_DockSpace);
ImGui::DockBuilderSetNodeSize(dockspace_id, ImVec2(1280, 720));
auto dock_id_left = ImGui::DockBuilderSplitNode(dockspace_id, ImGuiDir_Left, 0.2, nullptr, &dockspace_id);
auto dock_id_down = ImGui::DockBuilderSplitNode(dockspace_id, ImGuiDir_Down, 0.2, nullptr, &dockspace_id);
ImGui::DockBuilderDockWindow("Down", dock_id_down);
ImGui::DockBuilderDockWindow("Left", dock_id_left);
ImGui::DockBuilderFinish(dockspace_id);
}
ImGui::Begin("Left");
ImGui::Text("left");
ImGui::End();
ImGui::Begin("Down");
ImGui::Text("down");
ImGui::End();
ImGui::End();
}
}
#endif
void gameEditor::renderEditor(gameMain *game) {
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplSDL2_NewFrame(game->ctx.window);
ImGui::NewFrame();
// initDocking();
menubar(game);
// TODO: this could probably be reduced to like a map of
// window names to states...
// as simple as name -> opened?
// or name -> pair<opened, draw()>, something like that
// or even name -> draw(), and being in the map implies it's opened...
if (showMetricsWindow) {
//ImGui::ShowMetricsWindow();
metricsWindow(game);
}
if (showMapWindow) {
mapWindow(game);
}
if (showObjectSelectWindow) {
objectSelectWindow(game);
}
if (selectedNode && showObjectEditorWindow) {
objectEditorWindow(game);
}
if (showEntitySelectWindow) {
entitySelectWindow(game);
}
if (showAddEntityWindow) {
addEntityWindow(game);
}
if (showEntityEditorWindow) {
// TODO
//entityEditorWindow(game);
}
if (showProfilerWindow) {
profilerWindow(game);
}
if (showSettingsWindow) {
settingsWindow(game);
}
}
| 29.650206 | 109 | 0.684386 | [
"mesh",
"render",
"object",
"vector",
"model",
"transform"
] |
d5b203376f91afb2dda23c1f72d0c7623791ce0f | 1,600 | hpp | C++ | src/inc/win32/ctf/remote.hpp | clayne/pwn-- | 531ed0baa087a890da32bb6a581de42524804cb8 | [
"MIT"
] | 64 | 2020-11-10T07:49:03.000Z | 2022-03-12T17:16:55.000Z | src/inc/win32/ctf/remote.hpp | clayne/pwn-- | 531ed0baa087a890da32bb6a581de42524804cb8 | [
"MIT"
] | 3 | 2021-07-14T03:48:37.000Z | 2021-11-29T18:00:12.000Z | src/inc/win32/ctf/remote.hpp | clayne/pwn-- | 531ed0baa087a890da32bb6a581de42524804cb8 | [
"MIT"
] | 2 | 2020-11-10T09:45:15.000Z | 2021-04-21T12:23:44.000Z | #pragma once
#include "common.hpp"
#include "tube.hpp"
#include "handle.hpp"
#include "utils.hpp"
#include <winsock2.h>
namespace pwn::win::ctf
{
///
/// A Remote session (pwntools-like)
///
class Remote : public Tube
{
public:
PWNAPI Remote(_In_ std::wstring const& host, _In_ u16 port);
PWNAPI ~Remote();
protected:
auto
__send_internal(_In_ std::vector<u8> const& out) -> size_t;
auto
__recv_internal(_In_ size_t size) -> std::vector<u8>;
auto
__peek_internal() -> size_t;
private:
auto
init() -> bool;
auto
connect() -> bool;
auto
disconnect() -> bool;
auto
cleanup() -> bool;
auto
reconnect() -> bool;
std::wstring m_host;
std::wstring m_protocol;
u16 m_port;
SOCKET m_socket;
};
///
/// A Process session (pwntools-like)
///
class Process : public Tube
{
public:
Process() = default;
~Process() = default;
protected:
auto
__send_internal(_In_ std::vector<u8> const& out) -> size_t;
auto
__recv_internal(_In_ size_t size = PWN_TUBE_PIPE_DEFAULT_SIZE) -> std::vector<u8>;
auto
__peek_internal() -> size_t;
private:
auto
create_pipes() -> bool;
auto
spawn_process() -> bool;
std::wstring m_processname;
std::wstring m_commandline;
::pwn::utils::GenericHandle<HANDLE> m_hProcess;
HANDLE m_ChildPipeStdin = INVALID_HANDLE_VALUE;
HANDLE m_ChildPipeStdout = INVALID_HANDLE_VALUE;
HANDLE m_ParentStdin = ::GetStdHandle(STD_INPUT_HANDLE);
HANDLE m_ParentStdout = ::GetStdHandle(STD_OUTPUT_HANDLE);
};
} | 16.666667 | 86 | 0.645 | [
"vector"
] |
d5b28bb770e10f9facdf09cde3b4782539ccdee4 | 6,525 | cpp | C++ | Code/PluginCustomizer/EditorPathValue.cpp | cy15196/FastCAE | 0870752ec2e590f3ea6479e909ebf6c345ac2523 | [
"BSD-3-Clause"
] | 117 | 2020-03-07T12:07:05.000Z | 2022-03-27T07:35:22.000Z | Code/PluginCustomizer/EditorPathValue.cpp | cy15196/FastCAE | 0870752ec2e590f3ea6479e909ebf6c345ac2523 | [
"BSD-3-Clause"
] | 4 | 2020-03-12T15:36:57.000Z | 2022-02-08T02:19:17.000Z | Code/PluginCustomizer/EditorPathValue.cpp | cy15196/FastCAE | 0870752ec2e590f3ea6479e909ebf6c345ac2523 | [
"BSD-3-Clause"
] | 76 | 2020-03-16T01:47:46.000Z | 2022-03-21T16:37:07.000Z | #include "EditorPathValue.h"
#include "ui_EditorPathValue.h"
#include "DataProperty/ParameterPath.h"
#include "InputValidator.h"
#include <QDebug>
#include <QTimer>
#include <QFileDialog>
namespace FastCAEDesigner{
EditorPathValue::EditorPathValue(QWidget *parent) :
QDialog(parent),
_ui(new Ui::EditorPathValue)
{
_ui->setupUi(this);
Init();
}
EditorPathValue::EditorPathValue(DataProperty::ParameterPath* model, QWidget *parent) :
QDialog(parent),
_ui(new Ui::EditorPathValue),
_model(model)
{
_ui->setupUi(this);
Init();
}
EditorPathValue::~EditorPathValue()
{
delete _ui;
_usedNameList.clear();
}
void EditorPathValue::setNameUsedList(QList<QString> list)
{
_usedNameList = list;
}
void EditorPathValue::Init()
{
UpdateDataToUi();
// UpdateUiDisplay(false);
InitErrorList();
connect(_ui->OkPBtn, SIGNAL(clicked()), this, SLOT(OnOkPBtnClicked()));
connect(_ui->CancelPBtn, SIGNAL(clicked()), this, SLOT(close()));
connect(_ui->TypeCB, SIGNAL(currentIndexChanged(int)), this, SLOT(OnComboxChanged(int)));
connect(_ui->PathPBtn, SIGNAL(clicked()), this, SLOT(OnPathPBtnClicked()));
}
void EditorPathValue::UpdateUiDisplay(bool l)
{
_ui->label_3->setVisible(l);
_ui->FIleSuffixLE->setVisible(l);
_ui->label_4->setVisible(l);
_ui->ValueLE->setText("");//Added xvdongming 2020-02-13 在切换路径类型时,清除原来的数据,避免数据错误。
}
void EditorPathValue::InitErrorList()
{
_errorList.insert(NameIsEmpty, tr("Name is empty."));
_errorList.insert(TheNameInUse, tr("The name is already in use."));
_errorList.insert(FileSuffixIsEmpty, tr("File suffix is empty."));
_errorList.insert(FileSuffixIsNotSure, tr("File suffix format is not correct,please follow *.dat"));
_errorList.insert(IllegalName, tr("The name is illegal string."));
}
void EditorPathValue::UpdateDataToUi()
{
int type;
QString s;
_ui->NameLE->setText(_model->getDescribe());
switch (_model->getType())
{
case DataProperty::PathType::None:
case DataProperty::PathType::Path:
UpdateUiDisplay(false);
type = 0;
s = _model->getPath();
break;
case DataProperty::PathType::File:
UpdateUiDisplay(true);
type = 1;
s = _model->getFile();
break;
case DataProperty::PathType::FileList:
UpdateUiDisplay(true);
type = 2;
s = _model->getFileList().join(";");
break;
default:
break;
}
_ui->TypeCB->setCurrentIndex(type);
int suffixError = IsFileSuffixSure(_model->getSuffix());
QString suffix;
if (suffixError == 0)
suffix = _model->getSuffix();
_ui->FIleSuffixLE->setText(suffix);
_ui->ValueLE->setText(s);
}
void EditorPathValue::UpdateUiToData()
{
_model->setDescribe(_ui->NameLE->text());
int type = _ui->TypeCB->currentIndex();
_model->setType(DataProperty::PathType(type + 1));
if (type == 0)
{
//_model->setSuffix(ui->FIleSuffixLE->text());
_model->setPath(_ui->ValueLE->text());
}
else if (type == 1)
{
_model->setSuffix(_ui->FIleSuffixLE->text());
_model->setFile(_ui->ValueLE->text());
}
else if (type == 2)
{
_model->setSuffix(_ui->FIleSuffixLE->text());
_model->setFileList(_ui->ValueLE->text().split(";"));
}
}
void EditorPathValue::OnComboxChanged(int index)
{
//qDebug() << index;
if (index != 0)
{
UpdateUiDisplay(true);
}
else
{
UpdateUiDisplay(false);
}
}
int EditorPathValue::IsNameSure()
{
QString name = _ui->NameLE->text().trimmed();
if (_usedNameList.contains(name))
return TheNameInUse;
if (name.isEmpty())
return NameIsEmpty;
if (InputValidator::getInstance()->FileNameIsAllow(name) == false)
return IllegalName;
return 0;
}
int EditorPathValue::IsFileSuffixSure()
{
QString suffix = _ui->FIleSuffixLE->text().trimmed();
if (suffix.isEmpty())
return FileSuffixIsEmpty;
if ((suffix.length() < 3) || (suffix.toLatin1().data()[0] != '*') || (suffix.toLatin1().data()[1] != '.'))
{
//qDebug() << suffix.length() << suffix.toLatin1().data()[0] << suffix.toLatin1().data()[1];
return FileSuffixIsNotSure;
}
return 0;
}
int EditorPathValue::IsFileSuffixSure(QString suffix)
{
if (suffix.isEmpty())
return FileSuffixIsEmpty;
if ((suffix.length() < 3) || (suffix.toLatin1().data()[0] != '*') || (suffix.toLatin1().data()[1] != '.'))
{
//qDebug() << suffix.length() << suffix.toLatin1().data()[0] << suffix.toLatin1().data()[1];
return FileSuffixIsNotSure;
}
return 0;
}
void EditorPathValue::setFileSuffixEnable(bool enable)
{
_ui->FIleSuffixLE->setEnabled(enable);
}
void EditorPathValue::OnOkPBtnClicked()
{
int type = _ui->TypeCB->currentIndex();
int nameError = IsNameSure();
if (nameError != 0)
{
QString errorMsg = _errorList[nameError];
_ui->ErrorText->setText(errorMsg);
_ui->ErrorText->show();
QTimer::singleShot(3000, this, SLOT(OnTimeout()));
return;
}
if (type != 0)
{
int suffixError = IsFileSuffixSure();
if (suffixError != 0)
{
QString errorMsg = _errorList[suffixError];
_ui->ErrorText->setText(errorMsg);
_ui->ErrorText->show();
QTimer::singleShot(3000, this, SLOT(OnTimeout()));
return;
}
}
UpdateUiToData();
this->accept();
close();
}
void EditorPathValue::OnPathPBtnClicked()
{
if ((_ui->TypeCB->currentIndex() == 1) || (_ui->TypeCB->currentIndex() == 2))
{
int suffixError = IsFileSuffixSure();
if (suffixError != 0)
{
QString errorMsg = _errorList[suffixError];
_ui->ErrorText->setText(errorMsg);
_ui->ErrorText->show();
QTimer::singleShot(3000, this, SLOT(OnTimeout()));
return;
}
}
QFileDialog *selectFile = new QFileDialog(this);
QString suffixName = QString("*.*");
selectFile->setWindowTitle(tr("Select File"));
selectFile->setDirectory(QCoreApplication::applicationDirPath());
if (_ui->FIleSuffixLE->text() != "")
suffixName = _ui->FIleSuffixLE->text();
selectFile->setNameFilter(suffixName);
if (_ui->TypeCB->currentIndex() == 0)
selectFile->setFileMode(QFileDialog::Directory);
else if (_ui->TypeCB->currentIndex() == 1)
selectFile->setFileMode(QFileDialog::ExistingFile);
else if (_ui->TypeCB->currentIndex() == 2)
selectFile->setFileMode(QFileDialog::ExistingFiles);
selectFile->setViewMode(QFileDialog::Detail);
QStringList fileNames;
if (selectFile->exec())
{
fileNames = selectFile->selectedFiles();
_ui->ValueLE->setText(fileNames.join(";"));
}
}
void EditorPathValue::OnTimeout()
{
_ui->ErrorText->setText("");
_ui->ErrorText->hide();
}
} | 24.622642 | 108 | 0.668812 | [
"model"
] |
d5b461e236934082d6ab273bf394cc4c7d38c4b9 | 6,517 | cpp | C++ | src/controller/src/commands/obstacle_course_command.cpp | P8P-7/core | 820873e7da867392729b2e65922205afe98e41d8 | [
"MIT"
] | 4 | 2018-04-16T17:56:25.000Z | 2018-06-22T17:02:26.000Z | src/controller/src/commands/obstacle_course_command.cpp | P8P-7/core | 820873e7da867392729b2e65922205afe98e41d8 | [
"MIT"
] | 1 | 2018-05-07T11:05:26.000Z | 2018-05-07T11:06:52.000Z | src/controller/src/commands/obstacle_course_command.cpp | P8P-7/core | 820873e7da867392729b2e65922205afe98e41d8 | [
"MIT"
] | 1 | 2018-05-07T11:04:15.000Z | 2018-05-07T11:04:15.000Z | #include <utility>
#include <goliath/controller/commands/obstacle_course_command.h>
#include <goliath/motor-controller/motor_controller.h>
#include <goliath/servo/wings/commandbuilder/wing_command_builder.h>
using namespace goliath::handles;
using namespace goliath;
const std::vector<size_t> leftMotors{HANDLE_LEFT_FRONT_MOTOR,
HANDLE_LEFT_BACK_MOTOR};
const std::vector<size_t> rightMotors{HANDLE_RIGHT_FRONT_MOTOR,
HANDLE_RIGHT_BACK_MOTOR};
commands::ObstacleCourseCommand::ObstacleCourseCommand(const size_t &id,
std::shared_ptr<repositories::WingStateRepository> repository)
: BasicCommand(id, {HANDLE_LEFT_FRONT_MOTOR, HANDLE_LEFT_BACK_MOTOR,
HANDLE_RIGHT_FRONT_MOTOR, HANDLE_RIGHT_BACK_MOTOR,
HANDLE_LEFT_FRONT_WING_SERVO, HANDLE_LEFT_BACK_WING_SERVO,
HANDLE_RIGHT_FRONT_WING_SERVO, HANDLE_RIGHT_BACK_WING_SERVO,
HANDLE_I2C_BUS, HANDLE_MOTOR_CONTROLLER, HANDLE_CAM}), repository(std::move(repository)) {}
void commands::ObstacleCourseCommand::execute(handles::HandleMap &handles, const proto::CommandMessage &message) {
handleMap = handles;
i2c::I2cSlave slave(*handles.get<handles::I2cBusHandle>(HANDLE_I2C_BUS),
*handles.get<handles::I2cSlaveHandle>(HANDLE_MOTOR_CONTROLLER));
motor_controller::MotorController motorController(slave);
servo::WingController wingController(repository);
vision::Webcam webcam = std::static_pointer_cast<WebcamHandle>(handles[HANDLE_CAM])->getDevice();
vision::FollowLineDetector followLineDetector(webcam.getFrame(), 4, 40, 10, 20, 10, 10000);
servo::WingCommandBuilder builder;
builder.setSpeed(1023).setAngle(20);
wingController.execute({
builder.setHandle(handles.get<handles::WingHandle>(HANDLE_LEFT_FRONT_MOTOR))
.setShortestDirection(repository->getState(HANDLE_LEFT_FRONT_MOTOR), 270)
.build(),
builder.setHandle(handles.get<handles::WingHandle>(HANDLE_RIGHT_FRONT_MOTOR))
.setShortestDirection(repository->getState(HANDLE_RIGHT_FRONT_MOTOR), 270)
.build()
});
builder.setAngle(190);
wingController.execute({
builder.setHandle(handles.get<handles::WingHandle>(HANDLE_LEFT_BACK_MOTOR))
.setShortestDirection(repository->getState(HANDLE_LEFT_BACK_MOTOR), 270)
.flipDirection()
.build(),
builder.setHandle(handles.get<handles::WingHandle>(HANDLE_RIGHT_BACK_MOTOR))
.setShortestDirection(repository->getState(HANDLE_RIGHT_BACK_MOTOR), 270)
.flipDirection()
.build(),
});
follow_line(followLineDetector, webcam, motorController);
BOOST_LOG_TRIVIAL(trace) << "setting speed to 0";
std::this_thread::sleep_for(std::chrono::seconds(1));
BOOST_LOG_TRIVIAL(trace) << "setting speed to 0";
move(0, 0, motorController);
}
void commands::ObstacleCourseCommand::follow_line(vision::FollowLineDetector &followLineDetector, vision::Webcam &camera,
motor_controller::MotorController &motorController) {
std::vector<cv::Vec4d> lines = followLineDetector.detect();
int noLinesCount = 0;
double lastDirection = 0;
while (noLinesCount < 30) {
if (isInterrupted()) {
move(0, 0, motorController);
return;
}
if (lines[0][0] == vision::FollowLineDirection::NO_LINE) {
noLinesCount++;
BOOST_LOG_TRIVIAL(trace) << "no line detected";
}
double direction = 0;
if (lines[0][0] == vision::FollowLineDirection::LEFT) {
direction = -lines[0][1] * 4;
} else if (lines[0][0] == vision::FollowLineDirection::RIGHT) {
direction = lines[0][1] * 4;
}
BOOST_LOG_TRIVIAL(trace) << "direction set to " << direction;
if (direction != lastDirection) {
move(direction, 50, motorController);
lastDirection = direction;
}
cv::Mat new_frame = camera.getFrame();
followLineDetector.update(new_frame);
lines = followLineDetector.detect();
}
}
void
commands::ObstacleCourseCommand::move(double direction, int speed, motor_controller::MotorController &motorController) {
std::vector<motor_controller::MotorStatus> commands{};
double leftSpeed = speed;
double rightSpeed = speed;
if (std::abs(direction) > 1) {
direction = direction / std::abs(direction);
}
if (direction < 0) {
leftSpeed -= leftSpeed * -direction;
rightSpeed += rightSpeed * -direction;
} else if (direction > 0) {
leftSpeed += leftSpeed * direction;
rightSpeed -= rightSpeed * direction;
}
BOOST_LOG_TRIVIAL(trace) << "speed left: " << leftSpeed << "\t right: " << rightSpeed;
motor_controller::MotorDirection gear = motor_controller::MotorDirection::BACKWARDS;
if (speed == 0) {
gear = motor_controller::MotorDirection::LOCKED;
}
for (size_t motor : leftMotors) {
auto handle = handleMap.get<handles::MotorHandle>(motor);
motor_controller::MotorStatus motorCommand{
.id = handle->getMotorId(),
.direction = gear,
.speed = static_cast<motor_controller::MotorSpeed>(leftSpeed)
};
commands.emplace_back(motorCommand);
}
for (size_t motor : rightMotors) {
auto handle = handleMap.get<handles::MotorHandle>(motor);
motor_controller::MotorStatus motorCommand{
.id = handle->getMotorId(),
.direction = gear,
.speed = static_cast<motor_controller::MotorSpeed>(rightSpeed)
};
commands.emplace_back(motorCommand);
}
if (!commands.empty()) {
motorController.sendCommands(commands.begin(), commands.end());
}
}
| 42.045161 | 121 | 0.600737 | [
"vector"
] |
d5b504ca9df3f9b6de3fc8b3873baaa86e8fb577 | 806 | cpp | C++ | Algorithms/0344.ReverseString/solution.cpp | stdstring/leetcode | 84e6bade7d6fc1a737eb6796cb4e2565440db5e3 | [
"MIT"
] | null | null | null | Algorithms/0344.ReverseString/solution.cpp | stdstring/leetcode | 84e6bade7d6fc1a737eb6796cb4e2565440db5e3 | [
"MIT"
] | null | null | null | Algorithms/0344.ReverseString/solution.cpp | stdstring/leetcode | 84e6bade7d6fc1a737eb6796cb4e2565440db5e3 | [
"MIT"
] | null | null | null | #include <vector>
#include "gtest/gtest.h"
namespace
{
class Solution
{
public:
void reverseString(std::vector<char> &s)
{
//std::reverse(s.begin(), s.end());
size_t first = 0;
size_t last = s.size() - 1;
while (first < last)
{
std::swap(s[first], s[last]);
++first;
--last;
}
}
};
}
namespace ReverseStringTask
{
TEST(ReverseStringTaskTests, Examples)
{
Solution solution;
std::vector<char> str1({'h', 'e', 'l', 'l', 'o'});
solution.reverseString(str1);
ASSERT_EQ(std::vector<char>({'o', 'l', 'l', 'e', 'h'}), str1);
std::vector<char> str2({'H', 'a', 'n', 'n', 'a', 'h'});
solution.reverseString(str2);
ASSERT_EQ(std::vector<char>({'h', 'a', 'n', 'n', 'a', 'H'}), str2);
}
} | 19.658537 | 71 | 0.512407 | [
"vector"
] |
d5b9eda31cd72bf8407207d49efad32b0428a28d | 6,025 | cpp | C++ | unit_tests/zero_page_mode_LSR.cpp | vcato/qt-quick-6502-emulator | 6202e546efddc612f229da078238f829dd756e12 | [
"Unlicense"
] | null | null | null | unit_tests/zero_page_mode_LSR.cpp | vcato/qt-quick-6502-emulator | 6202e546efddc612f229da078238f829dd756e12 | [
"Unlicense"
] | 3 | 2019-09-14T02:46:26.000Z | 2020-12-22T01:07:08.000Z | unit_tests/zero_page_mode_LSR.cpp | vcato/qt-quick-6502-emulator | 6202e546efddc612f229da078238f829dd756e12 | [
"Unlicense"
] | null | null | null | #include "addressing_mode_helpers.hpp"
struct LSR_ZeroPage_Expectations
{
NZCFlags flags;
uint8_t operand; // Data to be operated upon in Zero Page
};
using LSRZeroPage = LSR<ZeroPage, LSR_ZeroPage_Expectations, 5>;
using LSRZeroPageMode = ParameterizedInstructionExecutorTestFixture<LSRZeroPage>;
static void StoreTestValueAtEffectiveAddress(InstructionExecutorTestFixture &fixture, const LSRZeroPage &instruction_param)
{
fixture.fakeMemory[instruction_param.address.zero_page_address] = instruction_param.requirements.initial.operand;
}
static void SetupAffectedOrUsedRegisters(InstructionExecutorTestFixture &fixture, const LSRZeroPage &instruction_param)
{
fixture.r.SetFlag(FLAGS6502::N, instruction_param.requirements.initial.flags.n_value.expected_value);
fixture.r.SetFlag(FLAGS6502::Z, instruction_param.requirements.initial.flags.z_value.expected_value);
fixture.r.SetFlag(FLAGS6502::C, instruction_param.requirements.initial.flags.c_value.expected_value);
}
template<>
void LoadInstructionIntoMemoryAndSetRegistersToInitialState( InstructionExecutorTestFixture &fixture,
const LSRZeroPage &instruction_param)
{
SetupRAMForInstructionsThatHaveAnEffectiveAddress(fixture, instruction_param);
SetupAffectedOrUsedRegisters(fixture, instruction_param);
}
template<>
void RegistersAreInExpectedState(const Registers ®isters,
const LSR_ZeroPage_Expectations &expectations)
{
EXPECT_THAT(registers.GetFlag(FLAGS6502::N), Eq(expectations.flags.n_value.expected_value));
EXPECT_THAT(registers.GetFlag(FLAGS6502::Z), Eq(expectations.flags.z_value.expected_value));
EXPECT_THAT(registers.GetFlag(FLAGS6502::C), Eq(expectations.flags.c_value.expected_value));
}
template<>
void MemoryContainsInstruction(const InstructionExecutorTestFixture &fixture,
const Instruction<AbstractInstruction_e::LSR, ZeroPage> &instruction)
{
EXPECT_THAT(fixture.fakeMemory.at( fixture.executor.registers().program_counter ), Eq( OpcodeFor(AbstractInstruction_e::LSR, AddressMode_e::ZeroPage) ));
EXPECT_THAT(fixture.fakeMemory.at( fixture.executor.registers().program_counter + 1), Eq(instruction.address.zero_page_address));
}
template<>
void MemoryContainsExpectedComputation(const InstructionExecutorTestFixture &fixture,
const LSRZeroPage &instruction)
{
EXPECT_THAT(fixture.fakeMemory.at( instruction.address.zero_page_address ), Eq(instruction.requirements.initial.operand));
}
template<>
void MemoryContainsExpectedResult(const InstructionExecutorTestFixture &fixture,
const LSRZeroPage &instruction)
{
EXPECT_THAT(fixture.fakeMemory.at( instruction.address.zero_page_address ), Eq(instruction.requirements.final.operand));
}
static const std::vector<LSRZeroPage> LSRZeroPageModeTestValues {
LSRZeroPage{
// Beginning of a page
ZeroPage().address(0x8000).zp_address(6),
LSRZeroPage::Requirements{
.initial = {
.flags = { },
.operand = 0 },
.final = {
.flags = {
.n_value = { .expected_value = false },
.z_value = { .expected_value = true },
.c_value = { .expected_value = false } },
.operand = 0
}}
},
LSRZeroPage{
// Middle of a page
ZeroPage().address(0x8080).zp_address(6),
LSRZeroPage::Requirements{
.initial = {
.flags = { },
.operand = 0 },
.final = {
.flags = {
.n_value = { .expected_value = false },
.z_value = { .expected_value = true },
.c_value = { .expected_value = false } },
.operand = 0
}}
},
LSRZeroPage{
// End of a page
ZeroPage().address(0x80FE).zp_address(6),
LSRZeroPage::Requirements{
.initial = {
.flags = { },
.operand = 0 },
.final = {
.flags = {
.n_value = { .expected_value = false },
.z_value = { .expected_value = true },
.c_value = { .expected_value = false } },
.operand = 0
}}
},
LSRZeroPage{
// Crossing a page boundary
ZeroPage().address(0x80FF).zp_address(6),
LSRZeroPage::Requirements{
.initial = {
.flags = { },
.operand = 0 },
.final = {
.flags = {
.n_value = { .expected_value = false },
.z_value = { .expected_value = true },
.c_value = { .expected_value = false } },
.operand = 0
}}
},
LSRZeroPage{
// Check for Low bit going into carry
ZeroPage().address(0x8000).zp_address(6),
LSRZeroPage::Requirements{
.initial = {
.flags = { },
.operand = 0b01010101 },
.final = {
.flags = {
.n_value = { .expected_value = false },
.z_value = { .expected_value = false },
.c_value = { .expected_value = true } },
.operand = 0b00101010
}}
},
LSRZeroPage{
// Zero is set in highest bit
ZeroPage().address(0x8000).zp_address(6),
LSRZeroPage::Requirements{
.initial = {
.flags = { },
.operand = 0b11111111 },
.final = {
.flags = {
.n_value = { .expected_value = false },
.z_value = { .expected_value = false },
.c_value = { .expected_value = true } },
.operand = 0b01111111
}}
}
};
TEST_P(LSRZeroPageMode, TypicalInstructionExecution)
{
TypicalInstructionExecution(*this, GetParam());
}
INSTANTIATE_TEST_SUITE_P(LogicalShiftRightZeroPageAtVariousAddresses,
LSRZeroPageMode,
testing::ValuesIn(LSRZeroPageModeTestValues) );
| 35.650888 | 157 | 0.617593 | [
"vector"
] |
d5bc4fd6793c09afde145ce91635a89ad71b4ab8 | 1,439 | inl | C++ | owGameMap/Sky.inl | adan830/OpenWow | 9b6e9c248bd185b1677fe616d2a3a81a35ca8894 | [
"Apache-2.0"
] | null | null | null | owGameMap/Sky.inl | adan830/OpenWow | 9b6e9c248bd185b1677fe616d2a3a81a35ca8894 | [
"Apache-2.0"
] | null | null | null | owGameMap/Sky.inl | adan830/OpenWow | 9b6e9c248bd185b1677fe616d2a3a81a35ca8894 | [
"Apache-2.0"
] | 1 | 2020-05-11T13:32:49.000Z | 2020-05-11T13:32:49.000Z | #pragma once
template<typename T>
inline T GetByTimeTemplate(vector<Sky::SkyParam<T>>* _array, uint32 _paramNum, uint32 _time)
{
const vector<Sky::SkyParam<T>>& param = _array[_paramNum];
if (param.empty())
{
return T();
}
T parBegin, parEnd;
uint32 timeBegin, timeEnd;
uint32_t last = static_cast<uint32>(param.size()) - 1;
if (_time < param[0].time)
{
// interpolate between last and first
parBegin = param[last].value;
timeBegin = param[last].time;
parEnd = param[0].value;
timeEnd = param[0].time + C_Game_SecondsInDay; // next day
_time += C_Game_SecondsInDay;
}
else
{
for (uint32 i = last; i >= 0; i--)
{
if (_time >= param[i].time)
{
parBegin = param[i].value;
timeBegin = param[i].time;
if (i == last) // if current is last, then interpolate with first
{
parEnd = param[0].value;
timeEnd = param[0].time + C_Game_SecondsInDay;
}
else
{
parEnd = param[i + 1].value;
timeEnd = param[i + 1].time;
}
break;
}
}
}
float tt = (float)(_time - timeBegin) / (float)(timeEnd - timeBegin);
return parBegin * (1.0f - tt) + (parEnd * tt);
}
| 27.673077 | 92 | 0.492008 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.